From 0b207f4e8540c56047f73991059cf2692c6006f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 17:04:58 -0800 Subject: [PATCH 01/77] Graphs: axis lines, tick marks and radar rings keep the paint set on them A graph drew its axis lines and tick marks in 0.5 pt black and a radar graph's rings in 0.25 pt gray every time, with nothing stored for them. A stroke, fill, weight, recolor, Appearance row, graphic style, Eyedropper pick or opacity given to them was lost when the graph was drawn again. - The graph now stores the rows of its axis lines and tick marks (axisRows) and, separately, of a radar graph's rings (ringRows): the paint, weight, opacity and blend mode of the topmost visible fill and stroke row, their order, and the line's object opacity and blend mode. Every line of the kind is drawn with them. Dashes, caps, joins and arrowheads are not stored. - These commands store a line's rows: paint.setFill, paint.setStroke, the stroke, gradient and recolor commands, paint.swap, paint.default, Apply Fill to Stroke and Stroke to Fill, the appearance commands with the Eyedropper, graphic styles, transparency.set and object.setProps. paint.setFill, paint.setStroke and the recolor commands given a whole graph now also store what they give its lines. - When one command reaches several lines of a kind, the frontmost line in paint order sets what the kind keeps. A gradient is stored without its placement. - Lines that show their default stroke store nothing, and a global swatch edit or a document color conversion reaches the stored paint. Docs: docs/mcp.md, the params text of these commands, docs/target-app-parity.md. --- crates/doc/src/graph.rs | 10 +- crates/doc/src/swatches.rs | 24 ++- crates/engine/src/cmd/addons/color.rs | 12 +- crates/engine/src/cmd/appearance.rs | 33 +-- crates/engine/src/cmd/colorcmds.rs | 2 +- crates/engine/src/cmd/colormgmt.rs | 9 +- crates/engine/src/cmd/freeform.rs | 2 +- crates/engine/src/cmd/gradient.rs | 4 +- crates/engine/src/cmd/graph.rs | 2 +- crates/engine/src/cmd/graph/generate.rs | 2 +- crates/engine/src/cmd/graph/labels.rs | 61 +++++- crates/engine/src/cmd/graph/series.rs | 163 +++++++++++++-- crates/engine/src/cmd/graph/tests.rs | 254 +++++++++++++++++++++++ crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/paint.rs | 10 +- crates/engine/src/cmd/recolor.rs | 2 +- crates/engine/src/cmd/stroke.rs | 4 +- crates/engine/src/cmd/style.rs | 4 +- crates/engine/src/tests/swatches.rs | 14 +- docs/mcp.md | 20 +- docs/target-app-parity.md | 2 +- 21 files changed, 555 insertions(+), 81 deletions(-) diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 43074a4e80..1ef8e99e75 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -140,7 +140,7 @@ impl crate::Document { /// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the /// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para` /// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each -/// label's alignment. +/// label's alignment. [`Self::axis_rows`] and [`Self::ring_rows`] are the rows the graph's lines keep the same way. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct LabelStyles { @@ -176,6 +176,14 @@ pub struct LabelStyles { /// The object fill and stroke rows the legend labels keep, as [`Self::values_rows`]. #[serde(skip_serializing_if = "Option::is_none")] pub legend_rows: Option, + /// The object rows the axis lines and tick marks keep once set with the paint, stroke or Appearance controls + /// ([`LabelRows`]). They replace the default 0.5 pt black stroke; kept rows without paint draw none. `None`: the + /// default stroke. + #[serde(skip_serializing_if = "Option::is_none")] + pub axis_rows: Option, + /// The object rows the rings of a radar graph keep, as [`Self::axis_rows`]. `None`: the default 0.25 pt gray stroke. + #[serde(skip_serializing_if = "Option::is_none")] + pub ring_rows: Option, } impl LabelStyles { diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 844aa8c810..34e21fa6fa 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -382,14 +382,14 @@ pub fn override_paints(n: &Node) -> impl Iterator { n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten() } -/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its -/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out. +/// The paints a graph keeps for its series, its labels and its lines ([`crate::graph::GraphSpec`]), which +/// its marks, labels and lines take each time it is drawn again and which [`node_paints`] leaves out. pub fn graph_paints(n: &Node) -> impl Iterator { let g = n.extras().graph.as_deref(); let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten(); let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten(); let l = g.map(|g| &g.label_styles); - let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows]).flatten(); + let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows, &l.axis_rows, &l.ring_rows]).flatten(); series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])).chain(rows.flat_map(|r| [r.paint.fill.as_ref(), r.paint.stroke.as_ref()]).flatten()) } @@ -398,7 +398,7 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue; - assert_eq!(d.map_solid_paints(&mut to_blue), 5); + assert_eq!(d.map_solid_paints(&mut to_blue), 7); let g = d.node(a).unwrap().extras().graph.clone().unwrap(); assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand"))); assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand"))); let legend = g.label_styles.legend.unwrap(); assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None)); assert_eq!(g.label_styles.values_rows.unwrap().paint.fill, Some(linked(blue, "Brand"))); + assert_eq!(g.label_styles.axis_rows.unwrap().paint.stroke, Some(linked(blue, "Brand"))); + assert_eq!(g.label_styles.ring_rows.unwrap().paint.stroke, Some(linked(blue, "Brand"))); let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None); - assert_eq!(d.map_paints(&mut cleared), 5, "the fill and the graph's four"); + assert_eq!(d.map_paints(&mut cleared), 7, "the fill and the graph's six"); assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none)); } diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8701d379f7..3f8cbf936f 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Apply as Filter", ["Object", "Plug-ins", "Color Effects"], None, - "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step; their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed}", + "{effect: a colour adjustment's effect id (adjust.brightnessContrast, adjust.curves, adjust.hueSaturation, adjust.levels, adjust.shiftToColor, adjust.temperatureTint, addon.color.exposure, addon.color.desaturate, addon.color.duotone or addon.color.invert), params?: {…} (as effect.apply; missing keys take the dialog defaults), fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?: [id…] (default: the selection)} recolour the objects and everything inside them as the live effect would draw them, but in their colours, as edit.colors.invert does (fills, strokes, type, gradient meshes, embedded images and pattern tiles), as one undo step; their effects stay. Duotone links a colour to its one tone's swatch as the live effect does. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed}", has_selection, filter ), @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "Print Ink Fixes", ["Object", "Plug-ins", "Color Effects"], None, - "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", + "{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}", has_doc, print_fixes::run ), @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Apply Nearest Swatch", ["Object", "Plug-ins", "Color Effects"], None, - "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", + "{library?: as addon.color.nearestSwatch (default: \"document\"), fill?: true, stroke?: true, ids?: [id…] (default: the selection)} give each solid colour and gradient stop of the selected objects' fills and strokes (their type's and those of the objects inside them; gradient meshes too) the colour of its nearest swatch in the library, as addon.color.nearestSwatch finds it, as one undo step: a global or spot swatch's colour links to it. A library's swatches the colours take are added to the document's first, as swatch.library.add adds them (a spot colour stays spot); images and patterns keep their colours. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed: paints changed, swatches: [the document swatches the colours took], added: [swatches added to the document]}", has_selection, nearest::apply ), @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Apply Fill to Stroke", ["Object", "Plug-ins", "Color Effects"], None, - "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", + "{ids?|id?, skipNone?: bool} each target's top stroke takes its own top fill, as it is (a colour in its model, a global or spot colour linked at its tint, a gradient or pattern with its placement, None); a stroke given paint at width 0 gets 1 pt, as Swap Fill and Stroke does. Type: each run's stroke takes its own fill, and while the Type tool has characters selected (no ids), only those. A graph's labels keep the paint when the graph is drawn again, and its axis lines, tick marks and radar rings keep their new rows for every line of their kind. On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row (exceptions: docs/mcp.md). skipNone: leave alone a target whose fill is None. A target whose stroke already has that paint is left as it is, and when nothing changes no undo step is recorded. The default stroke takes the default fill the same way → {objects}", has_doc, |s, p| copy_paint(s, p, true) ), @@ -259,7 +259,9 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result { // The graph keeps the paint its series marks and labels now have. let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written); let labels = super::super::graph::capture_label_styles(d, &ids, ©_run); - Ok(objects + usize::from(series || labels)) + let painted: Vec = written.iter().map(|(id, _)| *id).collect(); + let lines = super::super::graph::capture_line_rows(d, &painted); + Ok(objects + usize::from(series || labels || lines)) })?; } // The defaults for new art change the same way, as Swap Fill and Stroke changes them. diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 94b35e9f93..1b5279a799 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, |s, p| add_item(s, p, true) ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, |s, p| add_item(s, p, false) ), @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Clear Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, clear_appearance ), @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, reduce_basic ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Appearance Item", [], None, - "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, set_item ), @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Remove Item", [], None, - "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, remove_item ), @@ -111,7 +111,7 @@ pub fn specs() -> Vec { "Duplicate Item", ["Window", "Appearance"], None, - "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind", + "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, duplicate_item ), @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder Appearance Item", [], None, - "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}", + "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {index: where the item landed | contents: the row's slot}", has_doc, move_item ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows and object opacity and blend mode for every line of its kind → {ids}", has_doc, copy_from ), @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Show All Hidden Attributes", ["Window", "Appearance"], None, - "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}", + "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {ids}", has_doc, show_all_hidden ), @@ -165,7 +165,7 @@ pub fn specs() -> Vec { "Move Appearance", [], None, - "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}", + "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {source, target}", has_doc, transfer ), @@ -510,7 +510,8 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { /// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters). /// What the edit changes on the topmost visible fill and stroke of graph series marks, and on the /// rows and characters of graph labels, is stored on their graphs in the same step -/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not +/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]), and so are the rows of +/// the graph lines it reaches ([`super::graph::capture_line_rows`]). Nothing targeted is not /// an edit, and when `f` leaves every target as it was, the document and its undo history stay as /// they are. pub(crate) fn edit_items( @@ -566,7 +567,9 @@ pub(crate) fn edit_items_then( } let more = after(&before, d, &edited)?; let labels = super::graph::capture_label_rows(d, &rows); - Ok(count_changed(d, &before, &edited) + usize::from(more || labels)) + // A graph line keeps the rows the edit wrote, also when the line already showed them. + let lines = super::graph::capture_line_rows(d, &edited); + Ok(count_changed(d, &before, &edited) + usize::from(more || labels || lines)) })?; Ok(()) } @@ -1639,7 +1642,9 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { }; // `append` adds rows and leaves the characters as they were. let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?; - Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text)) + // A graph line is a path: every pick writes its rows. + let lines = super::graph::capture_line_rows(d, &targets); + Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines)) })?; Ok(finish(s, &targets)) } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 7ad53d5bf5..6eb6dda499 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Invert Colors", ["Edit", "Edit Colors"], None, - "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}", + "{fill?: true, stroke?: true, includeImages?: true, includePatterns?: true, ids?} replace each colour by its RGB inverse (keeps the colour model) in fills, strokes, text, gradient meshes (with fills), colorized image fills (their pixels stay unchanged), other embedded images (a recoloured copy) and pattern tiles (a new pattern swatch; the original stays), as one undo step. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, notChanged: {locked, hidden} (when the selection is everything select.all takes: the locked and hidden objects it left out whose colors would have changed; an object both hidden and locked counts as hidden), warning?: set when notChanged counts any object}", has_selection, |s, p| recolor(s, p, "edit.colors.invert", "Invert Colors", &invert) ), diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 66295f50f2..7eaab7ab6a 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -653,8 +653,8 @@ fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Col } } -/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and -/// labels take each time it is drawn again. +/// `f` applied to the series paints, the label styles and the line rows that graph `g` keeps, which +/// its marks, labels and lines take each time it is drawn again. fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { for p in g.series_paints.iter_mut() { for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() { @@ -666,7 +666,10 @@ fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color map_paint_colors(&mut st.fill, f); map_paint_colors(&mut st.stroke, f); } - for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows].into_iter().flatten() { + for r in [&mut styles.values_rows, &mut styles.categories_rows, &mut styles.legend_rows, &mut styles.axis_rows, &mut styles.ring_rows] + .into_iter() + .flatten() + { for paint in [&mut r.paint.fill, &mut r.paint.stroke].into_iter().flatten() { map_paint_colors(paint, f); } diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index 5f2a5e4070..dcc2e4d849 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", has_doc, add_point ), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 8062d6110a..0a85d111a5 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label", has_doc, edit_gradient ), @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Gradient Vector", [], None, - "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label", + "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label", has_doc, set_gradient_geom ), diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 0413a55dbb..8cbf933134 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -46,7 +46,7 @@ use generate::generate; use series::default_series_color; pub(crate) use series::{ LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, - capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, + capture_label_styles, capture_label_text, capture_line_rows, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs, shown_paint, }; diff --git a/crates/engine/src/cmd/graph/generate.rs b/crates/engine/src/cmd/graph/generate.rs index 60217105d8..e12cd2a291 100644 --- a/crates/engine/src/cmd/graph/generate.rs +++ b/crates/engine/src/cmd/graph/generate.rs @@ -437,7 +437,7 @@ impl<'a> Plot<'a> { } for v in tick_values(lo, hi, step).into_iter().skip(1) { let ring: Vec = (0..ncat).map(|c| at(c, v)).collect(); - axes.push(self.b.path(polyline(&ring, true), Paint::None, Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25)); + axes.push(self.b.ring(polyline(&ring, true))); } let ax = self.b.group("Axes", axes); self.b.out.push(ax); diff --git a/crates/engine/src/cmd/graph/labels.rs b/crates/engine/src/cmd/graph/labels.rs index 290e099500..ac2aaf9dec 100644 --- a/crates/engine/src/cmd/graph/labels.rs +++ b/crates/engine/src/cmd/graph/labels.rs @@ -82,9 +82,49 @@ fn kept_rows(styles: &vectorcraft_doc::LabelStyles, role: Role) -> Option<&vecto } } -/// Give label `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their kept order and -/// place relative to the characters, and the object opacity and blend mode. An opacity read from a file is held to 0..1 -/// and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt). +/// What a graph line is, for the rows it keeps: an axis line or tick mark, or a ring of a radar graph. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Line { + Axis, + Ring, +} + +impl Line { + /// The stroke and weight the graph draws lines of this kind with when they keep no rows. They have no fill. + fn default_stroke(self) -> (Paint, f64) { + match self { + Line::Axis => (Paint::solid(Color::BLACK), 0.5), + Line::Ring => (Paint::solid(Color::rgb(0.6, 0.6, 0.6)), 0.25), + } + } + + /// The rows ([`super::series::label_rows`]) a line of this kind shows as the graph draws it with no kept rows. + pub(super) fn default_rows(self) -> vectorcraft_doc::LabelRows { + let (stroke, width) = self.default_stroke(); + let paint = vectorcraft_doc::SeriesPaint { fill: Some(Paint::None), stroke: Some(stroke), stroke_width: Some(width), ..Default::default() }; + vectorcraft_doc::LabelRows { paint, ..Default::default() } + } +} + +/// The rows lines of kind `line` keep, if any. +pub(super) fn kept_line_rows(styles: &vectorcraft_doc::LabelStyles, line: Line) -> Option<&vectorcraft_doc::LabelRows> { + match line { + Line::Axis => styles.axis_rows.as_ref(), + Line::Ring => styles.ring_rows.as_ref(), + } +} + +/// The slot of `styles` that holds the rows lines of kind `line` keep. +pub(super) fn line_slot(styles: &mut vectorcraft_doc::LabelStyles, line: Line) -> &mut Option { + match line { + Line::Axis => &mut styles.axis_rows, + Line::Ring => &mut styles.ring_rows, + } +} + +/// Give label or graph line `n` the object rows `kept` keeps: a fill row and a stroke row for the kept paints, in their +/// kept order and place relative to the contents, and the object opacity and blend mode. An opacity read from a file is +/// held to 0..1 and a weight to 0..1000 pt; one that is not a number is left out (a stroke then takes 1 pt). fn apply_label_rows(n: &mut Node, kept: &vectorcraft_doc::LabelRows) { use vectorcraft_doc::{AppearanceItem, FillLayer, StrokeLayer}; let rows = &kept.paint; @@ -124,7 +164,20 @@ impl Gen<'_> { let mut bp = BezPath::new(); bp.move_to(a); bp.line_to(b); - self.path(PathData::from_bezpath(&bp), Paint::None, Paint::solid(Color::BLACK), 0.5) + self.kept_line(Line::Axis, PathData::from_bezpath(&bp)) + } + /// A ring of a radar graph through `pd`. + pub(super) fn ring(&mut self, pd: PathData) -> Arc { + self.kept_line(Line::Ring, pd) + } + /// A graph line of kind `line` through `pd`, with the rows lines of its kind keep, else its default stroke. + fn kept_line(&mut self, line: Line, pd: PathData) -> Arc { + let (stroke, width) = line.default_stroke(); + let mut n = Node::path(self.d.alloc_id(), pd, Appearance::basic(Paint::None, stroke, width)); + if let Some(rows) = kept_line_rows(self.styles, line) { + apply_label_rows(&mut n, rows); + } + Arc::new(n) } pub(super) fn text(&mut self, role: Role, at: Point, s: &str, justify: Justify) -> Arc { let t = self.text_object(role, at, s, justify); diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 806d95047f..8d5847f7d5 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1,7 +1,7 @@ use vectorcraft_color::BlendMode; use super::axis::radar_axis; -use super::labels::{Role, filled_lines_on, label_para, label_style}; +use super::labels::{Line, Role, filled_lines_on, kept_line_rows, label_para, label_style, line_slot}; use super::{Arc, CharStyle, Color, Document, GraphKind, GraphSpec, HashMap, Node, NodeId, NodeKind, Paint, Result, Session, Value, bad}; // ---------- generation ---------- @@ -561,16 +561,117 @@ pub(crate) fn label_rows(n: &Node) -> Option { (rows != vectorcraft_doc::LabelRows::default()).then_some(rows) } +/// The graph and kind of graph line `id`: a path directly in a graph's Axes group. Looked up through its parents, with no +/// pass over the document. +fn graph_line(doc: &Document, id: NodeId) -> Option<(NodeId, Line)> { + let line = doc.node(id)?; + if !matches!(line.kind, NodeKind::Path { .. }) { + return None; + } + let path = doc.ancestry(id)?; + let [.., graph, axes, _] = path.as_slice() else { return None }; + let spec = doc.node(*graph)?.extras().graph.as_deref()?; + Some((*graph, line_in(spec, doc.node(*axes)?, line)?)) +} + +/// The kind of graph line `line` is when `axes` is the Axes group of a graph drawn from `spec` and `line` a path directly +/// in it. A radar graph's rings are its closed paths; its spokes, open, are axis lines. +fn line_in(spec: &GraphSpec, axes: &Node, line: &Node) -> Option { + if axes.name.as_deref() != Some("Axes") || axes.extras().series_index.is_some() || !matches!(axes.kind, NodeKind::Group { .. }) { + return None; + } + let NodeKind::Path { path, .. } = &line.kind else { return None }; + Some(if spec.kind == GraphKind::Radar && path.is_closed() { Line::Ring } else { Line::Axis }) +} + +/// The graph lines among `ids`, each with its graph and kind, from the back to the front and each once: a later line's +/// capture replaces an earlier one's, so the frontmost line of a kind sets what the kind keeps. +fn lines_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, NodeId, Line)> { + let mut out: Vec<(NodeId, NodeId, Line)> = ids.iter().filter_map(|id| graph_line(doc, *id).map(|(g, line)| (*id, g, line))).collect(); + out.sort_by_cached_key(|(id, ..)| doc.index_path(*id)); + out.dedup_by_key(|(id, ..)| *id); + out +} + +/// What lines of kind `line` keep (`slot`) after line `n` shows its rows ([`label_rows`]), or with `object_only` what +/// `slot` keeps with the line's object opacity and blend mode: `None` when that is how the graph draws them with no +/// kept rows. +fn line_rows_after(slot: Option<&vectorcraft_doc::LabelRows>, line: Line, n: &Node, object_only: bool) -> Option { + let shown = label_rows(n).unwrap_or_default(); + let rows = if object_only { + let mut kept = slot.cloned().unwrap_or_else(|| line.default_rows()); + (kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend); + kept + } else { + shown + }; + (rows != line.default_rows()).then_some(rows) +} + +/// Keep the object rows ([`label_rows`]) of the graph lines among `ids` for every line of their kind (axis lines and tick +/// marks, or a radar graph's rings), with `object_only` only their object opacity and blend mode, even when a line +/// already showed them. Returns whether kept rows changed. +fn store_line_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool { + let mut changed = false; + for (id, graph, line) in lines_of(doc, ids) { + let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { continue }; + let Some(n) = doc.node(id) else { continue }; + let kept = line_rows_after(kept_line_rows(&spec.label_styles, line), line, n, object_only); + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + changed |= *slot != kept; + *slot = kept; + } + changed +} + +/// Keep the object rows of graph lines `ids` for every line of their kind, as [`capture_label_rows`] keeps a label's, +/// for an edit that wrote their fill or stroke. Lines of a kind that the edit reached differently take the frontmost +/// one's rows. Called inside the same edit, so they undo together. Returns whether kept rows changed. +pub(crate) fn capture_line_rows(doc: &mut Document, ids: &[NodeId]) -> bool { + store_line_rows(doc, ids, false) +} + +/// Keep the object rows of the graph lines among `ids` whose rows an edit changed (`before`: the document before the +/// edit) for every line of their kind. Returns whether kept rows changed. +fn capture_line_changes(before: &Document, doc: &mut Document, ids: &[NodeId]) -> bool { + let changed: Vec = ids + .iter() + .copied() + .filter(|id| graph_line(doc, *id).is_some() && before.node(*id).map(label_rows) != doc.node(*id).map(label_rows)) + .collect(); + store_line_rows(doc, &changed, false) +} + +/// Would [`store_line_rows`] with `object_only` change what a graph keeps for the lines among `ids`? Reads the document +/// without copying it. +fn line_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { + let mut kept: Vec<(NodeId, Line, Option)> = vec![]; + for (id, graph, line) in lines_of(doc, ids) { + let (Some(spec), Some(n)) = (doc.node(graph).and_then(|n| n.extras().graph.as_deref()), doc.node(id)) else { continue }; + let slot = match kept.iter().position(|(g, l, _)| *g == graph && *l == line) { + Some(i) => kept.swap_remove(i).2, + None => kept_line_rows(&spec.label_styles, line).cloned(), + }; + kept.push((graph, line, line_rows_after(slot.as_ref(), line, n, true))); + } + kept.into_iter().any(|(graph, line, rows)| { + doc.node(graph).and_then(|n| n.extras().graph.as_deref()).is_some_and(|spec| kept_line_rows(&spec.label_styles, line) != rows.as_ref()) + }) +} + /// Keep the object rows ([`label_rows`]) of graph labels `ids` for every label of their kind, as /// [`capture_label_styles`] keeps a character format, even when a label already showed them: the last label of a kind /// in the order of `ids` sets what that kind keeps. Objects other than type are left out before the graph's labels are -/// looked up. Called inside the same edit, so they undo together. Returns whether kept rows changed. +/// looked up. The graph lines among `ids` keep their rows for every line of their kind too ([`capture_line_rows`]). +/// Called inside the same edit, so they undo together. Returns whether kept rows changed. pub(crate) fn capture_label_rows(doc: &mut Document, ids: &[NodeId]) -> bool { store_label_rows(doc, ids, false) } -/// Keep the object opacity and blend mode of graph labels `ids` for every label of their kind, as [`capture_label_rows`] -/// keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph keeps changed. +/// Keep the object opacity and blend mode of graph labels and graph lines `ids` for every label or line of their kind, as +/// [`capture_label_rows`] keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph +/// keeps changed. pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) -> bool { store_label_rows(doc, ids, true) } @@ -578,20 +679,21 @@ pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) - /// Would [`capture_label_object_opacity`] change what a graph keeps for labels `ids`? Reads the document without copying /// it. pub(crate) fn label_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { - label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| { - let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false }; - let slot = match role { - Role::Value => &spec.label_styles.values_rows, - Role::Category => &spec.label_styles.categories_rows, - Role::Legend => &spec.label_styles.legend_rows, - }; - *slot != kept_label_rows(slot, rows, true) - }) + line_object_opacity_differs(doc, ids) + || label_rows_of(doc, ids).into_iter().any(|(graph, role, rows)| { + let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { return false }; + let slot = match role { + Role::Value => &spec.label_styles.values_rows, + Role::Category => &spec.label_styles.categories_rows, + Role::Legend => &spec.label_styles.legend_rows, + }; + *slot != kept_label_rows(slot, rows, true) + }) } /// [`capture_label_rows`], or with `object_only` [`capture_label_object_opacity`]. fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool { - let mut changed = false; + let mut changed = store_line_rows(doc, ids, object_only); for (graph, role, rows) in label_rows_of(doc, ids) { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; let slot = match role { @@ -741,23 +843,38 @@ pub(super) fn picks_legend_fill(g: &GraphSpec) -> bool { && !g.label_styles.legend.as_ref().is_some_and(|st| st.fill != Paint::solid(Color::BLACK)) } -/// The graph labels among `roots` and inside them, for an edit that reaches graph labels without naming them. +/// The graph labels and graph lines among `roots` and inside them, for an edit that reaches them without naming them. pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec { let mut texts = Vec::new(); + let mut lines = Vec::new(); for id in roots { + // A root that is a line, or the Axes group: found through its parents. + if graph_line(doc, *id).is_some() { + lines.push(*id); + } let Some(root) = doc.node(*id) else { continue }; + if let Some(parent) = doc.parent_of(*id).and_then(|p| doc.node(p)) + && let Some(spec) = parent.extras().graph.as_deref() + { + lines.extend(root.children().into_iter().flatten().filter(|c| line_in(spec, root, c).is_some()).map(|c| c.id)); + } root.walk(&mut |n| { if matches!(n.kind, NodeKind::Text(_)) { texts.push(n.id); } + if let Some(spec) = n.extras().graph.as_deref() { + for axes in n.children().into_iter().flatten() { + lines.extend(axes.children().into_iter().flatten().filter(|c| line_in(spec, axes, c).is_some()).map(|c| c.id)); + } + } }); } // Graph labels are type: without type among `roots`, the graph's labels are not looked up. - if texts.is_empty() { - return texts; + if !texts.is_empty() { + let labels = graph_labels(doc); + texts.retain(|id| labels.contains_key(id)); } - let labels = graph_labels(doc); - texts.retain(|id| labels.contains_key(id)); + texts.extend(lines.into_iter().filter(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))); // Nested roots (a graph and one of its labels) reach a label twice. texts.sort_unstable(); texts.dedup(); @@ -769,10 +886,12 @@ pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec { /// and stroke attributes ([`RUN_PAINT`]) that changed on all of a label's characters, on the kind's kept style. The /// frontmost label of a kind sets what that kind keeps, whatever order `ids` are in. On a graph that colors its legend /// labels itself ([`picks_legend_fill`]), their fill is kept only when the legend labels among `ids` end up with one -/// fill. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. +/// fill. The graph lines among `ids` whose rows changed keep them for every line of their kind ([`capture_line_rows`]), +/// with or without `rows`. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool) -> bool { + let lines = capture_line_changes(before, doc, ids); if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) { - return false; + return lines; } let labels = graph_labels(doc); let mut picked: Vec = ids.iter().copied().filter(|id| labels.contains_key(id)).collect(); @@ -800,7 +919,7 @@ pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: let fill = kind.1 != Role::Legend || one_fill(kind.0); characters.extend(run_paint_change(was, now, fill).map(|change| (kind, change))); } - let mut changed = capture_label_rows(doc, &changed_rows); + let mut changed = capture_label_rows(doc, &changed_rows) | lines; for ((graph, role), (style, entries)) in &characters { changed |= store_label_style(doc, *graph, *role, &|st| { for i in entries { diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index ea47c82112..672408d899 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5839,6 +5839,260 @@ fn a_recolor_leaves_wedge_legend_labels_their_contrast() { assert_eq!(kept.and_then(|f| f.color()).map(|c| c.to_hex()).as_deref(), Some("#ffffff")); } +/// The lines in graph `id`'s Axes group (axis lines, tick marks and a radar graph's rings), in paint order. +fn line_nodes(s: &Session, id: NodeId) -> Vec { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + group(&n, "Axes").children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Text(_))).map(|c| (**c).clone()).collect() +} + +/// How line `n` looks: its stroke color (empty without one), stroke weight and object opacity. +fn line_look(n: &vectorcraft_doc::Node) -> (String, f64, f32) { + let stroke = n.appearance.stroke_paint().color().map(|c| c.to_hex()).unwrap_or_default(); + (stroke, n.appearance.stroke_width(), n.opacity) +} + +/// The looks of graph `id`'s lines after it is drawn again. +fn redrawn_line_looks(s: &mut Session, id: NodeId) -> Vec<(String, f64, f32)> { + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + line_nodes(s, id).iter().map(line_look).collect() +} + +/// A stroke, a weight, no stroke or an opacity given to one axis line is kept for every axis line and tick mark when the +/// graph is drawn again, and undo takes it back with its edit. +#[test] +fn paint_set_on_one_axis_line_is_kept_for_every_line() { + let cases = [ + ("paint.setStroke", json!({"color": "#ff0000"}), ("#ff0000", 0.5, 1.0)), + ("stroke.set", json!({"weight": 2}), ("#000000", 2.0, 1.0)), + ("paint.setStroke", json!({"none": true}), ("", 0.0, 1.0)), + ("appearance.clear", json!({}), ("", 0.0, 1.0)), + ("transparency.set", json!({"opacity": 40}), ("#000000", 0.5, 0.4)), + ]; + every_case(cases, |(cmd, params, (hex, width, opacity))| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + assert!(lines.len() > 2, "{lines:?}"); + let mut p = params.clone(); + p["ids"] = json!([lines[0].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + let want = (hex.to_string(), *width, *opacity); + assert!(looks.iter().all(|l| (&l.0, (l.1 - want.1).abs() < 1e-9, (l.2 - want.2).abs() < 1e-6) == (&want.0, true, true)), "{cmd}: {looks:?}"); + // Undo takes back the redraw, then the edit and what the graph keeps. + for _ in 0..2 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(spec(&s, id).label_styles.axis_rows, None, "{cmd}"); + }); +} + +/// A recolor of the whole graph, or Swap Fill and Stroke on its axis lines, is kept for its axis lines, and the labels' +/// paint stays its own. +#[test] +fn recoloring_a_graph_keeps_its_axis_lines_paint() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ffffff"), "inverted black lines are white"); + let ids: Vec = line_nodes(&s, id).iter().map(|n| n.id.0).collect(); + s.execute("paint.swap", &json!({"ids": ids})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap(); + assert_eq!((kept.paint.fill.and_then(|p| p.color()).map(|c| c.to_hex()), kept.paint.stroke), (Some("#ffffff".into()), Some(Paint::None))); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0.is_empty()), "the lines have no stroke after the swap"); + // The value labels keep their inverted fill, not the lines' swapped paint. + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let label_paint: Vec<(String, bool)> = group(&n, "Axes") + .children() + .unwrap() + .iter() + .filter_map(|c| match &c.kind { + NodeKind::Text(t) => Some((t.runs[0].style.fill.color().map(|c| c.to_hex()).unwrap_or_default(), t.runs[0].style.stroke.is_none())), + _ => None, + }) + .collect(); + assert!(!label_paint.is_empty() && label_paint.iter().all(|l| *l == ("#ffffff".to_string(), true)), "{label_paint:?}"); +} + +/// A stroke given the whole graph, or its Axes group, is kept for its axis lines. +#[test] +fn a_stroke_given_the_whole_graph_or_its_axes_group_is_kept_for_its_axis_lines() { + for axes in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let target = if axes { group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id } else { id }; + s.execute("paint.setStroke", &json!({"ids": [target.0], "color": "#ff0000"})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000"), "axes: {axes}"); + } +} + +/// A radar graph's rings keep what is set on one of them, apart from its spokes. +#[test] +fn a_radar_graphs_rings_keep_their_paint_apart_from_its_spokes() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let lines = line_nodes(&s, id); + // Three categories: three spokes, then the rings. + assert_eq!(line_look(&lines[3]), ("#999999".into(), 0.25, 1.0)); + s.execute("paint.setStroke", &json!({"ids": [lines[3].id.0], "color": "#00ff00"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#000000" && l.1 == 0.5), "{looks:?}"); + assert!(looks[3..].iter().all(|l| l.0 == "#00ff00" && l.1 == 0.25), "{looks:?}"); + s.execute("paint.setStroke", &json!({"ids": [line_nodes(&s, id)[0].id.0], "color": "#0000ff"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#0000ff") && looks[3..].iter().all(|l| l.0 == "#00ff00"), "{looks:?}"); +} + +/// When an edit gives axis lines different paint, the frontmost one sets what they keep, whatever order `ids` are in. +#[test] +fn the_frontmost_axis_line_sets_what_its_recolor_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let (back, front) = (lines[0].id, lines[lines.len() - 1].id); + s.execute("paint.setStroke", &json!({"ids": [front.0], "color": "#ff0000"})).unwrap(); + s.execute("edit.colors.invert", &json!({"ids": [front.0, back.0]})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#00ffff"), "the inverted red of the frontmost line"); +} + +/// A radar graph's spoke brought in front of its rings is still a spoke: what is set on it is kept for the spokes. +#[test] +fn a_radar_spoke_moved_in_front_of_the_rings_keeps_its_kind() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let spoke = line_nodes(&s, id)[0].id; + s.execute("object.arrange.bringToFront", &json!({"ids": [spoke.0]})).unwrap(); + assert_eq!(line_nodes(&s, id).last().map(|n| n.id), Some(spoke), "the spoke is in front of the rings"); + s.execute("paint.setStroke", &json!({"ids": [spoke.0], "color": "#0000ff"})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| l.0 == "#0000ff") && looks[3..].iter().all(|l| l.0 == "#999999"), "{looks:?}"); +} + +/// A graphic style linked to an axis line passes a redefinition on to every axis line. +#[test] +fn a_redefined_graphic_style_on_an_axis_line_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Axis"})).unwrap(); + let line = line_nodes(&s, id)[0].id; + s.execute("graphicStyle.apply", &json!({"name": "Axis", "ids": [line.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Axis", "id": rect.0})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#00ff00")); +} + +/// An Eyedropper pick and Apply Stroke to Fill on an axis line are kept for every axis line. +#[test] +fn an_eyedropper_pick_and_stroke_to_fill_on_an_axis_line_are_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + let line = line_nodes(&s, id)[0].id; + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000" && l.1 == 1.0), "the picked 1 pt red stroke"); + let line = line_nodes(&s, id)[1].id; + s.execute("addon.color.strokeToFill", &json!({"ids": [line.0]})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let fills: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == "#ff0000"), "{fills:?}"); +} + +/// Setting a line to the paint it is drawn with by default keeps nothing, and is no edit. +#[test] +fn axis_lines_given_their_default_paint_keep_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + let undo = s.doc().unwrap().history.undo.len(); + s.execute("paint.setStroke", &json!({"ids": [line.0], "color": "#000000"})).unwrap(); + assert_eq!(spec(&s, id).label_styles.axis_rows, None); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); +} + +/// `object.setProps` and `transparency.set` without an `item` keep only a line's object opacity: the stroke its kind +/// keeps from another line stays, though the line they are given still shows the default stroke. +#[test] +fn an_object_opacity_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + for (cmd, params) in [("object.setProps", json!({"opacity": 50})), ("transparency.set", json!({"opacity": 50}))] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{cmd}: {looks:?}"); + } +} + +/// An opacity and a stroke weight given to a radar graph's ring are kept for its rings, and its spokes keep their own. +#[test] +fn transparency_and_stroke_weight_on_a_radar_ring_are_kept_for_its_rings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let ring = line_nodes(&s, id)[3].id; + s.execute("transparency.set", &json!({"ids": [ring.0], "opacity": 40})).unwrap(); + s.execute("stroke.set", &json!({"ids": [ring.0], "weight": 1})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks[..3].iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{looks:?}"); + assert!(looks[3..].iter().all(|l| l.0 == "#999999" && l.1 == 1.0 && (l.2 - 0.4).abs() < 1e-6), "{looks:?}"); +} + +/// A placed gradient on an axis line's stroke is kept for every axis line without its placement. +#[test] +fn a_gradient_on_an_axis_line_is_kept_without_its_placement() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + s.execute("paint.editGradient", &json!({"ids": [line.0], "kind": "linear", "stroke": true})).unwrap(); + let placement = json!({"ids": [line.0], "stroke": true, "start": [100, 100], "end": [200, 100], "aspect": 50}); + s.execute("paint.setGradientGeom", &placement).unwrap(); + let shown = line_nodes(&s, id)[0].appearance.stroke_paint().clone(); + assert!(matches!(&shown, Paint::Gradient(g) if g.geom.is_some()), "the line's gradient is placed: {shown:?}"); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke; + assert!(matches!(&kept, Some(Paint::Gradient(g)) if g.geom.is_none() && g.freeform.is_none()), "{kept:?}"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert!(line_nodes(&s, id).iter().all(|n| matches!(n.appearance.stroke_paint(), Paint::Gradient(_)))); +} + +/// Default Fill and Stroke and Apply Fill to Stroke on an axis line are kept for every axis line. +#[test] +fn default_fill_and_stroke_and_fill_to_stroke_on_an_axis_line_are_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let line = line_nodes(&s, id)[0].id; + s.execute("paint.setStroke", &json!({"ids": [line.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.default", &json!({"ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| *l == ("#000000".into(), 1.0, 1.0)), "the 1 pt black default stroke"); + let fills: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == "#ffffff"), "{fills:?}"); + let line = line_nodes(&s, id)[1].id; + s.execute("paint.setFill", &json!({"ids": [line.0], "color": "#0000ff"})).unwrap(); + s.execute("addon.color.fillToStroke", &json!({"ids": [line.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#0000ff"), "the blue fill on the stroke"); +} + #[test] fn pie_names_and_wedge_labels_keep_their_style() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 6ffdb04a5c..52f18f3e3c 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -251,7 +251,7 @@ pub fn specs() -> Vec { "Object Properties", [], None, - "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind", + "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind", has_doc, set_props ), diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 60c5180f40..850feb1c6a 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Swap Fill and Stroke", [], Some("Shift+X"), - "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, swap ), @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, default_paint ), @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Transparency", ["Window", "Transparency"], None, - "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores the label's object opacity and blend mode for every label of its kind, and with `item` its topmost visible fill and stroke rows too", + "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind, and with `item` its topmost visible fill and stroke rows too", has_doc, transparency ), @@ -96,7 +96,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind (docs/mcp.md) → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 5d7e1ab633..fa725e03c3 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step. On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 14282c5112..f9dca54298 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Stroke Weight Up", [], Some("Cmd+Alt+."), - "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind (docs/mcp.md) → {objects}", + "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}", has_doc, |s, p| stroke_step(s, p, true) ), diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 1c41006b3f..55b0fcccf7 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {name}", + "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", has_doc, style_redefine ), diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index a80769dd98..01eb90e8b9 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -262,8 +262,8 @@ fn document_color_mode_converts_effect_colors() { assert_eq!((object(&s), style(&s)), before); } -/// Document Color Mode converts the series paints and label styles a graph keeps, so a graph drawn -/// again after the switch paints its series and labels in the new mode. +/// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a +/// graph drawn again after the switch paints its series, labels and lines in the new mode. #[test] fn document_color_mode_converts_the_paints_a_graph_keeps() { let mut s = session(); @@ -284,22 +284,26 @@ fn document_color_mode_converts_the_paints_a_graph_keeps() { } // A fill row on the label, which the graph keeps with the label's rows. run(&mut s, "appearance.addFill", json!({"ids": [label.0]})); + // A stroke on an axis line, which the graph keeps for its axis lines and tick marks. + let line = part(&s, "Axes").children().unwrap().iter().find(|c| matches!(c.kind, vectorcraft_doc::NodeKind::Path { .. })).unwrap().id; + run(&mut s, "paint.setStroke", json!({"color": "#ff0000", "ids": [line.0]})); let kept = |s: &Session| -> Vec { let g = doc(s).node(id).unwrap().extras().graph.as_deref().unwrap().clone(); let rows = [&g.label_styles.values_rows, &g.label_styles.categories_rows, &g.label_styles.legend_rows]; let rows: Vec = rows.into_iter().flatten().filter_map(|r| r.paint.fill.as_ref()?.color()).collect(); + let lines = g.label_styles.axis_rows.iter().filter_map(|r| r.paint.stroke.as_ref()?.color()); let labels = [g.label_styles.values, g.label_styles.categories, g.label_styles.legend]; let labels = labels.into_iter().flatten().map(|st| st.fill.color().unwrap()); - g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).collect() + g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).chain(rows).chain(lines).collect() }; let before = kept(&s); - assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 3]); + assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 4]); let undo = s.doc().unwrap().history.undo.len(); run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); let cmyk = first_fill(doc(&s).node(red).unwrap()); assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}"); - assert_eq!(kept(&s), [cmyk; 3]); + assert_eq!(kept(&s), [cmyk; 4]); assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); // Drawn again from new data, the series keeps the converted color. run(&mut s, "graph.setData", json!({"id": id.0, "rows": [[2, 3], [4, 5]]})); diff --git a/docs/mcp.md b/docs/mcp.md index 4f6eb742cc..0b23ed3947 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -821,8 +821,7 @@ placement they set there. A stroke weight and dashes are stored as the label sho scaled. When the characters of labels of one kind change differently, the frontmost label sets what the kind keeps. On a pie with Legends in Wedges whose legend labels have no fill of their own, the legend labels' fill is stored only when every legend label the command reaches ends up with the same fill. Otherwise they are drawn again in black, or white on -a dark wedge. These commands do not store the colors they give a graph's axis lines, ticks and radar rings, which are -drawn again with their default paint. +a dark wedge. What they change on a graph's axis lines, tick marks and radar rings is stored as described below. `text.setFormat` without `start` and `end`, on a graph or on its labels, stores the character and paragraph attributes it sets for each kind of label it reaches (value axis numbers, category labels, legend labels), and every label of that @@ -846,6 +845,23 @@ the paragraph attributes. `paint.setFill` and `paint.setStroke` store a characte the label's characters (the whole label, or all of its text highlighted with the Type tool), and the row when it goes to a row. A stored character gradient also fits each label. +On a graph's axis lines and tick marks, and separately on a radar graph's rings, `paint.setFill`, `paint.setStroke`, +`addon.color.fillToStroke`, `addon.color.strokeToFill`, the stroke, gradient and recolor commands above, `paint.swap`, +`paint.default`, the `appearance.*` commands (`appearance.copyFrom`, the Eyedropper, included), `graphicStyle.apply`, +`graphicStyle.redefine`, `transparency.set` and `object.setProps` store what a line shows for every line of its kind: +the paint, weight, opacity and blend mode of its topmost visible fill and stroke row, their order, and the line's object +opacity and blend mode. `paint.setFill`, `paint.setStroke` and the recolor commands also store them when given the +graph, its Axes group or a group that holds the graph, so the lines keep the paint those commands give a whole graph. +The other commands store them when given the line itself. `transparency.set` without an `item` and `object.setProps` +store only the object opacity and blend mode. `appearance.copyFrom` stores the rows whatever it picks up, with or +without `append`. The recolor commands, `paint.swap` and `paint.default` store a line's rows when they change them. The +other commands store them even when the line already showed them, except that rows equal to a kind's default stroke +(0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in +paint order sets what the kind keeps, whatever order the `ids` are in. A gradient is stored without its placement, and +each line fits it when the graph is drawn again. The graph saves the rows as `axisRows` and `ringRows` in its label +styles. Other stroke options (caps, joins, miter limit, alignment, dashes and arrowheads), rows below the topmost one of +each kind, and effects are not stored, so a dash set on a line is drawn solid again. + `effect.apply {"effect": "path.outlineObject"}` (Effect › Path › Outline Object) takes no parameters. Type that carries it is drawn, exported and expanded as its glyph outlines and stays editable type, and the effects after it reshape those outlines. On paths, compound paths and images it does not change what is drawn. On an image's own fill or stroke diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1e41bde132..1afedccf73 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1098,7 +1098,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile and arrowheads turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. As VectorCraft's own rule, the axis lines and tick marks, and separately a radar graph's rings, keep the paint, weight, opacity and blend mode of their topmost fill and stroke rows and their object opacity and blend mode through the graph being drawn again after a paint, stroke weight, gradient, recolor, Appearance, Transparency or Graphic Styles edit, the Eyedropper, Swap Fill and Stroke or Default Fill and Stroke, the frontmost line of a kind setting what the kind keeps; their dashes, caps, joins and arrowheads are not kept. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). An Eyedropper pick that includes transparency and leaves a mark's top fill or stroke row without paint, or removes that row when the source has no row of that kind, where that row had paint before, also replaces the opacity and blend mode the graph keeps for that kind of row in the series; a row that had no paint before the pick leaves them as they are. What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks. - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. From 33be0b9e58fdb5923db5274312b725ccf89e415f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 18:43:30 -0800 Subject: [PATCH 02/77] Graphs: Appearance edits given the Axes or Legend group are kept The appearance.* commands, graphicStyle.apply, graphicStyle.redefine, graphicStyle.breakLink and transparency.set with an item, given a graph's Axes group or Legend group, edited the group's own appearance stack. The graph draws those groups again with no rows of their own, so the next redraw (for example after graph.setData) removed the edit. These commands now read such a group as they read a series group: the Axes group stands for the axis lines, tick marks, radar rings and labels directly in it, and the Legend group for the legend labels. The graph keeps what the command sets for every line and label of each kind. graphicStyle.new and the other commands that read a look read the topmost member of a group that holds nothing of its own. A group with a fill or stroke row of its own, or with no line or label in it, is still edited itself, except by graphicStyle.redefine, which passes the style to the members of a linked group. The lines and labels of a new graph have different rows, so a row index given the Axes group would name a different row in each. An index or item given such a group is now an error unless `aligned` is true, which makes it a row of the backmost member's stack. Docs: docs/mcp.md, params text, docs/target-app-parity.md Graphs line. --- crates/engine/src/cmd/appearance.rs | 56 +++++++++--- crates/engine/src/cmd/graph.rs | 2 +- crates/engine/src/cmd/graph/series.rs | 29 +++++- crates/engine/src/cmd/graph/tests.rs | 123 ++++++++++++++++++++++++++ crates/engine/src/cmd/paint.rs | 5 +- crates/engine/src/cmd/style.rs | 8 +- docs/mcp.md | 30 +++++-- docs/target-app-parity.md | 2 +- 8 files changed, 224 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 1b5279a799..7a7c945555 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, |s, p| add_item(s, p, true) ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, |s, p| add_item(s, p, false) ), @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Clear Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, clear_appearance ), @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, reduce_basic ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Appearance Item", [], None, - "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `index` needs `aligned` and is a row of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, set_item ), @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Remove Item", [], None, - "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, remove_item ), @@ -111,7 +111,7 @@ pub fn specs() -> Vec { "Duplicate Item", ["Window", "Appearance"], None, - "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, the indices need `aligned` and are rows of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", has_doc, duplicate_item ), @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder Appearance Item", [], None, - "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {index: where the item landed | contents: the row's slot}", + "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; moving rows of such a group whose members' rows differ is an error), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {index: where the item landed | contents: the row's slot}", has_doc, move_item ), @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Show All Hidden Attributes", ["Window", "Appearance"], None, - "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {ids}", + "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {ids}", has_doc, show_all_hidden ), @@ -165,7 +165,7 @@ pub fn specs() -> Vec { "Move Appearance", [], None, - "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {source, target}", + "{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {source, target}", has_doc, transfer ), @@ -420,7 +420,8 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result> } /// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside -/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays: +/// it, and each such Axes or Legend group of a graph by the lines and labels directly inside it +/// ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays: /// the Appearance panel lists those rows and edits them by index. pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec { super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty()) @@ -441,8 +442,9 @@ fn holds_no_look(group: &Node) -> bool { } /// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own -/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or -/// another attribute of its own is read itself, with that attribute. +/// ([`holds_no_look`]) gives the paths directly inside it, backmost first, and such an Axes or Legend group of a graph +/// the lines and labels directly inside it. A series group with an effect, an opacity or another attribute of its own is +/// read itself, with that attribute. fn look_holders(d: &Document, id: NodeId) -> Vec { super::graph::series_group_marks_where(d, &[id], holds_no_look) } @@ -506,6 +508,28 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { Ok(ids) } +/// Refuse a row index given a graph's Axes or Legend group that stands for lines and labels whose stacks differ +/// ([`rowless_series_marks`]), unless the index is `aligned`, a row of the backmost one's stack: the same index names a +/// different row in each of them. +pub(crate) fn check_part_rows(s: &Session, p: &Value, aligned: bool, cmd: &str) -> Result<()> { + if aligned { + return Ok(()); + } + let d = &s.doc()?.doc; + for id in appearance_targets(s, p)? { + let Some(n) = d.node(id).filter(|n| n.appearance.items.is_empty()) else { continue }; + if let Some(members) = super::graph::graph_part_members(d, n) + && appearances_differ(d, &members) + { + return Err(bad( + cmd, + format!("the lines and labels in graph group {} have different appearance rows: pass `aligned: true` or their ids", id.0), + )); + } + } + Ok(()) +} + /// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke /// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters). /// What the edit changes on the topmost visible fill and stroke of graph series marks, and on the @@ -890,7 +914,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { let mut targets: Vec = marks.iter().copied().filter(|id| !within.contains(id)).collect(); if targets.is_empty() { if stands { - return Err(bad(C, "`source` is the only path in series group `target`")); + return Err(bad(C, "`source` is the only path, line or label that graph group `target` stands for")); } targets.push(target); } @@ -1011,6 +1035,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad("appearance.setItem", "select objects or give ids")); } + check_part_rows(s, p, aligned(p, "appearance.setItem")?, "appearance.setItem")?; let blend = str_param(p, "blend").and_then(BlendMode::parse); // When every object comes out as it was (for example, when none has item `index`), the document // and its undo history stay as they are. @@ -1099,6 +1124,7 @@ pub(super) fn item_indices(p: &Value, cmd: &str) -> Result> { fn remove_item(s: &mut Session, p: &Value) -> Result { let idx = item_indices(p, "appearance.removeItem")?; let ids = require_targets(s, p, "appearance.removeItem")?; + check_part_rows(s, p, aligned(p, "appearance.removeItem")?, "appearance.removeItem")?; // When no object has an item at any of the indices, the document and its undo history stay as // they are. let before = s.doc()?.doc.clone(); @@ -1137,6 +1163,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "`contents` goes with `to`")); } let ids = require_targets(s, p, C)?; + check_part_rows(s, p, aligned(p, C)?, C)?; // Where the first target's copy landed, and where it landed on the active row's object (the // first selected one, not always the first target): copies placed at `to` land at a different // index on stacks of other lengths. @@ -1262,6 +1289,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { return move_contents(s, &ids, to); } let ids = require_targets(s, p, C)?; + check_part_rows(s, p, aligned, C)?; // Where an aligned row would go in each of several different stacks isn't one place. if aligned && appearances_differ(&s.doc()?.doc, &ids) { return Err(bad(C, "rows of objects whose appearances differ can't be reordered together")); diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 8cbf933134..16f0684d85 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -47,7 +47,7 @@ use series::default_series_color; pub(crate) use series::{ LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_text, capture_line_rows, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, - label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, + graph_part_members, label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs, shown_paint, }; diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 8d5847f7d5..abd0947d6f 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -149,13 +149,32 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec { } /// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series -/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other -/// ids and the art of a graph design pass through, and the order of `ids` is kept. +/// group: the graph draws its series groups again with no rows of their own. A graph's Axes group is replaced by the +/// lines and labels directly inside it, and its Legend group by the labels directly inside it, which the graph keeps +/// rows for ([`capture_label_rows`]). A group with no such member, other ids and the art of a graph design pass +/// through, and the order of `ids` is kept. pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec { series_group_marks_where(doc, ids, |_| true) } -/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through. +/// The lines and labels directly in `n` when it is the Axes group of a graph, or the labels directly in it when it is +/// the graph's Legend group, in paint order. `None` for any other object. +pub(crate) fn graph_part_members(doc: &Document, n: &Node) -> Option> { + if !matches!(n.kind, NodeKind::Group { .. }) || n.extras().series_index.is_some() { + return None; + } + let axes = match n.name.as_deref() { + Some("Axes") => true, + Some("Legend") => false, + _ => return None, + }; + let spec = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref())?; + let member = |c: &Node| matches!(c.kind, NodeKind::Text(_)) || (axes && line_in(spec, n, c).is_some()); + Some(n.children().into_iter().flatten().filter(|c| member(c)).map(|c| c.id).collect()) +} + +/// [`series_group_marks`] for the series groups, Axes groups and Legend groups `stands` accepts; the others pass +/// through. pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec { // A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is // looked up through its parent, with no pass over the document: the panels call this while they draw. @@ -173,6 +192,10 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect(); if marks.is_empty() { out.push(*id) } else { out.extend(marks) } } + Some(part) if stands(part) => match graph_part_members(doc, part) { + Some(members) if !members.is_empty() => out.extend(members), + _ => out.push(*id), + }, _ => out.push(*id), } } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 672408d899..b7816c412d 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6093,6 +6093,129 @@ fn default_fill_and_stroke_and_fill_to_stroke_on_an_axis_line_are_kept() { assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#0000ff"), "the blue fill on the stroke"); } +/// The Appearance commands and `graphicStyle.apply` given a graph's Axes group or Legend group edit the lines and labels +/// directly in it, as given a series group they edit its paths: every line and label of each kind keeps what they set +/// when the graph is drawn again, and the groups keep no rows of their own. +#[test] +fn appearance_commands_given_the_axes_or_legend_group_edit_its_lines_and_labels() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let part = |s: &Session, name: &str| group(s.doc().unwrap().doc.node(id).unwrap(), name).clone(); + s.execute("appearance.clear", &json!({"ids": [part(&s, "Axes").id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0.is_empty()), "the cleared lines have no stroke"); + let (_, blue) = blue_style(&mut s, "Blue", false); + for name in ["Axes", "Legend"] { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [part(&s, name).id.0]})).unwrap(); + } + let kept = spec(&s, id).label_styles; + let fill = |rows: Option| rows.and_then(|r| r.paint.fill); + assert_eq!(fill(kept.axis_rows), Some(blue.clone()), "axis lines"); + assert_eq!(fill(kept.values_rows), Some(blue.clone()), "value labels"); + assert_eq!(fill(kept.legend_rows), Some(blue.clone()), "legend labels"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + for name in ["Axes", "Legend"] { + let g = part(&s, name); + assert!(g.appearance.items.is_empty(), "{name} keeps no rows of its own"); + let members: Vec = g.children().unwrap().iter().map(|c| c.appearance.fill_paint()).collect(); + assert!(!members.is_empty() && members.iter().all(|p| *p == blue), "{name}: {members:?}"); + } +} + +/// A row index given the Axes group, whose lines and labels have different rows, is refused unless it is `aligned`, a row +/// of the backmost member's stack: then the members that share that row change, the labels keep theirs, and the graph +/// keeps the change when it is drawn again. +#[test] +fn a_row_index_given_the_axes_group_is_a_row_of_its_backmost_member_with_aligned() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let back = axes.children().unwrap()[0].id; + assert!(line_nodes(&s, id).iter().any(|l| l.id == back), "the backmost member is a line"); + let stroke = top_row(&s, back, false); + for (cmd, p) in [ + ("appearance.setItem", json!({"ids": [axes.id.0], "index": stroke, "color": "#ff0000"})), + ("appearance.removeItem", json!({"ids": [axes.id.0], "index": stroke})), + ("appearance.duplicateItem", json!({"ids": [axes.id.0], "index": stroke})), + ("appearance.moveItem", json!({"ids": [axes.id.0], "from": stroke, "to": 0})), + ("transparency.set", json!({"ids": [axes.id.0], "item": stroke, "opacity": 40})), + ] { + let err = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(err.contains("aligned"), "{cmd}: {err}"); + } + let labels = |s: &Session| -> Vec { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + group(&n, "Axes").children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| (*c.appearance).clone()).collect() + }; + let was = labels(&s); + s.execute("appearance.setItem", &json!({"ids": [axes.id.0], "index": stroke, "color": "#ff0000", "aligned": true})).unwrap(); + s.execute("transparency.set", &json!({"ids": [axes.id.0], "item": stroke, "opacity": 40, "aligned": true})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); + let rows = spec(&s, id).label_styles.axis_rows.unwrap(); + assert_eq!(rows.paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + let now = labels(&s); + assert!(!now.is_empty() && now.iter().all(|a| *a == was[0]), "the labels keep their rows"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let l = &group(&n, "Axes").children().unwrap()[0]; + assert!((l.appearance.items[top_row(&s, l.id, false)].opacity() - 0.4).abs() < 1e-6, "the stroke row's opacity is kept"); +} + +/// Redefine Graphic Style on an Axes group linked to the style with rows of its own (as a file can hold it) restyles and +/// links the lines and labels in it, and clears and unlinks the group; Break Link given the group unlinks them. A style +/// applied through the group links its lines and labels, and the graph keeps their look, not the link, when it is drawn +/// again. +#[test] +fn graphic_style_links_given_the_axes_group() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id; + let (rect, _) = blue_style(&mut s, "Blue", false); + let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone(); + s.edit("Link", |d, _| { + let g = d.node_mut(axes).unwrap(); + g.appearance = style.appearance.clone().into(); + g.extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap(); + let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + let axes_now = |s: &Session| group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let members = |s: &Session| -> Vec<(Paint, Option)> { + axes_now(s).children().unwrap().iter().map(|c| (c.appearance.fill_paint(), c.extras().graphic_style)).collect() + }; + let g = axes_now(&s); + assert!(g.appearance.items.is_empty() && g.extras().graphic_style.is_none(), "the group is cleared and unlinked"); + assert!(members(&s).iter().all(|m| *m == (green.clone(), Some(style.id))), "{:?}", members(&s)); + s.execute("graphicStyle.breakLink", &json!({"ids": [axes_now(&s).id.0]})).unwrap(); + assert!(members(&s).iter().all(|m| m.1.is_none()), "unlinked"); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [axes_now(&s).id.0]})).unwrap(); + assert!(members(&s).iter().all(|m| m.1 == Some(style.id)), "linked"); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert!(members(&s).iter().all(|m| *m == (green.clone(), None)), "{:?}", members(&s)); +} + +/// The Appearance commands given a radar graph's Axes group reach its spokes and rings, which keep the edit apart. +#[test] +fn a_style_given_a_radar_graphs_axes_group_is_kept_for_spokes_and_rings() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "radar"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").id; + let (_, blue) = blue_style(&mut s, "Blue", false); + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [axes.0]})).unwrap(); + let kept = spec(&s, id).label_styles; + let fill = |rows: Option| rows.and_then(|r| r.paint.fill); + assert_eq!(fill(kept.axis_rows), Some(blue.clone()), "spokes"); + assert_eq!(fill(kept.ring_rows), Some(blue.clone()), "rings"); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0.is_empty()), "the style has no stroke: {looks:?}"); +} + #[test] fn pie_names_and_wedge_labels_keep_their_style() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 850feb1c6a..d59b9f8bd9 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Transparency", ["Window", "Transparency"], None, - "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind, and with `item` its topmost visible fill and stroke rows too", + "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (for a fill or stroke item, a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `item` needs `aligned` and is a row of the backmost one), the graph stores that object's opacity and blend mode for every label or line of its kind, and with `item` its topmost visible fill and stroke rows too", has_doc, transparency ), @@ -1105,6 +1105,9 @@ fn transparency(s: &mut Session, p: &Value) -> Result { }; // Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level. let item_ids = if editing_mask { ids } else { row_targets(s, p)? }; + if !editing_mask { + super::appearance::check_part_rows(s, p, aligned || !explicit, C)?; + } if explicit { let d = &s.doc()?.doc; if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) { diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 55b0fcccf7..2f0ccf77ca 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "New Graphic Style", ["Window", "Graphic Styles"], None, - "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}", + "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it, and a graph's Axes or Legend group with none of these for its topmost line or label; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}", has_doc, style_new ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", + "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", has_doc, style_redefine ), @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Break Link to Graphic Style", ["Window", "Graphic Styles"], None, - "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it", + "{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it, a graph's Axes group for the group and its lines and labels, and its Legend group for the group and its labels", has_doc, style_break_link ), diff --git a/docs/mcp.md b/docs/mcp.md index 0b23ed3947..de782981be 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -790,10 +790,25 @@ look was edited keep their look. Read as a source, by `graphicStyle.new`, `graph style link of its own gives the look and the style link of the topmost path directly in it, and a move with `appearance.transfer` clears each of those paths; a series group that has one of them is read itself. -The other commands given a series group's id edit the group itself, and the graph does not store what they set on it: -`transparency.set` and `object.setProps` with an opacity or blend mode for the object, the `effect.*` commands and -`appearance.addEffect`, and the paint, stroke and gradient commands with a fill or stroke `item`, which is a row of the -group's own stack. The Appearance panel and `appearance.setActiveItem` read the selected group's own rows. +The commands in the paragraph above read a graph's Axes group and Legend group, given by id or selected with Group +Selection, as they read a series group: the Axes group stands for the axis lines, tick marks, radar rings and labels +directly in it, and the Legend group for the legend labels directly in it. The graph stores what they set for every +line and label of each kind, as described below for a line or label given itself, and the groups keep no rows of their +own. An Axes or Legend group that has a fill or stroke row of its own, or holds no line or label, is edited itself, +except by `graphicStyle.redefine`, which passes the style to the lines and labels of a linked group whatever the group +holds. An `index`, `indices` or fill or stroke `item` given an Axes or Legend group whose lines and labels have +different rows, as the lines and labels of a new graph do, is an error unless `aligned` is true, which makes it a row +of the stack of the backmost line or label in the group, and `appearance.moveItem` does not move the rows of such a +group. The graph keeps no graphic style link on its lines and +labels: they keep the look of a style applied to them, and are unlinked when the graph is drawn again. The commands +find these groups by their names, so a renamed Axes or Legend group is edited itself. + +The other commands given a series group's id, or a graph's Axes or Legend group, edit the group itself, and the graph +does not store what they set on it: `transparency.set` and `object.setProps` with an opacity or blend mode for the +object, the `effect.*` commands and `appearance.addEffect`, and the paint, stroke and gradient commands with a fill or +stroke `item`, which is a row of the group's own stack. `paint.setFill`, `paint.setStroke` and the recolor commands +given the Axes group store the line rows, as described below. The Appearance panel and `appearance.setActiveItem` read +the selected group's own rows. The graph also stores a paint or stroke weight that one of these commands changes on the topmost visible fill or stroke of a path directly in a series: a weight set with `stroke.set`, `stroke.weightUp` or `stroke.weightDown`; a gradient @@ -852,9 +867,10 @@ On a graph's axis lines and tick marks, and separately on a radar graph's rings, the paint, weight, opacity and blend mode of its topmost visible fill and stroke row, their order, and the line's object opacity and blend mode. `paint.setFill`, `paint.setStroke` and the recolor commands also store them when given the graph, its Axes group or a group that holds the graph, so the lines keep the paint those commands give a whole graph. -The other commands store them when given the line itself. `transparency.set` without an `item` and `object.setProps` -store only the object opacity and blend mode. `appearance.copyFrom` stores the rows whatever it picks up, with or -without `append`. The recolor commands, `paint.swap` and `paint.default` store a line's rows when they change them. The +The other commands store them when given the line itself, and the `appearance.*` and graphic style commands and +`transparency.set` with an `item` also when given the Axes group, as described above. `transparency.set` without an +`item` and `object.setProps` store only the object opacity and blend mode. `appearance.copyFrom` stores the rows +whatever it picks up, with or without `append`. The recolor commands, `paint.swap` and `paint.default` store a line's rows when they change them. The other commands store them even when the line already showed them, except that rows equal to a kind's default stroke (0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in paint order sets what the kind keeps, whatever order the `ids` are in. A gradient is stored without its placement, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1afedccf73..64b7ace1f9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1098,7 +1098,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile and arrowheads turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. As VectorCraft's own rule, the axis lines and tick marks, and separately a radar graph's rings, keep the paint, weight, opacity and blend mode of their topmost fill and stroke rows and their object opacity and blend mode through the graph being drawn again after a paint, stroke weight, gradient, recolor, Appearance, Transparency or Graphic Styles edit, the Eyedropper, Swap Fill and Stroke or Default Fill and Stroke, the frontmost line of a kind setting what the kind keeps; their dashes, caps, joins and arrowheads are not kept. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). + - **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, or recolored, given Swap Fill and Stroke or Default Fill and Stroke, or given stroke options or a gradient, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. As VectorCraft's own rule, the axis lines and tick marks, and separately a radar graph's rings, keep the paint, weight, opacity and blend mode of their topmost fill and stroke rows and their object opacity and blend mode through the graph being drawn again after a paint, stroke weight, gradient, recolor, Appearance, Transparency or Graphic Styles edit, the Eyedropper, Swap Fill and Stroke or Default Fill and Stroke, the frontmost line of a kind setting what the kind keeps; the lines' dashes, caps, joins and arrowheads are not kept. An Appearance, Transparency (with a fill or stroke row) or Graphic Styles edit given the Axes group or the Legend group reaches the lines and labels in it and is kept the same way. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485). An Eyedropper pick that includes transparency and leaves a mark's top fill or stroke row without paint, or removes that row when the source has no row of that kind, where that row had paint before, also replaces the opacity and blend mode the graph keeps for that kind of row in the series; a row that had no paint before the pick leaves them as they are. What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks. - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. From f0a8c750a3a6c7950272520b85f7ce40bb12243d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:44:06 -0800 Subject: [PATCH 03/77] Graphs: a whole-pie recolor leaves wedge legend labels their contrast A recolor that reached a pie's legend labels through the graph kept their new fill as the legend's own when every label ended up with one color (a one-series pie), so a wedge painted light again kept a white label. Legend label fills on such a pie are now kept only when the edit named the labels. --- crates/engine/src/cmd/appearance.rs | 2 +- crates/engine/src/cmd/colorcmds.rs | 2 +- crates/engine/src/cmd/graph/series.rs | 11 +++++++---- crates/engine/src/cmd/graph/tests.rs | 18 ++++++++++++++++++ crates/engine/src/cmd/paint.rs | 4 ++-- 5 files changed, 29 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index f006d7314e..6689a25014 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -547,7 +547,7 @@ pub(crate) fn edit_items( edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| { let series = capture_series_changes(before, d, edited); // The rows `f` edited are kept by `edit_items_then`. - let labels = super::graph::capture_label_changes(before, d, edited, false); + let labels = super::graph::capture_label_changes(before, d, edited, false, None); Ok(series || labels) }) } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index baaef20c56..d811a9dffe 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -522,7 +522,7 @@ pub(crate) fn keeping_series_paint(d: &mut Document, roots: &[NodeId], recolor: let n = recolor(d)?; if let Some(before) = before.filter(|_| n > 0) { super::appearance::capture_series_changes(&before, d, &marks); - super::graph::capture_label_changes(&before, d, &labels, true); + super::graph::capture_label_changes(&before, d, &labels, true, Some(roots)); } Ok(n) } diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index df99ebef51..69cf88d62c 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -899,9 +899,11 @@ pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec { /// and stroke attributes ([`RUN_PAINT`]) that changed on all of a label's characters, on the kind's kept style. The /// frontmost label of a kind sets what that kind keeps, whatever order `ids` are in. On a graph that colors its legend /// labels itself ([`picks_legend_fill`]), their fill is kept only when the legend labels among `ids` end up with one -/// fill. The graph lines among `ids` whose rows changed keep them for every line of their kind ([`capture_line_rows`]), -/// with or without `rows`. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. -pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool) -> bool { +/// fill and the edit named them: with `named`, only a legend label among `named` (an edit that reached the others +/// through the graph or a group leaves them the graph's black or white); without it, every label in `ids`. The graph +/// lines among `ids` whose rows changed keep them for every line of their kind ([`capture_line_rows`]), with or without +/// `rows`. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. +pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool, named: Option<&[NodeId]>) -> bool { let lines = capture_line_changes(before, doc, ids); if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) { return lines; @@ -929,7 +931,8 @@ pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: if rows && label_rows(was) != label_rows(now) { changed_rows.push(id); } - let fill = kind.1 != Role::Legend || one_fill(kind.0); + let aimed = !wedge_fills.contains_key(&kind.0) || named.is_none_or(|n| n.contains(&id)); + let fill = kind.1 != Role::Legend || (one_fill(kind.0) && aimed); characters.extend(run_paint_change(was, now, fill).map(|change| (kind, change))); } let mut changed = capture_label_rows(doc, &changed_rows) | lines; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 35987ce15d..13b2542ff3 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5971,6 +5971,24 @@ fn a_recolor_leaves_wedge_legend_labels_their_contrast() { assert_eq!(kept.and_then(|f| f.color()).map(|c| c.to_hex()).as_deref(), Some("#ffffff")); } +/// A recolor of the whole graph that turns every wedge legend label the same color (one series) still leaves them to +/// the graph's black or white, so a label stays readable when its wedge is painted light again. +#[test] +fn a_recolor_of_a_one_series_pie_leaves_its_wedge_label_its_contrast() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = make(&mut s, "pie", ",a\nP1,1"); + s.execute("graph.setType", &json!({"id": id.0, "pieLegend": "wedges"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [series_0_group(&s, id).0.0], "color": "#ffffff"})).unwrap(); + // The white wedge turns black and its black label white. + s.execute("edit.colors.invert", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(spec(&s, id).label_styles.legend, None); + s.execute("paint.setFill", &json!({"ids": [series_0_group(&s, id).0.0], "color": "#ffffff"})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1]]})).unwrap(); + let NodeKind::Text(t) = label_node(&s, id, "Legend", "a").kind else { panic!("a is not type") }; + assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()).as_deref(), Some("#000000")); +} + /// The lines in graph `id`'s Axes group (axis lines, tick marks and a radar graph's rings), in paint order. fn line_nodes(s: &Session, id: NodeId) -> Vec { let n = s.doc().unwrap().doc.node(id).unwrap().clone(); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 67a0281528..32a8fdb2c2 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -925,7 +925,7 @@ fn swap(s: &mut Session, p: &Value) -> Result { } // The swap writes the paint of the topmost fill and stroke, not their opacity. let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false); - let labels = super::graph::capture_label_changes(&before, d, &ids, false); + let labels = super::graph::capture_label_changes(&before, d, &ids, false, None); Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) })?; } @@ -955,7 +955,7 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); - let labels = super::graph::capture_label_changes(&before, d, &ids, false); + let labels = super::graph::capture_label_changes(&before, d, &ids, false, None); Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) })?; } From 429f37a2216fa76e72414caca399b11398d7b620 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:21:38 -0800 Subject: [PATCH 04/77] i18n: script interpreter core errors are translated in every complete-message catalog A script run that fails on an error the interpreter's core throws (an unknown name, a property of null or undefined, a property that cannot be defined, assigned or deleted, a value that is not a function or a constructor) showed that error in English in the status bar. Seven of these messages were built in a variable, so the untranslated-strings report did not list them. Of the 23 complete-message catalogs, 17 had no rows for the interpreter's messages, and the other six (de, it, pl, pt-br, uk, zh-hans) had none for "invalid assignment target", the reasons or the error types. - Every complete-message catalog has rows for these errors, for the reasons a property cannot be defined or assigned, for "invalid assignment target", and for the error types (TypeError: {e} and the others), so the failed-run line translates the message after the type. Names, property names, null, undefined, 'in', 'instanceof' and the type are kept, and e.message stays English for scripts. French rows keep the no-break space before the colon. - A value a message quotes in '...' is shown as written, like one in "...", so a property named like a translated message keeps its name. - An error about a property of null or undefined reached through a computed key or a member assignment named an empty property ("cannot read property '' of null"). It now names a key that is not an object and is at most 256 units long, and otherwise says "cannot read a property of null" or "cannot set a property of undefined". An increment (u['k']++) and a delete (delete null[true]) give the "cannot read" form. - The message scan reads the interpreter's .reject and .reject_bool reasons. Tests: i18n::tests::script_interpreter_core_errors_are_translated, message_scan_reads_script_interpreter_errors, interp_tests::errors_about_null_and_undefined_name_the_property. --- crates/js/src/interp.rs | 74 +++++++++------- crates/js/src/interp_tests.rs | 21 +++++ crates/ui-egui/src/i18n.rs | 6 +- crates/ui-egui/src/i18n/ca.tsv | 38 ++++++++ crates/ui-egui/src/i18n/cs.tsv | 38 ++++++++ crates/ui-egui/src/i18n/de.tsv | 25 ++++++ crates/ui-egui/src/i18n/el.tsv | 38 ++++++++ crates/ui-egui/src/i18n/es.tsv | 38 ++++++++ crates/ui-egui/src/i18n/fi.tsv | 38 ++++++++ crates/ui-egui/src/i18n/fr.tsv | 38 ++++++++ crates/ui-egui/src/i18n/hi.tsv | 38 ++++++++ crates/ui-egui/src/i18n/hu.tsv | 38 ++++++++ crates/ui-egui/src/i18n/it.tsv | 25 ++++++ crates/ui-egui/src/i18n/ja.tsv | 38 ++++++++ crates/ui-egui/src/i18n/ka.tsv | 38 ++++++++ crates/ui-egui/src/i18n/ko.tsv | 38 ++++++++ crates/ui-egui/src/i18n/nl.tsv | 38 ++++++++ crates/ui-egui/src/i18n/pl.tsv | 25 ++++++ crates/ui-egui/src/i18n/pt-br.tsv | 25 ++++++ crates/ui-egui/src/i18n/ru.tsv | 38 ++++++++ crates/ui-egui/src/i18n/sv.tsv | 38 ++++++++ crates/ui-egui/src/i18n/tests.rs | 133 +++++++++++++++++++++++++++- crates/ui-egui/src/i18n/tr.tsv | 38 ++++++++ crates/ui-egui/src/i18n/uk.tsv | 25 ++++++ crates/ui-egui/src/i18n/vi.tsv | 38 ++++++++ crates/ui-egui/src/i18n/zh-hans.tsv | 25 ++++++ crates/ui-egui/src/i18n/zh-hant.tsv | 38 ++++++++ docs/target-app-parity.md | 1 + 28 files changed, 994 insertions(+), 37 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index edc5282fe5..4d814828a1 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -310,6 +310,10 @@ pub(crate) const MAX_APPLY_ARGS: usize = 1 << 16; /// The estimated bytes of a name's entries in the list and the set `for-in` builds. const KEY_ENTRY_BYTES: usize = 32; +/// The most units of a computed property name an error about a property of `null` or `undefined` +/// names; a longer name is left out of the message. +const NAMED_KEY_UNITS: usize = 256; + #[cfg(test)] thread_local! { /// Tests: the [`Interp::finally_sites`] entries that leaving a block or a frame has looked at. @@ -1077,8 +1081,8 @@ impl Interp { } fn not_defined(&mut self, name: &[u16]) -> Abrupt { - let message = format!("{} is not defined", String::from_utf16_lossy(name)); - self.throw(ErrorType::Reference, &message) + let name = String::from_utf16_lossy(name); + self.throw(ErrorType::Reference, &format!("{name} is not defined")) } fn get_var(&mut self, name: &Key) -> JsResult<(Value, Value)> { @@ -1332,12 +1336,9 @@ impl Interp { Value::Number(_) => Ok(self.intrinsics.number_proto), Value::Bool(_) => Ok(self.intrinsics.boolean_proto), Value::Undefined | Value::Null => { - let message = format!( - "cannot read property '{}' of {}", - String::from_utf16_lossy(k), - if matches!(v, Value::Null) { "null" } else { "undefined" } - ); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(k); + let base = if matches!(v, Value::Null) { "null" } else { "undefined" }; + Err(self.type_error(&format!("cannot read property '{key}' of {base}"))) } } } @@ -1434,8 +1435,8 @@ impl Interp { fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { if throw { - let message = format!("cannot define property '{}': {why}", String::from_utf16_lossy(k)); - return Err(self.type_error(&message)); + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot define property '{key}': {why}"))); } Ok(false) } @@ -1588,8 +1589,8 @@ impl Interp { fn reject(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult<()> { if throw { - let message = format!("cannot assign to property '{}': {why}", String::from_utf16_lossy(k)); - return Err(self.type_error(&message)); + let key = String::from_utf16_lossy(k); + return Err(self.type_error(&format!("cannot assign to property '{key}': {why}"))); } Ok(()) } @@ -1684,8 +1685,8 @@ impl Interp { Ok(true) } Some(_) if throw => { - let message = format!("cannot delete property '{}'", String::from_utf16_lossy(k)); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(k); + Err(self.type_error(&format!("cannot delete property '{key}'"))) } Some(_) => Ok(false), } @@ -1703,12 +1704,9 @@ impl Interp { self.put(*o, k, v, throw) } Value::Undefined | Value::Null => { - let message = format!( - "cannot set property '{}' of {}", - String::from_utf16_lossy(&k), - if matches!(base, Value::Null) { "null" } else { "undefined" } - ); - Err(self.type_error(&message)) + let key = String::from_utf16_lossy(&k); + let base = if matches!(base, Value::Null) { "null" } else { "undefined" }; + Err(self.type_error(&format!("cannot set property '{key}' of {base}"))) } _ => { let proto = self.primitive_proto(base, &k)?; @@ -1742,16 +1740,30 @@ impl Interp { self.replace(2, v) } - fn check_coercible(&mut self, base: &Value, k: &[u16]) -> JsResult<()> { - if base.is_nullish() { - self.primitive_proto(base, k)?; + /// Throws when `base` is `null` or `undefined`, naming the property `k` when it is a primitive + /// of at most [`NAMED_KEY_UNITS`] units, which converts without running script code, and the + /// access as a read, or as a write when `set`. + fn check_coercible(&mut self, base: &Value, k: Option<&Value>, set: bool) -> JsResult<()> { + if !base.is_nullish() { + return Ok(()); } - Ok(()) + let key = match k { + Some(Value::String(s)) if s.len() > NAMED_KEY_UNITS => None, + Some(Value::Object(_)) | None => None, + Some(k) => Some(self.to_str(k)?.to_rust_string()), + }; + let base = if matches!(base, Value::Null) { "null" } else { "undefined" }; + Err(match (key, set) { + (Some(key), false) => self.type_error(&format!("cannot read property '{key}' of {base}")), + (Some(key), true) => self.type_error(&format!("cannot set property '{key}' of {base}")), + (None, false) => self.type_error(&format!("cannot read a property of {base}")), + (None, true) => self.type_error(&format!("cannot set a property of {base}")), + }) } fn op_check_object(&mut self) -> JsResult<()> { let base = self.peek(0)?; - self.check_coercible(&base, &[]) + self.check_coercible(&base, None, true) } fn op_to_key(&mut self) -> JsResult<()> { @@ -1760,7 +1772,7 @@ impl Interp { if self.is_xml_access(&base, &k) { return Ok(()); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), true)?; let name = self.to_key(&k)?; self.replace(1, Value::String(Str::from_rc(name))) } @@ -1778,7 +1790,7 @@ impl Interp { let v = self.xml_get(&base, &k)?; return self.replace(2, v); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let name = self.to_key(&k)?; let v = self.get_value(&base, &name)?; self.replace(2, v)?; @@ -1818,7 +1830,7 @@ impl Interp { let r = self.xml_delete(&base, &k)?; return self.replace(2, Value::Bool(r)); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let name = self.to_key(&k)?; let o = self.to_object(&base)?; let strict = self.strict(); @@ -1851,7 +1863,7 @@ impl Interp { self.xml_put(&base, &k, &Value::Number(new))?; return self.replace(2, Value::Number(if prefix { new } else { old })); } - self.check_coercible(&base, &[])?; + self.check_coercible(&base, Some(&k), false)?; let name = self.to_key(&k)?; let r = self.inc_property(&base, name, prefix, dec)?; self.replace(2, r) @@ -2575,8 +2587,8 @@ impl Interp { self.put(object, name.clone(), v, true) } Some(_) => { - let message = format!("cannot declare function {}", String::from_utf16_lossy(name)); - Err(self.type_error(&message)) + let name = String::from_utf16_lossy(name); + Err(self.type_error(&format!("cannot declare function {name}"))) } } } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 93c487b378..9f9c59a96f 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -239,6 +239,27 @@ fn errors_carry_line_and_column() { assert_eq!(e.message, "42"); } +/// An error about a property of `null` or `undefined` names a computed property whose name is a +/// primitive, and says whether the script read or set it, never naming an empty property; a +/// member assignment, an object key and a long name leave the name out. +#[test] +fn errors_about_null_and_undefined_name_the_property() { + for (source, message) in [ + ("null[1]", "TypeError: cannot read property '1' of null"), + ("var u; u['k'] += 1", "TypeError: cannot set property 'k' of undefined"), + ("var u; u['k']++", "TypeError: cannot read property 'k' of undefined"), + ("delete null[true]", "TypeError: cannot read property 'true' of null"), + ("var u; u['k'] = 1", "TypeError: cannot set property 'k' of undefined"), + ("null.x", "TypeError: cannot read property 'x' of null"), + ("var u; u.y = 1", "TypeError: cannot set a property of undefined"), + ("var u; u[{}] = 1", "TypeError: cannot set a property of undefined"), + ("null[new Array(300).join('a')]", "TypeError: cannot read a property of null"), + ] { + assert_eq!(fail(source).message, message, "{source}"); + } + truth("var k = {toString: function () { throw 1; }}; try { null[k]; false } catch (e) { e instanceof TypeError }"); +} + #[test] fn host_functions_receive_arguments_and_return_values() { let mut realm = Realm::new(); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 9d15012784..ff2a2567f3 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -659,8 +659,8 @@ const MESSAGE_DEPTH: usize = 5; /// Translate a status or error message for display (see the module docs). Unknown messages, and /// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as -/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”` or backticks, such as a -/// symbol's name), stay as they are. A part that starts with `{` or `[` is translated only +/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”`, `'…'` or backticks, such as a +/// symbol's or a script property's name), stay as they are. A part that starts with `{` or `[` is translated only /// when it is a whole message with an exact entry, such as `[x, y] (two numbers)`. pub fn message(lang: Lang, s: &str) -> String { message_at(lang, s, MESSAGE_DEPTH) @@ -671,7 +671,7 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::().ok()); let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); let Some(template) = forms.get(form) else { return s.to_string() }; - let quoted = |v: &str| [('"', '"'), ('“', '”'), ('`', '`')].iter().any(|(a, b)| s.contains(&format!("{a}{v}{b}"))); + let quoted = |v: &str| [('"', '"'), ('“', '”'), ('\'', '\''), ('`', '`')].iter().any(|(a, b)| s.contains(&format!("{a}{v}{b}"))); let nested = |v: &str| { if depth <= 1 || quoted(v) { v.to_string() diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 373eb0b79d..f52d80b83e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5516,6 +5516,44 @@ digits Malayalam Malaiàlam @msg $.evalFile requires a file path $.evalFile requereix un camí de fitxer @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: el temps d'espera ha de ser un nombre finit de mil·lisegons, 0 o més @msg $.evalFile: takes a file path and a timeout $.evalFile: rep un camí de fitxer i un temps d'espera +@msg assignment to a constant binding assignació a un enllaç constant +@msg invalid array length longitud de matriu no vàlida +@msg array literal too long el literal de matriu és massa llarg +@msg the value is not a function el valor no és una funció +@msg apply was called on a value that is not a function s'ha cridat apply sobre un valor que no és una funció +@msg the argument list is not an object la llista d'arguments no és un objecte +@msg too many arguments massa arguments +@msg the value is not a constructor el valor no és un constructor +@msg cannot convert the object to a primitive value no es pot convertir l'objecte en un valor primitiu +@msg cannot convert undefined or null to an object no es pot convertir undefined ni null en un objecte +@msg the right side of 'in' is not an object el costat dret de 'in' no és un objecte +@msg the right side of 'instanceof' is not a function el costat dret de 'instanceof' no és una funció +@msg the function's prototype is not an object el prototip de la funció no és un objecte +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} no està definit +@msg cannot read property '{key}' of {base} no es pot llegir la propietat '{key}' de {base} +@msg cannot set property '{key}' of {base} no es pot establir la propietat '{key}' de {base} +@msg cannot read a property of {base} no es pot llegir cap propietat de {base} +@msg cannot set a property of {base} no es pot establir cap propietat de {base} +@msg cannot define property '{key}': {why} no es pot definir la propietat '{key}': {why} +@msg cannot assign to property '{key}': {why} no es pot assignar a la propietat '{key}': {why} +@msg cannot delete property '{key}' no es pot suprimir la propietat '{key}' +@msg cannot declare function {name} no es pot declarar la funció {name} +@msg invalid assignment target destinació d'assignació no vàlida +@msg the array's length is read-only la longitud de la matriu és només de lectura +@msg the property cannot be redefined la propietat no es pot redefinir +@msg the object is not extensible l'objecte no és extensible +@msg the length cannot be redefined la longitud no es pot redefinir +@msg it is read-only és només de lectura +@msg an element cannot be deleted no es pot suprimir un element +@msg it has only a getter només té un getter +@msg the value is a primitive el valor és primitiu @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: línia {line}, columna {column} de {file}: {e} (llançat) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: línia {line}, columna {column}: {e} (llançat) @msg {name}: {e} (thrown) {name}: {e} (llançat) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7178be3143..f5de2f6ffe 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4625,6 +4625,44 @@ imageTrace Outline Obrys @msg $.evalFile requires a file path $.evalFile vyžaduje cestu k souboru @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: časový limit musí být konečný počet milisekund, 0 nebo více @msg $.evalFile: takes a file path and a timeout $.evalFile: přijímá cestu k souboru a časový limit +@msg assignment to a constant binding přiřazení do konstantní vazby +@msg invalid array length neplatná délka pole +@msg array literal too long literál pole je příliš dlouhý +@msg the value is not a function hodnota není funkce +@msg apply was called on a value that is not a function apply bylo voláno na hodnotě, která není funkcí +@msg the argument list is not an object seznam argumentů není objekt +@msg too many arguments příliš mnoho argumentů +@msg the value is not a constructor hodnota není konstruktor +@msg cannot convert the object to a primitive value objekt nelze převést na primitivní hodnotu +@msg cannot convert undefined or null to an object undefined ani null nelze převést na objekt +@msg the right side of 'in' is not an object pravá strana 'in' není objekt +@msg the right side of 'instanceof' is not a function pravá strana 'instanceof' není funkce +@msg the function's prototype is not an object prototyp funkce není objekt +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} není definováno +@msg cannot read property '{key}' of {base} nelze číst vlastnost '{key}' hodnoty {base} +@msg cannot set property '{key}' of {base} nelze nastavit vlastnost '{key}' hodnoty {base} +@msg cannot read a property of {base} nelze číst vlastnost hodnoty {base} +@msg cannot set a property of {base} nelze nastavit vlastnost hodnoty {base} +@msg cannot define property '{key}': {why} nelze definovat vlastnost '{key}': {why} +@msg cannot assign to property '{key}': {why} nelze přiřadit do vlastnosti '{key}': {why} +@msg cannot delete property '{key}' nelze odstranit vlastnost '{key}' +@msg cannot declare function {name} nelze deklarovat funkci {name} +@msg invalid assignment target neplatný cíl přiřazení +@msg the array's length is read-only délka pole je jen pro čtení +@msg the property cannot be redefined vlastnost nelze znovu definovat +@msg the object is not extensible objekt nelze rozšiřovat +@msg the length cannot be redefined délku nelze znovu definovat +@msg it is read-only je jen pro čtení +@msg an element cannot be deleted prvek nelze odstranit +@msg it has only a getter má pouze getter +@msg the value is a primitive hodnota je primitivní @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: řádek {line}, sloupec {column} v {file}: {e} (vyvolána výjimka) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: řádek {line}, sloupec {column}: {e} (vyvolána výjimka) @msg {name}: {e} (thrown) {name}: {e} (vyvolána výjimka) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 951f6f9c37..e08fd4203f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4238,6 +4238,31 @@ theme Appearance Erscheinungsbild @msg $.evalFile requires a file path $.evalFile erfordert einen Dateipfad @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: Die Zeitüberschreitung muss eine endliche Anzahl von Millisekunden sein, 0 oder mehr @msg $.evalFile: takes a file path and a timeout $.evalFile: nimmt einen Dateipfad und eine Zeitüberschreitung +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} ist nicht definiert +@msg cannot read property '{key}' of {base} die Eigenschaft '{key}' von {base} kann nicht gelesen werden +@msg cannot set property '{key}' of {base} die Eigenschaft '{key}' von {base} kann nicht gesetzt werden +@msg cannot read a property of {base} eine Eigenschaft von {base} kann nicht gelesen werden +@msg cannot set a property of {base} eine Eigenschaft von {base} kann nicht gesetzt werden +@msg cannot define property '{key}': {why} die Eigenschaft '{key}' kann nicht definiert werden: {why} +@msg cannot assign to property '{key}': {why} der Eigenschaft '{key}' kann nichts zugewiesen werden: {why} +@msg cannot delete property '{key}' die Eigenschaft '{key}' kann nicht gelöscht werden +@msg cannot declare function {name} die Funktion {name} kann nicht deklariert werden +@msg invalid assignment target ungültiges Zuweisungsziel +@msg the array's length is read-only die Länge des Arrays ist schreibgeschützt +@msg the property cannot be redefined die Eigenschaft kann nicht neu definiert werden +@msg the object is not extensible das Objekt ist nicht erweiterbar +@msg the length cannot be redefined die Länge kann nicht neu definiert werden +@msg it is read-only sie ist schreibgeschützt +@msg an element cannot be deleted ein Element kann nicht gelöscht werden +@msg it has only a getter sie hat nur einen Getter +@msg the value is a primitive der Wert ist ein primitiver Wert @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: Zeile {line}, Spalte {column} in {file}: {e} (ausgelöst) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: Zeile {line}, Spalte {column}: {e} (ausgelöst) @msg {name}: {e} (thrown) {name}: {e} (ausgelöst) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 62e3adc491..614e5b20d5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2385,6 +2385,44 @@ axis Both Και τα δύο @msg $.evalFile requires a file path Το $.evalFile απαιτεί διαδρομή αρχείου @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: το χρονικό όριο πρέπει να είναι πεπερασμένος αριθμός χιλιοστών του δευτερολέπτου, 0 ή περισσότερο @msg $.evalFile: takes a file path and a timeout $.evalFile: δέχεται μια διαδρομή αρχείου και ένα χρονικό όριο +@msg assignment to a constant binding ανάθεση σε σταθερή δέσμευση +@msg invalid array length μη έγκυρο μήκος πίνακα +@msg array literal too long η κυριολεκτική τιμή πίνακα είναι πολύ μεγάλη +@msg the value is not a function η τιμή δεν είναι συνάρτηση +@msg apply was called on a value that is not a function η apply κλήθηκε σε τιμή που δεν είναι συνάρτηση +@msg the argument list is not an object η λίστα ορισμάτων δεν είναι αντικείμενο +@msg too many arguments πάρα πολλά ορίσματα +@msg the value is not a constructor η τιμή δεν είναι κατασκευαστής +@msg cannot convert the object to a primitive value το αντικείμενο δεν μπορεί να μετατραπεί σε πρωτογενή τιμή +@msg cannot convert undefined or null to an object το undefined ή το null δεν μπορεί να μετατραπεί σε αντικείμενο +@msg the right side of 'in' is not an object η δεξιά πλευρά του 'in' δεν είναι αντικείμενο +@msg the right side of 'instanceof' is not a function η δεξιά πλευρά του 'instanceof' δεν είναι συνάρτηση +@msg the function's prototype is not an object το πρωτότυπο της συνάρτησης δεν είναι αντικείμενο +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined το {name} δεν έχει οριστεί +@msg cannot read property '{key}' of {base} δεν είναι δυνατή η ανάγνωση της ιδιότητας '{key}' του {base} +@msg cannot set property '{key}' of {base} δεν είναι δυνατός ο ορισμός της ιδιότητας '{key}' του {base} +@msg cannot read a property of {base} δεν είναι δυνατή η ανάγνωση ιδιότητας του {base} +@msg cannot set a property of {base} δεν είναι δυνατός ο ορισμός ιδιότητας του {base} +@msg cannot define property '{key}': {why} δεν είναι δυνατός ο καθορισμός της ιδιότητας '{key}': {why} +@msg cannot assign to property '{key}': {why} δεν είναι δυνατή η ανάθεση στην ιδιότητα '{key}': {why} +@msg cannot delete property '{key}' δεν είναι δυνατή η διαγραφή της ιδιότητας '{key}' +@msg cannot declare function {name} δεν είναι δυνατή η δήλωση της συνάρτησης {name} +@msg invalid assignment target μη έγκυρος στόχος ανάθεσης +@msg the array's length is read-only το μήκος του πίνακα είναι μόνο για ανάγνωση +@msg the property cannot be redefined η ιδιότητα δεν μπορεί να οριστεί ξανά +@msg the object is not extensible το αντικείμενο δεν είναι επεκτάσιμο +@msg the length cannot be redefined το μήκος δεν μπορεί να οριστεί ξανά +@msg it is read-only είναι μόνο για ανάγνωση +@msg an element cannot be deleted ένα στοιχείο δεν μπορεί να διαγραφεί +@msg it has only a getter έχει μόνο getter +@msg the value is a primitive η τιμή είναι πρωτογενής @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: γραμμή {line}, στήλη {column} στο {file}: {e} (εξαίρεση) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: γραμμή {line}, στήλη {column}: {e} (εξαίρεση) @msg {name}: {e} (thrown) {name}: {e} (εξαίρεση) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d1c6aa53af..50a6e23da4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4315,6 +4315,44 @@ axis Both Ambos @msg $.evalFile requires a file path $.evalFile requiere una ruta de archivo @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: el tiempo de espera debe ser un número finito de milisegundos, 0 o más @msg $.evalFile: takes a file path and a timeout $.evalFile: recibe una ruta de archivo y un tiempo de espera +@msg assignment to a constant binding asignación a un enlace constante +@msg invalid array length longitud de array no válida +@msg array literal too long el literal de array es demasiado largo +@msg the value is not a function el valor no es una función +@msg apply was called on a value that is not a function se llamó a apply sobre un valor que no es una función +@msg the argument list is not an object la lista de argumentos no es un objeto +@msg too many arguments demasiados argumentos +@msg the value is not a constructor el valor no es un constructor +@msg cannot convert the object to a primitive value no se puede convertir el objeto en un valor primitivo +@msg cannot convert undefined or null to an object no se puede convertir undefined ni null en un objeto +@msg the right side of 'in' is not an object el lado derecho de 'in' no es un objeto +@msg the right side of 'instanceof' is not a function el lado derecho de 'instanceof' no es una función +@msg the function's prototype is not an object el prototipo de la función no es un objeto +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} no está definido +@msg cannot read property '{key}' of {base} no se puede leer la propiedad '{key}' de {base} +@msg cannot set property '{key}' of {base} no se puede establecer la propiedad '{key}' de {base} +@msg cannot read a property of {base} no se puede leer una propiedad de {base} +@msg cannot set a property of {base} no se puede establecer una propiedad de {base} +@msg cannot define property '{key}': {why} no se puede definir la propiedad '{key}': {why} +@msg cannot assign to property '{key}': {why} no se puede asignar a la propiedad '{key}': {why} +@msg cannot delete property '{key}' no se puede eliminar la propiedad '{key}' +@msg cannot declare function {name} no se puede declarar la función {name} +@msg invalid assignment target destino de asignación no válido +@msg the array's length is read-only la longitud del array es de solo lectura +@msg the property cannot be redefined la propiedad no se puede redefinir +@msg the object is not extensible el objeto no es extensible +@msg the length cannot be redefined la longitud no se puede redefinir +@msg it is read-only es de solo lectura +@msg an element cannot be deleted no se puede eliminar un elemento +@msg it has only a getter solo tiene un getter +@msg the value is a primitive el valor es primitivo @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: línea {line}, columna {column} de {file}: {e} (lanzado) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: línea {line}, columna {column}: {e} (lanzado) @msg {name}: {e} (thrown) {name}: {e} (lanzado) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 45e47fd355..53a62bd095 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4539,6 +4539,44 @@ imageTrace Outline Ääriviiva @msg $.evalFile requires a file path $.evalFile vaatii tiedostopolun @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: aikakatkaisun on oltava äärellinen määrä millisekunteja, 0 tai enemmän @msg $.evalFile: takes a file path and a timeout $.evalFile: ottaa tiedostopolun ja aikakatkaisun +@msg assignment to a constant binding sijoitus vakiosidontaan +@msg invalid array length virheellinen taulukon pituus +@msg array literal too long taulukkoliteraali on liian pitkä +@msg the value is not a function arvo ei ole funktio +@msg apply was called on a value that is not a function apply kutsuttiin arvolle, joka ei ole funktio +@msg the argument list is not an object argumenttiluettelo ei ole objekti +@msg too many arguments liikaa argumentteja +@msg the value is not a constructor arvo ei ole konstruktori +@msg cannot convert the object to a primitive value objektia ei voi muuntaa primitiiviarvoksi +@msg cannot convert undefined or null to an object arvoja undefined tai null ei voi muuntaa objektiksi +@msg the right side of 'in' is not an object operaattorin 'in' oikea puoli ei ole objekti +@msg the right side of 'instanceof' is not a function operaattorin 'instanceof' oikea puoli ei ole funktio +@msg the function's prototype is not an object funktion prototyyppi ei ole objekti +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} ei ole määritelty +@msg cannot read property '{key}' of {base} arvon {base} ominaisuutta '{key}' ei voi lukea +@msg cannot set property '{key}' of {base} arvon {base} ominaisuutta '{key}' ei voi asettaa +@msg cannot read a property of {base} arvon {base} ominaisuutta ei voi lukea +@msg cannot set a property of {base} arvon {base} ominaisuutta ei voi asettaa +@msg cannot define property '{key}': {why} ominaisuutta '{key}' ei voi määrittää: {why} +@msg cannot assign to property '{key}': {why} ominaisuuteen '{key}' ei voi sijoittaa: {why} +@msg cannot delete property '{key}' ominaisuutta '{key}' ei voi poistaa +@msg cannot declare function {name} funktiota {name} ei voi esitellä +@msg invalid assignment target virheellinen sijoituksen kohde +@msg the array's length is read-only taulukon pituus on vain luku +@msg the property cannot be redefined ominaisuutta ei voi määrittää uudelleen +@msg the object is not extensible objektia ei voi laajentaa +@msg the length cannot be redefined pituutta ei voi määrittää uudelleen +@msg it is read-only se on vain luku +@msg an element cannot be deleted alkiota ei voi poistaa +@msg it has only a getter sillä on vain getter +@msg the value is a primitive arvo on primitiivi @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, rivi {line}, sarake {column}: {e} (heitetty) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: rivi {line}, sarake {column}: {e} (heitetty) @msg {name}: {e} (thrown) {name}: {e} (heitetty) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 057dce6872..f123f2272c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4304,6 +4304,44 @@ axis Both Les deux @msg $.evalFile requires a file path $.evalFile nécessite un chemin de fichier @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile : le délai doit être un nombre fini de millisecondes, 0 ou plus @msg $.evalFile: takes a file path and a timeout $.evalFile : prend un chemin de fichier et un délai +@msg assignment to a constant binding affectation à une liaison constante +@msg invalid array length longueur de tableau non valide +@msg array literal too long littéral de tableau trop long +@msg the value is not a function la valeur n'est pas une fonction +@msg apply was called on a value that is not a function apply a été appelé sur une valeur qui n'est pas une fonction +@msg the argument list is not an object la liste d'arguments n'est pas un objet +@msg too many arguments trop d'arguments +@msg the value is not a constructor la valeur n'est pas un constructeur +@msg cannot convert the object to a primitive value impossible de convertir l'objet en valeur primitive +@msg cannot convert undefined or null to an object impossible de convertir undefined ou null en objet +@msg the right side of 'in' is not an object le côté droit de 'in' n'est pas un objet +@msg the right side of 'instanceof' is not a function le côté droit de 'instanceof' n'est pas une fonction +@msg the function's prototype is not an object le prototype de la fonction n'est pas un objet +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} n'est pas défini +@msg cannot read property '{key}' of {base} impossible de lire la propriété '{key}' de {base} +@msg cannot set property '{key}' of {base} impossible de modifier la propriété '{key}' de {base} +@msg cannot read a property of {base} impossible de lire une propriété de {base} +@msg cannot set a property of {base} impossible de modifier une propriété de {base} +@msg cannot define property '{key}': {why} impossible de définir la propriété '{key}' : {why} +@msg cannot assign to property '{key}': {why} impossible d'affecter la propriété '{key}' : {why} +@msg cannot delete property '{key}' impossible de supprimer la propriété '{key}' +@msg cannot declare function {name} impossible de déclarer la fonction {name} +@msg invalid assignment target cible d'affectation non valide +@msg the array's length is read-only la longueur du tableau est en lecture seule +@msg the property cannot be redefined la propriété ne peut pas être redéfinie +@msg the object is not extensible l'objet n'est pas extensible +@msg the length cannot be redefined la longueur ne peut pas être redéfinie +@msg it is read-only elle est en lecture seule +@msg an element cannot be deleted un élément ne peut pas être supprimé +@msg it has only a getter elle n'a qu'un getter +@msg the value is a primitive la valeur est une primitive @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name} : ligne {line}, colonne {column} de {file} : {e} (levée) @msg {name}: line {line}, column {column}: {e} (thrown) {name} : ligne {line}, colonne {column} : {e} (levée) @msg {name}: {e} (thrown) {name} : {e} (levée) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9d056e085a..690dc39d44 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6628,6 +6628,44 @@ antiAlias Sharp शार्प @msg $.evalFile requires a file path $.evalFile के लिए फ़ाइल पाथ आवश्यक है @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: टाइमआउट मिलीसेकंड की एक सीमित संख्या होनी चाहिए, 0 या अधिक @msg $.evalFile: takes a file path and a timeout $.evalFile: एक फ़ाइल पाथ और एक टाइमआउट लेता है +@msg assignment to a constant binding स्थिर बाइंडिंग को मान दिया गया +@msg invalid array length ऐरे की लंबाई अमान्य है +@msg array literal too long ऐरे लिटरल बहुत लंबा है +@msg the value is not a function मान कोई फ़ंक्शन नहीं है +@msg apply was called on a value that is not a function apply को ऐसे मान पर कॉल किया गया जो फ़ंक्शन नहीं है +@msg the argument list is not an object आर्गुमेंट सूची कोई ऑब्जेक्ट नहीं है +@msg too many arguments बहुत अधिक आर्गुमेंट +@msg the value is not a constructor मान कोई कंस्ट्रक्टर नहीं है +@msg cannot convert the object to a primitive value ऑब्जेक्ट को प्रिमिटिव मान में नहीं बदला जा सकता +@msg cannot convert undefined or null to an object undefined या null को ऑब्जेक्ट में नहीं बदला जा सकता +@msg the right side of 'in' is not an object 'in' का दायाँ पक्ष कोई ऑब्जेक्ट नहीं है +@msg the right side of 'instanceof' is not a function 'instanceof' का दायाँ पक्ष कोई फ़ंक्शन नहीं है +@msg the function's prototype is not an object फ़ंक्शन का प्रोटोटाइप कोई ऑब्जेक्ट नहीं है +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} परिभाषित नहीं है +@msg cannot read property '{key}' of {base} {base} की प्रॉपर्टी '{key}' पढ़ी नहीं जा सकती +@msg cannot set property '{key}' of {base} {base} की प्रॉपर्टी '{key}' सेट नहीं की जा सकती +@msg cannot read a property of {base} {base} की कोई प्रॉपर्टी पढ़ी नहीं जा सकती +@msg cannot set a property of {base} {base} की कोई प्रॉपर्टी सेट नहीं की जा सकती +@msg cannot define property '{key}': {why} प्रॉपर्टी '{key}' परिभाषित नहीं की जा सकती: {why} +@msg cannot assign to property '{key}': {why} प्रॉपर्टी '{key}' को मान नहीं दिया जा सकता: {why} +@msg cannot delete property '{key}' प्रॉपर्टी '{key}' हटाई नहीं जा सकती +@msg cannot declare function {name} फ़ंक्शन {name} घोषित नहीं किया जा सकता +@msg invalid assignment target मान देने का लक्ष्य अमान्य है +@msg the array's length is read-only ऐरे की लंबाई केवल-पठन है +@msg the property cannot be redefined प्रॉपर्टी को फिर से परिभाषित नहीं किया जा सकता +@msg the object is not extensible ऑब्जेक्ट विस्तार योग्य नहीं है +@msg the length cannot be redefined लंबाई को फिर से परिभाषित नहीं किया जा सकता +@msg it is read-only यह केवल-पठन है +@msg an element cannot be deleted कोई तत्व हटाया नहीं जा सकता +@msg it has only a getter इसमें केवल getter है +@msg the value is a primitive मान प्रिमिटिव है @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file} की लाइन {line}, कॉलम {column}: {e} (थ्रो किया गया) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: लाइन {line}, कॉलम {column}: {e} (थ्रो किया गया) @msg {name}: {e} (thrown) {name}: {e} (थ्रो किया गया) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c2f1a52cd9..c9acbb7e07 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5125,6 +5125,44 @@ imageTrace Outline Körvonal @msg $.evalFile requires a file path A $.evalFile fájlútvonalat igényel @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: az időkorlátnak véges számú ezredmásodpercnek kell lennie, 0 vagy több @msg $.evalFile: takes a file path and a timeout $.evalFile: egy fájlútvonalat és egy időkorlátot vár +@msg assignment to a constant binding értékadás konstans kötésnek +@msg invalid array length érvénytelen tömbhossz +@msg array literal too long a tömbliterál túl hosszú +@msg the value is not a function az érték nem függvény +@msg apply was called on a value that is not a function az apply olyan értéken lett meghívva, amely nem függvény +@msg the argument list is not an object az argumentumlista nem objektum +@msg too many arguments túl sok argumentum +@msg the value is not a constructor az érték nem konstruktor +@msg cannot convert the object to a primitive value az objektum nem alakítható primitív értékké +@msg cannot convert undefined or null to an object az undefined és a null nem alakítható objektummá +@msg the right side of 'in' is not an object az 'in' jobb oldala nem objektum +@msg the right side of 'instanceof' is not a function az 'instanceof' jobb oldala nem függvény +@msg the function's prototype is not an object a függvény prototípusa nem objektum +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} nincs definiálva +@msg cannot read property '{key}' of {base} a(z) {base} '{key}' tulajdonsága nem olvasható +@msg cannot set property '{key}' of {base} a(z) {base} '{key}' tulajdonsága nem állítható be +@msg cannot read a property of {base} a(z) {base} tulajdonsága nem olvasható +@msg cannot set a property of {base} a(z) {base} tulajdonsága nem állítható be +@msg cannot define property '{key}': {why} a(z) '{key}' tulajdonság nem definiálható: {why} +@msg cannot assign to property '{key}': {why} a(z) '{key}' tulajdonságnak nem adható érték: {why} +@msg cannot delete property '{key}' a(z) '{key}' tulajdonság nem törölhető +@msg cannot declare function {name} a(z) {name} függvény nem deklarálható +@msg invalid assignment target érvénytelen értékadási cél +@msg the array's length is read-only a tömb hossza csak olvasható +@msg the property cannot be redefined a tulajdonság nem definiálható újra +@msg the object is not extensible az objektum nem bővíthető +@msg the length cannot be redefined a hossz nem definiálható újra +@msg it is read-only csak olvasható +@msg an element cannot be deleted elem nem törölhető +@msg it has only a getter csak gettere van +@msg the value is a primitive az érték primitív @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, {line}. sor, {column}. oszlop: {e} (kivétel) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line}. sor, {column}. oszlop: {e} (kivétel) @msg {name}: {e} (thrown) {name}: {e} (kivétel) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0ac2816b07..577c384b0d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4367,6 +4367,31 @@ axis Both Entrambi @msg $.evalFile requires a file path $.evalFile richiede un percorso di file @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: il timeout deve essere un numero finito di millisecondi, 0 o più @msg $.evalFile: takes a file path and a timeout $.evalFile: accetta un percorso di file e un timeout +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} non è definito +@msg cannot read property '{key}' of {base} impossibile leggere la proprietà '{key}' di {base} +@msg cannot set property '{key}' of {base} impossibile impostare la proprietà '{key}' di {base} +@msg cannot read a property of {base} impossibile leggere una proprietà di {base} +@msg cannot set a property of {base} impossibile impostare una proprietà di {base} +@msg cannot define property '{key}': {why} impossibile definire la proprietà '{key}': {why} +@msg cannot assign to property '{key}': {why} impossibile assegnare alla proprietà '{key}': {why} +@msg cannot delete property '{key}' impossibile eliminare la proprietà '{key}' +@msg cannot declare function {name} impossibile dichiarare la funzione {name} +@msg invalid assignment target destinazione di assegnazione non valida +@msg the array's length is read-only la lunghezza dell'array è di sola lettura +@msg the property cannot be redefined la proprietà non può essere ridefinita +@msg the object is not extensible l'oggetto non è estensibile +@msg the length cannot be redefined la lunghezza non può essere ridefinita +@msg it is read-only è di sola lettura +@msg an element cannot be deleted un elemento non può essere eliminato +@msg it has only a getter ha solo un getter +@msg the value is a primitive il valore è primitivo @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: riga {line}, colonna {column} di {file}: {e} (generato) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: riga {line}, colonna {column}: {e} (generato) @msg {name}: {e} (thrown) {name}: {e} (generato) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 71de1ce91c..196e4702fc 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5129,6 +5129,44 @@ swatch Bright Violet ビビッドバイオレット @msg $.evalFile requires a file path $.evalFile にはファイルパスが必要です @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: タイムアウトは 0 以上の有限のミリ秒数にしてください @msg $.evalFile: takes a file path and a timeout $.evalFile: ファイルパスとタイムアウトを指定します +@msg assignment to a constant binding 定数バインディングへの代入です +@msg invalid array length 配列の長さが無効です +@msg array literal too long 配列リテラルが長すぎます +@msg the value is not a function 値は関数ではありません +@msg apply was called on a value that is not a function 関数ではない値に対して apply が呼び出されました +@msg the argument list is not an object 引数リストはオブジェクトではありません +@msg too many arguments 引数が多すぎます +@msg the value is not a constructor 値はコンストラクターではありません +@msg cannot convert the object to a primitive value オブジェクトをプリミティブ値に変換できません +@msg cannot convert undefined or null to an object undefined または null をオブジェクトに変換できません +@msg the right side of 'in' is not an object 'in' の右辺がオブジェクトではありません +@msg the right side of 'instanceof' is not a function 'instanceof' の右辺が関数ではありません +@msg the function's prototype is not an object 関数のプロトタイプがオブジェクトではありません +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} は定義されていません +@msg cannot read property '{key}' of {base} {base} のプロパティ '{key}' を読み取れません +@msg cannot set property '{key}' of {base} {base} のプロパティ '{key}' を設定できません +@msg cannot read a property of {base} {base} のプロパティを読み取れません +@msg cannot set a property of {base} {base} のプロパティを設定できません +@msg cannot define property '{key}': {why} プロパティ '{key}' を定義できません: {why} +@msg cannot assign to property '{key}': {why} プロパティ '{key}' に代入できません: {why} +@msg cannot delete property '{key}' プロパティ '{key}' を削除できません +@msg cannot declare function {name} 関数 {name} を宣言できません +@msg invalid assignment target 代入先が無効です +@msg the array's length is read-only 配列の長さは読み取り専用です +@msg the property cannot be redefined プロパティは再定義できません +@msg the object is not extensible オブジェクトは拡張できません +@msg the length cannot be redefined 長さは再定義できません +@msg it is read-only 読み取り専用です +@msg an element cannot be deleted 要素は削除できません +@msg it has only a getter ゲッターしかありません +@msg the value is a primitive 値はプリミティブです @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file} の {line} 行目、{column} 列目: {e} (スロー) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line} 行目、{column} 列目: {e} (スロー) @msg {name}: {e} (thrown) {name}: {e} (スロー) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2cff51d94b..745086f227 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5535,6 +5535,44 @@ imageTrace Outline კონტური @msg $.evalFile requires a file path $.evalFile-ს სჭირდება ფაილის მისამართი @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: დროის ლიმიტი უნდა იყოს მილიწამების სასრული რიცხვი, 0 ან მეტი @msg $.evalFile: takes a file path and a timeout $.evalFile: იღებს ფაილის მისამართს და დროის ლიმიტს +@msg assignment to a constant binding მინიჭება მუდმივ ბმაზე +@msg invalid array length მასივის არასწორი სიგრძე +@msg array literal too long მასივის ლიტერალი ძალიან გრძელია +@msg the value is not a function მნიშვნელობა არ არის ფუნქცია +@msg apply was called on a value that is not a function apply გამოიძახეს მნიშვნელობაზე, რომელიც არ არის ფუნქცია +@msg the argument list is not an object არგუმენტების სია არ არის ობიექტი +@msg too many arguments ზედმეტად ბევრი არგუმენტი +@msg the value is not a constructor მნიშვნელობა არ არის კონსტრუქტორი +@msg cannot convert the object to a primitive value ობიექტი პრიმიტიულ მნიშვნელობად ვერ გარდაიქმნება +@msg cannot convert undefined or null to an object undefined ან null ობიექტად ვერ გარდაიქმნება +@msg the right side of 'in' is not an object 'in' ოპერატორის მარჯვენა მხარე არ არის ობიექტი +@msg the right side of 'instanceof' is not a function 'instanceof' ოპერატორის მარჯვენა მხარე არ არის ფუნქცია +@msg the function's prototype is not an object ფუნქციის პროტოტიპი არ არის ობიექტი +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} არ არის განსაზღვრული +@msg cannot read property '{key}' of {base} {base} მნიშვნელობის თვისება '{key}' ვერ წაიკითხება +@msg cannot set property '{key}' of {base} {base} მნიშვნელობის თვისება '{key}' ვერ დაყენდება +@msg cannot read a property of {base} {base} მნიშვნელობის თვისება ვერ წაიკითხება +@msg cannot set a property of {base} {base} მნიშვნელობის თვისება ვერ დაყენდება +@msg cannot define property '{key}': {why} თვისება '{key}' ვერ განისაზღვრება: {why} +@msg cannot assign to property '{key}': {why} თვისებას '{key}' მნიშვნელობა ვერ მიენიჭება: {why} +@msg cannot delete property '{key}' თვისება '{key}' ვერ წაიშლება +@msg cannot declare function {name} ფუნქცია {name} ვერ გამოცხადდება +@msg invalid assignment target მინიჭების არასწორი სამიზნე +@msg the array's length is read-only მასივის სიგრძე მხოლოდ წასაკითხია +@msg the property cannot be redefined თვისება ხელახლა ვერ განისაზღვრება +@msg the object is not extensible ობიექტი არ არის გაფართოებადი +@msg the length cannot be redefined სიგრძე ხელახლა ვერ განისაზღვრება +@msg it is read-only ის მხოლოდ წასაკითხია +@msg an element cannot be deleted ელემენტი ვერ წაიშლება +@msg it has only a getter მას მხოლოდ getter აქვს +@msg the value is a primitive მნიშვნელობა პრიმიტიულია @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, სტრიქონი {line}, სვეტი {column}: {e} (გამონაკლისი) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: სტრიქონი {line}, სვეტი {column}: {e} (გამონაკლისი) @msg {name}: {e} (thrown) {name}: {e} (გამონაკლისი) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 4715a413f4..5385d46a09 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5056,6 +5056,44 @@ theme Appearance 외관 @msg $.evalFile requires a file path $.evalFile에는 파일 경로가 필요합니다 @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: 시간 제한은 0 이상의 유한한 밀리초 수여야 합니다 @msg $.evalFile: takes a file path and a timeout $.evalFile: 파일 경로와 시간 제한을 받습니다 +@msg assignment to a constant binding 상수 바인딩에 대입했습니다 +@msg invalid array length 배열 길이가 잘못되었습니다 +@msg array literal too long 배열 리터럴이 너무 깁니다 +@msg the value is not a function 값이 함수가 아닙니다 +@msg apply was called on a value that is not a function 함수가 아닌 값에 apply가 호출되었습니다 +@msg the argument list is not an object 인수 목록이 객체가 아닙니다 +@msg too many arguments 인수가 너무 많습니다 +@msg the value is not a constructor 값이 생성자가 아닙니다 +@msg cannot convert the object to a primitive value 객체를 원시 값으로 변환할 수 없습니다 +@msg cannot convert undefined or null to an object undefined 또는 null을 객체로 변환할 수 없습니다 +@msg the right side of 'in' is not an object 'in'의 오른쪽이 객체가 아닙니다 +@msg the right side of 'instanceof' is not a function 'instanceof'의 오른쪽이 함수가 아닙니다 +@msg the function's prototype is not an object 함수의 프로토타입이 객체가 아닙니다 +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name}이(가) 정의되지 않았습니다 +@msg cannot read property '{key}' of {base} {base}의 속성 '{key}'을(를) 읽을 수 없습니다 +@msg cannot set property '{key}' of {base} {base}의 속성 '{key}'을(를) 설정할 수 없습니다 +@msg cannot read a property of {base} {base}의 속성을 읽을 수 없습니다 +@msg cannot set a property of {base} {base}의 속성을 설정할 수 없습니다 +@msg cannot define property '{key}': {why} 속성 '{key}'을(를) 정의할 수 없습니다: {why} +@msg cannot assign to property '{key}': {why} 속성 '{key}'에 대입할 수 없습니다: {why} +@msg cannot delete property '{key}' 속성 '{key}'을(를) 삭제할 수 없습니다 +@msg cannot declare function {name} 함수 {name}을(를) 선언할 수 없습니다 +@msg invalid assignment target 대입 대상이 잘못되었습니다 +@msg the array's length is read-only 배열의 길이는 읽기 전용입니다 +@msg the property cannot be redefined 속성을 다시 정의할 수 없습니다 +@msg the object is not extensible 객체를 확장할 수 없습니다 +@msg the length cannot be redefined 길이를 다시 정의할 수 없습니다 +@msg it is read-only 읽기 전용입니다 +@msg an element cannot be deleted 요소를 삭제할 수 없습니다 +@msg it has only a getter getter만 있습니다 +@msg the value is a primitive 값이 원시 값입니다 @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}의 {line}행 {column}열: {e} (발생) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: {line}행 {column}열: {e} (발생) @msg {name}: {e} (thrown) {name}: {e} (발생) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 94957fb782..779fa5ba78 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -91,6 +91,44 @@ @msg $.evalFile requires a file path $.evalFile vereist een bestandspad @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: de time-out moet een eindig aantal milliseconden zijn, 0 of meer @msg $.evalFile: takes a file path and a timeout $.evalFile: verwacht een bestandspad en een time-out +@msg assignment to a constant binding toewijzing aan een constante binding +@msg invalid array length ongeldige arraylengte +@msg array literal too long de arrayliteral is te lang +@msg the value is not a function de waarde is geen functie +@msg apply was called on a value that is not a function apply is aangeroepen op een waarde die geen functie is +@msg the argument list is not an object de argumentenlijst is geen object +@msg too many arguments te veel argumenten +@msg the value is not a constructor de waarde is geen constructor +@msg cannot convert the object to a primitive value het object kan niet worden omgezet in een primitieve waarde +@msg cannot convert undefined or null to an object undefined of null kan niet worden omgezet in een object +@msg the right side of 'in' is not an object de rechterkant van 'in' is geen object +@msg the right side of 'instanceof' is not a function de rechterkant van 'instanceof' is geen functie +@msg the function's prototype is not an object het prototype van de functie is geen object +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} is niet gedefinieerd +@msg cannot read property '{key}' of {base} kan eigenschap '{key}' van {base} niet lezen +@msg cannot set property '{key}' of {base} kan eigenschap '{key}' van {base} niet instellen +@msg cannot read a property of {base} kan geen eigenschap van {base} lezen +@msg cannot set a property of {base} kan geen eigenschap van {base} instellen +@msg cannot define property '{key}': {why} kan eigenschap '{key}' niet definiëren: {why} +@msg cannot assign to property '{key}': {why} kan niet toewijzen aan eigenschap '{key}': {why} +@msg cannot delete property '{key}' kan eigenschap '{key}' niet verwijderen +@msg cannot declare function {name} kan functie {name} niet declareren +@msg invalid assignment target ongeldig toewijzingsdoel +@msg the array's length is read-only de lengte van de array is alleen-lezen +@msg the property cannot be redefined de eigenschap kan niet opnieuw worden gedefinieerd +@msg the object is not extensible het object is niet uitbreidbaar +@msg the length cannot be redefined de lengte kan niet opnieuw worden gedefinieerd +@msg it is read-only deze is alleen-lezen +@msg an element cannot be deleted een element kan niet worden verwijderd +@msg it has only a getter deze heeft alleen een getter +@msg the value is a primitive de waarde is primitief @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: regel {line}, kolom {column} van {file}: {e} (opgeworpen) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: regel {line}, kolom {column}: {e} (opgeworpen) @msg {name}: {e} (thrown) {name}: {e} (opgeworpen) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 48f2671c2d..aa9da22678 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4449,6 +4449,31 @@ imageTrace Outline Kontur @msg $.evalFile requires a file path $.evalFile wymaga ścieżki pliku @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: limit czasu musi być skończoną liczbą milisekund, 0 lub więcej @msg $.evalFile: takes a file path and a timeout $.evalFile: przyjmuje ścieżkę pliku i limit czasu +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} nie jest zdefiniowane +@msg cannot read property '{key}' of {base} nie można odczytać właściwości '{key}' wartości {base} +@msg cannot set property '{key}' of {base} nie można ustawić właściwości '{key}' wartości {base} +@msg cannot read a property of {base} nie można odczytać właściwości wartości {base} +@msg cannot set a property of {base} nie można ustawić właściwości wartości {base} +@msg cannot define property '{key}': {why} nie można zdefiniować właściwości '{key}': {why} +@msg cannot assign to property '{key}': {why} nie można przypisać do właściwości '{key}': {why} +@msg cannot delete property '{key}' nie można usunąć właściwości '{key}' +@msg cannot declare function {name} nie można zadeklarować funkcji {name} +@msg invalid assignment target nieprawidłowy cel przypisania +@msg the array's length is read-only długość tablicy jest tylko do odczytu +@msg the property cannot be redefined właściwości nie można zdefiniować ponownie +@msg the object is not extensible obiektu nie można rozszerzać +@msg the length cannot be redefined długości nie można zdefiniować ponownie +@msg it is read-only jest tylko do odczytu +@msg an element cannot be deleted elementu nie można usunąć +@msg it has only a getter ma tylko getter +@msg the value is a primitive wartość jest prymitywna @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: wiersz {line}, kolumna {column} w {file}: {e} (zgłoszony wyjątek) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: wiersz {line}, kolumna {column}: {e} (zgłoszony wyjątek) @msg {name}: {e} (thrown) {name}: {e} (zgłoszony wyjątek) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index f6e54552d4..53e35bdd04 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5344,6 +5344,31 @@ axis Both Ambos @msg $.evalFile requires a file path $.evalFile requer um caminho de arquivo @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: o tempo limite deve ser um número finito de milissegundos, 0 ou mais @msg $.evalFile: takes a file path and a timeout $.evalFile: recebe um caminho de arquivo e um tempo limite +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} não está definido +@msg cannot read property '{key}' of {base} não é possível ler a propriedade '{key}' de {base} +@msg cannot set property '{key}' of {base} não é possível gravar a propriedade '{key}' de {base} +@msg cannot read a property of {base} não é possível ler uma propriedade de {base} +@msg cannot set a property of {base} não é possível gravar uma propriedade de {base} +@msg cannot define property '{key}': {why} não é possível definir a propriedade '{key}': {why} +@msg cannot assign to property '{key}': {why} não é possível atribuir à propriedade '{key}': {why} +@msg cannot delete property '{key}' não é possível excluir a propriedade '{key}' +@msg cannot declare function {name} não é possível declarar a função {name} +@msg invalid assignment target destino de atribuição inválido +@msg the array's length is read-only o comprimento do array é somente leitura +@msg the property cannot be redefined a propriedade não pode ser redefinida +@msg the object is not extensible o objeto não é extensível +@msg the length cannot be redefined o comprimento não pode ser redefinido +@msg it is read-only ela é somente leitura +@msg an element cannot be deleted um elemento não pode ser excluído +@msg it has only a getter ela tem apenas um getter +@msg the value is a primitive o valor é primitivo @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: linha {line}, coluna {column} de {file}: {e} (lançado) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: linha {line}, coluna {column}: {e} (lançado) @msg {name}: {e} (thrown) {name}: {e} (lançado) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 8dc8336089..4ae67ba4e7 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4352,6 +4352,44 @@ axis Both Оба @msg $.evalFile requires a file path $.evalFile требует путь к файлу @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: тайм-аут должен быть конечным числом миллисекунд, 0 или больше @msg $.evalFile: takes a file path and a timeout $.evalFile: принимает путь к файлу и тайм-аут +@msg assignment to a constant binding присваивание константной привязке +@msg invalid array length недопустимая длина массива +@msg array literal too long литерал массива слишком длинный +@msg the value is not a function значение не является функцией +@msg apply was called on a value that is not a function apply вызван для значения, которое не является функцией +@msg the argument list is not an object список аргументов не является объектом +@msg too many arguments слишком много аргументов +@msg the value is not a constructor значение не является конструктором +@msg cannot convert the object to a primitive value невозможно преобразовать объект в примитивное значение +@msg cannot convert undefined or null to an object невозможно преобразовать undefined или null в объект +@msg the right side of 'in' is not an object правая часть 'in' не является объектом +@msg the right side of 'instanceof' is not a function правая часть 'instanceof' не является функцией +@msg the function's prototype is not an object прототип функции не является объектом +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} не определено +@msg cannot read property '{key}' of {base} невозможно прочитать свойство '{key}' у {base} +@msg cannot set property '{key}' of {base} невозможно задать свойство '{key}' у {base} +@msg cannot read a property of {base} невозможно прочитать свойство у {base} +@msg cannot set a property of {base} невозможно задать свойство у {base} +@msg cannot define property '{key}': {why} невозможно определить свойство '{key}': {why} +@msg cannot assign to property '{key}': {why} невозможно присвоить значение свойству '{key}': {why} +@msg cannot delete property '{key}' невозможно удалить свойство '{key}' +@msg cannot declare function {name} невозможно объявить функцию {name} +@msg invalid assignment target недопустимая цель присваивания +@msg the array's length is read-only длина массива доступна только для чтения +@msg the property cannot be redefined свойство нельзя переопределить +@msg the object is not extensible объект нерасширяем +@msg the length cannot be redefined длину нельзя переопределить +@msg it is read-only оно доступно только для чтения +@msg an element cannot be deleted элемент нельзя удалить +@msg it has only a getter у него есть только геттер +@msg the value is a primitive значение примитивное @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: строка {line}, столбец {column} в {file}: {e} (исключение) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: строка {line}, столбец {column}: {e} (исключение) @msg {name}: {e} (thrown) {name}: {e} (исключение) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cfb9d9734b..ad906f98d4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4225,6 +4225,44 @@ axis Both Båda @msg $.evalFile requires a file path $.evalFile kräver en filsökväg @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: tidsgränsen måste vara ett ändligt antal millisekunder, 0 eller mer @msg $.evalFile: takes a file path and a timeout $.evalFile: tar en filsökväg och en tidsgräns +@msg assignment to a constant binding tilldelning till en konstant bindning +@msg invalid array length ogiltig arraylängd +@msg array literal too long arrayliteralen är för lång +@msg the value is not a function värdet är inte en funktion +@msg apply was called on a value that is not a function apply anropades på ett värde som inte är en funktion +@msg the argument list is not an object argumentlistan är inte ett objekt +@msg too many arguments för många argument +@msg the value is not a constructor värdet är inte en konstruktor +@msg cannot convert the object to a primitive value objektet kan inte konverteras till ett primitivt värde +@msg cannot convert undefined or null to an object undefined eller null kan inte konverteras till ett objekt +@msg the right side of 'in' is not an object högersidan av 'in' är inte ett objekt +@msg the right side of 'instanceof' is not a function högersidan av 'instanceof' är inte en funktion +@msg the function's prototype is not an object funktionens prototyp är inte ett objekt +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} är inte definierat +@msg cannot read property '{key}' of {base} det går inte att läsa egenskapen '{key}' för {base} +@msg cannot set property '{key}' of {base} det går inte att sätta egenskapen '{key}' för {base} +@msg cannot read a property of {base} det går inte att läsa en egenskap för {base} +@msg cannot set a property of {base} det går inte att sätta en egenskap för {base} +@msg cannot define property '{key}': {why} det går inte att definiera egenskapen '{key}': {why} +@msg cannot assign to property '{key}': {why} det går inte att tilldela egenskapen '{key}': {why} +@msg cannot delete property '{key}' det går inte att ta bort egenskapen '{key}' +@msg cannot declare function {name} det går inte att deklarera funktionen {name} +@msg invalid assignment target ogiltigt tilldelningsmål +@msg the array's length is read-only arrayens längd är skrivskyddad +@msg the property cannot be redefined egenskapen kan inte definieras om +@msg the object is not extensible objektet kan inte utökas +@msg the length cannot be redefined längden kan inte definieras om +@msg it is read-only den är skrivskyddad +@msg an element cannot be deleted ett element kan inte tas bort +@msg it has only a getter den har bara en getter +@msg the value is a primitive värdet är primitivt @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: rad {line}, kolumn {column} i {file}: {e} (kastat) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: rad {line}, kolumn {column}: {e} (kastat) @msg {name}: {e} (thrown) {name}: {e} (kastat) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 705fc68db2..39aaf43202 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2763,12 +2763,23 @@ fn f(i: &mut Interp, interp: &mut Interp) -> JsResult { let _ = self.error("the path has an empty step"); let _ = self.throw_host(t, "not an error: a longer name"); let _ = throw_type_error(interp, "not an error: a function"); + let _ = self.reject_bool(throw, &k, "the object is not extensible"); + let _ = self.reject(throw, &key("length"), "it is read-only"); Ok(Value::Undefined) } "#; let js: Vec<_> = ERROR_HELPERS.iter().filter(|(c, _, _)| *c == "js").map(|&(_, call, before)| (call, before)).collect(); let found = source_messages(code, &js, &Default::default()); - assert_eq!(found, ["{what}: the object is not a File or a Folder", "File.seek: the mode must be 0, 1 or 2", "the path has an empty step"]); + assert_eq!( + found, + [ + "{what}: the object is not a File or a Folder", + "File.seek: the mode must be 0, 1 or 2", + "the path has an empty step", + "the object is not extensible", + "it is read-only" + ] + ); } /// The scan reads the message a `.map_err` closure returns, a literal, a `format!` string or a @@ -3169,6 +3180,119 @@ fn script_host_errors_are_translated() { } } +/// The errors the script interpreter's core throws at a script (an unknown name, a property of +/// `null` or `undefined`, a property that cannot be defined, assigned or deleted and why, a value +/// that is not a function or a constructor) are translated in every language of +/// [`COMPLETE_MESSAGES`], on their own and in the status bar's line for a run that ends with one. +/// Names, property names, `null`, `undefined` and the operators `in` and `instanceof` stay as they +/// are, and a script that catches one reads its English message. +#[test] +fn script_interpreter_core_errors_are_translated() { + use serde_json::json; + let scanned = message_literals(); + let templates = [ + "assignment to a constant binding", + "invalid array length", + "array literal too long", + "the value is not a function", + "apply was called on a value that is not a function", + "the argument list is not an object", + "too many arguments", + "the value is not a constructor", + "cannot convert the object to a primitive value", + "cannot convert undefined or null to an object", + "the right side of 'in' is not an object", + "the right side of 'instanceof' is not a function", + "the function's prototype is not an object", + "{name} is not defined", + "cannot read property '{key}' of {base}", + "cannot set property '{key}' of {base}", + "cannot read a property of {base}", + "cannot set a property of {base}", + "cannot define property '{key}': {why}", + "cannot assign to property '{key}': {why}", + "cannot delete property '{key}'", + "cannot declare function {name}", + "the array's length is read-only", + "the property cannot be redefined", + "the object is not extensible", + "the length cannot be redefined", + "it is read-only", + "an element cannot be deleted", + "it has only a getter", + "the value is a primitive", + ]; + for template in templates { + assert!(scanned.contains(template), "{template}"); + } + // The compiler gives this one to the interpreter as the text of the error it throws. + let compiler = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../js/src/compiler.rs"); + assert!(std::fs::read_to_string(compiler).unwrap_or_default().contains("\"invalid assignment target\"")); + let mut s = vectorcraft_engine::Session::new(); + let mut lines: Vec<(String, String, Vec<&str>)> = vec![]; + for (source, inner, kept) in [ + ("nope", "nope is not defined", vec!["nope"]), + ("null.x", "cannot read property 'x' of null", vec!["'x'", "null"]), + ("var u; u['y'] = 1", "cannot set property 'y' of undefined", vec!["'y'", "undefined"]), + ("var u; u.y = 1", "cannot set a property of undefined", vec!["undefined"]), + ("null[new Array(300).join('a')]", "cannot read a property of null", vec!["null"]), + ("null['invalid array length']", "cannot read property 'invalid array length' of null", vec!["'invalid array length'", "null"]), + ( + "'use strict'; var o = {}; Object.defineProperty(o, 'a', {value: 1}); o.a = 2", + "cannot assign to property 'a': it is read-only", + vec!["'a'"], + ), + ( + "'use strict'; var o = {}; Object.defineProperty(o, 'g', {get: function () { return 1; }}); o.g = 2", + "cannot assign to property 'g': it has only a getter", + vec!["'g'"], + ), + ("'use strict'; var o = Object.preventExtensions({}); o.b = 1", "cannot assign to property 'b': the object is not extensible", vec!["'b'"]), + ( + "Object.defineProperty(Object.preventExtensions({}), 'c', {value: 1})", + "cannot define property 'c': the object is not extensible", + vec!["'c'"], + ), + ( + "var o = {}; Object.defineProperty(o, 'd', {value: 1}); Object.defineProperty(o, 'd', {value: 2})", + "cannot define property 'd': the property cannot be redefined", + vec!["'d'"], + ), + ("'use strict'; delete Object.prototype", "cannot delete property 'prototype'", vec!["'prototype'"]), + ("'use strict'; 'abc'.x = 1", "cannot assign to property 'x': the value is a primitive", vec!["'x'"]), + ("(function f() { 'use strict'; f = 1; })()", "assignment to a constant binding", vec![]), + ("new Array(-1)", "invalid array length", vec![]), + ("var n = 1; n()", "the value is not a function", vec![]), + ("new 1", "the value is not a constructor", vec![]), + ("'a' in 1", "the right side of 'in' is not an object", vec!["'in'"]), + ("1 instanceof 1", "the right side of 'instanceof' is not a function", vec!["'instanceof'"]), + ("function f() {} for (f() in {a: 1}) {}", "invalid assignment target", vec![]), + ] { + let e = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_err().to_string(); + assert!(e.starts_with("t.js: ") && e.contains(&format!("Error: {inner} (")), "{source}: {e}"); + lines.push((e, inner.to_string(), kept)); + } + // A script that catches one of these errors reads it in English, whatever the interface's language. + let caught = "try { nope; } catch (e) { if (e.message !== 'nope is not defined') throw new Error(e.message); }"; + assert!(s.execute("script.run", &json!({"source": caught, "name": "t.js"})).is_ok()); + let reasons = &templates[22..]; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for m in templates[..13].iter().chain(reasons).chain(["invalid assignment target"].iter()) { + assert_ne!(message(lang, m), *m, "{code}"); + } + for (line, inner, kept) in &lines { + let shown = message(lang, inner); + assert_ne!(shown, *inner, "{code}"); + assert!(kept.iter().all(|k| shown.contains(k)), "{code}: {inner} -> {shown}"); + assert!(reasons.iter().all(|r| !inner.ends_with(r) || shown.ends_with(&message(lang, r))), "{code}: {inner} -> {shown}"); + let whole = message(lang, line); + let kinds = ["(thrown)", "(limit)", "(syntax)", "(stopped)", "(internal)"]; + assert!(whole.starts_with("t.js") && whole.contains(&shown) && kinds.iter().all(|k| !whole.contains(k)), "{code}: {line} -> {whole}"); + } + } +} + /// A manifest whose `commands` value has the wrong shape is refused with an error that every /// language of [`COMPLETE_MESSAGES`] translates whole, the command's name and the place in the /// manifest included. @@ -4058,8 +4182,9 @@ const MESSAGE_MARKERS: &[&str] = &[".status(", "ui.status = ", "status = ", "Oth /// value), `out_err(at, msg)` (plug-in output), `in_range(x, lo, hi, at, what)` and /// `unit(x, at, what)` (a painted effect's numbers) and `.read_packed(packed, what, max)` (the block /// a plug-in returned), and the script interpreter's methods that throw an error at a script: -/// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`. A helper that -/// starts with `.` is a method of any receiver. +/// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`, with the reasons +/// it gives for a property it cannot define or assign (`.reject_bool(throw, key, why)` and +/// `.reject(throw, key, why)`). A helper that starts with `.` is a method of any receiver. const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("engine", "bad(", 1), ("engine", "err(", 0), @@ -4078,6 +4203,8 @@ const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("js", ".type_error(", 0), ("js", ".throw(", 1), ("js", ".error(", 0), + ("js", ".reject_bool(", 2), + ("js", ".reject(", 2), ]; /// Error variants whose first argument is a name, not a message: a command id diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2b3e843ba3..47c729cc86 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4080,6 +4080,44 @@ axis Both Her İkisi @msg $.evalFile requires a file path $.evalFile bir dosya yolu gerektirir @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: zaman aşımı sonlu bir milisaniye sayısı olmalıdır, 0 veya daha fazla @msg $.evalFile: takes a file path and a timeout $.evalFile: bir dosya yolu ve bir zaman aşımı alır +@msg assignment to a constant binding sabit bir bağlamaya atama +@msg invalid array length geçersiz dizi uzunluğu +@msg array literal too long dizi değişmezi çok uzun +@msg the value is not a function değer bir fonksiyon değil +@msg apply was called on a value that is not a function apply, fonksiyon olmayan bir değer üzerinde çağrıldı +@msg the argument list is not an object argüman listesi bir nesne değil +@msg too many arguments çok fazla argüman +@msg the value is not a constructor değer bir yapıcı değil +@msg cannot convert the object to a primitive value nesne ilkel bir değere dönüştürülemiyor +@msg cannot convert undefined or null to an object undefined veya null bir nesneye dönüştürülemiyor +@msg the right side of 'in' is not an object 'in' işlecinin sağ tarafı bir nesne değil +@msg the right side of 'instanceof' is not a function 'instanceof' işlecinin sağ tarafı bir fonksiyon değil +@msg the function's prototype is not an object fonksiyonun prototipi bir nesne değil +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} tanımlı değil +@msg cannot read property '{key}' of {base} {base} değerinin '{key}' özelliği okunamıyor +@msg cannot set property '{key}' of {base} {base} değerinin '{key}' özelliği ayarlanamıyor +@msg cannot read a property of {base} {base} değerinin bir özelliği okunamıyor +@msg cannot set a property of {base} {base} değerinin bir özelliği ayarlanamıyor +@msg cannot define property '{key}': {why} '{key}' özelliği tanımlanamıyor: {why} +@msg cannot assign to property '{key}': {why} '{key}' özelliğine atama yapılamıyor: {why} +@msg cannot delete property '{key}' '{key}' özelliği silinemiyor +@msg cannot declare function {name} {name} fonksiyonu bildirilemiyor +@msg invalid assignment target geçersiz atama hedefi +@msg the array's length is read-only dizinin uzunluğu salt okunur +@msg the property cannot be redefined özellik yeniden tanımlanamaz +@msg the object is not extensible nesne genişletilemez +@msg the length cannot be redefined uzunluk yeniden tanımlanamaz +@msg it is read-only salt okunur +@msg an element cannot be deleted bir öğe silinemez +@msg it has only a getter yalnızca getter'ı var +@msg the value is a primitive değer ilkel @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: {file}, satır {line}, sütun {column}: {e} (fırlatıldı) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: satır {line}, sütun {column}: {e} (fırlatıldı) @msg {name}: {e} (thrown) {name}: {e} (fırlatıldı) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 50690fa0c7..5d8ab2c718 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4351,6 +4351,31 @@ axis Both Обидві @msg $.evalFile requires a file path $.evalFile потребує шляху до файлу @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: тайм-аут має бути скінченним числом мілісекунд, 0 або більше @msg $.evalFile: takes a file path and a timeout $.evalFile: приймає шлях до файлу і тайм-аут +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} не визначено +@msg cannot read property '{key}' of {base} неможливо прочитати властивість '{key}' у {base} +@msg cannot set property '{key}' of {base} неможливо встановити властивість '{key}' у {base} +@msg cannot read a property of {base} неможливо прочитати властивість у {base} +@msg cannot set a property of {base} неможливо встановити властивість у {base} +@msg cannot define property '{key}': {why} неможливо визначити властивість '{key}': {why} +@msg cannot assign to property '{key}': {why} неможливо присвоїти значення властивості '{key}': {why} +@msg cannot delete property '{key}' неможливо видалити властивість '{key}' +@msg cannot declare function {name} неможливо оголосити функцію {name} +@msg invalid assignment target недійсна ціль присвоєння +@msg the array's length is read-only довжина масиву доступна лише для читання +@msg the property cannot be redefined властивість не можна перевизначити +@msg the object is not extensible об'єкт не можна розширювати +@msg the length cannot be redefined довжину не можна перевизначити +@msg it is read-only вона доступна лише для читання +@msg an element cannot be deleted елемент не можна видалити +@msg it has only a getter вона має лише гетер +@msg the value is a primitive значення примітивне @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: рядок {line}, стовпець {column} у {file}: {e} (виняток) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: рядок {line}, стовпець {column}: {e} (виняток) @msg {name}: {e} (thrown) {name}: {e} (виняток) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d8469bce53..890ef47e4e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4779,6 +4779,44 @@ theme Appearance Giao diện @msg $.evalFile requires a file path $.evalFile cần đường dẫn tệp @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: thời gian chờ phải là một số mili giây hữu hạn, từ 0 trở lên @msg $.evalFile: takes a file path and a timeout $.evalFile: nhận một đường dẫn tệp và một thời gian chờ +@msg assignment to a constant binding gán cho một ràng buộc hằng +@msg invalid array length độ dài mảng không hợp lệ +@msg array literal too long literal mảng quá dài +@msg the value is not a function giá trị không phải là hàm +@msg apply was called on a value that is not a function apply được gọi trên một giá trị không phải là hàm +@msg the argument list is not an object danh sách đối số không phải là đối tượng +@msg too many arguments quá nhiều đối số +@msg the value is not a constructor giá trị không phải là hàm tạo +@msg cannot convert the object to a primitive value không thể chuyển đối tượng thành giá trị nguyên thủy +@msg cannot convert undefined or null to an object không thể chuyển undefined hoặc null thành đối tượng +@msg the right side of 'in' is not an object vế phải của 'in' không phải là đối tượng +@msg the right side of 'instanceof' is not a function vế phải của 'instanceof' không phải là hàm +@msg the function's prototype is not an object nguyên mẫu của hàm không phải là đối tượng +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} chưa được định nghĩa +@msg cannot read property '{key}' of {base} không thể đọc thuộc tính '{key}' của {base} +@msg cannot set property '{key}' of {base} không thể đặt thuộc tính '{key}' của {base} +@msg cannot read a property of {base} không thể đọc thuộc tính của {base} +@msg cannot set a property of {base} không thể đặt thuộc tính của {base} +@msg cannot define property '{key}': {why} không thể định nghĩa thuộc tính '{key}': {why} +@msg cannot assign to property '{key}': {why} không thể gán cho thuộc tính '{key}': {why} +@msg cannot delete property '{key}' không thể xóa thuộc tính '{key}' +@msg cannot declare function {name} không thể khai báo hàm {name} +@msg invalid assignment target đích gán không hợp lệ +@msg the array's length is read-only độ dài của mảng là chỉ đọc +@msg the property cannot be redefined không thể định nghĩa lại thuộc tính +@msg the object is not extensible đối tượng không thể mở rộng +@msg the length cannot be redefined không thể định nghĩa lại độ dài +@msg it is read-only nó là chỉ đọc +@msg an element cannot be deleted không thể xóa một phần tử +@msg it has only a getter nó chỉ có getter +@msg the value is a primitive giá trị là kiểu nguyên thủy @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: dòng {line}, cột {column} của {file}: {e} (đã ném) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: dòng {line}, cột {column}: {e} (đã ném) @msg {name}: {e} (thrown) {name}: {e} (đã ném) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d9d9110276..1acbba444a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4809,6 +4809,31 @@ imageTrace Outline 轮廓 @msg $.evalFile requires a file path $.evalFile 需要文件路径 @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile:超时必须是 0 或更大的有限毫秒数 @msg $.evalFile: takes a file path and a timeout $.evalFile:接受一个文件路径和一个超时值 +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} 未定义 +@msg cannot read property '{key}' of {base} 无法读取 {base} 的属性 '{key}' +@msg cannot set property '{key}' of {base} 无法设置 {base} 的属性 '{key}' +@msg cannot read a property of {base} 无法读取 {base} 的属性 +@msg cannot set a property of {base} 无法设置 {base} 的属性 +@msg cannot define property '{key}': {why} 无法定义属性 '{key}':{why} +@msg cannot assign to property '{key}': {why} 无法为属性 '{key}' 赋值:{why} +@msg cannot delete property '{key}' 无法删除属性 '{key}' +@msg cannot declare function {name} 无法声明函数 {name} +@msg invalid assignment target 赋值目标无效 +@msg the array's length is read-only 数组的长度是只读的 +@msg the property cannot be redefined 属性无法重新定义 +@msg the object is not extensible 对象不可扩展 +@msg the length cannot be redefined 长度无法重新定义 +@msg it is read-only 它是只读的 +@msg an element cannot be deleted 无法删除元素 +@msg it has only a getter 它只有 getter +@msg the value is a primitive 该值是原始值 @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}:{file} 第 {line} 行,第 {column} 列:{e}(抛出) @msg {name}: line {line}, column {column}: {e} (thrown) {name}:第 {line} 行,第 {column} 列:{e}(抛出) @msg {name}: {e} (thrown) {name}:{e}(抛出) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a0d987fe69..615f9d0155 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2523,6 +2523,44 @@ file-filter Templates 範本 @msg $.evalFile requires a file path $.evalFile 需要檔案路徑 @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile:逾時必須是 0 或更大的有限毫秒數 @msg $.evalFile: takes a file path and a timeout $.evalFile:接受一個檔案路徑和一個逾時值 +@msg assignment to a constant binding 對常數繫結賦值 +@msg invalid array length 陣列長度無效 +@msg array literal too long 陣列常值過長 +@msg the value is not a function 值不是函式 +@msg apply was called on a value that is not a function 對不是函式的值呼叫了 apply +@msg the argument list is not an object 引數清單不是物件 +@msg too many arguments 引數過多 +@msg the value is not a constructor 值不是建構函式 +@msg cannot convert the object to a primitive value 無法將物件轉換為基本值 +@msg cannot convert undefined or null to an object 無法將 undefined 或 null 轉換為物件 +@msg the right side of 'in' is not an object 'in' 的右側不是物件 +@msg the right side of 'instanceof' is not a function 'instanceof' 的右側不是函式 +@msg the function's prototype is not an object 函式的原型不是物件 +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {name} is not defined {name} 未定義 +@msg cannot read property '{key}' of {base} 無法讀取 {base} 的屬性 '{key}' +@msg cannot set property '{key}' of {base} 無法設定 {base} 的屬性 '{key}' +@msg cannot read a property of {base} 無法讀取 {base} 的屬性 +@msg cannot set a property of {base} 無法設定 {base} 的屬性 +@msg cannot define property '{key}': {why} 無法定義屬性 '{key}':{why} +@msg cannot assign to property '{key}': {why} 無法為屬性 '{key}' 賦值:{why} +@msg cannot delete property '{key}' 無法刪除屬性 '{key}' +@msg cannot declare function {name} 無法宣告函式 {name} +@msg invalid assignment target 賦值目標無效 +@msg the array's length is read-only 陣列的長度是唯讀的 +@msg the property cannot be redefined 屬性無法重新定義 +@msg the object is not extensible 物件不可擴充 +@msg the length cannot be redefined 長度無法重新定義 +@msg it is read-only 它是唯讀的 +@msg an element cannot be deleted 無法刪除元素 +@msg it has only a getter 它只有 getter +@msg the value is a primitive 該值是基本值 @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}:{file} 第 {line} 行,第 {column} 欄:{e}(擲回) @msg {name}: line {line}, column {column}: {e} (thrown) {name}:第 {line} 行,第 {column} 欄:{e}(擲回) @msg {name}: {e} (thrown) {name}:{e}(擲回) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 296bd84b2b..7b48965a41 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -895,6 +895,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates the errors a script's `File` and `Folder` objects, `vc.run`, `$.evalFile`, the `$` object's properties and functions, `alert`, `confirm` and `prompt`, `vc.document` and `vc.log` raise, the limits a run can pass, and the errors of Drop Script Engine, and the line for a run that fails (a syntax error, a thrown error, a limit, a stop or an internal error, with the script's name, the line and column, the included file it is in and the files left written), in every language that translates every message. The script's name, paths, numbers, command ids and the text a script throws itself are shown as they are. A failure with no line and column, such as an error in code `eval` compiled, is shown with one colon after the script's name (`an_error_without_a_place_names_the_script_and_kind`). A message template that names a value twice matches only when both places hold the same text, so the line for a failed run is not taken for the message inside it (`a_repeated_placeholder_matches_the_same_text`). The untranslated-strings report also lists the messages the script host's `fail`, `value` and `over` helpers take and the errors the script interpreter throws, and a constant's text comes from the file or crate that declares it, so the Scripts menu's headers are not listed as messages (`script_errors_are_translated`, `script_host_errors_are_translated`, `message_scan_reads_script_interpreter_errors`, `message_scan_reads_constants_of_the_file_and_its_crate`, `message_scan_skips_test_modules_with_any_test_cfg`). + - The status bar also translates the errors the script interpreter's core throws (an unknown name, a property of `null` or `undefined`, a property that cannot be defined, assigned or deleted and the reason, a value that is not a function or a constructor, an invalid array length, an invalid assignment target), on their own and in the line for a failed run, in every language that translates every message. Names, property names (a value a message quotes in `'…'` is shown as written, like one in `"…"`, even when it matches a translated message), `null`, `undefined`, `in`, `instanceof` and the error's type (`TypeError`, `ReferenceError` and the others) are shown as they are, and a script that catches the error still reads its English message. An error about a property of `null` or `undefined` names a computed property whose name is not an object and is at most 256 units long, and otherwise says only that the script read or set a property, instead of naming an empty property (`script_interpreter_core_errors_are_translated`, `errors_about_null_and_undefined_name_the_property`, `message_scan_reads_script_interpreter_errors`). - Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Korean, Vietnamese, German, Spanish, French, Italian, Polish, Brazilian Portuguese, Russian, Ukrainian, Georgian and Catalan ship complete, and Czech covers every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a Language preference and, on macOS, a VectorCraft ▸ Language menu. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins). The counts that Package's status and question, the folder search of Missing Fonts and Find Linked Files, the modified and missing linked file prompts and the CSS Properties panel's notes show use the interface language's plural forms instead of a fixed "(s)" form. Evidence: `the_missing_links_note_uses_each_count_form` in `crates/ui-egui/src/dialogs/tests_package.rs`, `the_modified_links_question_uses_each_count_form` in `crates/ui-egui/src/dialogs/missing_links.rs`, `search_counts_use_each_count_form` in `crates/ui-egui/src/dialogs/missing_fonts/tests.rs` and `the_unnamed_objects_note_uses_each_count_form` in `crates/ui-egui/src/panels/tests_css_properties.rs`. The status bar's messages for relinked, replaced, updated and embedded images, broken links, linked files that can't be read or changed on disk, images that can't be decoded, added and unavailable fonts, copied CSS, downloads and exports with their notes name one item in the singular and more in the plural, in English and in each language's plural forms (`counted_status_messages_take_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). From 2fe4b96e48a804db604ba4aabd0766e56478673e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:38:07 -0800 Subject: [PATCH 05/77] Graphs: aligned row edits, opacity-only picks and Default Fill and Stroke keep what each kind stores An aligned appearance.setItem, removeItem or duplicateItem given the Axes group stores the rows of only the lines and labels that have that row, so a category label without it no longer replaces the rows its kind keeps. An Eyedropper pick of only the object's transparency stores only the opacity and blend mode of an axis line or radar ring, as transparency.set does. Default Fill and Stroke stores the black fill and no stroke for a label's kind, and the default rows for a line's kind, also when the label or line already showed them; a kind that keeps no style and is left at the default style still keeps none. --- crates/engine/src/cmd/appearance.rs | 40 +++++++++++--- crates/engine/src/cmd/graph/series.rs | 8 ++- crates/engine/src/cmd/graph/tests.rs | 77 +++++++++++++++++++++++++++ crates/engine/src/cmd/paint.rs | 10 +++- docs/mcp.md | 12 +++-- 5 files changed, 133 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 78a258ac1c..1ce0228b9d 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows and object opacity and blend mode for every line of its kind → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows (not for a pick of only the object's transparency) and object opacity and blend mode for every line of its kind → {ids}", has_doc, copy_from ), @@ -1069,6 +1069,9 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let per = items_per_target(&before, &ids, &[idx], aligned(p, "appearance.setItem")?); super::overprint::edit_counted(s, "Appearance", |d| { let mut edited = Vec::new(); + // The targets that have the row: an aligned row leaves out the members of a graph's Axes or Legend group that + // lack it, and the graph keeps the rows of the labels and lines it reached only. + let mut reached = Vec::new(); for (id, at) in ids.iter().zip(&per) { let Some(&idx) = at.first() else { continue }; let Some(n) = d.node_mut(*id) else { continue }; @@ -1079,6 +1082,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { } let bounds = n.geometric_bounds(); let Some(item) = n.appearance.items.get_mut(idx) else { continue }; + reached.push(*id); let (pp, op, bl, vis, bounds) = match item { AppearanceItem::Fill(f) => (&mut f.paint, &mut f.opacity, &mut f.blend, &mut f.visible, bounds), AppearanceItem::Stroke(st) => { @@ -1121,7 +1125,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, written)); let painted = super::graph::capture_series_top_paints(d, &rows); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = super::graph::capture_label_rows(d, &reached); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; if let Some(pa) = &paint { @@ -1156,8 +1160,13 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { let before = s.doc()?.doc.clone(); let per = items_per_target(&before, &ids, &idx, aligned(p, "appearance.removeItem")?); super::overprint::edit_counted(s, "Remove Item", |d| { + // The targets that had a row to remove, as in `set_item`. + let mut reached = Vec::new(); for (id, idx) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { + if idx.iter().any(|i| *i < n.appearance.items.len()) { + reached.push(*id); + } let mut idx = idx.clone(); idx.sort_unstable(); // From the top down, so the lower indices stay valid. @@ -1169,7 +1178,7 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = super::graph::capture_label_rows(d, &reached); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The rows removed from the active row's object, which need not come first in `ids`. @@ -1207,6 +1216,8 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { // Copies that became the topmost visible row of their kind: the series stores their paint even when the object // showed it. let mut added = Vec::new(); + // The targets that took a copy, as in `set_item`. + let mut reached = Vec::new(); for (id, idx) in ids.iter().zip(&per) { let Some(n) = d.node_mut(*id) else { continue }; let has_contents = n.contents_label().is_some(); @@ -1231,6 +1242,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { ap.set_contents_at(c); } any = true; + reached.push(*id); continue; } let mut idx = idx.clone(); @@ -1245,6 +1257,9 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { added.push((*id, kind)); } any = true; + if reached.last() != Some(id) { + reached.push(*id); + } } } } @@ -1255,7 +1270,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); - super::graph::capture_label_rows(d, &ids); + super::graph::capture_label_rows(d, &reached); Ok(()) })?; // Rows at or above each copy move up by one (by the block, for copies placed at `to`). @@ -1697,8 +1712,21 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { }; // `append` adds rows and leaves the characters as they were. let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?; - // A graph line is a path: every pick writes its rows. - let lines = super::graph::capture_line_rows(d, &targets); + // A graph line is a path: a pick of fill or stroke attributes writes its rows. A pick of only the object's + // opacity and blend mode leaves the fill and stroke its kind keeps, as `capture_label_object_opacity` keeps them. + let to_rows = append + || fill.color + || fill.transparency + || fill.overprint + || stroke.color + || stroke.transparency + || stroke.overprint + || stroke.weight + || stroke.cap + || stroke.join + || stroke.miter + || stroke.dash; + let lines = to_rows && super::graph::capture_line_rows(d, &targets); Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines)) })?; Ok(finish(s, &targets)) diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 7c3dcf90e6..e9b4b15185 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -529,16 +529,20 @@ pub(crate) fn capture_label_styles(doc: &mut Document, ids: &[NodeId], change: & } /// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). Returns whether -/// the kept style changed. +/// the kept style changed. A kind that keeps no style and that `change` leaves at the default style keeps none. fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false }; - let mut style = label_style(&spec.label_styles, role); + let was = label_style(&spec.label_styles, role); + let mut style = was.clone(); change(&mut style); let slot = match role { Role::Value => &mut spec.label_styles.values, Role::Category => &mut spec.label_styles.categories, Role::Legend => &mut spec.label_styles.legend, }; + if slot.is_none() && style == was { + return false; + } let changed = slot.as_ref() != Some(&style); *slot = Some(style); changed diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 967d4dc9f2..5e4d99f7ad 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6294,6 +6294,83 @@ fn a_row_index_given_the_axes_group_is_a_row_of_its_backmost_member_with_aligned assert!((l.appearance.items[top_row(&s, l.id, false)].opacity() - 0.4).abs() < 1e-6, "the stroke row's opacity is kept"); } +/// An aligned row edit given the Axes group leaves alone what a kind of label keeps from a label without that row: the +/// category labels keep the orange fill row of one of them through an edit of the lines' stroke rows. +#[test] +fn an_aligned_row_edit_given_the_axes_group_keeps_the_rows_of_labels_it_did_not_reach() { + let cases = [("appearance.setItem", json!({"color": "#0000ff"})), ("appearance.duplicateItem", json!({})), ("appearance.removeItem", json!({}))]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let c = text_id(&s, id, "Axes", "Q2"); + s.execute("appearance.addFill", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [c.0], "index": 0, "color": "#ff8000"})).unwrap(); + let kept = spec(&s, id).label_styles.categories_rows; + assert!(kept.is_some(), "the category labels keep the orange row"); + let axes = group(s.doc().unwrap().doc.node(id).unwrap(), "Axes").clone(); + let back = axes.children().unwrap()[0].id; + let mut p = params.clone(); + p["ids"] = json!([axes.id.0]); + p["index"] = json!(top_row(&s, back, false)); + p["aligned"] = json!(true); + s.execute(cmd, &p).unwrap(); + assert_eq!(spec(&s, id).label_styles.categories_rows, kept, "{cmd}"); + }); +} + +/// An Eyedropper pick of only the object's opacity on an axis line keeps the stroke its kind keeps from another line, +/// though the line it is given still shows the default stroke. +#[test] +fn an_eyedropper_pick_of_only_the_opacity_keeps_the_stroke_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"ids": [rect.0], "opacity": 50})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false}); + let opacity_only = json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke}}); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "pickUp": opacity_only})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{looks:?}"); +} + +/// Default Fill and Stroke on a label or an axis line that already shows the default paint is kept for its kind, in +/// place of the paint the kind keeps from another label or line. +#[test] +fn default_fill_and_stroke_on_a_label_or_line_that_shows_it_is_kept_for_its_kind() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("paint.setFill", &json!({"ids": [text_id(&s, id, "Axes", "4").0], "color": "#ff0000"})).unwrap(); + let hex = |st: &CharStyle| st.fill.color().map(|c| c.to_hex()); + assert_eq!(hex(&label_run_style(&s, id, "Axes", "0")).as_deref(), Some("#000000"), "the other labels show black until the graph is drawn again"); + s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "0").0]})).unwrap(); + label_looks(&mut s, id); + let st = label_run_style(&s, id, "Axes", "4"); + assert_eq!((hex(&st).as_deref(), st.stroke.is_none()), (Some("#000000"), true)); + let lines = line_nodes(&s, id); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| *l == ("#000000".into(), 1.0, 1.0)), "the 1 pt black default stroke"); +} + +/// Default Fill and Stroke on a label of a kind that keeps no style, which already shows the default paint, is no edit. +#[test] +fn default_fill_and_stroke_on_a_label_that_shows_it_is_no_edit() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("paint.default", &json!({"ids": [text_id(&s, id, "Axes", "4").0]})).unwrap(); + assert_eq!(spec(&s, id).label_styles.values, None); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); +} + /// Redefine Graphic Style on an Axes group linked to the style with rows of its own (as a file can hold it) restyles and /// links the lines and labels in it, and clears and unlinks the group; Break Link given the group unlinks them. A style /// applied through the group links its lines and labels, and the graph keeps their look, not the link, when it is drawn diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 174d259164..db0769d718 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -955,8 +955,14 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); - let labels = super::graph::capture_label_changes(&before, d, &ids, false); - Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) + // The graph keeps the default paint for every label and line of a kind it reached, also when one already + // showed it. + let labels = super::graph::capture_label_styles(d, &ids, &|st| { + st.fill = Paint::solid(Color::BLACK); + st.stroke = Paint::None; + }); + let lines = super::graph::capture_line_rows(d, &ids); + Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines)) })?; } super::newart::reset(s); diff --git a/docs/mcp.md b/docs/mcp.md index bcbee312fd..dbfe3f4a2a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -809,7 +809,8 @@ except by `graphicStyle.redefine`, which passes the style to the lines and label holds. An `index`, `indices` or fill or stroke `item` given an Axes or Legend group whose lines and labels have different rows, as the lines and labels of a new graph do, is an error unless `aligned` is true, which makes it a row of the stack of the backmost line or label in the group, and `appearance.moveItem` does not move the rows of such a -group. The graph keeps no graphic style link on its lines and +group. With `aligned`, the graph stores the rows of only the lines and labels that have that row; a kind of label none +of whose labels has it keeps what it stored before. The graph keeps no graphic style link on its lines and labels: they keep the look of a style applied to them, and are unlinked when the graph is drawn again. The commands find these groups by their names, so a renamed Axes or Legend group is edited itself. @@ -856,7 +857,9 @@ placement they set there. A stroke weight and dashes are stored as the label sho scaled. When the characters of labels of one kind change differently, the frontmost label sets what the kind keeps. On a pie with Legends in Wedges whose legend labels have no fill of their own, the legend labels' fill is stored only when every legend label the command reaches ends up with the same fill. Otherwise they are drawn again in black, or white on -a dark wedge. What they change on a graph's axis lines, tick marks and radar rings is stored as described below. +a dark wedge. `paint.default` stores the black fill and no stroke for the kind of each label it reaches, also when the +label already showed them. What they change on a graph's axis lines, tick marks and radar rings is stored as described +below. `text.setFormat` without `start` and `end`, on a graph or on its labels, stores the character and paragraph attributes it sets for each kind of label it reaches (value axis numbers, category labels, legend labels), and every label of that @@ -889,8 +892,9 @@ opacity and blend mode. `paint.setFill`, `paint.setStroke` and the recolor comma graph, its Axes group or a group that holds the graph, so the lines keep the paint those commands give a whole graph. The other commands store them when given the line itself, and the `appearance.*` and graphic style commands and `transparency.set` with an `item` also when given the Axes group, as described above. `transparency.set` without an -`item` and `object.setProps` store only the object opacity and blend mode. `appearance.copyFrom` stores the rows -whatever it picks up, with or without `append`. The recolor commands, `paint.swap` and `paint.default` store a line's rows when they change them. The +`item` and `object.setProps` store only the object opacity and blend mode. `appearance.copyFrom` stores the rows when it +picks up a fill or stroke attribute or adds rows with `append`; a pick of only the object's transparency stores only the +object opacity and blend mode. The recolor commands and `paint.swap` store a line's rows when they change them. The other commands store them even when the line already showed them, except that rows equal to a kind's default stroke (0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in paint order sets what the kind keeps, whatever order the `ids` are in. A gradient is stored without its placement, and From 13c5df3aeb4898fe22f3c505adbcf76b115aad5d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 22:07:19 -0800 Subject: [PATCH 06/77] Graphs: an edit of a hidden row leaves what a label or line kind keeps An Appearance, paint, stroke or transparency edit of a hidden fill or stroke row of a graph label or axis line no longer stores that object's unchanged visible rows for its kind, so a paint the kind keeps from another label or line stays. --- crates/engine/src/cmd/appearance.rs | 28 +++++++++++++++++++++++--- crates/engine/src/cmd/graph.rs | 4 ++-- crates/engine/src/cmd/graph/tests.rs | 30 ++++++++++++++++++++++++++++ docs/mcp.md | 5 +++-- 4 files changed, 60 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 1ce0228b9d..35cd93ce94 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -551,6 +551,20 @@ pub(crate) fn check_part_rows(s: &Session, p: &Value, aligned: bool, cmd: &str) Ok(()) } +/// Whether row `index` of `n` is the topmost visible row of its kind, the row a graph keeps for a label or line. +fn is_top_shown(n: &Node, index: usize) -> bool { + let items = &n.appearance.items; + items.get(index).is_some_and(|it| items.iter().rposition(|o| o.is_fill() == it.is_fill() && o.visible()) == Some(index)) +} + +/// `ids` without the objects whose topmost visible fill and stroke rows ([`super::graph::label_rows`]) an edit left as +/// they were (`before`: the document before it), unless `wrote` says the edit wrote one of those rows. An edit of a +/// hidden row of a graph label or line then leaves what the graph keeps for its kind as it is. +fn shown_rows_edited(before: &Document, d: &Document, ids: Vec, wrote: impl Fn(NodeId) -> bool) -> Vec { + let shown = |doc: &Document, id: NodeId| doc.node(id).map(super::graph::label_rows); + ids.into_iter().filter(|id| wrote(*id) || shown(before, *id) != shown(d, *id)).collect() +} + /// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke /// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters). /// What the edit changes on the topmost visible fill and stroke of graph series marks, and on the @@ -600,6 +614,8 @@ pub(crate) fn edit_items_then( let mut edited = Vec::new(); // The objects whose rows `f` edited: on type, no row means its characters. let mut rows = Vec::new(); + // The objects where `f` wrote the topmost visible row of its kind. + let mut wrote = Vec::new(); for (id, item) in ids.iter().zip(&per) { let Some(item) = item else { continue }; let Some(n) = d.node_mut(*id) else { continue }; @@ -609,11 +625,14 @@ pub(crate) fn edit_items_then( if index.is_some() { rows.push(*id); } + if index.is_none_or(|i| is_top_shown(n, i)) { + wrote.push(*id); + } } let more = after(&before, d, &edited)?; - let labels = super::graph::capture_label_rows(d, &rows); + let labels = super::graph::capture_label_rows(d, &shown_rows_edited(&before, d, rows, |id| wrote.contains(&id))); // A graph line keeps the rows the edit wrote, also when the line already showed them. - let lines = super::graph::capture_line_rows(d, &edited); + let lines = super::graph::capture_line_rows(d, &shown_rows_edited(&before, d, edited.clone(), |id| wrote.contains(&id))); Ok(count_changed(d, &before, &edited) + usize::from(more || labels || lines)) })?; Ok(()) @@ -1125,6 +1144,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, written)); let painted = super::graph::capture_series_top_paints(d, &rows); + let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id)); let labels = super::graph::capture_label_rows(d, &reached); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; @@ -1178,7 +1198,7 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &reached); + let labels = super::graph::capture_label_rows(d, &shown_rows_edited(&before, d, reached, |_| false)); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The rows removed from the active row's object, which need not come first in `ids`. @@ -1268,8 +1288,10 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let mut rows = top_paint_changed(&before, d, &ids); + let top_copies: Vec = added.iter().map(|(id, _)| *id).collect(); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); + let reached = shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id)); super::graph::capture_label_rows(d, &reached); Ok(()) })?; diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 1654940e87..85ed559ae5 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -47,8 +47,8 @@ use series::default_series_color; pub(crate) use series::{ LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_text, capture_line_rows, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, - graph_part_members, is_design_art, label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, - series_marks_in, series_object_opacity_differs, shown_paint, + graph_part_members, is_design_art, label_object_opacity_differs, label_rows, labels_in, paint_targets, series_group_marks, + series_group_marks_where, series_marks_in, series_object_opacity_differs, shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 5e4d99f7ad..99c05fb2a7 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6319,6 +6319,36 @@ fn an_aligned_row_edit_given_the_axes_group_keeps_the_rows_of_labels_it_did_not_ }); } +/// An edit of a hidden row of an axis line leaves what its kind keeps from another line: the line's visible rows did not +/// change. +#[test] +fn an_edit_of_a_hidden_row_of_an_axis_line_keeps_what_its_kind_keeps() { + let cases = [ + ("appearance.setItem", json!({"color": "#0000ff"})), + ("appearance.duplicateItem", json!({})), + ("appearance.removeItem", json!({})), + ("transparency.set", json!({"opacity": 40})), + ("paint.setStroke", json!({"color": "#0000ff"})), + ]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let line = lines[1].id; + s.execute("appearance.addStroke", &json!({"ids": [line.0]})).unwrap(); + let hidden = top_row(&s, line, false); + s.execute("appearance.setItem", &json!({"ids": [line.0], "index": hidden, "visible": false})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows; + let mut p = params.clone(); + p["ids"] = json!([line.0]); + p[if cmd.starts_with("appearance.") { "index" } else { "item" }] = json!(hidden); + s.execute(cmd, &p).unwrap(); + assert_eq!(spec(&s, id).label_styles.axis_rows, kept, "{cmd}"); + }); +} + /// An Eyedropper pick of only the object's opacity on an axis line keeps the stroke its kind keeps from another line, /// though the line it is given still shows the default stroke. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index dbfe3f4a2a..56d8b484a6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -871,7 +871,7 @@ The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, a transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its kind of label: the paint, weight, opacity and blend mode of its topmost visible fill and stroke row, their order and their place relative to the Characters row, and the label's object opacity and blend mode. They store them even when the -label already showed them. `transparency.set` without an `item`, `object.setProps` with an opacity or blend mode, and +label already showed them, but an edit of a hidden row that leaves the topmost visible rows as they were stores nothing. `transparency.set` without an `item`, `object.setProps` with an opacity or blend mode, and an `appearance.copyFrom` (Eyedropper) pick of transparency store only the label's object opacity and blend mode; `appearance.copyFrom` with `append` stores the rows. When the graph is drawn again, every label of that kind gets what is stored, with a placed gradient fitted to each label, and the graph saves it as `valuesRows`, `categoriesRows` and @@ -896,7 +896,8 @@ The other commands store them when given the line itself, and the `appearance.*` picks up a fill or stroke attribute or adds rows with `append`; a pick of only the object's transparency stores only the object opacity and blend mode. The recolor commands and `paint.swap` store a line's rows when they change them. The other commands store them even when the line already showed them, except that rows equal to a kind's default stroke -(0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in +(0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved, and an edit of a hidden row that +leaves the topmost visible rows as they were stores nothing. When one command reaches several lines of one kind, the frontmost line in paint order sets what the kind keeps, whatever order the `ids` are in. A gradient is stored without its placement, and each line fits it when the graph is drawn again. The graph saves the rows as `axisRows` and `ringRows` in its label styles. Other stroke options (caps, joins, miter limit, alignment, dashes and arrowheads), rows below the topmost one of From f1a79b92cc4500beaee7f384e7bf174d9e9d5f3a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:36:59 -0800 Subject: [PATCH 07/77] Graphs: an edit of some attributes on an axis line keeps the rest its kind keeps An edit that changed only some attributes of a graph line, such as a transparency-only Eyedropper pick, a cap, or a fill, kept that line's whole fill and stroke rows for every line of its kind. A line that still showed the default stroke until the graph was drawn again then replaced the stroke its kind kept from another line. Such edits now keep only the attributes they change; Clear Appearance, Move Appearance, graphic styles, and a pick of every attribute or with append still keep the whole rows. --- crates/engine/src/cmd/addons/color.rs | 2 +- crates/engine/src/cmd/appearance.rs | 61 +++++++++++++++++---------- crates/engine/src/cmd/graph.rs | 6 +-- crates/engine/src/cmd/graph/series.rs | 59 +++++++++++++++++++++----- crates/engine/src/cmd/graph/tests.rs | 47 +++++++++++++++++++++ crates/engine/src/cmd/stroke.rs | 2 +- docs/mcp.md | 10 +++-- 7 files changed, 145 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index fe594903a0..8462e35207 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -260,7 +260,7 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result { let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written); let labels = super::super::graph::capture_label_styles(d, &ids, ©_run); let painted: Vec = written.iter().map(|(id, _)| *id).collect(); - let lines = super::super::graph::capture_line_rows(d, &painted); + let lines = super::super::graph::capture_line_changes(&before, d, &painted); Ok(objects + usize::from(series || labels || lines)) })?; } diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 6689a25014..5302e38ed9 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, |s, p| add_item(s, p, true) ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, |s, p| add_item(s, p, false) ), @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, reduce_basic ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Appearance Item", [], None, - "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, set_item ), @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Remove Item", [], None, - "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, remove_item ), @@ -111,7 +111,7 @@ pub fn specs() -> Vec { "Duplicate Item", ["Window", "Appearance"], None, - "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind", + "{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", has_doc, duplicate_item ), @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder Appearance Item", [], None, - "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {index: where the item landed | contents: the row's slot}", + "{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {index: where the item landed | contents: the row's slot}", has_doc, move_item ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows and object opacity and blend mode for every line of its kind → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows and object opacity and blend mode for every line of its kind (a pick of some attributes without `append`: only what it changes) → {ids}", has_doc, copy_from ), @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Show All Hidden Attributes", ["Window", "Appearance"], None, - "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {ids}", + "{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes) → {ids}", has_doc, show_all_hidden ), @@ -532,7 +532,7 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result> { /// What the edit changes on the topmost visible fill and stroke of graph series marks, and on the /// rows and characters of graph labels, is stored on their graphs in the same step /// ([`capture_series_changes`], [`super::graph::capture_label_changes`]), and so are the rows of -/// the graph lines it reaches ([`super::graph::capture_line_rows`]). Nothing targeted is not +/// the graph lines it reaches ([`super::graph::capture_line_changes`]). Nothing targeted is not /// an edit, and when `f` leaves every target as it was, the document and its undo history stay as /// they are. pub(crate) fn edit_items( @@ -587,14 +587,27 @@ pub(crate) fn edit_items_then( } } let more = after(&before, d, &edited)?; + // A graph line keeps only the attributes of its rows that the edit changed: the others stay as its kind keeps + // them, which the line may not show yet. + rows.retain(|id| !super::graph::is_graph_line(d, *id)); let labels = super::graph::capture_label_rows(d, &rows); - // A graph line keeps the rows the edit wrote, also when the line already showed them. - let lines = super::graph::capture_line_rows(d, &edited); + let lines = super::graph::capture_line_changes(&before, d, &edited); Ok(count_changed(d, &before, &edited) + usize::from(more || labels || lines)) })?; Ok(()) } +/// Keep the object rows of the graph labels among `ids` for every label of their kind +/// ([`super::graph::capture_label_rows`]), and of the graph lines among them only the attributes the edit changed +/// ([`super::graph::capture_line_changes`]): a line's other attributes stay as its kind keeps them, which the line may +/// not show yet. Returns whether what a graph keeps changed. +fn capture_row_edits(before: &vectorcraft_doc::Document, d: &mut vectorcraft_doc::Document, ids: &[NodeId]) -> bool { + let labels: Vec = ids.iter().copied().filter(|id| !super::graph::is_graph_line(d, *id)).collect(); + let labels = super::graph::capture_label_rows(d, &labels); + let lines = super::graph::capture_line_changes(before, d, ids); + labels || lines +} + /// How many of `ids` differ in `d` from `before`. pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_doc::Document, ids: &[NodeId]) -> usize { ids.iter().filter(|id| d.node(**id) != before.node(**id)).count() @@ -727,7 +740,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); - super::graph::capture_label_rows(d, &ids); + capture_row_edits(&before, d, &ids); Ok(()) })?; // A fill added above the active row becomes the active row; otherwise the rows above the new @@ -1020,7 +1033,7 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &both_kinds(&ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = capture_row_edits(&before, d, &ids); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; s.active_appearance_item = None; @@ -1096,7 +1109,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, written)); let painted = super::graph::capture_series_top_paints(d, &rows); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = capture_row_edits(&before, d, &ids); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; if let Some(pa) = &paint { @@ -1143,7 +1156,7 @@ fn remove_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = capture_row_edits(&before, d, &ids); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The rows removed from the active row's object, which need not come first in `ids`. @@ -1228,7 +1241,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); - super::graph::capture_label_rows(d, &ids); + capture_row_edits(&before, d, &ids); Ok(()) })?; // Rows at or above each copy move up by one (by the block, for copies placed at `to`). @@ -1268,7 +1281,7 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &shown)); super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &shown)); - super::graph::capture_label_rows(d, &shown); + capture_row_edits(&before, d, &shown); Ok(shown) })?; Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>() })) @@ -1314,7 +1327,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = capture_row_edits(&before, d, &ids); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The moved row stays the active one; the rows it passed shift by one. @@ -1360,7 +1373,7 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result Result { } slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?; // A graph label's kind keeps where its rows paint relative to the characters. - let labels = super::graph::capture_label_rows(d, ids); + let labels = capture_row_edits(&before, d, ids); Ok(count_changed(d, &before, ids) + usize::from(labels)) })?; Ok(json!({ "contents": slot })) @@ -1669,8 +1682,10 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { }; // `append` adds rows and leaves the characters as they were. let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?; - // A graph line is a path: every pick writes its rows. - let lines = super::graph::capture_line_rows(d, &targets); + // A graph line is a path: a whole pick and `append` write its rows. A pick of some attributes keeps those it + // changed, and the rest stay as its kind keeps them, which the line may not show yet. + let lines = + if rows_written { super::graph::capture_line_rows(d, &targets) } else { super::graph::capture_line_changes(&before, d, &targets) }; Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines)) })?; Ok(finish(s, &targets)) diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index b8a88b0bc5..e49ff91f04 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -46,9 +46,9 @@ use generate::generate; use series::default_series_color; pub(crate) use series::{ LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, - capture_label_styles, capture_label_text, capture_line_rows, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, - is_design_art, label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, - series_object_opacity_differs, shown_paint, + capture_label_styles, capture_label_text, capture_line_changes, capture_line_rows, capture_series_object_opacity, capture_series_opacity, + capture_series_top_paints, is_design_art, is_graph_line, label_object_opacity_differs, labels_in, paint_targets, series_group_marks, + series_group_marks_where, series_marks_in, series_object_opacity_differs, shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 69cf88d62c..0c6803bcc4 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -645,15 +645,54 @@ pub(crate) fn capture_line_rows(doc: &mut Document, ids: &[NodeId]) -> bool { store_line_rows(doc, ids, false) } -/// Keep the object rows of the graph lines among `ids` whose rows an edit changed (`before`: the document before the -/// edit) for every line of their kind. Returns whether kept rows changed. -fn capture_line_changes(before: &Document, doc: &mut Document, ids: &[NodeId]) -> bool { - let changed: Vec = ids - .iter() - .copied() - .filter(|id| graph_line(doc, *id).is_some() && before.node(*id).map(label_rows) != doc.node(*id).map(label_rows)) - .collect(); - store_line_rows(doc, &changed, false) +/// Keep, for every line of their kind, the attributes of the object rows ([`label_rows`]) that an edit changed on the +/// graph lines among `ids` (`before`: the document before the edit). The attributes the edit left alone stay as the kind +/// keeps them, also when a line still shows other ones until the graph is drawn again. Lines of a kind that the edit +/// changed differently take the frontmost one's attributes. Called inside the same edit, so they undo together. Returns +/// whether kept rows changed. +pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: &[NodeId]) -> bool { + let mut changed = false; + for (id, graph, line) in lines_of(doc, ids) { + let old = before.node(id).and_then(label_rows).unwrap_or_default(); + let new = doc.node(id).and_then(label_rows).unwrap_or_default(); + if old == new { + continue; + } + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + let mut rows = slot.clone().unwrap_or_else(|| line.default_rows()); + merge_row_edits(&mut rows, &old, &new); + let kept = (rows != line.default_rows()).then_some(rows); + changed |= *slot != kept; + *slot = kept; + } + changed +} + +/// Is `id` a graph line: a path directly in a graph's Axes group? +pub(crate) fn is_graph_line(doc: &Document, id: NodeId) -> bool { + graph_line(doc, id).is_some() +} + +/// Set each attribute of `rows` that differs between `old` and `new` as `new` has it. +fn merge_row_edits(rows: &mut vectorcraft_doc::LabelRows, old: &vectorcraft_doc::LabelRows, new: &vectorcraft_doc::LabelRows) { + fn take(kept: &mut T, old: &T, new: &T) { + if old != new { + *kept = new.clone(); + } + } + let (k, o, n) = (&mut rows.paint, &old.paint, &new.paint); + take(&mut k.fill, &o.fill, &n.fill); + take(&mut k.stroke, &o.stroke, &n.stroke); + take(&mut k.stroke_width, &o.stroke_width, &n.stroke_width); + take(&mut k.fill_opacity, &o.fill_opacity, &n.fill_opacity); + take(&mut k.stroke_opacity, &o.stroke_opacity, &n.stroke_opacity); + take(&mut k.fill_blend, &o.fill_blend, &n.fill_blend); + take(&mut k.stroke_blend, &o.stroke_blend, &n.stroke_blend); + take(&mut k.opacity, &o.opacity, &n.opacity); + take(&mut k.blend, &o.blend, &n.blend); + take(&mut rows.below, &old.below, &new.below); + take(&mut rows.stroke_under, &old.stroke_under, &new.stroke_under); } /// Would [`store_line_rows`] with `object_only` change what a graph keeps for the lines among `ids`? Reads the document @@ -901,7 +940,7 @@ pub(crate) fn labels_in(doc: &Document, roots: &[NodeId]) -> Vec { /// labels itself ([`picks_legend_fill`]), their fill is kept only when the legend labels among `ids` end up with one /// fill and the edit named them: with `named`, only a legend label among `named` (an edit that reached the others /// through the graph or a group leaves them the graph's black or white); without it, every label in `ids`. The graph -/// lines among `ids` whose rows changed keep them for every line of their kind ([`capture_line_rows`]), with or without +/// lines among `ids` whose rows changed keep what changed for every line of their kind ([`capture_line_changes`]), with or without /// `rows`. Called inside the same edit, so they undo together. Returns whether what a graph keeps changed. pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: &[NodeId], rows: bool, named: Option<&[NodeId]>) -> bool { let lines = capture_line_changes(before, doc, ids); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 13b2542ff3..0ab174cba0 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6193,6 +6193,53 @@ fn an_object_opacity_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { } } +/// An Eyedropper pick that applies only the object's transparency to an axis line keeps the stroke its kind keeps, though +/// the line it is applied to still shows the default stroke. +#[test] +fn a_transparency_only_pick_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("transparency.set", &json!({"ids": [rect.0], "opacity": 50})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false}); + let apply = json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "apply": apply})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{looks:?}"); +} + +/// An edit of some attributes on an axis line that still shows the default stroke keeps what it changes, and the stroke +/// its kind keeps from another line stays: a cap is not kept, so it changes nothing the kind keeps. +#[test] +fn an_edit_of_some_attributes_on_an_axis_line_keeps_the_rest_its_kind_keeps() { + let cases = [ + ("stroke.set", json!({"cap": "round"}), ""), + ("paint.setFill", json!({"color": "#0000ff"}), "#0000ff"), + ("appearance.setItem", json!({"index": 0, "color": "#00ff00"}), "#00ff00"), + ]; + for (cmd, params, fill) in cases { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "{cmd}: the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#ff0000".into(), 0.5, 1.0)), "{cmd}: {looks:?}"); + let fills: Vec = + line_nodes(&s, id).iter().map(|n| n.appearance.fill_paint().color().map(|c| c.to_hex()).unwrap_or_default()).collect(); + assert!(fills.iter().all(|f| f == fill), "{cmd}: {fills:?}"); + } +} + /// An opacity and a stroke weight given to a radar graph's ring are kept for its rings, and its spokes keep their own. #[test] fn transparency_and_stroke_weight_on_a_radar_ring_are_kept_for_its_rings() { diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index f9dca54298..95483e76c9 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/docs/mcp.md b/docs/mcp.md index 46fef29862..5789c7ed50 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -873,10 +873,12 @@ the paint, weight, opacity and blend mode of its topmost visible fill and stroke opacity and blend mode. `paint.setFill`, `paint.setStroke` and the recolor commands also store them when given the graph, its Axes group or a group that holds the graph, so the lines keep the paint those commands give a whole graph. The other commands store them when given the line itself. `transparency.set` without an `item` and `object.setProps` -store only the object opacity and blend mode. `appearance.copyFrom` stores the rows whatever it picks up, with or -without `append`. The recolor commands, `paint.swap` and `paint.default` store a line's rows when they change them. The -other commands store them even when the line already showed them, except that rows equal to a kind's default stroke -(0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in +store only the object opacity and blend mode. `appearance.clear`, `appearance.transfer`, `graphicStyle.apply`, +`graphicStyle.redefine`, and `appearance.copyFrom` with every attribute picked up and applied or with `append`, store a +line's rows even when the line already showed them. The other commands, an `appearance.copyFrom` of some attributes +included, store only what they change on a line's rows; the kind keeps its other attributes, also when the line still +shows different ones until the graph is drawn again. Rows equal to a kind's default stroke (0.5 pt black for axis lines +and tick marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in paint order sets what the kind keeps, whatever order the `ids` are in. A gradient is stored without its placement, and each line fits it when the graph is drawn again. The graph saves the rows as `axisRows` and `ringRows` in its label styles. Other stroke options (caps, joins, miter limit, alignment, dashes and arrowheads), rows below the topmost one of From db1dd678187f767d394919e8b3440d5a2b0198c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 22:33:58 -0800 Subject: [PATCH 08/77] Graphs: an Eyedropper pick of stroke options leaves the rows axis lines keep A pick of only overprint, caps, joins, miter limit or dashes on an axis line or radar ring no longer stores the line's paint and weight for its kind, since the graph keeps none of those options. --- crates/engine/src/cmd/appearance.rs | 21 +++++------------ crates/engine/src/cmd/graph/tests.rs | 34 ++++++++++++++++------------ docs/mcp.md | 4 ++-- 3 files changed, 28 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 35cd93ce94..5cb4ebb6b4 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows (not for a pick of only the object's transparency) and object opacity and blend mode for every line of its kind → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows (when the pick takes a paint, a stroke weight or a row's opacity and blend mode, or appends) and object opacity and blend mode for every line of its kind → {ids}", has_doc, copy_from ), @@ -1734,20 +1734,11 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { }; // `append` adds rows and leaves the characters as they were. let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?; - // A graph line is a path: a pick of fill or stroke attributes writes its rows. A pick of only the object's - // opacity and blend mode leaves the fill and stroke its kind keeps, as `capture_label_object_opacity` keeps them. - let to_rows = append - || fill.color - || fill.transparency - || fill.overprint - || stroke.color - || stroke.transparency - || stroke.overprint - || stroke.weight - || stroke.cap - || stroke.join - || stroke.miter - || stroke.dash; + // A graph line is a path: a pick of a paint, a weight or a row's opacity and blend mode writes the rows its kind + // keeps. A pick of only the object's opacity and blend mode, or of row attributes the graph does not keep (overprint, + // caps, joins, miter limit, dashes), leaves the fill and stroke its kind keeps, as `capture_label_object_opacity` + // keeps them. + let to_rows = append || fill.color || fill.transparency || stroke.color || stroke.transparency || stroke.weight; let lines = to_rows && super::graph::capture_line_rows(d, &targets); Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines)) })?; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 99c05fb2a7..1ebc6b460e 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6349,23 +6349,29 @@ fn an_edit_of_a_hidden_row_of_an_axis_line_keeps_what_its_kind_keeps() { }); } -/// An Eyedropper pick of only the object's opacity on an axis line keeps the stroke its kind keeps from another line, -/// though the line it is given still shows the default stroke. +/// An Eyedropper pick of only the object's opacity, or of only stroke options the graph does not keep, on an axis line +/// keeps the stroke its kind keeps from another line, though the line it is given still shows the default stroke. #[test] fn an_eyedropper_pick_of_only_the_opacity_keeps_the_stroke_its_kind_keeps() { - let mut s = Session::new(); - s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); - let id = graph(&mut s, "column"); - let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); - s.execute("object.setProps", &json!({"ids": [rect.0], "opacity": 50})).unwrap(); - let lines = line_nodes(&s, id); - s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); let fill = json!({"color": false, "transparency": false, "overprint": false}); - let stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false}); - let opacity_only = json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke}}); - s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "pickUp": opacity_only})).unwrap(); - let looks = redrawn_line_looks(&mut s, id); - assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{looks:?}"); + let stroke = |dash: bool| json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": dash}); + let cases = [ + (json!({"appearance": {"transparency": true, "fill": fill, "stroke": stroke(false)}}), 0.5), + (json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke(true)}}), 1.0), + ]; + every_case(cases, |(pick, opacity)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"ids": [rect.0], "opacity": 50})).unwrap(); + s.execute("stroke.set", &json!({"ids": [rect.0], "dash": [4, 2]})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "pickUp": pick})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - *opacity).abs() < 1e-6), "{pick}: {looks:?}"); + }); } /// Default Fill and Stroke on a label or an axis line that already shows the default paint is kept for its kind, in diff --git a/docs/mcp.md b/docs/mcp.md index 56d8b484a6..96ba3f8c3a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -893,8 +893,8 @@ graph, its Axes group or a group that holds the graph, so the lines keep the pai The other commands store them when given the line itself, and the `appearance.*` and graphic style commands and `transparency.set` with an `item` also when given the Axes group, as described above. `transparency.set` without an `item` and `object.setProps` store only the object opacity and blend mode. `appearance.copyFrom` stores the rows when it -picks up a fill or stroke attribute or adds rows with `append`; a pick of only the object's transparency stores only the -object opacity and blend mode. The recolor commands and `paint.swap` store a line's rows when they change them. The +picks up a paint, a stroke weight or a row's opacity and blend mode, or adds rows with `append`; any other pick stores +only the object opacity and blend mode, when it picks them up. The recolor commands and `paint.swap` store a line's rows when they change them. The other commands store them even when the line already showed them, except that rows equal to a kind's default stroke (0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved, and an edit of a hidden row that leaves the topmost visible rows as they were stores nothing. When one command reaches several lines of one kind, the frontmost line in From d6ba9d267761b4443ea5854a99ce1adc8bd97d0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 04:19:47 -0800 Subject: [PATCH 09/77] .ai save: a clipping object written cut keeps its text wrap options A clipping group whose clipping object is a group, an image, a symbol instance or type, or whose clipping path sits inside art cut to another clipping object, is written as its members cut to that object. The object's text wrap options went only on its fill or stroke, so an object with no paint lost them, and a fill cut by the outer clipping object changed the outline area type wraps around after the file was opened. The options now go on an unpainted path (a compound path for several subpaths) of the outline area type wraps around, written under the clipped art, uncut, locked and hidden as the object is. The .ai reader reads such a path and gives it the dictionary after it. Without room under the object limit the options are left out. --- crates/doc/src/text.rs | 2 +- crates/doc/src/text/wrap.rs | 10 ++ crates/eps/src/ai_editing/tests.rs | 148 ++++++++++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 31 +++++- docs/target-app-parity.md | 1 + 5 files changed, 186 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 440c379283..7481fc77a2 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -34,7 +34,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_work}; +pub use wrap::{resolve_wrap, wrap_outline, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 0b5fe45dc2..81cb7d9c8f 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -32,6 +32,16 @@ fn outline(n: &Node, out: &mut PathData) { } } +/// The outline area type wraps around for wrap object `n`, in document coordinates, as +/// [`resolve_wrap`] makes it: a path's subpaths that are closed or have more than two anchors, those +/// of the shown members of a group or compound path, a clip group's clipping object's, and the +/// bounds of other art. Empty when `n` has none. +pub fn wrap_outline(n: &Node) -> PathData { + let mut pd = PathData::default(); + outline(n, &mut pd); + pd +} + enum Item<'a> { Wrap(&'a Node), Text(&'a Node), diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index a3b2800fd3..31e4d155a1 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -10222,3 +10222,151 @@ fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() { same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]); } } + +/// The wrap shapes [`vectorcraft_doc::text::resolve_wrap`] gives the area type in `doc`. +fn area_wrap(doc: &Document) -> Vec { + let mut d = doc.clone(); + vectorcraft_doc::text::resolve_wrap(None, &mut d); + let mut out = vec![]; + d.layers[0].walk(&mut |n| { + if let NodeKind::Text(t) = &n.kind + && matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) + { + out.clone_from(&t.wrap); + } + }); + out +} + +/// `got` and `want` are the same wrap shapes: the same options, offsets within `1e-6`, and the +/// same subpaths with anchors within `1e-3`. +fn same_shapes(got: &[vectorcraft_doc::WrapShape], want: &[vectorcraft_doc::WrapShape], case: &str) { + let same = got.len() == want.len() + && got.iter().zip(want).all(|(g, w)| { + g.wrap.invert == w.wrap.invert + && (g.wrap.offset - w.wrap.offset).abs() < 1e-6 + && g.path.subpaths.len() == w.path.subpaths.len() + && g.path.subpaths.iter().zip(&w.path.subpaths).all(|(a, b)| { + a.closed == b.closed + && a.anchors.len() == b.anchors.len() + && a.anchors.iter().zip(&b.anchors).all(|(p, q)| (p.p - q.p).hypot() < 1e-3) + }) + }); + assert!(same, "{case}\n{got:?}\n{want:?}"); +} + +/// A clipping object that isn't written as an object of its own (a group, an image, a symbol +/// instance, a path or compound path without paint in art cut to a clipping object) or is written +/// as its outlines or cut (type, a path the outer clipping object cuts) keeps its text wrap options on one unpainted object +/// of its wrap outline: area type below it wraps alike after a round trip, and the object stays +/// locked or hidden as it was. A clipping object without options gets no such object. +#[test] +fn a_clipping_object_not_written_whole_keeps_its_text_wrap() { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + let cases = ["group", "hidden", "locked", "image", "instance", "type", "unpainted path", "unpainted compound", "cut path", "no options"]; + for case in cases { + let mut doc = Document::new(400.0, 200.0); + let layer = doc.layers[0].id; + let st = style(10.0, Color::BLACK); + let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone()); + area.runs = vec![TextRun::new("One two three four five six", st)]; + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 200.0)) }; + area.xf = Affine::IDENTITY; + let area = text_node(&mut doc, area); + doc.insert(Some(layer), usize::MAX, area).unwrap(); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) }); + let mut cutter = match case { + "group" | "hidden" | "locked" | "no options" => { + let mut off = square(&mut doc, Rect::new(200.0, 20.0, 230.0, 60.0), Color::gray(0.5)); + off.visible = false; + let members = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), + square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)), + off, + ]; + group(&mut doc, members, false) + } + "image" => image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([20.0, 0.0, 0.0, 20.0, 30.0, 40.0]), None), + "instance" => instance(&mut doc, "Leaf", Affine::translate((40.0, 30.0))), + "type" => { + let label = TextObject::point(vectorcraft_geom::Point::new(30.0, 50.0), "Clip", style(24.0, Color::BLACK)); + text_node(&mut doc, label) + } + "unpainted path" => clipping(&mut doc, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0))), + "unpainted compound" => { + let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::default()); + Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd }) + } + _ => { + let mut c = clipping(&mut doc, shapes::rectangle(Rect::new(50.0, 20.0, 150.0, 80.0))); + c.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into(); + c + } + }; + cutter.visible = case != "hidden"; + cutter.locked = case == "locked"; + let cutter = if case == "no options" { cutter } else { wrapped(cutter, -4.5, true) }; + let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let mut top = group(&mut doc, vec![cutter, member], true); + if matches!(case, "unpainted path" | "unpainted compound" | "cut path") { + let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9)); + let frame = group(&mut doc, vec![frame], false); + top = group(&mut doc, vec![frame, top], true); + } + doc.insert(Some(layer), usize::MAX, top).unwrap(); + let text = program(&doc); + let back = read_back(&doc); + if case == "no options" { + assert!(!text.contains("(AI11TextWrapOffset)"), "{text}"); + assert!(wraps(back.layers[0].children().unwrap()).is_empty()); + continue; + } + assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{case}\n{text}"); + same_wraps(&wraps(back.layers[0].children().unwrap()), &[(None, -4.5, true)]); + let mut carrier = None; + back.layers[0].walk(&mut |n| { + if n.extras().wrap.is_some() { + carrier = Some((n.locked, n.visible)); + } + }); + assert_eq!(carrier, Some((case == "locked", case != "hidden")), "{case}"); + let want = area_wrap(&doc); + assert_eq!(want.is_empty(), case == "hidden", "{case}"); + same_shapes(&area_wrap(&back), &want, case); + } +} + +/// With too little room for the unpainted object that carries a clipping object's text wrap +/// options, the options are left out, never written on another object, and the data stays readable. +#[test] +fn a_clipping_objects_text_wrap_is_left_out_without_room() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let members = vec![ + square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), + square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)), + ]; + let cutter = wrapped(group(&mut doc, members, false), 2.0, false); + let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0)); + let top = group(&mut doc, vec![cutter, member], true); + doc.insert(Some(layer), usize::MAX, top).unwrap(); + let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + for room in 0..=all { + let out = export_within(&doc, &opts(), room).unwrap(); + assert!(crate::import::objects_read(&out.program).unwrap() <= room); + let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n"); + // The group, then the compound path of the two squares (three objects): with room for all four + // the options are written, on that compound path. + assert_eq!(text.matches("(AI11TextWrapOffset)").count(), usize::from(room >= 4), "{room}\n{text}"); + let (back, _) = crate::ai_alone(&out.program).unwrap(); + let mut carriers = vec![]; + back.layers[0].walk(&mut |n| { + if n.extras().wrap.is_some() { + carriers.push(matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty()); + } + }); + assert_eq!(carriers, if room >= 4 { vec![true] } else { vec![] }, "{room}\n{text}"); + } +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 765856753c..c77d9d354d 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -1041,16 +1041,15 @@ impl<'a> Writer<'a> { /// A container's members, the first one's outline cutting the others: its fills painted /// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text - /// wrap options are written once: with its fills, or without fills with its strokes. + /// wrap options are written once, under them all ([`Self::wrap_carrier`]). fn clip_contents(&mut self, children: &[Arc]) { let Some((first, rest)) = children.split_first() else { return }; + self.wrap_carrier(first); // Nothing to clip by hides the clipped art. let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return }; let mut paint = first.clip_paint(); - if let (Some(_), Some(stroke)) = (&paint.fill, &mut paint.stroke) - && stroke.extras().wrap.is_some() - { - stroke.extras_mut().wrap = None; + for part in [&mut paint.fill, &mut paint.stroke].into_iter().flatten() { + part.extras_mut().wrap = None; } let outer = self.clip.clone(); let region = self.cut(&PathData::from_bezpath(&outline), rule); @@ -1067,6 +1066,28 @@ impl<'a> Writer<'a> { } } + /// The text wrap options of clipping object `first`, when it has them, on an unpainted path + /// (a compound path for several subpaths) of the outline area type wraps around + /// ([`vectorcraft_doc::text::wrap_outline`]), uncut, locked and hidden as `first` is. Nothing is + /// written for an empty outline or without room for the path ([`Self::take_objects`]). + fn wrap_carrier(&mut self, first: &Node) { + let Some(wrap) = first.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return }; + let outline = vectorcraft_doc::text::wrap_outline(first); + if outline.is_empty() { + return; + } + self.state(first.locked, !first.visible); + let start = self.body.len(); + self.plain_object(&outline, FillRule::NonZero, None, None, Xy::of(first).object()); + if self.body.len() == start { + return; + } + self.block_end = usize::MAX; + self.body.push_str("%_/ArtDictionary :\n"); + self.text_wrap(wrap); + self.body.push_str("%_;\n%_\n"); + } + /// `path` (filled by `rule`) cut to the region the art is cut to, as a non-zero path. fn cut(&self, path: &PathData, rule: FillRule) -> PathData { match &self.clip { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7e36c7f318..b7a72fca0a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1671,6 +1671,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes point type, area type and type on a path as type in its editing copy, and objects next to it keep their own transparency (`crates/eps/src/ai_editing/tests.rs`, `cmd::fileio::tests_pdfedit::type_comes_back_from_the_editing_copy`; [file-format-parity.md](file-format-parity.md) lists what is written as outlines). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps the document's variables, data sets and the bindings of objects to variables in its editing copy, in the form the variable library reader above reads, so they come back when the file is opened. Bindings to layers, to type written as outlines, to graphs and to linked images written as other objects, data set values of graphs, and variables, data sets, bindings and values past the writer's limits are left out with a warning (#6024; `crates/eps/src/ai_editing/tests.rs` `variables_data_sets_and_bindings_are_read_back`; `crates/eps/src/ai_editing/writer/variables.rs` lists what is left out). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps each wrap object's Text Wrap Options in its editing copy: the Offset, positive or negative, and Invert Wrap ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/wrap-or-unwrap-text-around-objects.html)), in the form the `.ai` reader reads them (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so they come back when the file is opened. An offset past the -1000 to 1000 pt the reader keeps is written as the nearer end of that range. On a large canvas the offset is written at the art's scale and comes back at its size. Art the writer draws for an object, such as a blend's steps or a symbol instance written as its art, has only that object's options, and a clipping path written as its fills and its strokes has its options once (`crates/eps/src/ai_editing/tests.rs` `text_wrap_options_are_written_and_read_back`, `drawn_art_keeps_only_its_objects_text_wrap`, `text_wrap_offsets_on_a_large_canvas_come_back_at_their_size`, `text_wrap_options_of_type_and_envelopes_are_read_back`, `a_clipping_path_written_as_its_paint_keeps_one_text_wrap`). + A clipping object whose clipped art is written cut to it (a group, an image, a symbol instance, type, or a path or compound path inside art cut to another clipping object) keeps its Text Wrap Options in the editing copy on an unpainted path, or compound path, of the outline area type wraps around, under the art it clips and locked or hidden as the object is. The `.ai` reader reads an unpainted path (`paint` in `crates/eps/src/import/ai/read/art.rs`) and gives it the options of the dictionary after it (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so area type below the object wraps the same way when the file is opened. Without room for that path under the object limit, the options are left out (`crates/eps/src/ai_editing/tests.rs` `a_clipping_object_not_written_whole_keeps_its_text_wrap`, `a_clipping_objects_text_wrap_is_left_out_without_room`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). From 78fa34fb05198d316736b7d77127377075ed11c5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 06:19:22 -0800 Subject: [PATCH 10/77] i18n: drop script error rows that main already translates The cs, fr, ko, nl and zh-hant catalogs had the same script interpreter error messages twice after merging main; the rows from main stay. --- crates/ui-egui/src/i18n/cs.tsv | 13 ------------- crates/ui-egui/src/i18n/fr.tsv | 13 ------------- crates/ui-egui/src/i18n/ko.tsv | 13 ------------- crates/ui-egui/src/i18n/nl.tsv | 13 ------------- crates/ui-egui/src/i18n/zh-hant.tsv | 13 ------------- 5 files changed, 65 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 203dd747c5..c9eece9d66 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4629,19 +4629,6 @@ imageTrace Outline Obrys @msg $.evalFile requires a file path $.evalFile vyžaduje cestu k souboru @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: časový limit musí být konečný počet milisekund, 0 nebo více @msg $.evalFile: takes a file path and a timeout $.evalFile: přijímá cestu k souboru a časový limit -@msg assignment to a constant binding přiřazení do konstantní vazby -@msg invalid array length neplatná délka pole -@msg array literal too long literál pole je příliš dlouhý -@msg the value is not a function hodnota není funkce -@msg apply was called on a value that is not a function apply bylo voláno na hodnotě, která není funkcí -@msg the argument list is not an object seznam argumentů není objekt -@msg too many arguments příliš mnoho argumentů -@msg the value is not a constructor hodnota není konstruktor -@msg cannot convert the object to a primitive value objekt nelze převést na primitivní hodnotu -@msg cannot convert undefined or null to an object undefined ani null nelze převést na objekt -@msg the right side of 'in' is not an object pravá strana 'in' není objekt -@msg the right side of 'instanceof' is not a function pravá strana 'instanceof' není funkce -@msg the function's prototype is not an object prototyp funkce není objekt @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3feaa001ac..4e540b1e76 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4307,19 +4307,6 @@ axis Both Les deux @msg $.evalFile requires a file path $.evalFile nécessite un chemin de fichier @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile : le délai doit être un nombre fini de millisecondes, 0 ou plus @msg $.evalFile: takes a file path and a timeout $.evalFile : prend un chemin de fichier et un délai -@msg assignment to a constant binding affectation à une liaison constante -@msg invalid array length longueur de tableau non valide -@msg array literal too long littéral de tableau trop long -@msg the value is not a function la valeur n'est pas une fonction -@msg apply was called on a value that is not a function apply a été appelé sur une valeur qui n'est pas une fonction -@msg the argument list is not an object la liste d'arguments n'est pas un objet -@msg too many arguments trop d'arguments -@msg the value is not a constructor la valeur n'est pas un constructeur -@msg cannot convert the object to a primitive value impossible de convertir l'objet en valeur primitive -@msg cannot convert undefined or null to an object impossible de convertir undefined ou null en objet -@msg the right side of 'in' is not an object le côté droit de 'in' n'est pas un objet -@msg the right side of 'instanceof' is not a function le côté droit de 'instanceof' n'est pas une fonction -@msg the function's prototype is not an object le prototype de la fonction n'est pas un objet @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 73be60f1db..c3a70e7ded 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5062,19 +5062,6 @@ theme Appearance 외관 @msg $.evalFile requires a file path $.evalFile에는 파일 경로가 필요합니다 @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: 시간 제한은 0 이상의 유한한 밀리초 수여야 합니다 @msg $.evalFile: takes a file path and a timeout $.evalFile: 파일 경로와 시간 제한을 받습니다 -@msg assignment to a constant binding 상수 바인딩에 대입했습니다 -@msg invalid array length 배열 길이가 잘못되었습니다 -@msg array literal too long 배열 리터럴이 너무 깁니다 -@msg the value is not a function 값이 함수가 아닙니다 -@msg apply was called on a value that is not a function 함수가 아닌 값에 apply가 호출되었습니다 -@msg the argument list is not an object 인수 목록이 객체가 아닙니다 -@msg too many arguments 인수가 너무 많습니다 -@msg the value is not a constructor 값이 생성자가 아닙니다 -@msg cannot convert the object to a primitive value 객체를 원시 값으로 변환할 수 없습니다 -@msg cannot convert undefined or null to an object undefined 또는 null을 객체로 변환할 수 없습니다 -@msg the right side of 'in' is not an object 'in'의 오른쪽이 객체가 아닙니다 -@msg the right side of 'instanceof' is not a function 'instanceof'의 오른쪽이 함수가 아닙니다 -@msg the function's prototype is not an object 함수의 프로토타입이 객체가 아닙니다 @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 13437b5826..71a7fed28d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -91,19 +91,6 @@ @msg $.evalFile requires a file path $.evalFile vereist een bestandspad @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: de time-out moet een eindig aantal milliseconden zijn, 0 of meer @msg $.evalFile: takes a file path and a timeout $.evalFile: verwacht een bestandspad en een time-out -@msg assignment to a constant binding toewijzing aan een constante binding -@msg invalid array length ongeldige arraylengte -@msg array literal too long de arrayliteral is te lang -@msg the value is not a function de waarde is geen functie -@msg apply was called on a value that is not a function apply is aangeroepen op een waarde die geen functie is -@msg the argument list is not an object de argumentenlijst is geen object -@msg too many arguments te veel argumenten -@msg the value is not a constructor de waarde is geen constructor -@msg cannot convert the object to a primitive value het object kan niet worden omgezet in een primitieve waarde -@msg cannot convert undefined or null to an object undefined of null kan niet worden omgezet in een object -@msg the right side of 'in' is not an object de rechterkant van 'in' is geen object -@msg the right side of 'instanceof' is not a function de rechterkant van 'instanceof' is geen functie -@msg the function's prototype is not an object het prototype van de functie is geen object @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1d9bee9f4f..311b84809b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2529,19 +2529,6 @@ file-filter Templates 範本 @msg $.evalFile requires a file path $.evalFile 需要檔案路徑 @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile:逾時必須是 0 或更大的有限毫秒數 @msg $.evalFile: takes a file path and a timeout $.evalFile:接受一個檔案路徑和一個逾時值 -@msg assignment to a constant binding 對常數繫結賦值 -@msg invalid array length 陣列長度無效 -@msg array literal too long 陣列常值過長 -@msg the value is not a function 值不是函式 -@msg apply was called on a value that is not a function 對不是函式的值呼叫了 apply -@msg the argument list is not an object 引數清單不是物件 -@msg too many arguments 引數過多 -@msg the value is not a constructor 值不是建構函式 -@msg cannot convert the object to a primitive value 無法將物件轉換為基本值 -@msg cannot convert undefined or null to an object 無法將 undefined 或 null 轉換為物件 -@msg the right side of 'in' is not an object 'in' 的右側不是物件 -@msg the right side of 'instanceof' is not a function 'instanceof' 的右側不是函式 -@msg the function's prototype is not an object 函式的原型不是物件 @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} From e4a7d419cc9c3a93ddd1ccf7d32e5ed443433d64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 07:51:01 -0800 Subject: [PATCH 11/77] i18n: script identifiers in error messages stay as written The not-defined and function-declaration errors name the identifier with an {ident} placeholder, whose value is never translated, so a script name that matches another message (such as damaged) is shown unchanged. --- crates/js/src/interp.rs | 8 ++++---- crates/ui-egui/src/i18n.rs | 7 ++++--- crates/ui-egui/src/i18n/ca.tsv | 4 ++-- crates/ui-egui/src/i18n/cs.tsv | 4 ++-- crates/ui-egui/src/i18n/de.tsv | 4 ++-- crates/ui-egui/src/i18n/el.tsv | 4 ++-- crates/ui-egui/src/i18n/es.tsv | 4 ++-- crates/ui-egui/src/i18n/fi.tsv | 4 ++-- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- crates/ui-egui/src/i18n/hi.tsv | 4 ++-- crates/ui-egui/src/i18n/hu.tsv | 4 ++-- crates/ui-egui/src/i18n/it.tsv | 4 ++-- crates/ui-egui/src/i18n/ja.tsv | 4 ++-- crates/ui-egui/src/i18n/ka.tsv | 4 ++-- crates/ui-egui/src/i18n/ko.tsv | 4 ++-- crates/ui-egui/src/i18n/nl.tsv | 4 ++-- crates/ui-egui/src/i18n/pl.tsv | 4 ++-- crates/ui-egui/src/i18n/pt-br.tsv | 4 ++-- crates/ui-egui/src/i18n/ru.tsv | 4 ++-- crates/ui-egui/src/i18n/sv.tsv | 4 ++-- crates/ui-egui/src/i18n/tests.rs | 6 ++++-- crates/ui-egui/src/i18n/tr.tsv | 4 ++-- crates/ui-egui/src/i18n/uk.tsv | 4 ++-- crates/ui-egui/src/i18n/vi.tsv | 4 ++-- crates/ui-egui/src/i18n/zh-hans.tsv | 4 ++-- crates/ui-egui/src/i18n/zh-hant.tsv | 4 ++-- 26 files changed, 58 insertions(+), 55 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 4d814828a1..a6c329155f 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1081,8 +1081,8 @@ impl Interp { } fn not_defined(&mut self, name: &[u16]) -> Abrupt { - let name = String::from_utf16_lossy(name); - self.throw(ErrorType::Reference, &format!("{name} is not defined")) + let ident = String::from_utf16_lossy(name); + self.throw(ErrorType::Reference, &format!("{ident} is not defined")) } fn get_var(&mut self, name: &Key) -> JsResult<(Value, Value)> { @@ -2587,8 +2587,8 @@ impl Interp { self.put(object, name.clone(), v, true) } Some(_) => { - let name = String::from_utf16_lossy(name); - Err(self.type_error(&format!("cannot declare function {name}"))) + let ident = String::from_utf16_lossy(name); + Err(self.type_error(&format!("cannot declare function {ident}"))) } } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 63e214dbf7..1c5b0e3e1b 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -682,8 +682,9 @@ const MESSAGE_DEPTH: usize = 5; /// Translate a status or error message for display (see the module docs). Unknown messages, and /// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as /// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”`, `'…'` or backticks, such as a -/// symbol's or a script property's name), stay as they are. A part that starts with `{` or `[` is translated only -/// when it is a whole message with an exact entry, such as `[x, y] (two numbers)`. +/// symbol's or a script property's name, and an `{ident}` placeholder's value, a script identifier), +/// stay as they are. A part that starts with `{` or `[` is translated only when it is a whole +/// message with an exact entry, such as `[x, y] (two numbers)`. pub fn message(lang: Lang, s: &str) -> String { message_at(lang, s, MESSAGE_DEPTH) } @@ -703,7 +704,7 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { message_at(lang, v, depth - 1) } }; - let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, nested(v))).collect(); + let values: Vec<(&str, String)> = caps.into_iter().map(|(k, v)| (k, if k == "ident" { v.to_string() } else { nested(v) })).collect(); let args: Vec<(&str, &str)> = values.iter().map(|(k, v)| (*k, v.as_str())).collect(); fill_once(template, &args) } diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 23b6a1b6ad..fddf62b897 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5543,7 +5543,7 @@ digits Malayalam Malaiàlam @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} no està definit +@msg {ident} is not defined {ident} no està definit @msg cannot read property '{key}' of {base} no es pot llegir la propietat '{key}' de {base} @msg cannot set property '{key}' of {base} no es pot establir la propietat '{key}' de {base} @msg cannot read a property of {base} no es pot llegir cap propietat de {base} @@ -5551,7 +5551,7 @@ digits Malayalam Malaiàlam @msg cannot define property '{key}': {why} no es pot definir la propietat '{key}': {why} @msg cannot assign to property '{key}': {why} no es pot assignar a la propietat '{key}': {why} @msg cannot delete property '{key}' no es pot suprimir la propietat '{key}' -@msg cannot declare function {name} no es pot declarar la funció {name} +@msg cannot declare function {ident} no es pot declarar la funció {ident} @msg invalid assignment target destinació d'assignació no vàlida @msg the array's length is read-only la longitud de la matriu és només de lectura @msg the property cannot be redefined la propietat no es pot redefinir diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0e4ccb9c2f..bfb053a1f6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4636,7 +4636,7 @@ imageTrace Outline Obrys @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} není definováno +@msg {ident} is not defined {ident} není definováno @msg cannot read property '{key}' of {base} nelze číst vlastnost '{key}' hodnoty {base} @msg cannot set property '{key}' of {base} nelze nastavit vlastnost '{key}' hodnoty {base} @msg cannot read a property of {base} nelze číst vlastnost hodnoty {base} @@ -4644,7 +4644,7 @@ imageTrace Outline Obrys @msg cannot define property '{key}': {why} nelze definovat vlastnost '{key}': {why} @msg cannot assign to property '{key}': {why} nelze přiřadit do vlastnosti '{key}': {why} @msg cannot delete property '{key}' nelze odstranit vlastnost '{key}' -@msg cannot declare function {name} nelze deklarovat funkci {name} +@msg cannot declare function {ident} nelze deklarovat funkci {ident} @msg invalid assignment target neplatný cíl přiřazení @msg the array's length is read-only délka pole je jen pro čtení @msg the property cannot be redefined vlastnost nelze znovu definovat diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 307c0d86a4..fc6674d64a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4248,7 +4248,7 @@ theme Appearance Erscheinungsbild @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} ist nicht definiert +@msg {ident} is not defined {ident} ist nicht definiert @msg cannot read property '{key}' of {base} die Eigenschaft '{key}' von {base} kann nicht gelesen werden @msg cannot set property '{key}' of {base} die Eigenschaft '{key}' von {base} kann nicht gesetzt werden @msg cannot read a property of {base} eine Eigenschaft von {base} kann nicht gelesen werden @@ -4256,7 +4256,7 @@ theme Appearance Erscheinungsbild @msg cannot define property '{key}': {why} die Eigenschaft '{key}' kann nicht definiert werden: {why} @msg cannot assign to property '{key}': {why} der Eigenschaft '{key}' kann nichts zugewiesen werden: {why} @msg cannot delete property '{key}' die Eigenschaft '{key}' kann nicht gelöscht werden -@msg cannot declare function {name} die Funktion {name} kann nicht deklariert werden +@msg cannot declare function {ident} die Funktion {ident} kann nicht deklariert werden @msg invalid assignment target ungültiges Zuweisungsziel @msg the array's length is read-only die Länge des Arrays ist schreibgeschützt @msg the property cannot be redefined die Eigenschaft kann nicht neu definiert werden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7536674e15..89259ad173 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2407,7 +2407,7 @@ axis Both Και τα δύο @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined το {name} δεν έχει οριστεί +@msg {ident} is not defined το {ident} δεν έχει οριστεί @msg cannot read property '{key}' of {base} δεν είναι δυνατή η ανάγνωση της ιδιότητας '{key}' του {base} @msg cannot set property '{key}' of {base} δεν είναι δυνατός ο ορισμός της ιδιότητας '{key}' του {base} @msg cannot read a property of {base} δεν είναι δυνατή η ανάγνωση ιδιότητας του {base} @@ -2415,7 +2415,7 @@ axis Both Και τα δύο @msg cannot define property '{key}': {why} δεν είναι δυνατός ο καθορισμός της ιδιότητας '{key}': {why} @msg cannot assign to property '{key}': {why} δεν είναι δυνατή η ανάθεση στην ιδιότητα '{key}': {why} @msg cannot delete property '{key}' δεν είναι δυνατή η διαγραφή της ιδιότητας '{key}' -@msg cannot declare function {name} δεν είναι δυνατή η δήλωση της συνάρτησης {name} +@msg cannot declare function {ident} δεν είναι δυνατή η δήλωση της συνάρτησης {ident} @msg invalid assignment target μη έγκυρος στόχος ανάθεσης @msg the array's length is read-only το μήκος του πίνακα είναι μόνο για ανάγνωση @msg the property cannot be redefined η ιδιότητα δεν μπορεί να οριστεί ξανά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 38b87d973a..82dae7fe08 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4338,7 +4338,7 @@ axis Both Ambos @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} no está definido +@msg {ident} is not defined {ident} no está definido @msg cannot read property '{key}' of {base} no se puede leer la propiedad '{key}' de {base} @msg cannot set property '{key}' of {base} no se puede establecer la propiedad '{key}' de {base} @msg cannot read a property of {base} no se puede leer una propiedad de {base} @@ -4346,7 +4346,7 @@ axis Both Ambos @msg cannot define property '{key}': {why} no se puede definir la propiedad '{key}': {why} @msg cannot assign to property '{key}': {why} no se puede asignar a la propiedad '{key}': {why} @msg cannot delete property '{key}' no se puede eliminar la propiedad '{key}' -@msg cannot declare function {name} no se puede declarar la función {name} +@msg cannot declare function {ident} no se puede declarar la función {ident} @msg invalid assignment target destino de asignación no válido @msg the array's length is read-only la longitud del array es de solo lectura @msg the property cannot be redefined la propiedad no se puede redefinir diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 3a3d25548b..0ececd03ce 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4563,7 +4563,7 @@ imageTrace Outline Ääriviiva @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} ei ole määritelty +@msg {ident} is not defined {ident} ei ole määritelty @msg cannot read property '{key}' of {base} arvon {base} ominaisuutta '{key}' ei voi lukea @msg cannot set property '{key}' of {base} arvon {base} ominaisuutta '{key}' ei voi asettaa @msg cannot read a property of {base} arvon {base} ominaisuutta ei voi lukea @@ -4571,7 +4571,7 @@ imageTrace Outline Ääriviiva @msg cannot define property '{key}': {why} ominaisuutta '{key}' ei voi määrittää: {why} @msg cannot assign to property '{key}': {why} ominaisuuteen '{key}' ei voi sijoittaa: {why} @msg cannot delete property '{key}' ominaisuutta '{key}' ei voi poistaa -@msg cannot declare function {name} funktiota {name} ei voi esitellä +@msg cannot declare function {ident} funktiota {ident} ei voi esitellä @msg invalid assignment target virheellinen sijoituksen kohde @msg the array's length is read-only taulukon pituus on vain luku @msg the property cannot be redefined ominaisuutta ei voi määrittää uudelleen diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8dd764e351..f14ccae052 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4314,7 +4314,7 @@ axis Both Les deux @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} n'est pas défini +@msg {ident} is not defined {ident} n'est pas défini @msg cannot read property '{key}' of {base} impossible de lire la propriété '{key}' de {base} @msg cannot set property '{key}' of {base} impossible de modifier la propriété '{key}' de {base} @msg cannot read a property of {base} impossible de lire une propriété de {base} @@ -4322,7 +4322,7 @@ axis Both Les deux @msg cannot define property '{key}': {why} impossible de définir la propriété '{key}' : {why} @msg cannot assign to property '{key}': {why} impossible d'affecter la propriété '{key}' : {why} @msg cannot delete property '{key}' impossible de supprimer la propriété '{key}' -@msg cannot declare function {name} impossible de déclarer la fonction {name} +@msg cannot declare function {ident} impossible de déclarer la fonction {ident} @msg invalid assignment target cible d'affectation non valide @msg the array's length is read-only la longueur du tableau est en lecture seule @msg the property cannot be redefined la propriété ne peut pas être redéfinie diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 5cb65d9639..572cae346c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6655,7 +6655,7 @@ antiAlias Sharp शार्प @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} परिभाषित नहीं है +@msg {ident} is not defined {ident} परिभाषित नहीं है @msg cannot read property '{key}' of {base} {base} की प्रॉपर्टी '{key}' पढ़ी नहीं जा सकती @msg cannot set property '{key}' of {base} {base} की प्रॉपर्टी '{key}' सेट नहीं की जा सकती @msg cannot read a property of {base} {base} की कोई प्रॉपर्टी पढ़ी नहीं जा सकती @@ -6663,7 +6663,7 @@ antiAlias Sharp शार्प @msg cannot define property '{key}': {why} प्रॉपर्टी '{key}' परिभाषित नहीं की जा सकती: {why} @msg cannot assign to property '{key}': {why} प्रॉपर्टी '{key}' को मान नहीं दिया जा सकता: {why} @msg cannot delete property '{key}' प्रॉपर्टी '{key}' हटाई नहीं जा सकती -@msg cannot declare function {name} फ़ंक्शन {name} घोषित नहीं किया जा सकता +@msg cannot declare function {ident} फ़ंक्शन {ident} घोषित नहीं किया जा सकता @msg invalid assignment target मान देने का लक्ष्य अमान्य है @msg the array's length is read-only ऐरे की लंबाई केवल-पठन है @msg the property cannot be redefined प्रॉपर्टी को फिर से परिभाषित नहीं किया जा सकता diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 239caad1e0..19eaedeccc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5150,7 +5150,7 @@ imageTrace Outline Körvonal @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} nincs definiálva +@msg {ident} is not defined {ident} nincs definiálva @msg cannot read property '{key}' of {base} a(z) {base} '{key}' tulajdonsága nem olvasható @msg cannot set property '{key}' of {base} a(z) {base} '{key}' tulajdonsága nem állítható be @msg cannot read a property of {base} a(z) {base} tulajdonsága nem olvasható @@ -5158,7 +5158,7 @@ imageTrace Outline Körvonal @msg cannot define property '{key}': {why} a(z) '{key}' tulajdonság nem definiálható: {why} @msg cannot assign to property '{key}': {why} a(z) '{key}' tulajdonságnak nem adható érték: {why} @msg cannot delete property '{key}' a(z) '{key}' tulajdonság nem törölhető -@msg cannot declare function {name} a(z) {name} függvény nem deklarálható +@msg cannot declare function {ident} a(z) {ident} függvény nem deklarálható @msg invalid assignment target érvénytelen értékadási cél @msg the array's length is read-only a tömb hossza csak olvasható @msg the property cannot be redefined a tulajdonság nem definiálható újra diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ccc49cd804..06ab3a97ae 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4377,7 +4377,7 @@ axis Both Entrambi @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} non è definito +@msg {ident} is not defined {ident} non è definito @msg cannot read property '{key}' of {base} impossibile leggere la proprietà '{key}' di {base} @msg cannot set property '{key}' of {base} impossibile impostare la proprietà '{key}' di {base} @msg cannot read a property of {base} impossibile leggere una proprietà di {base} @@ -4385,7 +4385,7 @@ axis Both Entrambi @msg cannot define property '{key}': {why} impossibile definire la proprietà '{key}': {why} @msg cannot assign to property '{key}': {why} impossibile assegnare alla proprietà '{key}': {why} @msg cannot delete property '{key}' impossibile eliminare la proprietà '{key}' -@msg cannot declare function {name} impossibile dichiarare la funzione {name} +@msg cannot declare function {ident} impossibile dichiarare la funzione {ident} @msg invalid assignment target destinazione di assegnazione non valida @msg the array's length is read-only la lunghezza dell'array è di sola lettura @msg the property cannot be redefined la proprietà non può essere ridefinita diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 789e1dc27a..c405960e2b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5155,7 +5155,7 @@ swatch Bright Violet ビビッドバイオレット @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} は定義されていません +@msg {ident} is not defined {ident} は定義されていません @msg cannot read property '{key}' of {base} {base} のプロパティ '{key}' を読み取れません @msg cannot set property '{key}' of {base} {base} のプロパティ '{key}' を設定できません @msg cannot read a property of {base} {base} のプロパティを読み取れません @@ -5163,7 +5163,7 @@ swatch Bright Violet ビビッドバイオレット @msg cannot define property '{key}': {why} プロパティ '{key}' を定義できません: {why} @msg cannot assign to property '{key}': {why} プロパティ '{key}' に代入できません: {why} @msg cannot delete property '{key}' プロパティ '{key}' を削除できません -@msg cannot declare function {name} 関数 {name} を宣言できません +@msg cannot declare function {ident} 関数 {ident} を宣言できません @msg invalid assignment target 代入先が無効です @msg the array's length is read-only 配列の長さは読み取り専用です @msg the property cannot be redefined プロパティは再定義できません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 22c9170d9e..03777a450d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5562,7 +5562,7 @@ imageTrace Outline კონტური @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} არ არის განსაზღვრული +@msg {ident} is not defined {ident} არ არის განსაზღვრული @msg cannot read property '{key}' of {base} {base} მნიშვნელობის თვისება '{key}' ვერ წაიკითხება @msg cannot set property '{key}' of {base} {base} მნიშვნელობის თვისება '{key}' ვერ დაყენდება @msg cannot read a property of {base} {base} მნიშვნელობის თვისება ვერ წაიკითხება @@ -5570,7 +5570,7 @@ imageTrace Outline კონტური @msg cannot define property '{key}': {why} თვისება '{key}' ვერ განისაზღვრება: {why} @msg cannot assign to property '{key}': {why} თვისებას '{key}' მნიშვნელობა ვერ მიენიჭება: {why} @msg cannot delete property '{key}' თვისება '{key}' ვერ წაიშლება -@msg cannot declare function {name} ფუნქცია {name} ვერ გამოცხადდება +@msg cannot declare function {ident} ფუნქცია {ident} ვერ გამოცხადდება @msg invalid assignment target მინიჭების არასწორი სამიზნე @msg the array's length is read-only მასივის სიგრძე მხოლოდ წასაკითხია @msg the property cannot be redefined თვისება ხელახლა ვერ განისაზღვრება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 7836910bf6..066e27cb92 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5069,7 +5069,7 @@ theme Appearance 외관 @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name}이(가) 정의되지 않았습니다 +@msg {ident} is not defined {ident}이(가) 정의되지 않았습니다 @msg cannot read property '{key}' of {base} {base}의 속성 '{key}'을(를) 읽을 수 없습니다 @msg cannot set property '{key}' of {base} {base}의 속성 '{key}'을(를) 설정할 수 없습니다 @msg cannot read a property of {base} {base}의 속성을 읽을 수 없습니다 @@ -5077,7 +5077,7 @@ theme Appearance 외관 @msg cannot define property '{key}': {why} 속성 '{key}'을(를) 정의할 수 없습니다: {why} @msg cannot assign to property '{key}': {why} 속성 '{key}'에 대입할 수 없습니다: {why} @msg cannot delete property '{key}' 속성 '{key}'을(를) 삭제할 수 없습니다 -@msg cannot declare function {name} 함수 {name}을(를) 선언할 수 없습니다 +@msg cannot declare function {ident} 함수 {ident}을(를) 선언할 수 없습니다 @msg invalid assignment target 대입 대상이 잘못되었습니다 @msg the array's length is read-only 배열의 길이는 읽기 전용입니다 @msg the property cannot be redefined 속성을 다시 정의할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index ee629427b9..5c62f10b8b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -98,7 +98,7 @@ @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} is niet gedefinieerd +@msg {ident} is not defined {ident} is niet gedefinieerd @msg cannot read property '{key}' of {base} kan eigenschap '{key}' van {base} niet lezen @msg cannot set property '{key}' of {base} kan eigenschap '{key}' van {base} niet instellen @msg cannot read a property of {base} kan geen eigenschap van {base} lezen @@ -106,7 +106,7 @@ @msg cannot define property '{key}': {why} kan eigenschap '{key}' niet definiëren: {why} @msg cannot assign to property '{key}': {why} kan niet toewijzen aan eigenschap '{key}': {why} @msg cannot delete property '{key}' kan eigenschap '{key}' niet verwijderen -@msg cannot declare function {name} kan functie {name} niet declareren +@msg cannot declare function {ident} kan functie {ident} niet declareren @msg invalid assignment target ongeldig toewijzingsdoel @msg the array's length is read-only de lengte van de array is alleen-lezen @msg the property cannot be redefined de eigenschap kan niet opnieuw worden gedefinieerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0b05001c68..52f6c13b32 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4460,7 +4460,7 @@ imageTrace Outline Kontur @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} nie jest zdefiniowane +@msg {ident} is not defined {ident} nie jest zdefiniowane @msg cannot read property '{key}' of {base} nie można odczytać właściwości '{key}' wartości {base} @msg cannot set property '{key}' of {base} nie można ustawić właściwości '{key}' wartości {base} @msg cannot read a property of {base} nie można odczytać właściwości wartości {base} @@ -4468,7 +4468,7 @@ imageTrace Outline Kontur @msg cannot define property '{key}': {why} nie można zdefiniować właściwości '{key}': {why} @msg cannot assign to property '{key}': {why} nie można przypisać do właściwości '{key}': {why} @msg cannot delete property '{key}' nie można usunąć właściwości '{key}' -@msg cannot declare function {name} nie można zadeklarować funkcji {name} +@msg cannot declare function {ident} nie można zadeklarować funkcji {ident} @msg invalid assignment target nieprawidłowy cel przypisania @msg the array's length is read-only długość tablicy jest tylko do odczytu @msg the property cannot be redefined właściwości nie można zdefiniować ponownie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 46f950f8cb..a4b0c25cf2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5358,7 +5358,7 @@ axis Both Ambos @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} não está definido +@msg {ident} is not defined {ident} não está definido @msg cannot read property '{key}' of {base} não é possível ler a propriedade '{key}' de {base} @msg cannot set property '{key}' of {base} não é possível gravar a propriedade '{key}' de {base} @msg cannot read a property of {base} não é possível ler uma propriedade de {base} @@ -5366,7 +5366,7 @@ axis Both Ambos @msg cannot define property '{key}': {why} não é possível definir a propriedade '{key}': {why} @msg cannot assign to property '{key}': {why} não é possível atribuir à propriedade '{key}': {why} @msg cannot delete property '{key}' não é possível excluir a propriedade '{key}' -@msg cannot declare function {name} não é possível declarar a função {name} +@msg cannot declare function {ident} não é possível declarar a função {ident} @msg invalid assignment target destino de atribuição inválido @msg the array's length is read-only o comprimento do array é somente leitura @msg the property cannot be redefined a propriedade não pode ser redefinida diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 404de27efb..1d62ec9020 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4375,7 +4375,7 @@ axis Both Оба @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} не определено +@msg {ident} is not defined {ident} не определено @msg cannot read property '{key}' of {base} невозможно прочитать свойство '{key}' у {base} @msg cannot set property '{key}' of {base} невозможно задать свойство '{key}' у {base} @msg cannot read a property of {base} невозможно прочитать свойство у {base} @@ -4383,7 +4383,7 @@ axis Both Оба @msg cannot define property '{key}': {why} невозможно определить свойство '{key}': {why} @msg cannot assign to property '{key}': {why} невозможно присвоить значение свойству '{key}': {why} @msg cannot delete property '{key}' невозможно удалить свойство '{key}' -@msg cannot declare function {name} невозможно объявить функцию {name} +@msg cannot declare function {ident} невозможно объявить функцию {ident} @msg invalid assignment target недопустимая цель присваивания @msg the array's length is read-only длина массива доступна только для чтения @msg the property cannot be redefined свойство нельзя переопределить diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4c16cf4c3e..997d5972b8 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4248,7 +4248,7 @@ axis Both Båda @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} är inte definierat +@msg {ident} is not defined {ident} är inte definierat @msg cannot read property '{key}' of {base} det går inte att läsa egenskapen '{key}' för {base} @msg cannot set property '{key}' of {base} det går inte att sätta egenskapen '{key}' för {base} @msg cannot read a property of {base} det går inte att läsa en egenskap för {base} @@ -4256,7 +4256,7 @@ axis Both Båda @msg cannot define property '{key}': {why} det går inte att definiera egenskapen '{key}': {why} @msg cannot assign to property '{key}': {why} det går inte att tilldela egenskapen '{key}': {why} @msg cannot delete property '{key}' det går inte att ta bort egenskapen '{key}' -@msg cannot declare function {name} det går inte att deklarera funktionen {name} +@msg cannot declare function {ident} det går inte att deklarera funktionen {ident} @msg invalid assignment target ogiltigt tilldelningsmål @msg the array's length is read-only arrayens längd är skrivskyddad @msg the property cannot be redefined egenskapen kan inte definieras om diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 017d7b6560..e9046369ce 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3327,7 +3327,7 @@ fn script_interpreter_core_errors_are_translated() { "the right side of 'in' is not an object", "the right side of 'instanceof' is not a function", "the function's prototype is not an object", - "{name} is not defined", + "{ident} is not defined", "cannot read property '{key}' of {base}", "cannot set property '{key}' of {base}", "cannot read a property of {base}", @@ -3335,7 +3335,7 @@ fn script_interpreter_core_errors_are_translated() { "cannot define property '{key}': {why}", "cannot assign to property '{key}': {why}", "cannot delete property '{key}'", - "cannot declare function {name}", + "cannot declare function {ident}", "the array's length is read-only", "the property cannot be redefined", "the object is not extensible", @@ -3355,6 +3355,8 @@ fn script_interpreter_core_errors_are_translated() { let mut lines: Vec<(String, String, Vec<&str>)> = vec![]; for (source, inner, kept) in [ ("nope", "nope is not defined", vec!["nope"]), + // An identifier that is also a message with its own entry stays as written. + ("damaged", "damaged is not defined", vec!["damaged"]), ("null.x", "cannot read property 'x' of null", vec!["'x'", "null"]), ("var u; u['y'] = 1", "cannot set property 'y' of undefined", vec!["'y'", "undefined"]), ("var u; u.y = 1", "cannot set a property of undefined", vec!["undefined"]), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 319051ff66..f21edae945 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4111,7 +4111,7 @@ axis Both Her İkisi @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} tanımlı değil +@msg {ident} is not defined {ident} tanımlı değil @msg cannot read property '{key}' of {base} {base} değerinin '{key}' özelliği okunamıyor @msg cannot set property '{key}' of {base} {base} değerinin '{key}' özelliği ayarlanamıyor @msg cannot read a property of {base} {base} değerinin bir özelliği okunamıyor @@ -4119,7 +4119,7 @@ axis Both Her İkisi @msg cannot define property '{key}': {why} '{key}' özelliği tanımlanamıyor: {why} @msg cannot assign to property '{key}': {why} '{key}' özelliğine atama yapılamıyor: {why} @msg cannot delete property '{key}' '{key}' özelliği silinemiyor -@msg cannot declare function {name} {name} fonksiyonu bildirilemiyor +@msg cannot declare function {ident} {ident} fonksiyonu bildirilemiyor @msg invalid assignment target geçersiz atama hedefi @msg the array's length is read-only dizinin uzunluğu salt okunur @msg the property cannot be redefined özellik yeniden tanımlanamaz diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 65fda3caac..1ea2c2c184 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4361,7 +4361,7 @@ axis Both Обидві @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} не визначено +@msg {ident} is not defined {ident} не визначено @msg cannot read property '{key}' of {base} неможливо прочитати властивість '{key}' у {base} @msg cannot set property '{key}' of {base} неможливо встановити властивість '{key}' у {base} @msg cannot read a property of {base} неможливо прочитати властивість у {base} @@ -4369,7 +4369,7 @@ axis Both Обидві @msg cannot define property '{key}': {why} неможливо визначити властивість '{key}': {why} @msg cannot assign to property '{key}': {why} неможливо присвоїти значення властивості '{key}': {why} @msg cannot delete property '{key}' неможливо видалити властивість '{key}' -@msg cannot declare function {name} неможливо оголосити функцію {name} +@msg cannot declare function {ident} неможливо оголосити функцію {ident} @msg invalid assignment target недійсна ціль присвоєння @msg the array's length is read-only довжина масиву доступна лише для читання @msg the property cannot be redefined властивість не можна перевизначити diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index f8706a0ab0..d474dd825c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4804,7 +4804,7 @@ theme Appearance Giao diện @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} chưa được định nghĩa +@msg {ident} is not defined {ident} chưa được định nghĩa @msg cannot read property '{key}' of {base} không thể đọc thuộc tính '{key}' của {base} @msg cannot set property '{key}' of {base} không thể đặt thuộc tính '{key}' của {base} @msg cannot read a property of {base} không thể đọc thuộc tính của {base} @@ -4812,7 +4812,7 @@ theme Appearance Giao diện @msg cannot define property '{key}': {why} không thể định nghĩa thuộc tính '{key}': {why} @msg cannot assign to property '{key}': {why} không thể gán cho thuộc tính '{key}': {why} @msg cannot delete property '{key}' không thể xóa thuộc tính '{key}' -@msg cannot declare function {name} không thể khai báo hàm {name} +@msg cannot declare function {ident} không thể khai báo hàm {ident} @msg invalid assignment target đích gán không hợp lệ @msg the array's length is read-only độ dài của mảng là chỉ đọc @msg the property cannot be redefined không thể định nghĩa lại thuộc tính diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 14f6ee1545..ab670aebf8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4822,7 +4822,7 @@ imageTrace Outline 轮廓 @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} 未定义 +@msg {ident} is not defined {ident} 未定义 @msg cannot read property '{key}' of {base} 无法读取 {base} 的属性 '{key}' @msg cannot set property '{key}' of {base} 无法设置 {base} 的属性 '{key}' @msg cannot read a property of {base} 无法读取 {base} 的属性 @@ -4830,7 +4830,7 @@ imageTrace Outline 轮廓 @msg cannot define property '{key}': {why} 无法定义属性 '{key}':{why} @msg cannot assign to property '{key}': {why} 无法为属性 '{key}' 赋值:{why} @msg cannot delete property '{key}' 无法删除属性 '{key}' -@msg cannot declare function {name} 无法声明函数 {name} +@msg cannot declare function {ident} 无法声明函数 {ident} @msg invalid assignment target 赋值目标无效 @msg the array's length is read-only 数组的长度是只读的 @msg the property cannot be redefined 属性无法重新定义 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 225ac8e67a..286c873eda 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2536,7 +2536,7 @@ file-filter Templates 範本 @msg SyntaxError: {e} SyntaxError: {e} @msg EvalError: {e} EvalError: {e} @msg URIError: {e} URIError: {e} -@msg {name} is not defined {name} 未定義 +@msg {ident} is not defined {ident} 未定義 @msg cannot read property '{key}' of {base} 無法讀取 {base} 的屬性 '{key}' @msg cannot set property '{key}' of {base} 無法設定 {base} 的屬性 '{key}' @msg cannot read a property of {base} 無法讀取 {base} 的屬性 @@ -2544,7 +2544,7 @@ file-filter Templates 範本 @msg cannot define property '{key}': {why} 無法定義屬性 '{key}':{why} @msg cannot assign to property '{key}': {why} 無法為屬性 '{key}' 賦值:{why} @msg cannot delete property '{key}' 無法刪除屬性 '{key}' -@msg cannot declare function {name} 無法宣告函式 {name} +@msg cannot declare function {ident} 無法宣告函式 {ident} @msg invalid assignment target 賦值目標無效 @msg the array's length is read-only 陣列的長度是唯讀的 @msg the property cannot be redefined 屬性無法重新定義 From a85203c5a7f6055ed503690198719aa1b461e18a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 08:25:37 -0800 Subject: [PATCH 12/77] i18n: an error that quotes an empty property name is translated A placeholder between two of the same quote may take no text, so cannot read property '' of null matches its catalog row. --- crates/ui-egui/src/i18n/catalog.rs | 28 +++++++++++++++++++++------- crates/ui-egui/src/i18n/tests.rs | 1 + 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index f2fab1fcfa..097183b142 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -92,17 +92,19 @@ impl Template { /// The placeholder values if `s` is an instance of this template. fn captures<'a>(&self, s: &'a str) -> Option> { let mut out = Vec::new(); - match_pieces(&self.pieces, s, self.counted, &mut out).then_some(out) + match_pieces(&self.pieces, s, self.counted, &mut out, None).then_some(out) } } /// Match `s` against `pieces`, a placeholder taking the shortest non-empty text that lets the -/// rest match (the last one takes what remains). With `counted`, `{n}` takes only a count. A -/// placeholder that occurs twice takes the same text both times. -fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mut Vec<(&'p str, &'a str)>) -> bool { +/// rest match (the last one takes what remains). A placeholder between two of the same quote +/// (`'{key}'`, `"{key}"` or `` `{key}` ``) may also take no text, as for a property named by the +/// empty string. With `counted`, `{n}` takes only a count. A placeholder that occurs twice takes +/// the same text both times. `before` is the last character of the text piece before `pieces`. +fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mut Vec<(&'p str, &'a str)>, before: Option) -> bool { let Some((first, rest)) = pieces.split_first() else { return s.is_empty() }; match first { - Piece::Text(t) => s.strip_prefix(t.as_str()).is_some_and(|tail| match_pieces(rest, tail, counted, out)), + Piece::Text(t) => s.strip_prefix(t.as_str()).is_some_and(|tail| match_pieces(rest, tail, counted, out, t.chars().last())), Piece::Hole(name) => { let earlier = out.iter().find(|(n, _)| *n == name.as_str()).map(|&(_, v)| v); let fits = |value: &str| (!(counted && name == "n") || value.parse::().is_ok()) && earlier.is_none_or(|e| e == value); @@ -114,7 +116,19 @@ fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mu return true; }; let Piece::Text(next) = next else { return false }; - // Every place the next literal occurs, nearest first (the hole is never empty). + let quoted = before.is_some_and(|q| matches!(q, '\'' | '"' | '`') && next.starts_with(q)); + if quoted + && fits("") + && let Some(tail) = s.strip_prefix(next.as_str()) + { + let mark = out.len(); + out.push((name.as_str(), "")); + if match_pieces(after, tail, counted, out, next.chars().last()) { + return true; + } + out.truncate(mark); + } + // Every other place the next literal occurs, nearest first. let mut from = s.chars().next().map_or(1, char::len_utf8); while let Some(at) = s.get(from..).and_then(|tail| tail.find(next.as_str())).map(|i| i + from) { let (Some(value), Some(tail)) = (s.get(..at), s.get(at + next.len()..)) else { return false }; @@ -124,7 +138,7 @@ fn match_pieces<'p, 'a>(pieces: &'p [Piece], s: &'a str, counted: bool, out: &mu } let mark = out.len(); out.push((name.as_str(), value)); - if match_pieces(after, tail, counted, out) { + if match_pieces(after, tail, counted, out, next.chars().last()) { return true; } out.truncate(mark); diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index e9046369ce..228ebece6e 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3361,6 +3361,7 @@ fn script_interpreter_core_errors_are_translated() { ("var u; u['y'] = 1", "cannot set property 'y' of undefined", vec!["'y'", "undefined"]), ("var u; u.y = 1", "cannot set a property of undefined", vec!["undefined"]), ("null[new Array(300).join('a')]", "cannot read a property of null", vec!["null"]), + ("null['']", "cannot read property '' of null", vec!["''", "null"]), ("null['invalid array length']", "cannot read property 'invalid array length' of null", vec!["'invalid array length'", "null"]), ( "'use strict'; var o = {}; Object.defineProperty(o, 'a', {value: 1}); o.a = 2", From a9b5bcc65658e5154dcbd442e697d99aa8c1ef79 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:45:33 -0800 Subject: [PATCH 13/77] MCP docs: a recolor stores a pie's legend label fill only when given the labels docs/mcp.md said the legend labels' fill on a pie with Legends in Wedges is stored whenever every legend label the command reaches ends up with one fill. The recolor commands also require the legend labels to be among the objects they are given; a recolor of the whole graph leaves the labels the graph's black or white. --- docs/mcp.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index a4d9d625b2..d816c0a46e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -857,8 +857,10 @@ own box when the graph is drawn again, so `paint.setGradientGeom` and the `paint placement they set there. A stroke weight and dashes are stored as the label shows them, also on a label that was scaled. When the characters of labels of one kind change differently, the frontmost label sets what the kind keeps. On a pie with Legends in Wedges whose legend labels have no fill of their own, the legend labels' fill is stored only when -every legend label the command reaches ends up with the same fill. Otherwise they are drawn again in black, or white on -a dark wedge. What they change on a graph's axis lines, tick marks and radar rings is stored as described below. +every legend label the command reaches ends up with the same fill. The recolor commands also need to be given the legend +labels themselves: a recolor given the graph or a group that holds it does not store their fill. When their fill is not +stored, they are drawn again in black, or white on a dark wedge. What these commands change on a graph's axis lines, tick marks +and radar rings is stored as described below. `text.setFormat` without `start` and `end`, on a graph or on its labels, stores the character and paragraph attributes it sets for each kind of label it reaches (value axis numbers, category labels, legend labels), and every label of that From 19f77ef9fc4ad9b36a3ba908ab84bc99abf00b20 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:55:41 -0800 Subject: [PATCH 14/77] i18n: a quoted message value is found at its own place message() kept a placeholder value in English whenever the same text appeared in quotes anywhere in the message, so for a property named like the reason, "cannot assign to property 'it is read-only': it is read-only", the reason after the colon stayed in English. The quote check now looks at the characters around the value's own position. The merge of main left 13 script interpreter rows twice in ja.tsv and hu.tsv, which failed bundled_catalogs_are_consistent. The rows this branch added are removed and main's rows stay. --- crates/ui-egui/src/i18n.rs | 10 ++++++++-- crates/ui-egui/src/i18n/hu.tsv | 13 ------------- crates/ui-egui/src/i18n/ja.tsv | 13 ------------- crates/ui-egui/src/i18n/tests.rs | 6 ++++++ 4 files changed, 14 insertions(+), 28 deletions(-) diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 1c5b0e3e1b..8099711ff5 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -694,9 +694,15 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String { let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::().ok()); let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1))); let Some(template) = forms.get(form) else { return s.to_string() }; - let quoted = |v: &str| [('"', '"'), ('“', '”'), ('\'', '\''), ('`', '`')].iter().any(|(a, b)| s.contains(&format!("{a}{v}{b}"))); + // A value is quoted when quotes surround it at its own place in `s`. The same text quoted at + // another place in `s` (a property named like the reason given for it) does not count. + let quoted = |v: &str| { + let at = (v.as_ptr() as usize).checked_sub(s.as_ptr() as usize); + let Some((before, after)) = at.and_then(|at| Some((s.get(..at)?, s.get(at + v.len()..)?))) else { return false }; + [('"', '"'), ('“', '”'), ('\'', '\''), ('`', '`')].iter().any(|(a, b)| before.ends_with(*a) && after.starts_with(*b)) + }; let nested = |v: &str| { - if depth <= 1 || quoted(v) { + if depth <= 1 || v.is_empty() || quoted(v) { v.to_string() } else if v.starts_with(['{', '[']) { exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string()) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cfa07747f1..812333143e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5130,19 +5130,6 @@ imageTrace Outline Körvonal @msg $.evalFile requires a file path A $.evalFile fájlútvonalat igényel @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: az időkorlátnak véges számú ezredmásodpercnek kell lennie, 0 vagy több @msg $.evalFile: takes a file path and a timeout $.evalFile: egy fájlútvonalat és egy időkorlátot vár -@msg assignment to a constant binding értékadás konstans kötésnek -@msg invalid array length érvénytelen tömbhossz -@msg array literal too long a tömbliterál túl hosszú -@msg the value is not a function az érték nem függvény -@msg apply was called on a value that is not a function az apply olyan értéken lett meghívva, amely nem függvény -@msg the argument list is not an object az argumentumlista nem objektum -@msg too many arguments túl sok argumentum -@msg the value is not a constructor az érték nem konstruktor -@msg cannot convert the object to a primitive value az objektum nem alakítható primitív értékké -@msg cannot convert undefined or null to an object az undefined és a null nem alakítható objektummá -@msg the right side of 'in' is not an object az 'in' jobb oldala nem objektum -@msg the right side of 'instanceof' is not a function az 'instanceof' jobb oldala nem függvény -@msg the function's prototype is not an object a függvény prototípusa nem objektum @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 38281b99e4..5426b39315 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5135,19 +5135,6 @@ swatch Bright Violet ビビッドバイオレット @msg $.evalFile requires a file path $.evalFile にはファイルパスが必要です @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: タイムアウトは 0 以上の有限のミリ秒数にしてください @msg $.evalFile: takes a file path and a timeout $.evalFile: ファイルパスとタイムアウトを指定します -@msg assignment to a constant binding 定数バインディングへの代入です -@msg invalid array length 配列の長さが無効です -@msg array literal too long 配列リテラルが長すぎます -@msg the value is not a function 値は関数ではありません -@msg apply was called on a value that is not a function 関数ではない値に対して apply が呼び出されました -@msg the argument list is not an object 引数リストはオブジェクトではありません -@msg too many arguments 引数が多すぎます -@msg the value is not a constructor 値はコンストラクターではありません -@msg cannot convert the object to a primitive value オブジェクトをプリミティブ値に変換できません -@msg cannot convert undefined or null to an object undefined または null をオブジェクトに変換できません -@msg the right side of 'in' is not an object 'in' の右辺がオブジェクトではありません -@msg the right side of 'instanceof' is not a function 'instanceof' の右辺が関数ではありません -@msg the function's prototype is not an object 関数のプロトタイプがオブジェクトではありません @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 228ebece6e..c86626e998 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3368,6 +3368,12 @@ fn script_interpreter_core_errors_are_translated() { "cannot assign to property 'a': it is read-only", vec!["'a'"], ), + // A property named like the reason: the name stays as written, and the reason is translated. + ( + "'use strict'; var o = {}; Object.defineProperty(o, 'it is read-only', {value: 1}); o['it is read-only'] = 2", + "cannot assign to property 'it is read-only': it is read-only", + vec!["'it is read-only'"], + ), ( "'use strict'; var o = {}; Object.defineProperty(o, 'g', {get: function () { return 1; }}); o.g = 2", "cannot assign to property 'g': it has only a getter", From cc26358b9f6f961286f0423e22ff0a1b3f7ae0ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:05:09 -0800 Subject: [PATCH 15/77] Graphs: an appearance moved to an axis line behind its source is kept Move Appearance captured the cleared source and the targets together, and graph lines are captured in paint order, so a source in front of its target replaced the kept axis rows with its cleared ones. The targets are now captured again after the source. --- crates/engine/src/cmd/appearance.rs | 5 +++-- crates/engine/src/cmd/graph/tests.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index eab6f17fdf..9c810baeef 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -974,8 +974,9 @@ fn transfer(s: &mut Session, p: &Value) -> Result { rows.extend(painted_rows(d, both_kinds(&targets))); let painted = super::graph::capture_series_top_paints(d, &rows); let object = super::graph::capture_series_object_opacity(d, &changed); - // The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. - let labels = super::graph::capture_label_rows(d, &changed); + // The targets last: on two labels of one kind, the target's rows are the ones the kind keeps. Graph lines are + // taken in paint order, so the targets are captured again on their own, after a cleared source in front of them. + let labels = super::graph::capture_label_rows(d, &changed) | super::graph::capture_label_rows(d, &targets); let all: Vec = from.iter().chain(&targets).chain(&group).copied().collect(); Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels)) })?; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 8681442db3..7f516dd58b 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6473,6 +6473,21 @@ fn the_frontmost_axis_line_sets_what_its_recolor_keeps() { assert_eq!(kept.as_deref(), Some("#00ffff"), "the inverted red of the frontmost line"); } +/// An appearance moved from an axis line to one behind it is kept for every axis line, not the cleared source's. +#[test] +fn an_appearance_moved_to_an_axis_line_behind_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + let (back, front) = (lines[0].id, lines[lines.len() - 1].id); + s.execute("paint.setStroke", &json!({"ids": [front.0], "color": "#ff0000"})).unwrap(); + s.execute("appearance.transfer", &json!({"source": front.0, "target": back.0})).unwrap(); + let kept = spec(&s, id).label_styles.axis_rows.unwrap().paint.stroke.and_then(|p| p.color()).map(|c| c.to_hex()); + assert_eq!(kept.as_deref(), Some("#ff0000"), "the moved red, not the cleared source"); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000")); +} + /// A radar graph's spoke brought in front of its rings is still a spoke: what is set on it is kept for the spokes. #[test] fn a_radar_spoke_moved_in_front_of_the_rings_keeps_its_kind() { From 289fb4b7704880f60678e4007c31568b425dfe30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:20:46 -0800 Subject: [PATCH 16/77] Graphs: a pick or added style without transparency keeps the opacity a line or label kind keeps A whole pick of every fill and stroke attribute, or an append pick, onto a graph's axis line, tick mark or radar ring stored the line's rows in full, object opacity and blend mode included, even when the pick did not apply the object's transparency. On a line that still showed 100% until the graph was drawn again, that replaced the opacity its kind kept (40% set on another line became 100%). An append pick onto a graph label, and graphicStyle.apply with add on a label or line, did the same. Without Transparency applied, these picks, and a style added on top, now store the fill and stroke rows and leave the kept object opacity and blend mode as they were. --- crates/engine/src/cmd/appearance.rs | 21 +++--- crates/engine/src/cmd/graph.rs | 9 +-- crates/engine/src/cmd/graph/series.rs | 99 ++++++++++++++++++--------- crates/engine/src/cmd/graph/tests.rs | 86 +++++++++++++++++++++++ crates/engine/src/cmd/style.rs | 11 ++- docs/mcp.md | 13 ++-- 6 files changed, 186 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 9c810baeef..addacdfad6 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows and object opacity and blend mode for every line of its kind (a pick of some attributes without `append`: only what it changes) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: only what it changes) → {ids}", has_doc, copy_from ), @@ -1675,18 +1675,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { let object = super::graph::capture_series_object_opacity(d, &objects); // Graph labels keep their new rows, characters and paragraphs per kind of label. // On type, only `append` adds rows and a transparency pick changes the object's opacity and blend mode; the other - // attributes go to the characters. - let rows = if append { - super::graph::capture_label_rows(d, &targets) - } else { - attrs.appearance.transparency && super::graph::capture_label_object_opacity(d, &targets) + // attributes go to the characters. Without a transparency pick, the object opacity and blend mode a kind keeps stay, + // also when the label or line picked onto still shows other ones until the graph is drawn again. + let transparency = attrs.appearance.transparency; + let rows = match (append, transparency) { + (true, true) => super::graph::capture_label_rows(d, &targets), + (true, false) => super::graph::capture_label_fill_stroke_rows(d, &targets), + (false, _) => transparency && super::graph::capture_label_object_opacity(d, &targets), }; // `append` adds rows and leaves the characters as they were. let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?; // A graph line is a path: a whole pick and `append` write its rows. A pick of some attributes keeps those it // changed, and the rest stay as its kind keeps them, which the line may not show yet. - let lines = - if rows_written { super::graph::capture_line_rows(d, &targets) } else { super::graph::capture_line_changes(&before, d, &targets) }; + let lines = match (rows_written, transparency) { + (true, true) => super::graph::capture_line_rows(d, &targets), + (true, false) => super::graph::capture_line_fill_stroke_rows(d, &targets), + (false, _) => super::graph::capture_line_changes(&before, d, &targets), + }; Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines)) })?; Ok(finish(s, &targets)) diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index e49ff91f04..808b538f3d 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -45,10 +45,11 @@ use generate::generate; #[cfg(test)] use series::default_series_color; pub(crate) use series::{ - LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, - capture_label_styles, capture_label_text, capture_line_changes, capture_line_rows, capture_series_object_opacity, capture_series_opacity, - capture_series_top_paints, is_design_art, is_graph_line, label_object_opacity_differs, labels_in, paint_targets, series_group_marks, - series_group_marks_where, series_marks_in, series_object_opacity_differs, shown_paint, + LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_fill_stroke_rows, capture_label_object_opacity, + capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_text, capture_line_changes, capture_line_fill_stroke_rows, + capture_line_rows, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art, is_graph_line, + label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, + series_object_opacity_differs, shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index cb10be3154..318ba68505 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -732,30 +732,51 @@ fn lines_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, NodeId, Line)> { out } -/// What lines of kind `line` keep (`slot`) after line `n` shows its rows ([`label_rows`]), or with `object_only` what -/// `slot` keeps with the line's object opacity and blend mode: `None` when that is how the graph draws them with no -/// kept rows. -fn line_rows_after(slot: Option<&vectorcraft_doc::LabelRows>, line: Line, n: &Node, object_only: bool) -> Option { +/// Which of the object rows ([`label_rows`]) a graph label or line shows its kind keeps after an edit. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Keep { + /// All of them. + All, + /// Only the object opacity and blend mode; the fill and stroke rows stay as the kind keeps them. + Object, + /// The fill and stroke rows; the object opacity and blend mode stay as the kind keeps them. + Rows, +} + +/// `shown` with the parts of the rows `kept` keeps that `keep` leaves as they are. +fn keep_rows(kept: vectorcraft_doc::LabelRows, shown: vectorcraft_doc::LabelRows, keep: Keep) -> vectorcraft_doc::LabelRows { + match keep { + Keep::All => shown, + Keep::Object => { + let mut kept = kept; + (kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend); + kept + } + Keep::Rows => { + let mut shown = shown; + (shown.paint.opacity, shown.paint.blend) = (kept.paint.opacity, kept.paint.blend); + shown + } + } +} + +/// What lines of kind `line` keep (`slot`) after line `n` shows its rows ([`label_rows`]), of which `keep` says what is +/// taken from the line: `None` when that is how the graph draws them with no kept rows. +fn line_rows_after(slot: Option<&vectorcraft_doc::LabelRows>, line: Line, n: &Node, keep: Keep) -> Option { let shown = label_rows(n).unwrap_or_default(); - let rows = if object_only { - let mut kept = slot.cloned().unwrap_or_else(|| line.default_rows()); - (kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend); - kept - } else { - shown - }; + let rows = keep_rows(slot.cloned().unwrap_or_else(|| line.default_rows()), shown, keep); (rows != line.default_rows()).then_some(rows) } /// Keep the object rows ([`label_rows`]) of the graph lines among `ids` for every line of their kind (axis lines and tick -/// marks, or a radar graph's rings), with `object_only` only their object opacity and blend mode, even when a line -/// already showed them. Returns whether kept rows changed. -fn store_line_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool { +/// marks, or a radar graph's rings), the part of them `keep` says, even when a line already showed them. Returns whether +/// kept rows changed. +fn store_line_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool { let mut changed = false; for (id, graph, line) in lines_of(doc, ids) { let Some(spec) = doc.node(graph).and_then(|n| n.extras().graph.as_deref()) else { continue }; let Some(n) = doc.node(id) else { continue }; - let kept = line_rows_after(kept_line_rows(&spec.label_styles, line), line, n, object_only); + let kept = line_rows_after(kept_line_rows(&spec.label_styles, line), line, n, keep); let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; let slot = line_slot(&mut spec.label_styles, line); changed |= *slot != kept; @@ -768,7 +789,14 @@ fn store_line_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> boo /// for an edit that wrote their fill or stroke. Lines of a kind that the edit reached differently take the frontmost /// one's rows. Called inside the same edit, so they undo together. Returns whether kept rows changed. pub(crate) fn capture_line_rows(doc: &mut Document, ids: &[NodeId]) -> bool { - store_line_rows(doc, ids, false) + store_line_rows(doc, ids, Keep::All) +} + +/// [`capture_line_rows`] for an edit that wrote the fill and stroke rows of graph lines `ids` and left their object +/// opacity and blend mode alone: those stay as the kind keeps them, also when a line still shows other ones until the +/// graph is drawn again. +pub(crate) fn capture_line_fill_stroke_rows(doc: &mut Document, ids: &[NodeId]) -> bool { + store_line_rows(doc, ids, Keep::Rows) } /// Keep, for every line of their kind, the attributes of the object rows ([`label_rows`]) that an edit changed on the @@ -821,8 +849,8 @@ fn merge_row_edits(rows: &mut vectorcraft_doc::LabelRows, old: &vectorcraft_doc: take(&mut rows.stroke_under, &old.stroke_under, &new.stroke_under); } -/// Would [`store_line_rows`] with `object_only` change what a graph keeps for the lines among `ids`? Reads the document -/// without copying it. +/// Would [`store_line_rows`] with [`Keep::Object`] change what a graph keeps for the lines among `ids`? Reads the +/// document without copying it. fn line_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { let mut kept: Vec<(NodeId, Line, Option)> = vec![]; for (id, graph, line) in lines_of(doc, ids) { @@ -831,7 +859,7 @@ fn line_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { Some(i) => kept.swap_remove(i).2, None => kept_line_rows(&spec.label_styles, line).cloned(), }; - kept.push((graph, line, line_rows_after(slot.as_ref(), line, n, true))); + kept.push((graph, line, line_rows_after(slot.as_ref(), line, n, Keep::Object))); } kept.into_iter().any(|(graph, line, rows)| { doc.node(graph).and_then(|n| n.extras().graph.as_deref()).is_some_and(|spec| kept_line_rows(&spec.label_styles, line) != rows.as_ref()) @@ -844,14 +872,22 @@ fn line_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bool { /// looked up. The graph lines among `ids` keep their rows for every line of their kind too ([`capture_line_rows`]). /// Called inside the same edit, so they undo together. Returns whether kept rows changed. pub(crate) fn capture_label_rows(doc: &mut Document, ids: &[NodeId]) -> bool { - store_label_rows(doc, ids, false) + store_label_rows(doc, ids, Keep::All) } /// Keep the object opacity and blend mode of graph labels and graph lines `ids` for every label or line of their kind, as /// [`capture_label_rows`] keeps them, and leave the kept fill and stroke rows as they are. Returns whether what the graph /// keeps changed. pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) -> bool { - store_label_rows(doc, ids, true) + store_label_rows(doc, ids, Keep::Object) +} + +/// Keep the fill and stroke rows of graph labels and graph lines `ids` for every label or line of their kind, as +/// [`capture_label_rows`] keeps them, for an edit that left their object opacity and blend mode alone: those stay as the +/// kind keeps them, also when a label or line still shows other ones until the graph is drawn again. Returns whether what +/// the graph keeps changed. +pub(crate) fn capture_label_fill_stroke_rows(doc: &mut Document, ids: &[NodeId]) -> bool { + store_label_rows(doc, ids, Keep::Rows) } /// Would [`capture_label_object_opacity`] change what a graph keeps for labels `ids`? Reads the document without copying @@ -865,13 +901,13 @@ pub(crate) fn label_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bo Role::Category => &spec.label_styles.categories_rows, Role::Legend => &spec.label_styles.legend_rows, }; - *slot != kept_label_rows(slot, rows, true) + *slot != kept_label_rows(slot, rows, Keep::Object) }) } -/// [`capture_label_rows`], or with `object_only` [`capture_label_object_opacity`]. -fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bool { - let mut changed = store_line_rows(doc, ids, object_only); +/// [`capture_label_rows`], [`capture_label_object_opacity`] or [`capture_label_fill_stroke_rows`], as `keep` says. +fn store_label_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool { + let mut changed = store_line_rows(doc, ids, keep); for (graph, role, rows) in label_rows_of(doc, ids) { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; let slot = match role { @@ -879,26 +915,23 @@ fn store_label_rows(doc: &mut Document, ids: &[NodeId], object_only: bool) -> bo Role::Category => &mut spec.label_styles.categories_rows, Role::Legend => &mut spec.label_styles.legend_rows, }; - let kept = kept_label_rows(slot, rows, object_only); + let kept = kept_label_rows(slot, rows, keep); changed |= *slot != kept; *slot = kept; } changed } -/// What a kind keeps after a label of it shows `rows`: those rows, or with `object_only` what `slot` keeps with the -/// label's object opacity and blend mode. +/// What a kind keeps (`slot`) after a label of it shows `rows`, of which `keep` says what is taken from the label. fn kept_label_rows( slot: &Option, rows: Option, - object_only: bool, + keep: Keep, ) -> Option { - if !object_only { + if keep == Keep::All { return rows; } - let mut kept = slot.clone().unwrap_or_default(); - let shown = rows.unwrap_or_default(); - (kept.paint.opacity, kept.paint.blend) = (shown.paint.opacity, shown.paint.blend); + let kept = keep_rows(slot.clone().unwrap_or_default(), rows.unwrap_or_default(), keep); (kept != vectorcraft_doc::LabelRows::default()).then_some(kept) } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 7f516dd58b..5d734003b2 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6590,6 +6590,92 @@ fn a_transparency_only_pick_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.5).abs() < 1e-6), "{looks:?}"); } +/// The Eyedropper Options that apply every fill and stroke attribute but not the object's transparency. +fn every_row_attribute_without_transparency() -> serde_json::Value { + let fill = json!({"color": true, "transparency": true, "overprint": true}); + let stroke = + json!({"color": true, "transparency": true, "overprint": true, "weight": true, "cap": true, "join": true, "miter": true, "dash": true}); + json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}) +} + +/// An Eyedropper pick of every fill and stroke attribute without the object's transparency, with or without `append`, +/// keeps the object opacity the axis lines keep from another line, though the line it is applied to still shows 100%. +#[test] +fn a_pick_without_transparency_on_an_axis_line_keeps_the_opacity_its_kind_keeps() { + for append in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + let lines = line_nodes(&s, id); + s.execute("transparency.set", &json!({"ids": [lines[0].id.0], "opacity": 40})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).2, 1.0, "append {append}: the other lines show 100% until the graph is drawn again"); + let pick = json!({"source": rect.0, "ids": [lines[1].id.0], "apply": every_row_attribute_without_transparency(), "append": append}); + s.execute("appearance.copyFrom", &pick).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.4).abs() < 1e-6), "append {append}: {looks:?}"); + } +} + +/// A graphic style added on top of a graph label's or axis line's appearance keeps the object opacity its kind keeps +/// from another label or line, though the one it is added to still shows 100%. +#[test] +fn a_graphic_style_added_to_a_label_or_axis_line_keeps_the_opacity_its_kind_keeps() { + for label in [false, true] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + s.execute("graphicStyle.new", &json!({"id": rect.0, "name": "Red"})).unwrap(); + let (first, second) = if label { + (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")) + } else { + let lines = line_nodes(&s, id); + (lines[0].id, lines[1].id) + }; + s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40})).unwrap(); + assert_eq!(s.doc().unwrap().doc.node(second).unwrap().opacity, 1.0, "label {label}: 100% until the graph is drawn again"); + s.execute("graphicStyle.apply", &json!({"name": "Red", "ids": [second.0], "add": true})).unwrap(); + if label { + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, opacity) = rows_of(&looks, q); + assert!((opacity - 0.4).abs() < 1e-6 && rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?} {opacity}"); + } + } else { + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.2 - 0.4).abs() < 1e-6), "{looks:?}"); + } + } +} + +/// An Eyedropper pick with `append` and without the object's transparency on a graph label keeps the object opacity its +/// kind keeps from another label, though the label it is applied to still shows 100%. +#[test] +fn an_appended_pick_without_transparency_on_a_label_keeps_the_opacity_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#ff0000"})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [rect.0], "none": true})).unwrap(); + s.execute("transparency.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0], "opacity": 40})).unwrap(); + let q2 = text_id(&s, id, "Axes", "Q2"); + assert_eq!(s.doc().unwrap().doc.node(q2).unwrap().opacity, 1.0, "Q2 shows 100% until the graph is drawn again"); + let pick = json!({"source": rect.0, "ids": [q2.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, opacity) = rows_of(&looks, q); + assert!((opacity - 0.4).abs() < 1e-6, "{q}: {opacity}"); + assert!(rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?}"); + } +} + /// An edit of some attributes on an axis line that still shows the default stroke keeps what it changes, and the stroke /// its kind keeps from another line stays: a cap is not kept, so it changes nothing the kind keeps. #[test] diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index bdcd759f4a..36716a4905 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -374,8 +374,13 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { super::appearance::clear_stood_for(d, &groups); super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); } - // A label keeps its new rows for its kind of label. - super::graph::capture_label_rows(d, &ids); + // A label or graph line keeps its new rows for its kind. A style added on top leaves the object opacity and blend + // mode, so the kind keeps its own. + if add { + super::graph::capture_label_fill_stroke_rows(d, &ids); + } else { + super::graph::capture_label_rows(d, &ids); + } Ok(()) })?; ok() diff --git a/docs/mcp.md b/docs/mcp.md index d816c0a46e..fece2ab3a3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -874,9 +874,10 @@ kind of label: the paint, weight, opacity and blend mode of its topmost visible their place relative to the Characters row, and the label's object opacity and blend mode. They store them even when the label already showed them. `transparency.set` without an `item`, `object.setProps` with an opacity or blend mode, and an `appearance.copyFrom` (Eyedropper) pick of transparency store only the label's object opacity and blend mode; -`appearance.copyFrom` with `append` stores the rows. When the graph is drawn again, every label of that kind gets what -is stored, with a placed gradient fitted to each label, and the graph saves it as `valuesRows`, `categoriesRows` and -`legendRows` in its label styles. Rows below the topmost one of each kind, a row's effects, other stroke options (caps, +`appearance.copyFrom` with `append` stores the rows, and the object opacity and blend mode only when it also applies +the object's transparency. `graphicStyle.apply` with `add` stores the rows and leaves the object opacity and blend +mode the kind keeps. When the graph is drawn again, every label of that kind gets what is stored, with a placed +gradient fitted to each label, and the graph saves it as `valuesRows`, `categoriesRows` and `legendRows` in its label styles. Rows below the topmost one of each kind, a row's effects, other stroke options (caps, joins, dashes) and effects applied with `effect.*` are not stored. When labels of one kind are edited together, the last one in the order of the targets (`ids` as given, otherwise paint order) sets what the kind keeps. `appearance.copyFrom` onto the whole text of a label also stores the character attributes it applies and, from type, @@ -896,8 +897,10 @@ store only the object opacity and blend mode. `appearance.clear`, `appearance.tr `graphicStyle.redefine`, and `appearance.copyFrom` with every attribute picked up and applied or with `append`, store a line's rows even when the line already showed them. The other commands, an `appearance.copyFrom` of some attributes included, store only what they change on a line's rows; the kind keeps its other attributes, also when the line still -shows different ones until the graph is drawn again. Rows equal to a kind's default stroke (0.5 pt black for axis lines -and tick marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in +shows different ones until the graph is drawn again. An `appearance.copyFrom` that does not apply the object's +transparency, and `graphicStyle.apply` with `add`, leave the object opacity and blend mode a kind keeps as they are, +also when the line still shows other ones. Rows equal to a kind's default stroke (0.5 pt black for axis lines and tick +marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in paint order sets what the kind keeps, whatever order the `ids` are in. A gradient is stored without its placement, and each line fits it when the graph is drawn again. The graph saves the rows as `axisRows` and `ringRows` in its label styles. Other stroke options (caps, joins, miter limit, alignment, dashes and arrowheads), rows below the topmost one of From 69005d7b3ee3fab7643a0a1ee7c55112ed2cc1a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:30:21 -0800 Subject: [PATCH 17/77] Graphs: Default Fill and Stroke on an axis line stores the default rows for its kind Default Fill and Stroke on an axis line, tick mark or radar ring that already shows the default paint now stores the default fill and stroke rows for every line of its kind, so a stroke the kind kept from another line no longer comes back when the graph is drawn again. The object opacity and blend mode the kind keeps stay as they are. --- crates/engine/src/cmd/graph/tests.rs | 17 +++++++++++++++++ crates/engine/src/cmd/paint.rs | 5 ++++- docs/mcp.md | 3 ++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 5d734003b2..ef469f7dd9 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6753,6 +6753,23 @@ fn default_fill_and_stroke_and_fill_to_stroke_on_an_axis_line_are_kept() { assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#0000ff"), "the blue fill on the stroke"); } +/// Default Fill and Stroke on an axis line that already shows the default paint is kept for every axis line, in place of +/// the stroke the kind keeps from another line, and leaves the object opacity the kind keeps from another line. +#[test] +fn default_fill_and_stroke_on_an_axis_line_that_shows_it_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "color": "#ff0000"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [lines[1].id.0], "opacity": 50})).unwrap(); + s.execute("paint.default", &json!({"ids": [lines[0].id.0]})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| (l.0.as_str(), l.1) == ("#000000", 1.0)), "the 1 pt black default stroke: {looks:?}"); + assert!(looks.iter().all(|l| (l.2 - 0.5).abs() < 1e-6), "the kind keeps its 50% opacity: {looks:?}"); +} + #[test] fn pie_names_and_wedge_labels_keep_their_style() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 32e1a8bd38..264d23a737 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1020,7 +1020,10 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); let labels = super::graph::capture_label_changes(&before, d, &ids, false, None); - Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) + // The graph keeps the default fill and stroke rows for every line of a kind it reached, also when one already + // showed them; the object opacity the kind keeps stays. + let lines = super::graph::capture_line_fill_stroke_rows(d, &ids); + Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines)) })?; } super::newart::reset(s); diff --git a/docs/mcp.md b/docs/mcp.md index fece2ab3a3..e32f35ad8e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -899,7 +899,8 @@ line's rows even when the line already showed them. The other commands, an `appe included, store only what they change on a line's rows; the kind keeps its other attributes, also when the line still shows different ones until the graph is drawn again. An `appearance.copyFrom` that does not apply the object's transparency, and `graphicStyle.apply` with `add`, leave the object opacity and blend mode a kind keeps as they are, -also when the line still shows other ones. Rows equal to a kind's default stroke (0.5 pt black for axis lines and tick +also when the line still shows other ones. `paint.default` stores the default fill and stroke rows for a line's kind +even when the line already showed them, and leaves the object opacity and blend mode the kind keeps. Rows equal to a kind's default stroke (0.5 pt black for axis lines and tick marks, 0.25 pt gray for rings) are not saved. When one command reaches several lines of one kind, the frontmost line in paint order sets what the kind keeps, whatever order the `ids` are in. A gradient is stored without its placement, and each line fits it when the graph is drawn again. The graph saves the rows as `axisRows` and `ringRows` in its label From 9d1091331c404a7ce05394335ecaab40a210fd48 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:07:45 -0800 Subject: [PATCH 18/77] Graphs: a reorder that changes no row keeps the line rows its kind keeps A no-op appearance.moveItem on a graph axis line or label replaced the rows its kind keeps with the line's own. The reorder now keeps rows only for the lines and labels whose rows it changed. text.setStyle keeps the default label style for a kind only when the command gives a character attribute; justify-only and empty featureChanges requests record nothing. --- crates/engine/src/cmd/appearance.rs | 4 +- crates/engine/src/cmd/graph.rs | 6 +-- crates/engine/src/cmd/graph/series.rs | 41 +++++++++++++++------ crates/engine/src/cmd/graph/tests.rs | 18 +++++++++ crates/engine/src/cmd/typecmd.rs | 20 +++++++++- crates/engine/src/cmd/typecmd/noop_tests.rs | 28 ++++++++++++++ 6 files changed, 98 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index e5bc8fa97f..796b1ae405 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -1379,7 +1379,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result { } let kept = super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let painted = super::graph::capture_series_top_paints(d, &top_paint_changed(&before, d, &ids)); - let labels = super::graph::capture_label_rows(d, &ids); + let labels = super::graph::capture_label_changes(&before, d, &ids, true); Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) })?; // The moved row stays the active one; the rows it passed shift by one. @@ -1425,7 +1425,7 @@ fn move_items(s: &mut Session, p: &Value, ids: &[NodeId], to: usize) -> Result bool { let mut changed = false; for (graph, role) in label_kinds(doc, ids) { - changed |= store_label_style(doc, graph, role, change); + changed |= store_label_style(doc, graph, role, change, true); + } + changed +} + +/// [`capture_label_styles`], except that a kind that keeps no style keeps the default style when `change` leaves it +/// unchanged, for a command that gives character attributes (a size equal to the labels' own, for example). +pub(crate) fn capture_label_styles_given(doc: &mut Document, ids: &[NodeId], change: &dyn Fn(&mut CharStyle)) -> bool { + let mut changed = false; + for (graph, role) in label_kinds(doc, ids) { + changed |= store_label_style(doc, graph, role, change, false); } changed } /// Apply `change` to the style graph `graph` keeps for its labels of kind `role` (or the default one). A `change` that /// sets the fill of legend labels marks it as set on them, so a black one stays black on dark pie wedges. Returns whether -/// the kept style or that mark changed. A kind that keeps no style and that `change` leaves at the default style keeps -/// none, unless `change` sets the legend fill. -fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle)) -> bool { +/// the kept style or that mark changed. With `unless_default`, a kind that keeps no style and that `change` leaves at +/// the default style keeps none, unless `change` sets the legend fill. +fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Fn(&mut CharStyle), unless_default: bool) -> bool { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { return false }; let was = label_style(&spec.label_styles, role); let mut style = was.clone(); @@ -677,7 +688,7 @@ fn store_label_style(doc: &mut Document, graph: NodeId, role: Role, change: &dyn Role::Category => &mut styles.categories, Role::Legend => &mut styles.legend, }; - if slot.is_none() && style == was && !(sets_fill && !styles.legend_fill_set) { + if unless_default && slot.is_none() && style == was && !(sets_fill && !styles.legend_fill_set) { return false; } let mut changed = slot.as_ref() != Some(&style); @@ -1099,13 +1110,19 @@ pub(crate) fn capture_label_changes(before: &Document, doc: &mut Document, ids: } let mut changed = capture_label_rows(doc, &changed_rows) | lines; for ((graph, role), (style, entries)) in &characters { - changed |= store_label_style(doc, *graph, *role, &|st| { - for i in entries { - if let Some(copy) = RUN_PAINT.get(*i) { - copy(style, st); + changed |= store_label_style( + doc, + *graph, + *role, + &|st| { + for i in entries { + if let Some(copy) = RUN_PAINT.get(*i) { + copy(style, st); + } } - } - }); + }, + true, + ); } changed } diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index c800fb8269..51f78f70fb 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6537,6 +6537,24 @@ fn an_object_opacity_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { } } +/// A reorder that leaves an axis line's rows as they were keeps what its kind keeps from another line and is no edit. +#[test] +fn a_reorder_that_changes_nothing_on_an_axis_line_keeps_the_stroke_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + let stroke = top_row(&s, lines[1].id, false); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("appearance.moveItem", &json!({"ids": [lines[1].id.0], "from": stroke, "to": stroke})).unwrap(); + s.execute("appearance.moveItem", &json!({"ids": [lines[1].id.0], "indices": [stroke], "to": stroke})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); +} + /// An opacity and a stroke weight given to a radar graph's ring are kept for its rings, and its spokes keep their own. #[test] fn transparency_and_stroke_weight_on_a_radar_ring_are_kept_for_its_rings() { diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 05b45cc051..d6c45bb2f0 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -1026,7 +1026,17 @@ fn set_style(s: &mut Session, p: &Value) -> Result { // not in a scaled label's own units). let mut labels_changed = false; if range.is_none() { - labels_changed = super::graph::capture_label_styles(d, &ids, &|st| { + let gives_character = font.is_some() + || style.is_some() + || size.is_some() + || leading.is_some() + || tracking.is_some() + || fill.is_some() + || stroke.is_some() + || !stroke_weight.is_empty() + || features.is_some() + || feature_changes.as_ref().is_some_and(|c| !c.is_empty()); + let change = |st: &mut vectorcraft_doc::CharStyle| { if let Some(f) = &font { st.font_family = f.clone(); st.font_version = None; @@ -1067,7 +1077,13 @@ fn set_style(s: &mut Session, p: &Value) -> Result { if let Some(c) = &feature_changes { st.features = super::textedit::change_features(&st.features, c); } - }); + }; + // A command that gives character attributes keeps the style even when they equal the labels' own. + labels_changed = if gives_character { + super::graph::capture_label_styles_given(d, &ids, &change) + } else { + super::graph::capture_label_styles(d, &ids, &change) + }; } Ok(((), labels_changed)) })?; diff --git a/crates/engine/src/cmd/typecmd/noop_tests.rs b/crates/engine/src/cmd/typecmd/noop_tests.rs index 02481d8bee..b4f5cb2099 100644 --- a/crates/engine/src/cmd/typecmd/noop_tests.rs +++ b/crates/engine/src/cmd/typecmd/noop_tests.rs @@ -102,6 +102,34 @@ fn a_kept_graph_label_style_change_alone_records_one_undo_step() { records_nothing(&mut s, "text.setStyle", p); } +/// `text.setStyle` on a graph label with only `justify`, which the label already has, records no undo step and keeps no +/// character style for its kind of label. +#[test] +fn a_justify_only_style_change_on_a_graph_label_records_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let graph = NodeId( + s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(), + ); + let doc = s.doc().unwrap().doc.clone(); + let legend = doc.node(graph).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Legend")).unwrap(); + let label = legend + .children() + .unwrap() + .iter() + .find_map(|c| match &c.kind { + NodeKind::Text(t) if t.plain_text() == "2025" => Some(c.id), + _ => None, + }) + .unwrap(); + records_nothing(&mut s, "text.setStyle", json!({"ids": [label.0], "justify": "left"})); + let kept = s.doc().unwrap().doc.node(graph).unwrap().extras().graph.as_deref().unwrap().label_styles.legend.clone(); + assert!(kept.is_none(), "the legend keeps a style"); +} + /// `text.setText` with the text the type already has records no undo step; new text records one. #[test] fn the_same_text_records_no_undo_step() { From 3806f880e56984f1e76e8c419a967dfbd6c9fb72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:19:46 -0800 Subject: [PATCH 19/77] i18n: Danish rows for script interpreter errors Danish is now a complete-message language, so the interpreter's error messages, reasons and error types this branch adds get da rows. --- crates/ui-egui/src/i18n/da.tsv | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 59ce36d15f..fe5d89898c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -91,6 +91,44 @@ @msg $.evalFile requires a file path $.evalFile kræver en filsti @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: tidsgrænsen skal være et endeligt antal millisekunder, 0 eller mere @msg $.evalFile: takes a file path and a timeout $.evalFile: tager en filsti og en tidsgrænse +@msg assignment to a constant binding tildeling til en konstant binding +@msg invalid array length ugyldig arraylængde +@msg array literal too long arrayliteralen er for lang +@msg the value is not a function værdien er ikke en funktion +@msg apply was called on a value that is not a function apply blev kaldt på en værdi, der ikke er en funktion +@msg the argument list is not an object argumentlisten er ikke et objekt +@msg too many arguments for mange argumenter +@msg the value is not a constructor værdien er ikke en konstruktør +@msg cannot convert the object to a primitive value objektet kan ikke konverteres til en primitiv værdi +@msg cannot convert undefined or null to an object undefined eller null kan ikke konverteres til et objekt +@msg the right side of 'in' is not an object højre side af 'in' er ikke et objekt +@msg the right side of 'instanceof' is not a function højre side af 'instanceof' er ikke en funktion +@msg the function's prototype is not an object funktionens prototype er ikke et objekt +@msg Error: {e} Error: {e} +@msg TypeError: {e} TypeError: {e} +@msg ReferenceError: {e} ReferenceError: {e} +@msg RangeError: {e} RangeError: {e} +@msg SyntaxError: {e} SyntaxError: {e} +@msg EvalError: {e} EvalError: {e} +@msg URIError: {e} URIError: {e} +@msg {ident} is not defined {ident} er ikke defineret +@msg cannot read property '{key}' of {base} egenskaben '{key}' for {base} kan ikke læses +@msg cannot set property '{key}' of {base} egenskaben '{key}' for {base} kan ikke sættes +@msg cannot read a property of {base} en egenskab for {base} kan ikke læses +@msg cannot set a property of {base} en egenskab for {base} kan ikke sættes +@msg cannot define property '{key}': {why} egenskaben '{key}' kan ikke defineres: {why} +@msg cannot assign to property '{key}': {why} der kan ikke tildeles til egenskaben '{key}': {why} +@msg cannot delete property '{key}' egenskaben '{key}' kan ikke slettes +@msg cannot declare function {ident} funktionen {ident} kan ikke erklæres +@msg invalid assignment target ugyldigt tildelingsmål +@msg the array's length is read-only arrayets længde er skrivebeskyttet +@msg the property cannot be redefined egenskaben kan ikke defineres igen +@msg the object is not extensible objektet kan ikke udvides +@msg the length cannot be redefined længden kan ikke defineres igen +@msg it is read-only den er skrivebeskyttet +@msg an element cannot be deleted et element kan ikke slettes +@msg it has only a getter den har kun en getter +@msg the value is a primitive værdien er primitiv @msg {name}: line {line}, column {column} of {file}: {e} (thrown) {name}: linje {line}, kolonne {column} i {file}: {e} (kastet) @msg {name}: line {line}, column {column}: {e} (thrown) {name}: linje {line}, kolonne {column}: {e} (kastet) @msg {name}: {e} (thrown) {name}: {e} (kastet) From b78aa4cc338b170fe3a522ad05be7f1dfec29861 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:46:07 -0800 Subject: [PATCH 20/77] Graphs: a paint written to an axis line that already shows it is kept for its kind paint.setFill, paint.setStroke, addon.color.fillToStroke and addon.color.strokeToFill on an axis line, tick mark or radar ring that already showed the paint they write stored nothing, so a paint its kind kept from another line came back when the graph was drawn again. The paint written to the line's topmost visible fill or stroke row is now stored for its kind; its other attributes stay as the kind keeps them. --- crates/engine/src/cmd/addons/color.rs | 3 ++- crates/engine/src/cmd/graph.rs | 6 ++--- crates/engine/src/cmd/graph/series.rs | 33 +++++++++++++++++++++++++++ crates/engine/src/cmd/graph/tests.rs | 21 +++++++++++++++++ crates/engine/src/cmd/paint.rs | 4 +++- docs/mcp.md | 4 +++- 6 files changed, 65 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 8462e35207..f5a51beabb 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -260,7 +260,8 @@ fn copy_paint(s: &mut Session, p: &Value, to_stroke: bool) -> Result { let series = super::super::appearance::capture_series_paint_writes(&before, d, &ids, &written); let labels = super::super::graph::capture_label_styles(d, &ids, ©_run); let painted: Vec = written.iter().map(|(id, _)| *id).collect(); - let lines = super::super::graph::capture_line_changes(&before, d, &painted); + // A line keeps the paint written to it, also when it already showed it, and the rest stays as its kind keeps it. + let lines = super::super::graph::capture_line_changes(&before, d, &painted) | super::super::graph::capture_line_paint_writes(d, &written); Ok(objects + usize::from(series || labels || lines)) })?; } diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 6530ad364a..3bdaa4e875 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -48,9 +48,9 @@ use series::default_series_color; pub(crate) use series::{ LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_fill_stroke_rows, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, - capture_line_fill_stroke_rows, capture_line_rows, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, - graph_part_members, is_design_art, is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, series_group_marks, - series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, + capture_line_fill_stroke_rows, capture_line_paint_writes, capture_line_rows, capture_series_object_opacity, capture_series_opacity, + capture_series_top_paints, graph_part_members, is_design_art, is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, + series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index c1d97b9273..e979fd13d0 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -946,6 +946,39 @@ pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: & changed } +/// Keep, for every line of their kind, the paint an edit wrote to row `at` of graph line `id` for each `(id, at)` in +/// `written` when that row is the line's topmost visible fill or stroke, also when the line already showed that paint: +/// the paint replaces the one its kind keeps from another line. The other attributes stay as the kind keeps them. Lines +/// of a kind take the frontmost one's paint. Called inside the same edit, so they undo together. Returns whether kept +/// rows changed. +pub(crate) fn capture_line_paint_writes(doc: &mut Document, written: &[(NodeId, usize)]) -> bool { + let ids: Vec = written.iter().map(|(id, _)| *id).collect(); + let mut changed = false; + for (id, graph, line) in lines_of(doc, &ids) { + let Some(n) = doc.node(id) else { continue }; + let items = &n.appearance.items; + let wrote = |fill: bool| items.iter().rposition(|it| it.is_fill() == fill && it.visible()).is_some_and(|at| written.contains(&(id, at))); + let (fill, stroke) = (wrote(true), wrote(false)); + if !fill && !stroke { + continue; + } + let shown = label_rows(n).unwrap_or_default().paint; + let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + let slot = line_slot(&mut spec.label_styles, line); + let mut rows = slot.clone().unwrap_or_else(|| line.default_rows()); + if fill { + rows.paint.fill = shown.fill; + } + if stroke { + rows.paint.stroke = shown.stroke; + } + let kept = (rows != line.default_rows()).then_some(rows); + changed |= *slot != kept; + *slot = kept; + } + changed +} + /// Is `id` a graph line: a path directly in a graph's Axes group? pub(crate) fn is_graph_line(doc: &Document, id: NodeId) -> bool { graph_line(doc, id).is_some() diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 9b0313f2ae..6626b46051 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -7350,6 +7350,27 @@ fn default_fill_and_stroke_on_an_axis_line_that_shows_it_is_kept() { assert!(looks.iter().all(|l| (l.2 - 0.5).abs() < 1e-6), "the kind keeps its 50% opacity: {looks:?}"); } +/// A stroke paint written to an axis line that already shows it is kept for every axis line, in place of the stroke the +/// kind keeps from another line. +#[test] +fn a_stroke_written_to_an_axis_line_that_shows_it_is_kept() { + let cases = [("paint.setStroke", json!({"color": "#000000"})), ("addon.color.fillToStroke", json!({}))]; + every_case(cases, |(cmd, params)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setFill", &json!({"ids": [lines[1].id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "{cmd}: the other lines show black until the graph is drawn again"); + let mut p = params.clone(); + p["ids"] = json!([lines[1].id.0]); + s.execute(cmd, &p).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#000000"), "{cmd}: {looks:?}"); + }); +} + #[test] fn pie_names_and_wedge_labels_keep_their_style() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 79f54a9487..558c76fad9 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -640,6 +640,8 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) }, |before, d, changed| { let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow()); + // A graph line keeps the paint written to it, also when it already showed it. + let lines = super::graph::capture_line_paint_writes(d, &written.borrow()); let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| { if fill { st.fill = unplaced(&paint); @@ -650,7 +652,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) st.stroke = unplaced(&paint); } }); - Ok(series || labels) + Ok(series || lines || labels) }, )?; // Rejected edits leave the next shape's appearance and active proxy untouched. diff --git a/docs/mcp.md b/docs/mcp.md index 2ab7138f25..591f40334e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -931,7 +931,9 @@ The other commands store them when given the line itself, and the `appearance.*` `graphicStyle.apply`, `graphicStyle.redefine`, and `appearance.copyFrom` with every attribute picked up and applied or with `append`, store a line's rows even when the line already showed them. The other commands, an `appearance.copyFrom` of some attributes included, store only what they change on a line's rows; the kind keeps its other attributes, also -when the line still shows different ones until the graph is drawn again. An `appearance.copyFrom` that does not apply +when the line still shows different ones until the graph is drawn again. `paint.setFill`, `paint.setStroke`, +`addon.color.fillToStroke` and `addon.color.strokeToFill` also store the paint they write on a line's topmost visible +fill or stroke row when the line already showed it. An `appearance.copyFrom` that does not apply the object's transparency, and `graphicStyle.apply` with `add`, leave the object opacity and blend mode a kind keeps as they are, also when the line still shows other ones. `paint.default` stores the default fill and stroke rows for a line's kind even when the line already showed them, and leaves the object opacity and blend mode the kind keeps. Rows From f20fc32c3db720174003d4ffd2204f004968081b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:23:06 -0800 Subject: [PATCH 21/77] Graphs: a fill or stroke added to a label or axis line keeps the other kind its kind keeps graphicStyle.apply with add, and appearance.copyFrom with append, stored both the fill and stroke rows a graph label or axis line showed, so a fill-only style added to one axis line replaced the stroke the axis lines kept from another line with the line's own black stroke. They now store only the kinds of row they add; the row of the other kind keeps its paint and its place relative to the characters as the kind keeps them. appearance.moveItem of the Contents row stored the rows of every label it was given, so a move that changed nothing on a label replaced what its kind kept from another label. It now stores rows only for the labels whose rows it changed. --- crates/engine/src/cmd/appearance.rs | 18 +++--- crates/engine/src/cmd/graph.rs | 9 +-- crates/engine/src/cmd/graph/series.rs | 80 +++++++++++++++++++++--- crates/engine/src/cmd/graph/tests.rs | 90 +++++++++++++++++++++++++++ crates/engine/src/cmd/style.rs | 12 ++-- docs/mcp.md | 13 ++-- 6 files changed, 191 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index fd4e072537..fcc0147d04 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: only what it changes) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: only what it changes; with `append`: only the kinds of row it adds) → {ids}", has_doc, copy_from ), @@ -1473,8 +1473,8 @@ fn move_contents(s: &mut Session, ids: &[NodeId], to: usize) -> Result { slot.get_or_insert(n.appearance.contents_at()); } slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?; - // A graph label's kind keeps where its rows paint relative to the characters. - let labels = capture_row_edits(&before, d, ids); + // A graph label's kind keeps where its rows paint relative to the characters, from the labels the move changed. + let labels = capture_row_edits(&before, d, &shown_rows_edited(&before, d, ids.to_vec(), |_| false)); Ok(count_changed(d, &before, ids) + usize::from(labels)) })?; Ok(json!({ "contents": slot })) @@ -1742,12 +1742,13 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { // Graph labels keep their new rows, characters and paragraphs per kind of label. // On type, only `append` adds rows and a transparency pick changes the object's opacity and blend mode; the other // attributes go to the characters. Without a transparency pick, the object opacity and blend mode a kind keeps stay, - // also when the label or line picked onto still shows other ones until the graph is drawn again. + // also when the label or line picked onto still shows other ones until the graph is drawn again. `append` keeps + // only the kinds of row it added; a row of the other kind stays as the kind keeps it. let transparency = attrs.appearance.transparency; - let rows = match (append, transparency) { - (true, true) => super::graph::capture_label_rows(d, &targets), - (true, false) => super::graph::capture_label_fill_stroke_rows(d, &targets), - (false, _) => transparency && super::graph::capture_label_object_opacity(d, &targets), + let rows = if append { + super::graph::capture_label_kind_rows(d, &targets, paints, transparency) + } else { + transparency && super::graph::capture_label_object_opacity(d, &targets) }; // `append` adds rows and leaves the characters as they were. let text = !append && super::graph::capture_label_text(d, &targets, kept_text, kept_para)?; @@ -1755,6 +1756,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { // changed, and the rest stay as its kind keeps them, which the line may not show yet. Row attributes the graph // does not keep (overprint, caps, joins, miter limit, dashes) leave what its kind keeps as it is. let lines = match (rows_written, transparency) { + _ if append => super::graph::capture_line_kind_rows(d, &targets, paints, transparency), (true, true) => super::graph::capture_line_rows(d, &targets), (true, false) => super::graph::capture_line_fill_stroke_rows(d, &targets), (false, _) => super::graph::capture_line_changes(&before, d, &targets), diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 3bdaa4e875..c008507581 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -46,11 +46,12 @@ use generate::generate; #[cfg(test)] use series::default_series_color; pub(crate) use series::{ - LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_fill_stroke_rows, capture_label_object_opacity, + LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, - capture_line_fill_stroke_rows, capture_line_paint_writes, capture_line_rows, capture_series_object_opacity, capture_series_opacity, - capture_series_top_paints, graph_part_members, is_design_art, is_graph_line, label_object_opacity_differs, label_rows, labels_in, paint_targets, - series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, + capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_rows, capture_series_object_opacity, + capture_series_opacity, capture_series_top_paints, graph_part_members, is_design_art, is_graph_line, label_object_opacity_differs, label_rows, + labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, + shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index e979fd13d0..42fc640809 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -864,6 +864,46 @@ enum Keep { Object, /// The fill and stroke rows; the object opacity and blend mode stay as the kind keeps them. Rows, + /// The fill row with `fill`, the stroke row with `stroke`, and the object opacity and blend mode with `object`; the + /// others stay as the kind keeps them. Each row keeps its place relative to the characters; a row taken from the + /// label or line paints above a kept row on the same side of them, unless the label or line shows it below its own row + /// of that kind. + Kinds { fill: bool, stroke: bool, object: bool }, +} + +/// The kinds (true: fill) of the rows in `rows` from the bottom up, each with whether it paints below the characters. +fn row_places(rows: &vectorcraft_doc::LabelRows) -> Vec<(bool, bool)> { + let order = if rows.stroke_under { [false, true] } else { [true, false] }; + let has = |fill: bool| if fill { rows.paint.fill.is_some() } else { rows.paint.stroke.is_some() }; + let below = usize::from(rows.below.unwrap_or(0)); + order.into_iter().filter(|k| has(*k)).enumerate().map(|(i, k)| (k, i < below)).collect() +} + +/// Where the rows paint when the row of kind `taken` (true: fill) comes from `shown` and the row of the other kind from +/// `kept`, each keeping its place relative to the characters: `below` and `stroke_under` of [`vectorcraft_doc::LabelRows`]. +fn merged_places(kept: &vectorcraft_doc::LabelRows, shown: &vectorcraft_doc::LabelRows, taken: bool) -> (Option, bool) { + let in_shown = row_places(shown); + let t = in_shown.iter().copied().find(|p| p.0 == taken); + let o = row_places(kept).into_iter().find(|p| p.0 != taken); + let order = match (t, o) { + (Some(t), Some(o)) => { + // Rows on different sides of the characters: the one below them is lower. On the same side: as the label or + // line shows them, else the taken row on top. + let at = |kind: bool| in_shown.iter().position(|p| p.0 == kind); + let o_first = if t.1 != o.1 { + o.1 + } else { + match (at(!taken), at(taken)) { + (Some(o_at), Some(t_at)) => o_at < t_at, + _ => true, + } + }; + if o_first { vec![o, t] } else { vec![t, o] } + } + (t, o) => t.into_iter().chain(o).collect(), + }; + let below = order.iter().filter(|p| p.1).fold(0u8, |k, _| k + 1); + ((below > 0).then_some(below), order.len() == 2 && !order[0].0) } /// `shown` with the parts of the rows `kept` keeps that `keep` leaves as they are. @@ -880,6 +920,27 @@ fn keep_rows(kept: vectorcraft_doc::LabelRows, shown: vectorcraft_doc::LabelRows (shown.paint.opacity, shown.paint.blend) = (kept.paint.opacity, kept.paint.blend); shown } + Keep::Kinds { fill, stroke, object } => { + let places = match (fill, stroke) { + (true, true) => (shown.below, shown.stroke_under), + (false, false) => (kept.below, kept.stroke_under), + (taken, _) => merged_places(&kept, &shown, taken), + }; + let mut rows = shown; + (rows.below, rows.stroke_under) = places; + let (r, k) = (&mut rows.paint, kept.paint); + if !object { + (r.opacity, r.blend) = (k.opacity, k.blend); + } + if !fill { + (r.fill, r.fill_opacity, r.fill_blend, r.fill_unit_box) = (k.fill, k.fill_opacity, k.fill_blend, k.fill_unit_box); + } + if !stroke { + (r.stroke, r.stroke_width, r.stroke_opacity, r.stroke_blend, r.stroke_unit_box) = + (k.stroke, k.stroke_width, k.stroke_opacity, k.stroke_blend, k.stroke_unit_box); + } + rows + } } } @@ -1038,12 +1099,17 @@ pub(crate) fn capture_label_object_opacity(doc: &mut Document, ids: &[NodeId]) - store_label_rows(doc, ids, Keep::Object) } -/// Keep the fill and stroke rows of graph labels and graph lines `ids` for every label or line of their kind, as -/// [`capture_label_rows`] keeps them, for an edit that left their object opacity and blend mode alone: those stay as the -/// kind keeps them, also when a label or line still shows other ones until the graph is drawn again. Returns whether what -/// the graph keeps changed. -pub(crate) fn capture_label_fill_stroke_rows(doc: &mut Document, ids: &[NodeId]) -> bool { - store_label_rows(doc, ids, Keep::Rows) +/// Keep, for every label or line of their kind, the fill row (with `fill`) and the stroke row (with `stroke`) that graph +/// labels and graph lines `ids` show, and with `object` their object opacity and blend mode, as [`capture_label_rows`] +/// keeps them, for an edit that wrote only those: a row of the other kind stays as the kind keeps it, also when a label or +/// line still shows its own one until the graph is drawn again. Returns whether what the graph keeps changed. +pub(crate) fn capture_label_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool { + store_label_rows(doc, ids, Keep::Kinds { fill, stroke, object }) +} + +/// [`capture_label_kind_rows`] for the graph lines among `ids` alone. +pub(crate) fn capture_line_kind_rows(doc: &mut Document, ids: &[NodeId], (fill, stroke): (bool, bool), object: bool) -> bool { + store_line_rows(doc, ids, Keep::Kinds { fill, stroke, object }) } /// Would [`capture_label_object_opacity`] change what a graph keeps for labels `ids`? Reads the document without copying @@ -1061,7 +1127,7 @@ pub(crate) fn label_object_opacity_differs(doc: &Document, ids: &[NodeId]) -> bo }) } -/// [`capture_label_rows`], [`capture_label_object_opacity`] or [`capture_label_fill_stroke_rows`], as `keep` says. +/// [`capture_label_rows`], [`capture_label_object_opacity`] or [`capture_label_kind_rows`], as `keep` says. fn store_label_rows(doc: &mut Document, ids: &[NodeId], keep: Keep) -> bool { let mut changed = store_line_rows(doc, ids, keep); for (graph, role, rows) in label_rows_of(doc, ids) { diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 6626b46051..4f3b05cfa1 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6997,6 +6997,96 @@ fn a_graphic_style_added_to_a_label_or_axis_line_keeps_the_opacity_its_kind_keep } } +/// A fill-only graphic style added on top of a graph label or axis line, or a fill-only source appended to one with the +/// Eyedropper, keeps the stroke its kind keeps from another label or line, though the one it is added to still shows its +/// own. +#[test] +fn a_fill_added_to_a_label_or_axis_line_keeps_the_stroke_its_kind_keeps() { + let cases = [(false, false), (false, true), (true, false), (true, true)]; + every_case(cases, |&(label, append)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (rect, _) = blue_style(&mut s, "Blue", false); + let (first, second) = if label { + (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")) + } else { + let lines = line_nodes(&s, id); + (lines[0].id, lines[1].id) + }; + if label { + s.execute("appearance.addStroke", &json!({"ids": [first.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [first.0], "index": top_row(&s, first, false), "color": "#ff0000"})).unwrap(); + } else { + s.execute("paint.setStroke", &json!({"ids": [first.0], "color": "#ff0000"})).unwrap(); + } + if append { + let pick = json!({"source": rect.0, "ids": [second.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + } else { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [second.0], "add": true})).unwrap(); + } + if label { + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, _) = rows_of(&looks, q); + let shows = |fill: bool, hex: &str| rows.iter().any(|r| r.0 == fill && r.1 == hex); + assert!(shows(false, "#ff0000") && shows(true, "#0000ff"), "{q}: {rows:?}"); + } + } else { + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| l.0 == "#ff0000"), "{looks:?}"); + } + }); +} + +/// A stroke a label's kind keeps below the characters stays below them when a fill-only graphic style is added on top of +/// another label of the kind, or a fill-only source appended to it, and the new fill paints above the characters. +#[test] +fn a_fill_added_to_a_label_keeps_the_kept_stroke_below_the_characters() { + every_case([false, true], |&append| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (rect, _) = blue_style(&mut s, "Blue", false); + let (q1, q2) = (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")); + s.execute("appearance.addStroke", &json!({"ids": [q1.0]})).unwrap(); + s.execute("appearance.moveItem", &json!({"ids": [q1.0], "from": "contents", "to": 1})).unwrap(); + if append { + let pick = json!({"source": rect.0, "ids": [q2.0], "apply": every_row_attribute_without_transparency(), "append": true}); + s.execute("appearance.copyFrom", &pick).unwrap(); + } else { + s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [q2.0], "add": true})).unwrap(); + } + redrawn_label_rows(&mut s, id); + let look = |ap: &vectorcraft_doc::Appearance| (ap.contents_at(), ap.items.iter().map(|it| it.is_fill()).collect::>()); + for q in ["Q1", "Q2", "Q3"] { + assert_eq!(look(&label_node(&s, id, "Axes", q).appearance), (1, vec![false, true]), "append {append}: {q}"); + } + }); +} + +/// A Contents (Characters) row move that leaves a graph label as it was keeps the rows its kind keeps from another label +/// and is no edit. +#[test] +fn a_contents_move_that_changes_nothing_on_a_label_keeps_the_rows_its_kind_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let (q1, q2) = (text_id(&s, id, "Axes", "Q1"), text_id(&s, id, "Axes", "Q2")); + s.execute("appearance.addStroke", &json!({"ids": [q1.0]})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [q1.0], "index": top_row(&s, q1, false), "color": "#ff0000"})).unwrap(); + let at = s.doc().unwrap().doc.node(q2).unwrap().appearance.contents_at(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("appearance.moveItem", &json!({"ids": [q2.0], "from": "contents", "to": at})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changed"); + let looks = redrawn_label_rows(&mut s, id); + for q in ["Q1", "Q2", "Q3"] { + let (rows, _) = rows_of(&looks, q); + assert!(rows.iter().any(|r| !r.0 && r.1 == "#ff0000"), "{q}: {rows:?}"); + } +} + /// An Eyedropper pick with `append` and without the object's transparency on a graph label keeps the object opacity its /// kind keeps from another label, though the label it is applied to still shows 100%. #[test] diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index d415d6b4f1..914ad2b8bf 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -364,6 +364,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible()); let kinds = (shows(true), shows(false)); super::appearance::capture_series_writes(&before, d, &ids, kinds, kinds, false, false); + // A label or graph line keeps its new rows of those kinds for its kind. The other kind, the object opacity and + // the blend mode stay as the kind keeps them. + super::graph::capture_label_kind_rows(d, &ids, kinds, false); } else { d.graphic_style_id(i); let g = d.graphic_styles[i].clone(); @@ -373,12 +376,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { } super::appearance::clear_stood_for(d, &groups); super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); - } - // A label or graph line keeps its new rows for its kind. A style added on top leaves the object opacity and blend - // mode, so the kind keeps its own. - if add { - super::graph::capture_label_fill_stroke_rows(d, &ids); - } else { + // A label or graph line keeps its new rows for its kind. super::graph::capture_label_rows(d, &ids); } Ok(()) diff --git a/docs/mcp.md b/docs/mcp.md index 591f40334e..049423aae3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -905,11 +905,13 @@ The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, a transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its kind of label: the paint, weight, opacity and blend mode of its topmost visible fill and stroke row, their order and their place relative to the Characters row, and the label's object opacity and blend mode. They store them even when the -label already showed them, but an edit of a hidden row that leaves the topmost visible rows as they were stores nothing. `transparency.set` without an `item`, `object.setProps` with an opacity or blend mode, and +label already showed them, but an edit of a hidden row that leaves the topmost visible rows as they were, and an +`appearance.moveItem` of the Contents row that leaves them in place, store nothing. `transparency.set` without an `item`, `object.setProps` with an opacity or blend mode, and an `appearance.copyFrom` (Eyedropper) pick of transparency store only the label's object opacity and blend mode; -`appearance.copyFrom` with `append` stores the rows, and the object opacity and blend mode only when it also applies -the object's transparency. `graphicStyle.apply` with `add` stores the rows and leaves the object opacity and blend -mode the kind keeps. When the graph is drawn again, every label of that kind gets what is stored, with a placed +`appearance.copyFrom` with `append` stores the rows of the kinds it adds (fill, stroke or both), and the object opacity +and blend mode only when it also applies the object's transparency. `graphicStyle.apply` with `add` stores the rows of +the kinds the style shows. Both leave a row of the other kind as the kind keeps it, and `graphicStyle.apply` with `add` +also leaves the object opacity and blend mode the kind keeps. When the graph is drawn again, every label of that kind gets what is stored, with a placed gradient fitted to each label, and the graph saves it as `valuesRows`, `categoriesRows` and `legendRows` in its label styles. Rows below the topmost one of each kind, a row's effects, other stroke options (caps, joins, dashes) and effects applied with `effect.*` are not stored. When labels of one kind are edited together, the last one in the order of the targets (`ids` as given, otherwise paint order) sets what the kind keeps. @@ -929,7 +931,8 @@ The other commands store them when given the line itself, and the `appearance.*` `transparency.set` with an `item` also when given the Axes group, as described above. `transparency.set` without an `item` and `object.setProps` store only the object opacity and blend mode. `appearance.clear`, `appearance.transfer`, `graphicStyle.apply`, `graphicStyle.redefine`, and `appearance.copyFrom` with every attribute picked up and applied or -with `append`, store a line's rows even when the line already showed them. The other commands, an `appearance.copyFrom` +with `append`, store a line's rows even when the line already showed them; `graphicStyle.apply` with `add` and +`appearance.copyFrom` with `append` store only the kinds of row they add. The other commands, an `appearance.copyFrom` of some attributes included, store only what they change on a line's rows; the kind keeps its other attributes, also when the line still shows different ones until the graph is drawn again. `paint.setFill`, `paint.setStroke`, `addon.color.fillToStroke` and `addon.color.strokeToFill` also store the paint they write on a line's topmost visible From 6e06fca9fd9d364bb0b64db2c80bfb19d81532a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:43:20 -0800 Subject: [PATCH 22/77] i18n: drop Turkish script error rows that main already has MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Main's Turkish catalog now carries rows for 13 of the script interpreter errors this branch added, so bundled_catalogs_are_consistent reported duplicate @msg rows. The branch's copies are removed and main's wording stays. The remaining new row uses "işlev" for function, as the rest of the catalog does. --- crates/ui-egui/src/i18n/tr.tsv | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6f75e3aae7..1d89cd0000 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4109,19 +4109,6 @@ axis Both Her İkisi @msg $.evalFile requires a file path $.evalFile bir dosya yolu gerektirir @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: zaman aşımı sonlu bir milisaniye sayısı olmalıdır, 0 veya daha fazla @msg $.evalFile: takes a file path and a timeout $.evalFile: bir dosya yolu ve bir zaman aşımı alır -@msg assignment to a constant binding sabit bir bağlamaya atama -@msg invalid array length geçersiz dizi uzunluğu -@msg array literal too long dizi değişmezi çok uzun -@msg the value is not a function değer bir fonksiyon değil -@msg apply was called on a value that is not a function apply, fonksiyon olmayan bir değer üzerinde çağrıldı -@msg the argument list is not an object argüman listesi bir nesne değil -@msg too many arguments çok fazla argüman -@msg the value is not a constructor değer bir yapıcı değil -@msg cannot convert the object to a primitive value nesne ilkel bir değere dönüştürülemiyor -@msg cannot convert undefined or null to an object undefined veya null bir nesneye dönüştürülemiyor -@msg the right side of 'in' is not an object 'in' işlecinin sağ tarafı bir nesne değil -@msg the right side of 'instanceof' is not a function 'instanceof' işlecinin sağ tarafı bir fonksiyon değil -@msg the function's prototype is not an object fonksiyonun prototipi bir nesne değil @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} @@ -4137,7 +4124,7 @@ axis Both Her İkisi @msg cannot define property '{key}': {why} '{key}' özelliği tanımlanamıyor: {why} @msg cannot assign to property '{key}': {why} '{key}' özelliğine atama yapılamıyor: {why} @msg cannot delete property '{key}' '{key}' özelliği silinemiyor -@msg cannot declare function {ident} {ident} fonksiyonu bildirilemiyor +@msg cannot declare function {ident} {ident} işlevi bildirilemiyor @msg invalid assignment target geçersiz atama hedefi @msg the array's length is read-only dizinin uzunluğu salt okunur @msg the property cannot be redefined özellik yeniden tanımlanamaz From cf2de372c9e847991c7fe88e00f87085c4ce9a65 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 01:35:05 -0800 Subject: [PATCH 23/77] Image Trace: seam fills are clipped to the image and skip live shapes - The Seam Fills group is a clip group whose clipping path is the image's box, so a stroke that ends at the image's border stays inside it, and so do the trace's bounds. Where a shared edge ends at, or runs within 0.75 image pixels of, a transparent area or a color left out, its stroke can reach up to 0.75 image pixels into it. - Paths that became live shapes take no part. - Expand by color names the seam fills' group when it was moved above a path, instead of the Auto Grouping message. - Outline views leave the group out. - Canceling a trace run also stops it before the seam fills are found. Docs: docs/mcp.md, the params text, docs/target-app-parity.md. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/buildcmds/trace.rs | 72 +++++++---- crates/engine/src/tests/build.rs | 67 +++++++++- crates/render/src/renderer/nodes.rs | 14 ++- crates/trace/src/lib.rs | 2 +- crates/trace/src/seam.rs | 151 ++++++++++++++++------- docs/mcp.md | 22 ++-- docs/target-app-parity.md | 2 +- 8 files changed, 244 insertions(+), 88 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 66c9ec8fc4..817a34f6c8 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -144,7 +144,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" group under the paths holds 1.5 px strokes along the edges two filled paths share, in the color of the lower path, so that no light hairline shows along those edges; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path, clipped to the image's box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index e9288918e8..e1b524dc8d 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -22,20 +22,21 @@ fn is_trace_group(n: &Node) -> bool { && n.children().is_some_and(|c| c.first().is_some_and(|i| matches!(i.kind, NodeKind::Image(_)))) } -/// The name of the group that holds an Abutting trace's seam fills (see [`tr::TraceResult::seams`]). +/// The name of the clip group that holds an Abutting trace's seam fills (see [`tr::seam_fills`]). const SEAM_FILLS_NAME: &str = "Seam Fills"; -/// Whether `n` can be a trace's seam fills group: a group named as one, or a group of stroked paths -/// without fills, so that it is still found after it is renamed or its strokes are edited. (Auto -/// Grouping groups hold filled paths.) +/// Whether `n` can be a trace's seam fills group: a clip group named as one, or a clip group whose +/// members after the clipping path are stroked paths without fills, so that it is still found +/// after it is renamed or its strokes are edited. (Auto Grouping groups are not clip groups.) fn is_seam_fills(n: &Node) -> bool { let stroke_only = |m: &Arc| { matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && m.appearance.fill_paint() == Paint::None && m.appearance.stroke_paint() != Paint::None }; - matches!(n.kind, NodeKind::Group { clip: false, .. }) - && (n.name.as_deref() == Some(SEAM_FILLS_NAME) || n.children().is_some_and(|c| !c.is_empty() && c.iter().all(stroke_only))) + let NodeKind::Group { clip: true, children } = &n.kind else { return false }; + n.name.as_deref() == Some(SEAM_FILLS_NAME) + || children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(stroke_only)) } const LIVE_PATHFINDER_BY_COLOR: &str = "byColor can't regroup a trace with a live Pathfinder effect: expand without byColor"; @@ -410,7 +411,8 @@ fn by_color_param(cmd: &str, p: &Value) -> Result { /// starts another group of that paint, which keeps the stacking order of those items. Items /// farther apart can still share antialiased pixels at small view or raster-export scales, so /// their edge pixels may change. The seam fills' group, when it is the lowest item, stays as it is, -/// under every other group. Any other group among `items` (Auto Grouping) is refused. +/// under every other group; above another item it is refused. Any other group among `items` (Auto +/// Grouping) is refused. fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result>> { use std::collections::{BTreeMap, HashMap}; use std::ops::Bound::{Excluded, Unbounded}; @@ -464,6 +466,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec>) -> Result> = BTreeMap::new(); let mut all_boxes: BTreeMap> = BTreeMap::new(); for (item, bounds) in items { + if is_seam_fills(&item) { + return Err(bad(cmd, "byColor needs the seam fills' group under every path: move it to the bottom or delete it")); + } if matches!(item.kind, NodeKind::Group { .. }) { return Err(bad(cmd, "byColor can't split Auto Grouping groups: trace without Auto Grouping")); } @@ -630,12 +635,12 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { } /// What a trace made of an image: the size in pixels it was decoded at, the paths, and their seam -/// fills ([`seams_within`]). +/// fills, if any ([`seams_within`]). pub struct Traced { inputs: TraceInputs, raster: (u32, u32), res: tr::TraceResult, - seams: Vec, + seams: Option, } impl Traced { @@ -659,18 +664,23 @@ fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64 tr::TraceError::Cancelled => EngineError::Cancelled, e => EngineError::Other(e.to_string()), })?; - let seams = seams_within(&res, params, MAX_TRACE_ANCHORS); - Ok(Traced { inputs: inputs.clone(), raster: (raster.width, raster.height), res, seams }) + if !steps(0, 0) { + return Err(EngineError::Cancelled); + } + let size = (raster.width, raster.height); + let seams = seams_within(&res, params, size, MAX_TRACE_ANCHORS); + Ok(Traced { inputs: inputs.clone(), raster: size, res, seams }) } -/// The seam fills of `res`, traced with `params` ([`tr::seam_fills`]), while the paths and the seam -/// fills together stay within `max` anchors: the seam fills have at most as many anchors as the -/// paths, so a trace whose paths have more than half of `max` gets none. -fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, max: usize) -> Vec { - if res.anchor_count() > max / 2 { - return vec![]; +/// The seam fills of `res`, traced with `params` from a `size` raster ([`tr::seam_fills`]), while +/// the paths, the seam fills' strokes and their clip together stay within `max` anchors: the +/// strokes have at most as many anchors as the paths and the clip has four, so a trace whose paths +/// have more than half of `max` less two gets none. +fn seams_within(res: &tr::TraceResult, params: &tr::TraceParams, size: (u32, u32), max: usize) -> Option { + if res.anchor_count().saturating_mul(2).saturating_add(4) > max { + return None; } - tr::seam_fills(&res.paths, params) + tr::seam_fills(&res.paths, params, size) } /// An Image Trace made away from its command, off the UI thread (#3098). [`TraceRun::prepare`] @@ -801,9 +811,11 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result> = seam_fills + // Abutting: the seam fills, in a clip group of their own under every path, clipped to the + // image's box. + let strokes: Vec> = seam_fills .iter() + .flat_map(|f| &f.strokes) .filter_map(|tp| { let width = tp.stroke?; let mut n = shape_node(d, tp.path.transformed(xf), None); @@ -819,8 +831,13 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Node .unwrap() } -/// The traced paths of an Image Trace object: its children but the image and the seam fills. +/// The traced paths of an Image Trace object: its children but the image and the seam fills' +/// clip group (a trace makes no other clip group). fn traced_paths(n: &Node) -> Vec> { - n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_)) && c.name.as_deref() != Some("Seam Fills")).cloned().collect() + n.children().unwrap().iter().filter(|c| !matches!(c.kind, NodeKind::Image(_) | NodeKind::Group { clip: true, .. })).cloned().collect() } #[test] @@ -6092,7 +6093,12 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert!(matches!(kids[0].kind, NodeKind::Image(_))); let group = seams(&n).unwrap(); assert!(Arc::ptr_eq(&group, &kids[1]), "the seam fills come under the paths"); - let strokes = group.children().unwrap(); + assert!(matches!(group.kind, NodeKind::Group { clip: true, .. }), "{group:?}"); + // The two paths cover the image, so the strokes are clipped to its box. + let (clip, strokes) = group.children().unwrap().split_first().unwrap(); + assert!(matches!(clip.kind, NodeKind::Path { clipping: true, .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + assert!([cb.x0, cb.y0, cb.x1 - 80.0, cb.y1 - 40.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); assert_eq!(strokes.len(), 1); assert_eq!(strokes[0].appearance.fill_paint(), Paint::None); let AppearanceItem::Stroke(layer) = &strokes[0].appearance.items[0] else { panic!("{:?}", strokes[0].appearance) }; @@ -6110,6 +6116,14 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { assert_eq!(names.len(), 3, "{names:?}"); assert_eq!(names[0], "Edges", "{names:?}"); assert_eq!(n.children().unwrap()[0].id, group.id); + // Above a path, the seam fills' group is refused by name, not as an Auto Grouping group. + let (mut s, _, r) = made("abutting", "imageTrace.make", false); + let g = NodeId(r["id"].as_u64().unwrap()); + let kids = node(&s, g).children().unwrap().clone(); + s.execute("object.arrange.bringToFront", &json!({"ids": [kids[1].id.0]})).unwrap(); + assert_eq!(node(&s, g).children().unwrap().last().map(|c| c.id), Some(kids[1].id)); + let e = s.execute("imageTrace.expand", &json!({"id": g.0, "byColor": true})).unwrap_err().to_string(); + assert!(e.contains("seam fills") && !e.contains("Auto Grouping"), "{e}"); let (mut s, img, _) = made("abutting", "imageTrace.make", false); assert_eq!(ids(&s.execute("imageTrace.release", &json!({})).unwrap()), vec![img]); // Make and Expand by color too. @@ -6124,8 +6138,28 @@ fn image_trace_abutting_seam_fills_sit_under_the_paths() { add_image(&mut s, &art, Affine::scale_non_uniform(3.0, 0.5)); let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap(); - let AppearanceItem::Stroke(layer) = &group.children().unwrap()[0].appearance.items[0] else { panic!("{group:?}") }; + let AppearanceItem::Stroke(layer) = &group.children().unwrap()[1].appearance.items[0] else { panic!("{group:?}") }; assert!((layer.width - 4.5).abs() < 1e-9, "{}", layer.width); + // White left out: the strokes are still clipped to the image's box. + let band = vectorcraft_trace::Raster::from_fn(24, 16, |x, y| match ((4..12).contains(&y), x < 12) { + (false, _) => [255; 4], + (true, true) => [200, 30, 30, 255], + (true, false) => [30, 30, 200, 255], + }); + let mut s = session(); + add_image(&mut s, &band, Affine::IDENTITY); + let r = s + .execute( + "imageTrace.make", + &json!({"params": {"mode": "color", "palette": "limited", "colors": 3, "method": "abutting", "ignoreWhite": true}}), + ) + .unwrap(); + assert_eq!(r["paths"], 2, "{r}"); + let group = seams(&node(&s, NodeId(r["id"].as_u64().unwrap()))).unwrap(); + let clip = &group.children().unwrap()[0]; + assert!(matches!(clip.kind, NodeKind::Path { .. }), "{clip:?}"); + let cb = outline(clip).0.bounds().unwrap(); + assert!([cb.x0, cb.y0, cb.x1 - 24.0, cb.y1 - 16.0].iter().all(|v| v.abs() < 1e-9), "{cb:?}"); } /// Expand by color: each color's paths in a group of their own, named by the color, the groups @@ -7188,6 +7222,31 @@ fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { } } +/// Outline views draw the traced paths' outlines and leave out an Abutting trace's seam fills +/// (their clipping box and strokes). +#[test] +fn image_trace_outline_view_leaves_out_the_seam_fills() { + let mut s = session(); + // Red beside blue in the middle of a transparent 60 × 40 image, placed at 50, 50 and scaled 2×. + let art = vectorcraft_trace::Raster::from_fn(60, 40, |x, y| match ((10..50).contains(&x) && (10..30).contains(&y), x < 30) { + (false, _) => [0, 0, 0, 0], + (true, true) => [200, 30, 30, 255], + (true, false) => [30, 30, 200, 255], + }); + add_image(&mut s, &art, Affine::translate((50.0, 50.0)) * Affine::scale(2.0)); + let r = s.execute("imageTrace.make", &json!({"params": {"mode": "color", "palette": "limited", "colors": 2, "method": "abutting"}})).unwrap(); + let g = NodeId(r["id"].as_u64().unwrap()); + assert!(node(&s, g).children().unwrap().iter().any(|c| matches!(c.kind, NodeKind::Group { clip: true, .. })), "seam fills"); + s.execute("imageTrace.setView", &json!({"id": g.0, "view": "outlines"})).unwrap(); + let screen = render_doc(&s, true); + // The image's top edge (y = 50), away from the art: nothing drawn. + for x in [60, 110, 160] { + assert!(screen.pixel(x, 50)[0] > 245 && screen.pixel(x, 51)[0] > 245, "x = {x}: {:?}", screen.pixel(x, 50)); + } + // The art's left edge (x = 70) is outlined. + assert!((68..=72).any(|x| screen.pixel(x, 90)[0] < 128)); +} + /// #569: merging the regions of a rosette of unfilled ellipses (each off the centre, petals /// overlapping) merges every region the drags touch into one shape whose outline is only the /// merged area's border: no edge between merged regions stays in, as a stray line or a spur. diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 37f3fbf4f7..c3dae5c07f 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -653,7 +653,19 @@ impl Renderer { if view.shows_outlines() { let opts = RenderOptions { outline: true, ..f.opts.clone() }; let frame = Frame { opts: &opts, ..*f }; - for c in shapes { + // An Abutting trace's seam fills hold no traced outline: a clip group named "Seam Fills" + // of stroked paths without fills. + let seam_fills = |c: &Arc| { + let stroke_only = |m: &Arc| { + matches!(m.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && m.appearance.fill_paint().is_none() + && !m.appearance.stroke_paint().is_none() + }; + c.name.as_deref() == Some("Seam Fills") + && matches!(&c.kind, NodeKind::Group { clip: true, children } + if children.split_first().is_some_and(|(_, members)| !members.is_empty() && members.iter().all(stroke_only))) + }; + for c in shapes.iter().filter(|c| !seam_fills(c)) { self.draw_outline_member(ctx, &frame, c); } } diff --git a/crates/trace/src/lib.rs b/crates/trace/src/lib.rs index b489e4dd82..7bb59c79b1 100644 --- a/crates/trace/src/lib.rs +++ b/crates/trace/src/lib.rs @@ -72,7 +72,7 @@ pub use gradient::TracedGradient; pub use mosaic::mosaic; pub use opaque::{ALPHA_MAX_DECODE_BYTES, OUTLINE_MAX_ANCHORS, OUTLINE_MAX_PIXELS, decode_alpha, opaque_outline}; pub use quantize::{FULL_TONE_MAX, Quantized, TRANSPARENT, denoise, quantize}; -pub use seam::{SEAM_WIDTH, seam_fills}; +pub use seam::{SeamFills, seam_fills}; pub use shapes::TracedShape; use subpixel::Crack; diff --git a/crates/trace/src/seam.rs b/crates/trace/src/seam.rs index 5a1ffa96c5..b17d1dd6da 100644 --- a/crates/trace/src/seam.rs +++ b/crates/trace/src/seam.rs @@ -6,19 +6,38 @@ //! under every path, fills those pixels with that color: drawing the two paths over it then gives //! each pixel the colors of the two paths in the shares each covers. The paths themselves are not //! changed, and an edge a path shares with no other path (the image's border, a transparent area, -//! a color left out) gets no stroke. +//! a color left out) gets no stroke. The strokes are clipped to the image's box. Where a shared +//! edge ends at, or runs within half the stroke's width of, a transparent area or a color left +//! out, its stroke can reach that far into that area. use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; -use super::params::{Method, Mode, TraceParams}; -use super::pipeline::TracedPath; +use crate::{Method, Mode, TraceParams, TracedPath}; /// How wide each seam fill's stroke is, in pixels: it covers every pixel the shared edge passes /// through, at any angle (a pixel's corner is up to 0.71 px from a line through it). -pub const SEAM_WIDTH: f64 = 1.5; +const SEAM_WIDTH: f64 = 1.5; + +/// The seam fills of an Abutting trace ([`seam_fills`]). +#[derive(Clone, Debug, PartialEq)] +pub struct SeamFills { + /// For each color, one path stroked 1.5 pixels wide along the edges where a filled path of + /// that color meets a filled path drawn after it, with `color` and `gradient` that path's; the + /// paths with a gradient get one each. Bottom-most first, as the paths they lie under. + pub strokes: Vec, + /// The area to clip `strokes` to, in the same pixel coordinates: the image's box. + pub clip: PathData, +} + +impl SeamFills { + /// The anchors of the strokes and the clip together. + pub fn anchor_count(&self) -> usize { + self.strokes.iter().map(|s| s.path.anchor_count()).sum::() + self.clip.anchor_count() + } +} /// A segment, the same for the segment and the segment run backwards: two 64-bit hashes of its /// points' bits, 16 bytes a segment instead of 64. Two different segments with the same key would @@ -36,18 +55,23 @@ fn key(a: &Anchor, b: &Anchor) -> Key { (u128::from(hash(0)) << 64) | u128::from(hash(1)) } -/// The seam fills of a trace made with `params`: for Abutting with Fills (not Flat Logo), thin -/// strokes to draw under every path of `paths` (bottom-most first). For each color, one path -/// stroked [`SEAM_WIDTH`] pixels wide along the edges where a filled path of that color meets a -/// filled path drawn after it, with `color` and `gradient` that path's; the paths with a gradient -/// get one each. Bottom-most first, as the paths they lie under. The stroke has at most as many -/// anchors as `paths` (each of its segments is a segment of a path), and finding them keeps about -/// 40 bytes for each segment of `paths` while it runs. Empty for any other trace. -pub fn seam_fills(paths: &[TracedPath], params: &TraceParams) -> Vec { +/// The seam fills of a trace of a `size` (width, height in pixels) image made with `params`, for +/// Abutting with Fills (not Flat Logo): strokes to draw under every path of `paths` (bottom-most +/// first), clipped to the image's box. Filled paths that became a live shape (Shapes) take no part: +/// their outline is not the traced one. The strokes have at most as many anchors as `paths` (each +/// of their segments is a segment of a path), and the clip has four; finding them keeps about 40 +/// bytes for each segment of `paths` while it runs. `None` for any other trace, or when no filled +/// paths share an edge. +pub fn seam_fills(paths: &[TracedPath], params: &TraceParams, size: (u32, u32)) -> Option { if params.method != Method::Abutting || !params.fills || params.mode == Mode::Logo { - return vec![]; + return None; } - fills(paths) + fills(paths, size) +} + +/// Whether `p` takes part in the seam fills: filled, and drawn with its traced outline. +fn filled(p: &TracedPath) -> bool { + p.stroke.is_none() && p.shape.is_none() } /// The segments of `sp`: each anchor and the one after it (back to the first, if closed). @@ -57,11 +81,11 @@ fn segments(sp: &SubPath) -> impl Iterator { (0..count).filter_map(move |k| Some((sp.anchors.get(k)?, sp.anchors.get((k + 1) % n)?))) } -/// [`seam_fills`] of Abutting `paths`, whatever the settings. -fn fills(paths: &[TracedPath]) -> Vec { +/// [`seam_fills`] of Abutting `paths` traced from a `size` image, whatever the settings. +fn fills(paths: &[TracedPath], size: (u32, u32)) -> Option { // For each segment, the first path it is in, and whether another path has it too. let mut owner: HashMap = HashMap::new(); - for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) { + for (i, p) in paths.iter().enumerate().filter(|(_, p)| filled(p)) { for sp in &p.path.subpaths { for (a, b) in segments(sp).filter(|(a, b)| a.p != b.p) { let e = owner.entry(key(a, b)).or_insert((i, false)); @@ -74,11 +98,10 @@ fn fills(paths: &[TracedPath]) -> Vec { // One fill per color (per path, for a gradient), in the order of the first path it lies under. let mut out: Vec = vec![]; let mut by_color: HashMap<[u8; 3], usize> = HashMap::new(); - for (i, p) in paths.iter().enumerate().filter(|(_, p)| p.stroke.is_none()) { + for (i, p) in paths.iter().enumerate().filter(|(_, p)| filled(p)) { let mut runs: Vec = vec![]; for sp in &p.path.subpaths { - let lower = |a: &Anchor, b: &Anchor| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true)); - let marks: Vec = segments(sp).map(|(a, b)| lower(a, b)).collect(); + let marks: Vec = segments(sp).map(|(a, b)| a.p != b.p && owner.get(&key(a, b)) == Some(&(i, true))).collect(); let n = sp.anchors.len(); if marks.is_empty() { continue; @@ -129,7 +152,12 @@ fn fills(paths: &[TracedPath]) -> Vec { } } } - out + if out.is_empty() { + return None; + } + let (w, h) = (f64::from(size.0), f64::from(size.1)); + let clip = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)], true)); + Some(SeamFills { strokes: out, clip }) } /// An open run of anchors: the last one has no handle out. @@ -143,13 +171,18 @@ fn open_run(mut run: Vec) -> SubPath { #[cfg(test)] mod tests { use super::*; - use crate::{Method, Mode, Raster, TraceParams, trace}; + use crate::{Method, Mode, Raster, TraceParams, TracedGradient, TracedShape, trace}; fn polygon(rings: &[&[(f64, f64)]], color: u8) -> TracedPath { let subpaths = rings.iter().map(|r| SubPath::polyline(&r.iter().map(|&(x, y)| Point::new(x, y)).collect::>(), true)).collect(); TracedPath { path: PathData::new(subpaths), color: [color; 3], pixels: 1, stroke: None, shape: None, gradient: None, square_caps: false } } + /// The strokes of [`fills`] for `paths` in a box that no test path reaches the border of. + fn strokes(paths: &[TracedPath]) -> Vec { + fills(paths, (100, 100)).map(|f| f.strokes).unwrap_or_default() + } + fn points(sp: &SubPath) -> Vec<(f64, f64)> { sp.anchors.iter().map(|a| (a.p.x, a.p.y)).collect() } @@ -163,7 +196,7 @@ mod tests { fn a_shared_edge_gets_a_stroke_in_the_color_of_the_path_drawn_first() { let left = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); - let fills = fills(&[left.clone(), right.clone()]); + let fills = strokes(&[left.clone(), right.clone()]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!((fills[0].color, fills[0].stroke, fills[0].gradient.as_ref()), ([10; 3], Some(SEAM_WIDTH), None)); assert_eq!(fills[0].path.subpaths.len(), 1); @@ -171,7 +204,7 @@ mod tests { assert!(!sp.closed); assert_eq!(points(sp), [(2.0, 0.0), (2.0, 2.0)]); // Drawn the other way round, the stroke takes the other color. - let swapped = super::fills(&[right, left]); + let swapped = strokes(&[right, left]); assert_eq!(swapped.len(), 1); assert_eq!((swapped[0].color, points(&swapped[0].path.subpaths[0])), ([20; 3], vec![(2.0, 2.0), (2.0, 0.0)])); } @@ -181,7 +214,7 @@ mod tests { let hole: &[(f64, f64)] = &[(2.0, 2.0), (2.0, 4.0), (4.0, 4.0), (4.0, 2.0)]; let around = polygon(&[&[(0.0, 0.0), (6.0, 0.0), (6.0, 6.0), (0.0, 6.0)], hole], 10); let island = polygon(&[&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]], 20); - let fills = fills(&[around, island]); + let fills = strokes(&[around, island]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].color, [10; 3]); assert_eq!(fills[0].path.subpaths.len(), 1); @@ -195,7 +228,7 @@ mod tests { // at the same point. let left = polygon(&[&[(2.0, 1.0), (2.0, 2.0), (0.0, 2.0), (0.0, 0.0), (2.0, 0.0)]], 10); let right = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0), (2.0, 1.0)]], 20); - let fills = fills(&[left, right]); + let fills = strokes(&[left, right]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].path.subpaths.len(), 1); assert_eq!(points(&fills[0].path.subpaths[0]), [(2.0, 0.0), (2.0, 1.0), (2.0, 2.0)]); @@ -204,11 +237,15 @@ mod tests { #[test] fn edges_shared_with_no_other_filled_path_get_no_stroke() { let square = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); - assert_eq!(fills(std::slice::from_ref(&square)), []); - // A stroked line along the square's edge is not a filled neighbour. - let mut line = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); - line.stroke = Some(1.0); - assert_eq!(fills(&[square, line]), []); + assert_eq!(fills(std::slice::from_ref(&square), (100, 100)), None); + // A stroked path along the square's edge is not a filled neighbor. + let mut stroked = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); + stroked.stroke = Some(1.0); + assert_eq!(fills(&[square.clone(), stroked], (100, 100)), None); + // Nor is a path drawn as a live shape, whose outline is not the traced one. + let mut shape = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 2.0), (2.0, 2.0)]], 20); + shape.shape = Some(TracedShape::Rectangle { center: Point::new(3.0, 1.0), width: 2.0, height: 2.0, radius: 0.0, rotation: 0.0 }); + assert_eq!(fills(&[square, shape], (100, 100)), None); } #[test] @@ -216,9 +253,34 @@ mod tests { let a = polygon(&[&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]], 10); let b = polygon(&[&[(0.0, 4.0), (2.0, 4.0), (2.0, 6.0), (0.0, 6.0)]], 10); let c = polygon(&[&[(2.0, 0.0), (4.0, 0.0), (4.0, 6.0), (2.0, 6.0), (2.0, 4.0), (2.0, 2.0)]], 20); - let fills = fills(&[a, b, c]); + let fills = strokes(&[a.clone(), b.clone(), c.clone()]); assert_eq!(fills.len(), 1, "{fills:?}"); assert_eq!(fills[0].path.subpaths.iter().map(points).collect::>(), [vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]]); + // With a gradient each, the two paths of one color get a stroke each, with their gradient. + let ramp = |to: u8| TracedGradient { start: Point::new(0.0, 0.0), end: Point::new(2.0, 0.0), stops: vec![(0.0, [10; 3]), (1.0, [to; 3])] }; + let (mut a, mut b) = (a, b); + (a.gradient, b.gradient) = (Some(ramp(30)), Some(ramp(40))); + let fills = strokes(&[a.clone(), b.clone(), c]); + assert_eq!(fills.len(), 2, "{fills:?}"); + assert_eq!(fills.iter().map(|f| f.gradient.clone()).collect::>(), [a.gradient, b.gradient]); + assert_eq!( + fills.iter().map(|f| points(&f.path.subpaths[0])).collect::>(), + [vec![(2.0, 0.0), (2.0, 2.0)], vec![(2.0, 4.0), (2.0, 6.0)]] + ); + } + + #[test] + fn the_strokes_are_clipped_to_the_images_box() { + // A diagonal edge meeting the border: a corner of the stroke's butt end reaches past the + // box, and the clip is the box. + let lower = polygon(&[&[(0.0, 0.0), (3.0, 0.0), (1.0, 2.0), (0.0, 2.0)]], 10); + let upper = polygon(&[&[(3.0, 0.0), (4.0, 0.0), (4.0, 2.0), (1.0, 2.0)]], 20); + let diagonal = fills(&[lower, upper], (4, 2)).unwrap(); + assert_eq!(points(&diagonal.strokes[0].path.subpaths[0]), [(3.0, 0.0), (1.0, 2.0)]); + assert_eq!(diagonal.clip.subpaths.len(), 1); + assert!(diagonal.clip.subpaths[0].closed); + assert_eq!(points(&diagonal.clip.subpaths[0]), [(0.0, 0.0), (4.0, 0.0), (4.0, 2.0), (0.0, 2.0)]); + assert_eq!(diagonal.anchor_count(), 2 + 4); } /// Two colors side by side, the edge between them anti-aliased at `x = 10.4`. @@ -239,9 +301,9 @@ mod tests { let params = color(Method::Abutting); let res = trace(&two_colors(), ¶ms); assert_eq!(res.paths.len(), 2, "{res:?}"); - let seams = seam_fills(&res.paths, ¶ms); - assert_eq!(seams.len(), 1, "{seams:?}"); - let seam = &seams[0]; + let fills = seam_fills(&res.paths, ¶ms, (24, 16)).unwrap(); + assert_eq!(fills.strokes.len(), 1, "{fills:?}"); + let seam = &fills.strokes[0]; assert_eq!((seam.color, seam.stroke), (res.paths[0].color, Some(SEAM_WIDTH))); // Every piece of the stroke is a piece of both paths, and it runs from the image's top to // its bottom along the edge, not along the image's border. @@ -253,25 +315,28 @@ mod tests { } let ys: Vec = seam.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p.y)).collect(); assert_eq!((ys.iter().copied().fold(f64::INFINITY, f64::min), ys.iter().copied().fold(f64::NEG_INFINITY, f64::max)), (0.0, 16.0)); + // The clip is the image's box. + let corners: Vec<(f64, f64)> = fills.clip.subpaths.iter().flat_map(points).collect(); + assert_eq!(corners, [(0.0, 0.0), (24.0, 0.0), (24.0, 16.0), (0.0, 16.0)]); } #[test] fn only_abutting_fills_get_seam_strokes() { - let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params); + let seams = |img: &Raster, params: &TraceParams| seam_fills(&trace(img, params).paths, params, (img.width, img.height)); let img = two_colors(); - assert_eq!(seams(&img, &color(Method::Overlapping)), []); - assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), []); + assert_eq!(seams(&img, &color(Method::Overlapping)), None); + assert_eq!(seams(&img, &TraceParams { fills: false, strokes: true, ..color(Method::Abutting) }), None); // Flat Logo's shapes are stacked, whatever the method says. let abutting = trace(&img, &color(Method::Abutting)); - assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }), []); - // A color left out leaves no neighbour: a dark bar on white, with Ignore White. + assert_eq!(seam_fills(&abutting.paths, &TraceParams { mode: Mode::Logo, ..color(Method::Abutting) }, (24, 16)), None); + // A color left out leaves no neighbor: a dark bar on white, with Ignore White. let bar = Raster::from_fn(24, 16, |x, _| if (8..16).contains(&x) { [0, 0, 0, 255] } else { [255; 4] }); let bw = TraceParams { mode: Mode::BlackAndWhite, method: Method::Abutting, ignore_white: true, ..TraceParams::default() }; let res = trace(&bar, &bw); assert_eq!(res.paths.len(), 1, "{res:?}"); - assert_eq!(seam_fills(&res.paths, &bw), []); + assert_eq!(seam_fills(&res.paths, &bw, (24, 16)), None); // Both colors traced, the bar's two sides are shared. - let both = seams(&bar, &TraceParams { ignore_white: false, ..bw }); - assert_eq!(both.iter().map(|s| s.path.subpaths.len()).sum::(), 2, "{both:?}"); + let both = seams(&bar, &TraceParams { ignore_white: false, ..bw }).unwrap(); + assert_eq!(both.strokes.iter().map(|s| s.path.subpaths.len()).sum::(), 2, "{both:?}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index 87b1dc7ab4..47569c5492 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3829,16 +3829,18 @@ already walks Image Trace. Short agent entry points: black ring around a white disc around a black dot, black gets two groups. `layer.releaseToLayers` on the expanded group then gives each group a sublayer. A trace made with `autoGrouping` is refused. Expanding by color also refuses a trace with a live Pathfinder effect. - An Abutting trace with Fills (not Flat Logo) also holds a group named `Seam Fills` under its paths: for each color, a - stroke 1.5 image pixels wide (at the image's larger scale, when it is stretched more one way) with butt caps and round joins along the edges where a filled path of that color meets a - filled path drawn after it, in that color (a gradient path's stroke takes its gradient). Without it, a renderer that - anti-aliases each path on its own shows a light hairline along every shared edge. The traced paths and their shared - edges are the same with or without it, and edges against the image's border, a transparent area or a color left out - get no stroke. A trace whose paths have more than half of the trace's anchor limit (8,000,000, 2,000,000 on the web) - has no seam fills, so that paths and seam fills together stay within the limit. Both Expand commands keep the group, and `byColor` leaves it under every color's group. The strokes - are separate objects: after Expand, recoloring, moving or deleting a traced path leaves them as they are, and deleting - the group removes them. The reply's - `paths` and `anchors` count the traced paths only. + An Abutting trace with Fills (not Flat Logo) also holds a clip group named `Seam Fills` under its paths. For each + color it holds one stroke along the edges where a filled path of that color meets a filled path drawn after it, in + that color (a gradient path's stroke takes its gradient), with butt caps and round joins. The stroke is 1.5 image + pixels wide, VectorCraft's own width, at the image's larger scale when the image is stretched more one way. The group + clips the strokes to the image's box. Where a shared edge ends at, or runs within 0.75 image pixels of, a transparent + area or a color left out, its stroke can reach up to 0.75 image pixels into that area. Paths that became live shapes + (`shapes`) take no part. The traced paths and their shared edges are the same with or without the group. A trace + whose paths have more than about half of the trace's anchor limit (8,000,000, 2,000,000 on the web) has no seam + fills. Both Expand commands keep the group, and `byColor` leaves it under every color's group; `byColor` refuses a + trace whose seam fills' group was moved above a path. The strokes are separate objects, in a trace and after Expand: + recoloring, moving or deleting a traced path leaves them as they are, and deleting the group removes them. The + reply's `paths` and `anchors` count the traced paths only. With `keepColors` in `params`, the reply's `warnings` name each listed color that no traced color matches, and say when nothing was traced. `imageTrace.presets.save {name?, newName?, preset?, enhanced?, params?}` saves tracing settings as a preset kept with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2c05c6860a..6c0866af32 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1510,7 +1510,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Document Library color groups:** with Document Swatches, the panel's Colors menu and `"colorGroup"` trace with one color group's colors instead of every swatch, as the public panel documentation describes Document Library; code-drawn tests in `crates/engine` and the panel. - **Image Trace, Document Library colors:** with Document Swatches, traced fills and strokes use the displayed colors of process, global, spot and tint swatches without links, so editing a swatch leaves the trace unchanged; swatch-library colors are also unlinked; code-drawn tests in `crates/engine`. - **Image Trace, flattened slivers:** in a Color, Grayscale or Black and White trace with Fills, a traced region whose outline straightens onto one line (a single pixel, or a one-pixel row along an edge, its pieces shared with the regions beside it) is left out instead of becoming a selectable path with no area, which paints nothing. Snap Curves To Lines straightens more outlines, so it leaves out more of these. Without Fills, the region's 1 px stroke draws it, and it is kept. Code-drawn tests in `crates/trace`. -- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` group under its paths, with 1.5 px strokes along the edges two filled paths share, in the lower path's color (VectorCraft's own width), so renderers that anti-alias each path on its own show no light hairline along those edges. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` in `crates/engine`. Scores and hours unchanged. +- **Image Trace, Abutting seam fills:** an Abutting trace with Fills holds a `Seam Fills` clip group under its paths, with strokes along the edges two filled paths share, in the lower path's color, 1.5 image pixels wide (VectorCraft's own width) and clipped to the image's box. The paths and their shared edges are unchanged. Tests: `seam::tests` in `crates/trace`, `image_trace_abutting_seam_fills_sit_under_the_paths` in `crates/engine`. - **Image Trace, Auto Color rare colours:** the Automatic palette keeps colours too rare for its area count when they are distinct (Oklab) and drawn as coherent regions, at most six, protected from mixed-colour merging and Noise; code-drawn stem, highlight, low-contrast and scattered-noise tests (see [quality notes](image-trace-quality.md#auto-color-keeps-rare-colours)). - **Image Trace, nearly flat dark grounds:** with a Limited palette of 9 to 16 colors (16 Colors, and Document Library without swatches), by VectorCraft's own rule, a cut whose two sides both have a dark gray mean (Oklab lightness under 0.30, chroma under 0.03) and lie less than 0.03 apart in Oklab has its gain scaled by (distance / 0.03)². A near-black ground with faint noise then traces in one color, and the color it would have taken goes to another cut. Code-drawn tests `a_nearly_flat_dark_ground_keeps_one_color`, `only_a_limited_palette_of_nine_to_sixteen_colors_weighs_alike_sides` and `a_dark_colored_figure_on_a_nearly_flat_dark_ground_keeps_its_color` in `crates/trace`. - **Image Trace, Document Library keeps neutral tones neutral:** each pixel takes the library color nearest in Oklab with differences in hue and chroma counted three times, so a gray or a muted brown traces as a neutral library color instead of a saturated one of similar lightness; a code-drawn test of gray and brown patches with a black, light and blue library in `crates/trace`. From 495513f0b6f122054394d23855085fd87e2b25f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 03:20:41 -0800 Subject: [PATCH 24/77] Pen input: out-of-range pressure, tilt, rotation and size values are refused The drawing commands that read pen values at their points (path.freehand, brush.freehand, path.knife, path.eraseRegion, path.eraseSegments, path.smoothRegion, path.joinScrub and path.blob) now refuse a pressure outside 0 to 1, a tiltX or tiltY outside -90 to 90 and a rotation outside 0 to 360, naming the key. A tilt was kept within range and a pressure or rotation was passed on. A point array of more than six numbers is refused, naming the point, instead of having its extra entries ignored. path.blob and path.eraseRegion refuse a size outside 0.1 to 1000 pt, the range of the Blob Brush and Eraser tool options. path.blob refuses a sizeVariation outside 0 to 1000 pt in every sizeMode and with the mode left out. path.eraseRegion refuses a sizeVariation over 1000 pt in every mode with the same message, and a negative one still gives "sizeVariation must be 0 or more". Each refusal leaves the document, the selection and the undo history unchanged; null and omitted values still take the defaults. The tip variation test uses a 1000 pt tip and a 1000 pt Fixed variation, the largest values path.eraseRegion now takes. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/draw2/commands.rs | 14 +-- crates/engine/src/cmd/draw2/common.rs | 56 ++++++++--- crates/engine/src/cmd/draw2/cut.rs | 24 ++--- crates/engine/src/cmd/draw2/freehand.rs | 9 +- crates/engine/src/tests/draw2.rs | 118 +++++++++++++++++++++++- docs/mcp.md | 17 +++- docs/target-app-parity.md | 1 + 7 files changed, 194 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 49e277e5a0..f668889062 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), @@ -83,7 +83,7 @@ pub fn specs() -> Vec { "Knife", [], None, - "{points: [[x,y]…]} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the cut)} cut closed shapes (selected, or all when nothing is selected) along the polyline → {ids}", has_doc, knife ), @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing", has_doc, erase_region ), @@ -101,7 +101,7 @@ pub fn specs() -> Vec { "Path Eraser", [], None, - "{points: [[x,y]…], width?: pt (8)} erase the parts of selected paths under the drag → {ids}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change what is erased), width?: pt (8)} erase the parts of selected paths under the drag → {ids}", has_selection, erase_segments ), @@ -110,7 +110,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…], radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", has_selection, smooth_region ), @@ -119,7 +119,7 @@ pub fn specs() -> Vec { "Join", [], None, - "{points: [[x,y]…], tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", has_doc, join_scrub ), @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Blob Brush", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", + "{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), sizeMode?: \"fixed\" (default) | \"pressure\" (Blob Brush Tool Options' Size set to Pressure: the brush is size − sizeVariation wide at the lightest pen pressure and size + sizeVariation at the heaviest, at least 0.1 pt; a stroke without pressure keeps the size), sizeVariation?: pt (0; from 0 to 1000, checked with Fixed too), angle?: ° (0, kept within −180–180: the tip's long axis counter-clockwise from horizontal, kept on the page along the stroke), roundness?: % (100, kept within 0–100: the tip's short axis in percent of its long one, 100 round; 0 is drawn as 0.1), fidelity?: pt (0.01–100; the brush follows the stroke fitted at this tolerance as path.freehand fits a Pencil stroke, and a higher value gives a smoother shape; without it the brush follows every point), merge?: true, mergeOnlySelection?: bool (false: merge with any touching same-color blob; true: only with selected ones), keepSelected?: bool (false: the drawn or merged path is not selected, and the rest of the selection stays; true: it is selected)} filled brush shape, merged with the topmost touching same-color blob and the touching ones next to it in stacking order in its group or layer → {id}", has_doc, blob ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index fd8967f3fa..332ad331dc 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -28,6 +28,27 @@ pub(super) struct Sample { /// x and y. const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"]; +/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation +/// 0..360 degrees (360 is the same direction as 0). +const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)]; + +/// Blob Brush and Eraser Tool Options' Size, in points. +pub(super) const SIZES: (f64, f64) = (0.1, 1000.0); + +/// Blob Brush and Eraser Tool Options' Size Variation, in points. +pub(super) const SIZE_VARIATIONS: (f64, f64) = (0.0, 1000.0); + +/// `v`, or an error naming `key` when it is outside `lo..=hi` (or not a number at all, NaN). +fn within(v: f64, key: &str, (lo, hi): (f64, f64), cmd: &str) -> Result { + if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))) } +} + +/// The number `p` gives for `key`, `default` when it leaves it out or gives null, as [`number_or`] +/// reads it, or an error naming `key` when the number is outside `range`. +pub(super) fn ranged(p: &Value, key: &str, default: f64, range: (f64, f64), cmd: &str) -> Result { + within(number_or(p, key, default, cmd)?, key, range, cmd) +} + /// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite /// number. pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { @@ -42,27 +63,36 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { /// [`points_param`] with what a pen read at each point, as far as it is given: /// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure /// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in -/// degrees clockwise. A point whose x or y is not a number, or whose pressure, tilt or rotation is -/// neither a number nor null, is an error. +/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or +/// rotation is neither a number nor null or is outside its range, or an array of more than six +/// numbers, is an error. pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result> { let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?; let pts: Vec = a .iter() - .map(|v| { + .enumerate() + .map(|(at, v)| { + const MAX_ITEMS: usize = 2 + PEN_KEYS.len(); + if let Value::Array(xy) = v + && xy.len() > MAX_ITEMS + { + let key = format!("{key}[{at}]"); + return Err(bad(cmd, format!("`{key}` must be an array of at most {MAX_ITEMS} entries"))); + } let mut pen = [None; 4]; - for (i, (key, slot)) in PEN_KEYS.iter().zip(&mut pen).enumerate() { + for (i, ((key, range), slot)) in PEN_KEYS.iter().zip(PEN_RANGES).zip(&mut pen).enumerate() { let given = match v { Value::Array(xy) => xy.get(i + 2), _ => v.get(*key), }; *slot = match given { None | Some(Value::Null) => None, - Some(n @ Value::Number(_)) => n.as_f64(), + Some(n @ Value::Number(_)) => n.as_f64().map(|x| within(x, key, range, cmd)).transpose()?, Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))), }; } let [pressure, tx, ty, rotation] = pen; - let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0).clamp(-90.0, 90.0))); + let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0))); Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation }) }) .collect::>()?; @@ -186,18 +216,14 @@ impl PenRecord { } /// Blob Brush and Eraser Tool Options' Size set to Pressure (`sizeMode: "pressure"`, with -/// `sizeVariation` in points): the stroke's pen pressure along it and the variation, `None` for -/// Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the size. +/// `sizeVariation` in points, 0..1000): the stroke's pen pressure along it and the variation, `None` +/// for Fixed (the default), no variation or a stroke without pressure (a mouse), which keeps the +/// size. A `sizeVariation` outside its range is an error with Fixed too. pub(super) fn size_pressure(p: &Value, samples: &[Sample], cmd: &str) -> Result> { + let variation = ranged(p, "sizeVariation", 0.0, SIZE_VARIATIONS, cmd)?; match p.get("sizeMode").filter(|v| !v.is_null()).map(|v| v.as_str().ok_or(v)) { None | Some(Ok("fixed")) => Ok(None), - Some(Ok("pressure")) => { - let variation = number_or(p, "sizeVariation", 0.0, cmd)?; - if !(variation.is_finite() && variation >= 0.0) { - return Err(bad(cmd, "sizeVariation must be 0 or more")); - } - Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))) - } + Some(Ok("pressure")) => Ok(stroke_pressure(samples).filter(|_| variation > 0.0).map(|prof| (prof, variation))), Some(Ok(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not `{other}`"))), Some(Err(other)) => Err(bad(cmd, format!("sizeMode is \"fixed\" or \"pressure\", not {other}"))), } diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 64b8bdee16..e3a019e6a8 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -1,6 +1,6 @@ use super::common::{ - PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, - samples_param, sibling_with, size_pressure, target_paths, usize_opt, + PenRecord, SIZE_VARIATIONS, SIZES, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, + pressure_region, ranged, replace_with_pieces, samples_param, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session, @@ -275,10 +275,7 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseRegion"; let samples = samples_param(p, "points", C)?; - let size = number_or(p, "size", 10.0, C)?; - if !(size.is_finite() && size > 0.0) { - return Err(bad(C, "size must be positive")); - } + let size = ranged(p, "size", 10.0, SIZES, C)?; let angle = number_or(p, "angle", 0.0, C)?; let roundness = number_or(p, "roundness", 100.0, C)?; let vary = eraser_variations(p, C)?; @@ -331,12 +328,13 @@ const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bea /// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with /// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation` -/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how -/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null -/// is 0; any other mode, or a variation that is negative or past its most, is refused. +/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points, at most 1000), its +/// mode and how far it varies either way. A mode left out or null is Fixed, and a variation left +/// out or null is 0; any other mode, or a variation that is negative or past its most, is refused, +/// in every mode. fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> { const KEYS: [(&str, &str, f64); 3] = - [("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)]; + [("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", SIZE_VARIATIONS.1)]; let mut out = [(Variation::Fixed, 0.0); 3]; for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) { let mode = match p.get(mode_key).filter(|v| !v.is_null()) { @@ -349,7 +347,11 @@ fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> { return Err(bad(cmd, format!("{var_key} must be 0 or more"))); } if variation > most { - return Err(bad(cmd, format!("{var_key} must be at most {most}"))); + // Size Variation is refused as path.blob refuses it. + return Err(match var_key { + "sizeVariation" => bad(cmd, format!("`{var_key}` must be from {} to {most}", SIZE_VARIATIONS.0)), + _ => bad(cmd, format!("{var_key} must be at most {most}")), + }); } *slot = (mode, variation); } diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 977f3f921a..85b44c8445 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -1,6 +1,6 @@ use super::common::{ - PenRecord, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, samples_param, size_pressure, stroke_paint, - subpath_len, target_paths, within_input_bound, + PenRecord, SIZES, Sample, brush_region, path_kind, path_mut, path_of, poly_bounds, pressure_region, ranged, samples_param, size_pressure, + stroke_paint, subpath_len, target_paths, within_input_bound, }; use super::{ Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point, @@ -480,10 +480,7 @@ fn adjacent_to_topmost(doc: &Document, touched: &[NodeId], paint: &Paint) -> Vec pub(super) fn blob(s: &mut Session, p: &Value) -> Result { const C: &str = "path.blob"; let samples = samples_param(p, "points", C)?; - let size = number_or(p, "size", 10.0, C)?; - if !(size.is_finite() && size > 0.0) { - return Err(bad(C, "size must be positive")); - } + let size = ranged(p, "size", 10.0, SIZES, C)?; let angle = number_or(p, "angle", 0.0, C)?; let roundness = number_or(p, "roundness", 100.0, C)?; if !angle.is_finite() || !roundness.is_finite() { diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 45ff1f84c1..a4c4fe2a65 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -677,16 +677,16 @@ fn the_eraser_tip_varies_with_its_modes() { assert!((upright - 195.0).abs() < 0.3, "the upright tip left {upright} pt of the line"); let level_tip = left_of_line(json!([])); assert!((level_tip - 180.0).abs() < 0.3, "the level tip left {level_tip} pt of the line"); - // A 1500 pt tip on Tilt erases 1500 pt across with a mouse, as it does on Fixed. + // A 1000 pt tip on Tilt erases 1000 pt across with a mouse, as it does on Fixed. let mut s = session(); rect(&mut s, 0.0, 0.0, 4000.0, 4000.0); - let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1500, "sizeMode": "tilt", "sizeVariation": 10}); + let big = json!({"points": [[1000, 2000], [3000, 2000]], "size": 1000, "sizeMode": "tilt", "sizeVariation": 10}); s.execute("path.eraseRegion", &big).unwrap(); let filled = |x: f64, y: f64| paths(&s).iter().any(|(_, pd)| vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y))); - assert_eq!((filled(2000.0, 2740.0), filled(2000.0, 2760.0)), (false, true), "a 1500 pt tip"); + assert_eq!((filled(2000.0, 2490.0), filled(2000.0, 2510.0)), (false, true), "a 1000 pt tip"); // A Size Variation kept while Size is Fixed leaves the size alone. - let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000000})); + let kept = with(&on_rotation, json!({"sizeMode": "fixed", "sizeVariation": 1000})); assert_eq!(erased(kept, json!([]), &probes), [true, false], "Size on Fixed with a Variation"); let mut s = session(); let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); @@ -2771,6 +2771,116 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() { s.execute("path.eraseRegion", &sized).unwrap(); } +/// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90 +/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six +/// numbers, naming the point; the document, the selection and the undo history stay as they were. +/// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw. +#[test] +fn pen_values_outside_their_ranges_are_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let good = [json!([90, 150]), json!([150, 150]), json!([210, 150])]; + let cmds = [ + "path.freehand", + "brush.freehand", + "path.knife", + "path.eraseRegion", + "path.eraseSegments", + "path.smoothRegion", + "path.joinScrub", + "path.blob", + ]; + let pressure = "`pressure` must be from 0 to 1"; + let tilt_x = "`tiltX` must be from -90 to 90"; + let tilt_y = "`tiltY` must be from -90 to 90"; + let rotation = "`rotation` must be from 0 to 360"; + let entries = "`points[3]` must be an array of at most 6 entries"; + for cmd in cmds { + for (bad, want) in [ + (json!([150, 150, -0.01]), pressure), + (json!([150, 150, 1.5]), pressure), + (json!({"x": 150, "y": 150, "pressure": 1e300}), pressure), + (json!([150, 150, 0.5, -90.5]), tilt_x), + (json!([150, 150, 0.5, 91, 0]), tilt_x), + (json!({"x": 150, "y": 150, "tiltX": -1e300}), tilt_x), + (json!([150, 150, null, 0, -1e300]), tilt_y), + (json!({"x": 150, "y": 150, "tiltY": 90.01}), tilt_y), + (json!([150, 150, null, null, null, -1]), rotation), + (json!({"x": 150, "y": 150, "rotation": 360.5}), rotation), + (json!([150, 150, null, null, null, 720]), rotation), + (json!([150, 150, 0.5, 0, 0, 0, 1]), entries), + (json!([150, 150, null, null, null, null, null]), entries), + ] { + let points: Vec<_> = good.iter().cloned().chain([bad]).collect(); + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &json!({"points": points}), want); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {points:?} changed the selection"); + } + } + for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() { + let y = 300.0 + 50.0 * row as f64; + let points = json!([ + [100, y, 0, -90, 90, 0], + [150, y, 1, 90, -90, 360], + [200, y, 0.5, null, 30], + {"x": 250, "y": y, "tiltX": -45, "pressure": null}, + [300, y], + {"x": 350, "y": y, "rotation": 359.99}, + ]); + s.execute(cmd, &json!({"points": points})).unwrap_or_else(|e| panic!("{cmd}: {e}")); + let mouse = json!([[100, y + 20.0], [200, y + 20.0], [300, y + 25.0]]); + s.execute(cmd, &json!({"points": mouse})).unwrap_or_else(|e| panic!("{cmd} with mouse points: {e}")); + } +} + +/// `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt and a `sizeVariation` +/// outside 0 to 1000 pt, in every `sizeMode` each takes and with it left out, and a `sizeVariation` +/// that is not a number with Fixed too; nothing changes. The ends of each range and null still draw. +#[test] +fn blob_and_eraser_size_and_variation_outside_their_ranges_are_refused() { + let mut s = session(); + let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let stroke = json!({"points": [[90, 150, 0.2, 30, 0, 45], [150, 150, 0.6, 0, 30, 90], [210, 150, 1, -30, 0, 180]]}); + let size = "`size` must be from 0.1 to 1000"; + let variation = "`sizeVariation` must be from 0 to 1000"; + let blob_modes = [json!(null), json!("fixed"), json!("pressure")]; + let eraser_modes = [json!(null), json!("fixed"), json!("random"), json!("pressure"), json!("tilt"), json!("bearing"), json!("rotation")]; + // The Eraser keeps its own message for a negative Size Variation. + for (cmd, modes, negative) in + [("path.blob", &blob_modes[..], variation), ("path.eraseRegion", &eraser_modes[..], "sizeVariation must be 0 or more")] + { + for x in [json!(0.09), json!(0), json!(-1), json!(1000.5), json!(1e300)] { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &with(&stroke, json!({"size": x})), size); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} size {x} changed the selection"); + } + for mode in modes { + for (x, want) in [(json!(-0.5), negative), (json!(1000.01), variation), (json!(1e300), variation)] { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, cmd, &with(&stroke, json!({"sizeMode": mode, "sizeVariation": x})), want); + assert_eq!(s.doc().unwrap().selection, sel, "{cmd} {mode} sizeVariation {x} changed the selection"); + } + let text = json!({"sizeMode": mode, "sizeVariation": "8"}); + refuses_with(&mut s, cmd, &with(&stroke, text), "`sizeVariation` must be a number, not \"8\""); + } + } + for (row, (cmd, modes)) in [("path.blob", &blob_modes[..]), ("path.eraseRegion", &eraser_modes[..])].into_iter().enumerate() { + let y = 300.0 + 100.0 * row as f64; + let at = |p: serde_json::Value| with(&json!({"points": [[100, y, 0.2, 30, 0, 0], [200, y, 0.6, 0, 30, 90], [300, y, 1, -30, 0, 360]]}), p); + for extra in [json!({"size": 0.1}), json!({"size": 1000}), json!({"size": null, "sizeVariation": null, "sizeMode": null})] { + s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}")); + } + for mode in modes { + for x in [0, 1000] { + let extra = json!({"sizeMode": mode, "sizeVariation": x}); + s.execute(cmd, &at(extra.clone())).unwrap_or_else(|e| panic!("{cmd} {extra}: {e}")); + } + } + } +} + /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, /// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. diff --git a/docs/mcp.md b/docs/mcp.md index bb0fba8d46..e00a1e4731 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3420,7 +3420,7 @@ already walks Image Trace. Short agent entry points: `[x, y, pressure, tiltX, tiltY, rotation]` or `{x, y, pressure?, tiltX?, tiltY?, rotation?}`, with `null` for what a point lacks, and a `pointer_gesture` event takes `tiltX`, `tiltY` and `rotation`, which the Paintbrush records. `tiltX` and `tiltY` are degrees −90..90 in document axes, positive leaning right and leaning down the page (one - without the other is 0); `rotation` is the barrel's rotation in degrees clockwise. The stroke keeps how far the pen + without the other is 0); `rotation` is the barrel's rotation in degrees clockwise, 0..360. The stroke keeps how far the pen leaned (`tilt`, 0 upright to 1 lying flat), which way (`bearing`, degrees counter-clockwise from leaning right; a pen within 1° of upright takes the bearing before it, or at the start of the stroke its first one) and how far the barrel turned (`rotation`, degrees counter-clockwise). A point without a tilt that other points have counts as @@ -5717,11 +5717,24 @@ moves that point alone as the focal point, with or without Shift (Shift keeps th focal points stay highlighted where it left them; Escape during a drag puts the path back and keeps them, and switching to another tool clears them. +`path.freehand`, `brush.freehand`, `path.knife`, `path.eraseRegion`, `path.eraseSegments`, `path.smoothRegion`, +`path.joinScrub` and `path.blob` refuse a pen `pressure` outside 0 to 1, a `tiltX` or `tiltY` outside -90 to 90 and a +`rotation` outside 0 to 360 with an error such as `` `tiltX` must be from -90 to 90 ``, naming the key, and a point +given as an array of more than six numbers with `` `points[3]` must be an array of at most 6 entries ``, naming the +point. `path.blob` and `path.eraseRegion` refuse a `size` outside 0.1 to 1000 pt with +`` `size` must be from 0.1 to 1000 `` and a `sizeVariation` over 1000 pt with +`` `sizeVariation` must be from 0 to 1000 ``, in every `sizeMode` and when it is left out. `path.blob` refuses a +negative `sizeVariation` with the same message, and `path.eraseRegion` with "sizeVariation must be 0 or more". The +document and the selection do not change and no undo step is recorded. A null is read as a key left out, and a point given as `[x, y]` +has no pen values. The pressure and tilt ranges are those of +[Pointer Events](https://www.w3.org/TR/pointerevents3/); the rotation, size and size variation ranges are +VectorCraft's own values. + `path.eraseRegion` (the Eraser) takes a variation mode for each of its tip's values, as the variation menus of Eraser Tool Options set them ([Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)): `angleMode` with `angleVariation` (degrees, 0 to 180), `roundnessMode` with `roundnessVariation` (percent, 0 to 100) -and `sizeMode` with `sizeVariation` (points, 0 or more), each `"fixed"` (the default), `"random"`, `"pressure"`, +and `sizeMode` with `sizeVariation` (points, 0 to 1000), each `"fixed"` (the default), `"random"`, `"pressure"`, `"tilt"`, `"bearing"` or `"rotation"`. A value that varies takes up to its variation either way. Random draws one value for the drag. Pressure goes from the value less the variation where the pen presses lightest to the value plus it where the pen presses hardest. Tilt goes from less with the pen lying flat to more with it upright. Bearing and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f08f2b9f19..5a16c4b482 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1148,6 +1148,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. + `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). With the Blob Brush, Shift held during a drag keeps the stroke on the horizontal or vertical line through the press point, whichever is nearer to the pointer (90° steps from the Constrain Angle preference), and the points dragged since Shift went down move to the other line when the pointer crosses to it; the points dragged while Shift is up follow the pointer. With the Blob Brush, Alt held before the press, or pressed before the drag has moved, switches to the Smooth tool, as the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists: the cursor shows the Smooth tool (Not Allowed with no path selected that it can act on), the drag shows a thin line and, with a path selected that it can smooth, the dashed band it smooths, without the length label, Shift does not constrain it, and the release smooths the selected paths under the drag (`path.smoothRegion`) instead of painting; with nothing selected the release changes no path. A stroke that has moved keeps painting when Alt goes down. Curvature point markers are circular, with no direction handles. While drawing, its own point feedback replaces generic selection markers; existing paths use the selection overlay, including partial selections and Hide Edges. Anchor Size applies, and Direct Selection and Pen retain their handles. The real egui-frame regressions in `crates/ui-egui/src/canvas.rs` verify marker positions, counts and unchanged documents (#1236, in part); the existing-path interpolation request remains open. The curve through the points (`curvature_spline` in `crates/tools/src/draw2.rs`) makes each stretch of three points follow the circle through them: a smooth point's handles lie along that circle's tangent, each `chord / (3 cos²(α/2))` long (α between handle and chord, capped at 90°), and the ends of an open path mirror their neighbour's tangent in their chord, so a J or a U curves evenly, a turn tighter than 30° comes to a point, and uneven spacing doesn't loop; the rubber band, a dragged or inserted point and `path.convertAnchor` to smooth use the same rule, while the Pencil's fitting keeps its own; `tests/draw2.rs` checks that the rubber band is the path the click makes (#1236, in part). The Smooth tool smooths only the stretch of path under the drag (#1547, fixes #1512). A path the Smooth tool changes stays selected whole, and the anchor points and segments selected on it with Direct Selection are deselected. Selected paths the drag does not change keep their selected anchors, and undo restores the earlier selection (`tests/draw2.rs`, `smoothing_a_path_drops_its_direct_selected_anchors`). While the Smooth tool drags with a path selected that it can smooth, a dashed outline shows the band it smooths: everything within its radius of the drag (12 screen pixels, VectorCraft's own value), round at both ends; Alt smoothing with the Pencil, Paintbrush and Blob Brush shows the same band. From f9a2abad18eb1891e7ea1c107836138bcb149f16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:01:23 -0800 Subject: [PATCH 25/77] Paragraph: Kurikaeshi Moji Shori draws a line-start repeat mark as the character it repeats MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Paragraph panel menu > Kurikaeshi Moji Shori (text.setFormat {kurikaeshiMojiShori}) is a paragraph attribute, off by default, saved only when on and carried by paragraph styles. On, a repeat mark (々, ゝ, ゞ, ヽ, ヾ) that starts a line of point or area type is drawn as the character it repeats, with the mark's width, and the text keeps the mark. Threaded type looks back into the frames before when a paragraph continues. Live SVG text writes the drawn character and places the text after it. --- crates/doc/src/live/envelope.rs | 1 + crates/doc/src/text.rs | 6 + crates/doc/src/text/object.rs | 1 + crates/doc/src/text/para_style.rs | 9 ++ crates/engine/src/cmd/panelcmds.rs | 6 +- crates/engine/src/cmd/textedit.rs | 2 + crates/engine/src/cmd/textstyles.rs | 1 + crates/engine/src/cmd/threads.rs | 36 +++++- crates/engine/src/cmd/threads/tests.rs | 36 ++++++ crates/engine/src/cmd/typecmd/area_tests.rs | 56 +++++++++ crates/svg/src/export/text.rs | 27 ++++- crates/svg/tests/it/text_layout.rs | 31 +++++ crates/text/src/layout/flow.rs | 45 ++++++- crates/text/src/lib.rs | 7 +- crates/text/src/shape.rs | 59 ++++++++++ crates/text/src/test_fonts.rs | 53 +++++++++ crates/text/src/tests.rs | 117 +++++++++++++++++++ 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 + crates/ui-egui/src/panels/paragraph.rs | 17 ++- crates/ui-egui/src/panels/paragraph/tests.rs | 31 +++++ docs/mcp.md | 24 ++++ docs/type-parity.md | 1 + 49 files changed, 583 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 5aa43b0a67..a0ad0eb1e4 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -316,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> { let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits))); for h in &mut feed.0 { h.write_u8(u8::from(text.first_para_continues)); + h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from)); for b in inline_bounds.clone() { match b { None => h.write_u8(0), diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index d165a086fb..064f18effe 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -67,6 +67,12 @@ pub struct TextObject { /// it on a frame that leaves its thread and on a copy. Not saved. #[serde(skip)] pub first_para_continues: bool, + /// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the + /// last character of that paragraph in the frames before that a repeat mark could stand for + /// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout + /// reads it only while `first_para_continues` is on. Not saved. + #[serde(skip)] + pub first_para_lead: Option, /// Area Type Options (area type only). #[serde(default, skip_serializing_if = "crate::skip::is_default")] pub area: AreaOptions, diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index b787cebfe0..617d860927 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -94,6 +94,7 @@ impl TextObject { para: ParaStyle::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: AreaOptions::default(), path_effect: PathEffect::default(), path_align: PathAlign::default(), diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index c3db242ed0..62c6b8dd33 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -271,6 +271,9 @@ pub struct ParaStyle { /// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept /// with kinsoku None, where it has no effect. Off by default. pub bunri_kinshi: bool, + /// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts + /// a line is drawn as the character it repeats, and the text keeps the mark. Off by default. + pub kurikaeshi_moji_shori: bool, /// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and /// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses, /// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari. @@ -375,6 +378,8 @@ struct ParaStyleFile { #[serde(default, skip_serializing_if = "crate::skip::is_default")] bunri_kinshi: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] + kurikaeshi_moji_shori: bool, + #[serde(default, skip_serializing_if = "crate::skip::is_default")] roman_hanging: bool, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kashida: Kashida, @@ -412,6 +417,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -439,6 +445,7 @@ impl From for ParaStyleFile { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -470,6 +477,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, @@ -496,6 +504,7 @@ impl From for ParaStyle { kinsoku, kinsoku_type, bunri_kinshi, + kurikaeshi_moji_shori, roman_hanging, kashida, korean_line_break_anywhere, diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 20905ffdae..e012257c53 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; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", + "{ids?|id?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), underline?, strikethrough?, allCaps?, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), antiAlias?: \"none\"|\"sharp\"|\"crisp\"|\"strong\" (Character panel › Anti-aliasing Method, how the type's edges are drawn as pixels; it sets each targeted type object, with or without a range; each frame of a thread keeps its own method; graph labels keep it for every label of their kind when the graph is drawn again; new type: \"sharp\"), leftIndent?, rightIndent?, firstLineIndent?, spaceBefore?, spaceAfter?: pt (±1296), list?: \"none\"|\"bullet\"|\"number\", bullet?: \"none\"|\"dot\"|\"dash\"|\"circle\"|\"square\", number?: \"none\"|\"arabic\"|\"upperLetters\"|\"lowerLetters\"|\"upperRoman\"|\"lowerRoman\"|\"twoDigits\"|\"threeDigits\", listAlign?: \"left\"|\"right\", listLevel?: 1..9 (Paragraph panel › Bullets and Numbered List: each paragraph of a list starts with its marker, drawn in the font, size and color of the paragraph's first character, and its text starts at the next tab stop after the marker, the left indent counting as a stop; a bulleted list's marker is its bullet, and a numbered list's is the paragraph's number and a period: 1, 2, 3; A to Z, then AA, BB; a to z, then aa, bb; I, II, III; i, ii, iii; 01 to 99, then 100; 001 to 999, then 1000; letters and roman numerals past 3999 in Arabic digits; the numbers count the story's numbered paragraphs, its threaded frames included, from 1 after a paragraph in no list, and an empty or bulleted paragraph is not counted; list \"bullet\" keeps a list's bullet, else a dot, and list \"number\" keeps a numbered list's style, else arabic; without list, a number style makes a numbered list and a bullet makes a bulleted one; \"none\" in any of the three turns the list off; a paragraph that joins a list with left and first-line indents of 0 gets 18 and -18 unless the call sets an indent; a horizontal right-to-left list paragraph has its indents mirrored, measured from the right; listAlign \"right\" (Bullets and Numbering…'s Alignment) puts the marker against the text, and \"left\" (the default) puts it at the first line's start, the text starting at the same place with either; it sets the paragraphs that are in a list or that the call puts in one, and a list keeps it when it changes between bullets and numbers; listLevel (Tab and Shift+Tab at the start of a list paragraph, Bullets and Numbering…'s Level) is a whole number from 1 to 9 that sets the paragraphs in a list or that the call puts in one, a list keeping it when it changes between bullets and numbers, and a list turned on without listLevel starting at level 1; each level past the first sets the paragraph 18 pt further in than its left indent, and each level counts its own numbers: a list paragraph with text sets the counts of the levels deeper than its own back to 0, so a deeper numbered paragraph after it counts from 1, and a paragraph back at a shallower level goes on with that level's count), hyphenate?: bool, wordsLongerThan?: letters 1..25 (5), afterFirst?, beforeLast?: letters 1..15 (3), hyphenLimit?: lines 0..25 (0: no limit), hyphenationZone?: pt 0..1296 (0; Single-line Composer only), hyphenateCapitalized?: bool (true) (Paragraph panel menu › Hyphenation…: only words longer than wordsLongerThan break, keeping afterFirst letters before the hyphen and beforeLast after it; at most hyphenLimit lines in a row end with a hyphen; a line whose text already ends within hyphenationZone of its right edge breaks before the next word instead of hyphenating it; the counts are rounded, and every value is clamped to its range), wordSpacing?: % 0..1000 (80, 100, 133), letterSpacing?: % of a word space -100..500 (0, 0, 0), glyphScaling?: % 50..200 (100, 100, 100): each [min, desired, max] or {min?, desired?, max?} (Paragraph panel menu › Justification…: Desired applies to every line, Minimum and Maximum bound what justified lines may use; values are clamped to their range, and Minimum ≤ Desired ≤ Maximum must hold afterwards or nothing changes), autoLeading?: % of the size 0..500 (120; the leading of characters whose leading is Auto), singleWordJustification?: \"fullJustify\"|\"alignLeft\"|\"alignCenter\"|\"alignRight\" (a justified line holding one word), mojikumi?: \"none\"|\"yakumonoHankaku\"|\"gyomatsuYakumonoHankaku\"|\"gyomatsuYakumonoZenkaku\"|\"yakumonoZenkaku\"|\"lineEndHalf\" (Mojikumi Set: Japanese punctuation spacing), kinsoku?: \"none\"|\"hard\"|\"soft\" (Kinsoku Set: Soft lets 々, ー and small kana start a line), kinsokuType?: \"pushInFirst\"|\"pushOutFirst\"|\"pushOutOnly\" (Paragraph panel menu › Kinsoku Shori Type: how area type keeps those characters off a line's ends; pushInFirst sets them on the line when its gaps next to CJK characters can close up enough, by at most a tenth of an em each, pushOutFirst does so only when moving the character before them to the next line would leave the line more than an em short, and pushOutOnly, the default, moves it unless Burasagari hangs an overflowing comma or full stop; no effect with kinsoku \"none\"), bunriKinshi?: bool (Paragraph panel menu › Bunri-Kinshi: a line never breaks inside an inseparable pair, two em dashes, two horizontal ellipses, two two-dot leaders or the two halves of a vertical kana repeat mark, and justification adds no space inside one; kept but without effect with kinsoku \"none\"; off by default), kurikaeshiMojiShori?: bool (Paragraph panel menu › Kurikaeshi Moji Shori: a repeat mark 々, ゝ, ゞ, ヽ or ヾ that starts a line is drawn as the character before it, the voiced marks ゞ and ヾ as its voiced form when it has one, and the text keeps the mark; off by default),direction?: \"auto\"|\"leftToRight\"|\"rightToLeft\" (paragraph direction; auto: from each paragraph's first strong character), leadingModel?: \"romanBaseline\"|\"emBoxTop\" (leading measured baseline to baseline, or em box top to top), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (where characters smaller than the largest on their line line up with it), proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings, as text.setRangeStyle: a tate-chu-yoko block moves up or down, right or left, and on a vertical path toward or away from the path's start, to its left or right), warichu?: bool, warichuLines?: 1..6, warichuGap?: pt 0..100, warichuScale?: % 10..100, warichuAlign?: \"auto\"|\"left\"|\"center\"|\"right\"|\"justifyLeft\"|\"justifyCenter\"|\"justifyRight\"|\"justifyAll\" (Character panel menu › Warichu and Warichu Settings, as text.setRangeStyle: the characters set smaller and stacked on lines inside their line), akiLeft?, akiRight?: 1/1000 em 0..1000 (Character panel › Insert Aki Left and Right, with Show East Asian Options, as text.setRangeStyle: space before and after each character in reading order), tsume?: % 0..100 (Character panel › Tsume, with Show East Asian Options, as text.setRangeStyle: the share of the blank space beside each character's ink taken away 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; a form other than \"default\" takes away their glyph choice), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference, as text.setRangeStyle: the height of the font that the size measures), language?: name|tag (Character panel › Language, as text.setRangeStyle), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font, as text.setRangeStyle: each axis named set in its units and clamped to its range, null back to the style's own setting), burasagari?: \"none\"|\"standard\"|\"forced\" (Paragraph panel menu › Burasagari None/Regular/Force: an East Asian comma or full stop ending an area type line hangs outside it: when it doesn't fit, or always; new type: \"standard\"), romanHangingPunctuation?: bool (Paragraph panel menu › Roman Hanging Punctuation: quotation marks, hyphens, full stops and commas starting or ending a line hang outside the margin, asterisks, tildes, ellipses, dashes, colons and semicolons by half; off by default), koreanLineBreakAnywhere?: bool (Paragraph panel menu › Korean Line Break Anywhere: a line may break between any two Hangul syllables; off, a word with Hangul in it breaks only at its spaces and punctuation, or where it is wider than the line; new type: false, paragraphs saved before the option: true), kashida?: \"none\"|\"short\"|\"medium\"|\"long\"|\"stylistic\" (Paragraph panel › Insert Kashidas: justified lines of horizontal area type lengthen each Arabic word with a kashida between its last pair of joined letters, at most a quarter, half or whole em long, or whole tatweels up to an em for stylistic, before they widen their word spaces; none by default), composer?: \"singleLine\"|\"everyLine\"|\"standardSingleLine\"|\"standardEveryLine\" (line breaking, Every-line by default; singleLine and everyLine are the Middle Eastern & South Asian composers, which shape Indic, Arabic and Hebrew type; the standard ones set it glyph by glyph as the font maps its characters, for legacy fonts that keep a script on Latin character codes), start?: byte, end?: byte} (baselineShift is in document points and hScale includes the object transform; groups include their text descendants; with a range: the character attributes style that range and the paragraph attributes apply to the paragraphs it touches; without: all the text, and graph labels keep the character and paragraph attributes for every label of their kind when the graph is drawn again, the graph still setting each label's alignment; a number or switch given as another type fails the call, and a null value leaves its attribute as it is, so a call with only null values fails with nothing to change; a call that gives the values the text already has records no undo step). Or {paragraphIndents: [{id, start: byte where the paragraph starts, leftIndent?, firstLineIndent?: pt -1296..1296}…]} alone (Tabs panel indent markers over paragraphs with indents of their own): each entry sets one paragraph of a type object, at least one indent each, at most 100000 entries; every entry is checked before anything changes, and an unknown key, a value out of range, an object that is not type, a byte where no paragraph starts or two entries for one paragraph with other values fail the call; all of it is one edit, a threaded story flowing again once, and when no paragraph's indents change nothing is recorded → {ids}", has_doc, set_format ), @@ -522,6 +522,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "romanHangingPunctuation", "koreanLineBreakAnywhere", "bunriKinshi", + "kurikaeshiMojiShori", ], C, )?; @@ -597,6 +598,7 @@ fn set_format(s: &mut Session, p: &Value) -> Result { "kinsoku", "kinsokuType", "bunriKinshi", + "kurikaeshiMojiShori", "direction", "leadingModel", "charAlign", @@ -989,6 +991,8 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = flag("bunriKinshi") { para.bunri_kinshi = v; } + // An omitted or null value keeps the paragraph's own. + para.kurikaeshi_moji_shori = flag("kurikaeshiMojiShori").unwrap_or(para.kurikaeshi_moji_shori); if let Some(v) = direction { para.direction = v; } diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 769ca7e6c5..0602e23a9a 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1806,6 +1806,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { para: super::create::new_type_para(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), @@ -2112,6 +2113,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option { para: Default::default(), paras: Vec::new(), first_para_continues: false, + first_para_lead: None, area: Default::default(), path_effect: Default::default(), path_align: Default::default(), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 18f87d44f7..a6878032b0 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -253,6 +253,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map { ("kinsoku", json!(v.kinsoku)), ("kinsoku_type", json!(v.kinsoku_type)), ("bunri_kinshi", json!(v.bunri_kinshi)), + ("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)), ("roman_hanging", json!(v.roman_hanging)), ("kashida", json!(v.kashida)), ("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)), diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index ad41d1d220..7ccf26d3de 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -225,7 +225,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { .collect(); let refs: Vec<&TextObject> = frames.iter().collect(); let parts = vectorcraft_text::thread::distribute(vectorcraft_text::FontDb::global(), &refs, &story, ¶s); - for (id, part) in live.iter().zip(parts) { + let texts: Vec = parts.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect()).collect(); + let leads = first_para_leads(&texts, &parts.iter().map(|p| p.continues).collect::>()); + for ((id, part), lead) in live.iter().zip(parts).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) { let mut next = (**t).clone(); next.runs = part.runs; @@ -241,6 +243,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { || part.list_count != t.list_count || part.list_level_counts != t.list_level_counts || continues != t.first_para_continues + || lead != t.first_para_lead { t.runs = next.runs; t.para = next.para; @@ -250,6 +253,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) { t.list_count = part.list_count; t.list_level_counts = part.list_level_counts; t.first_para_continues = continues; + t.first_para_lead = lead; refresh_bounds(t); } } @@ -384,17 +388,43 @@ pub(crate) fn mark_continued(doc: &mut Document) { let live: Vec = thread.into_iter().filter(|id| text_of(doc, *id).is_some()).collect(); let frames: Vec<&TextObject> = live.iter().filter_map(|id| text_of(doc, *id)).collect(); let marks = vectorcraft_text::thread::continued(&frames); - for (id, on) in live.iter().zip(marks) { + let texts: Vec = frames.iter().map(|t| t.plain_text()).collect(); + let leads = first_para_leads(&texts, &marks); + for ((id, on), lead) in live.iter().zip(marks).zip(leads) { if let Some(NodeKind::Text(t)) = doc.node_mut(*id).map(|n| &mut n.kind) - && t.first_para_continues != on + && (t.first_para_continues != on || t.first_para_lead != lead) { t.first_para_continues = on; + t.first_para_lead = lead; refresh_bounds(t); } } } } +/// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and +/// whether each one's first paragraph `continues` from the frame before: the last character of +/// that paragraph in the frames before that a repeat mark could stand for, or None. +fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec> { + (0..texts.len()) + .map(|k| { + let mut j = k; + while continues.get(j) == Some(&true) && j > 0 { + j -= 1; + let text = texts.get(j)?; + let tail = text.rfind('\n').map_or(Some(text.as_str()), |at| text.get(at + 1..))?; + if let Some(c) = vectorcraft_text::repeat_base(tail) { + return Some(c); + } + if tail.len() != text.len() { + return None; + } + } + None + }) + .collect() +} + #[cfg(test)] thread_local! { /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] went through the document's diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 2694a61e6c..ba2cbaa1d4 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -2226,3 +2226,39 @@ fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing() assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0); } + +/// Kurikaeshi Moji Shori: a frame whose first paragraph continues carries the last character of +/// that paragraph in the frames before that a repeat mark can stand for, looking past frames that +/// hold only repeat marks and stopping at the paragraph's start; a frame that starts a paragraph +/// carries none. Flowing the story and opening a file both set it. +#[test] +fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() { + let leads = |texts: &[&str], continues: &[bool]| first_para_leads(&texts.iter().map(|t| t.to_string()).collect::>(), continues); + assert_eq!(leads(&["時", "々す"], &[false, true]), [None, Some('時')]); + assert_eq!(leads(&["時", "々", "々"], &[false, true, true]), [None, Some('時'), Some('時')]); + assert_eq!(leads(&["時\nか\u{3099}", "ゝ"], &[false, true]), [None, Some('か')]); + assert_eq!(leads(&["時\n々", "々"], &[false, true]), [None, None]); + assert_eq!(leads(&["時\n", "々"], &[false, false]), [None, None]); + assert_eq!(leads(&[], &[]), Vec::>::new()); + // Opening a file marks the frames as they were saved. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap(); + let mut ids = Vec::new(); + for (x, text) in [(10, "日時"), (200, "々す")] { + let id = + s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap(); + ids.push(NodeId(id)); + } + let mut d = (*s.doc().unwrap().doc).clone(); + d.text_threads = vec![ids.clone()]; + mark_continued(&mut d); + let tb = text_of(&d, ids[1]).unwrap(); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, Some('時')); + // Flowing the story through the frames sets it from the text each frame now holds. + reflow(&d.clone(), &mut d); + let (ta, tb) = (text_of(&d, ids[0]).unwrap(), text_of(&d, ids[1]).unwrap()); + assert_eq!([ta.plain_text(), tb.plain_text()].concat(), "日時々す"); + assert!(tb.first_para_continues); + assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text())); +} diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index a63ebff9c4..6cff9a95a4 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -504,6 +504,62 @@ fn bunri_kinshi_is_set_per_paragraph_and_saved_only_when_on() { assert!(!text(&s).para_at(0).bunri_kinshi && !text(&s).para_at(1).bunri_kinshi); } +/// Paragraph panel menu › Kurikaeshi Moji Shori: off for new type and for a paragraph saved before +/// it, and saved only when on; `text.setFormat {kurikaeshiMojiShori}` sets it per paragraph in one +/// undo step, records nothing when the paragraphs already have the value, refuses a value that is +/// not true or false, and paragraph styles carry it. The text keeps its repeat marks. +#[test] +fn kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on() { + 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": 10, "size": 20, "text": "時々\nすゝ"})).unwrap()["id"].as_u64().unwrap(); + let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("text"), + }; + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori, "new type has it off"); + assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("kurikaeshi_moji_shori").is_none()); + let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap(); + assert!(!old.kurikaeshi_moji_shori, "saved before the option: off"); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + // Only the second paragraph. + let second = "時々\n".len(); + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(text(&s).plain_text(), "時々\nすゝ", "the text keeps its marks"); + // The same value again records nothing. + s.execute("text.setFormat", &json!({"kurikaeshiMojiShori": true, "start": second, "end": second})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + let saved = serde_json::to_value(text(&s).para_at(1)).unwrap(); + assert_eq!(saved["kurikaeshi_moji_shori"], true); + let back: vectorcraft_doc::ParaStyle = serde_json::from_value(saved).unwrap(); + assert!(back.kurikaeshi_moji_shori); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert!(!back.para_at(0).kurikaeshi_moji_shori && back.para_at(1).kurikaeshi_moji_shori, "the file keeps it per paragraph"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(text(&s).para_at(1).kurikaeshi_moji_shori); + for bad in [json!("yes"), json!(1)] { + assert!(s.execute("text.setFormat", &json!({"ids": [id], "kurikaeshiMojiShori": bad, "kinsoku": "none"})).is_err(), "{bad}"); + } + assert!(s.execute("text.setRangeStyle", &json!({"id": id, "kurikaeshiMojiShori": false})).is_err()); + assert!( + text(&s).para_at(1).kurikaeshi_moji_shori && text(&s).para_at(1).kinsoku != vectorcraft_doc::Kinsoku::None, + "a refused call changes nothing" + ); + // A paragraph style carries it. + s.execute("paraStyle.new", &json!({"name": "Repeats", "attrs": {"kurikaeshi_moji_shori": true}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Repeats", "id": id})).unwrap(); + assert!(text(&s).para_at(0).kurikaeshi_moji_shori && text(&s).para_at(1).kurikaeshi_moji_shori); + s.execute("paraStyle.new", &json!({"name": "Marks", "attrs": {"kurikaeshi_moji_shori": false}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Marks", "id": id})).unwrap(); + assert!(!text(&s).para_at(0).kurikaeshi_moji_shori && !text(&s).para_at(1).kurikaeshi_moji_shori); +} + /// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one /// undo step, the paragraph is saved with it only when it is not None and opens with it, an /// unknown value changes nothing, and paragraph styles carry it. diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 2f8e8b8a1b..5a1e811062 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -491,7 +491,11 @@ impl Writer<'_> { }); let Some(chars) = self.fonts.get_mut(at).map(|u| &mut u.chars) else { continue }; // As written: a list marker's characters, a hyphen where a line breaks, capitals for All - // Caps, the style's Digits. + // Caps, the style's Digits, the character a repeat mark is drawn as. + if let Some(c) = shown_repeat(lay, i, g) { + chars.insert(c); + continue; + } let src = lay.marker_text(i).unwrap_or_else(|| if g.len == 0 { "-" } else { plain.get(g.byte..g.byte + g.len).unwrap_or("") }); for c in src.chars().filter(|c| !c.is_control() && *c != '\u{ad}').map(|c| st.digits.map(c)) { if st.all_caps { @@ -716,6 +720,17 @@ struct Segment { /// given its own position (points). const PLACE_TOLERANCE: f64 = 1e-6; +/// Kurikaeshi Moji Shori: the character glyph `i` of `lay` shows when the layout drew a repeat mark +/// as the character it repeats ([`vectorcraft_text::TextLayout::repeat_marks`]), or None. +fn shown_repeat(lay: &vectorcraft_text::TextLayout, i: usize, g: &vectorcraft_text::PositionedGlyph) -> Option { + if lay.repeat_marks.is_empty() || g.len == 0 || lay.marker_text(i).is_some() { + return None; + } + // The marks are in text order, one per line. + let at = lay.repeat_marks.binary_search_by_key(&g.byte, |&(byte, _)| byte).ok()?; + lay.repeat_marks.get(at).map(|&(_, c)| c) +} + /// The laid-out lines of `t` as segments: a new segment at every style change, after tabs and, /// on justified lines, after each word space (unless `fewer`). The text comes from the clusters /// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all @@ -804,9 +819,15 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - } None => (g.advance, g.origin.x), }; - let src: String = source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(); + let repeat = shown_repeat(lay, line.glyph_start + k, g); + let src: String = match repeat { + Some(c) => c.to_string(), + None => source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(), + }; let piece = if run.style.all_caps { src.to_uppercase() } else { src }; - let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)); + // The character a repeat mark is drawn as takes the mark's width on the canvas, which a + // reader does not know: the text after it is placed anew. + let brk = piece == "\t" || (split_words && !piece.is_empty() && piece.chars().all(char::is_whitespace)) || repeat.is_some(); // A glyph Glyph Scaling widens or narrows is a segment of its own, stretched to its width. let scale = if reader.is_some() && (g.scale - 1.0).abs() > 1e-9 && g.scale.is_finite() { g.scale } else { 1.0 }; let fresh = std::mem::take(&mut after_inline) || scale != 1.0 || segs.last().is_some_and(|last| last.scale != 1.0); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index c53318c358..a190f21dea 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -910,3 +910,34 @@ fn paragraphs_aligned_differently_keep_their_alignment() { assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.01); } } + +/// With Kurikaeshi Moji Shori on, live type writes a repeat mark that starts a line as the +/// character it is drawn as and places the text after it anew, with and without embedded fonts; a +/// mark inside a line stays. +#[test] +fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), ..style(12.0) }; + for on in [false, true] { + let mut t = TextObject::point(Point::new(20.0, 40.0), "龘\u{2028}々龘龘々", st.clone()); + t.para.kurikaeshi_moji_shori = on; + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + for embed_fonts in [false, true] { + let svg = export(&d, &ExportOptions { embed_fonts, ..Default::default() }); + if !on { + assert!(svg.contains(">々龘龘々<"), "{svg}"); + continue; + } + // The drawn character takes the mark's width on the canvas, so the text after it is + // placed where the canvas draws it. + let rest = svg.find(">龘龘々<").unwrap_or_else(|| panic!("{svg}")); + let tag = &svg[svg[..rest].rfind('<').unwrap_or(0)..rest]; + assert!(tag.contains(" x=\""), "{tag}: {svg}"); + assert_eq!(svg.matches('々').count(), 1, "only the mark inside the line stays: {svg}"); + } + } +} diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 0c4e1ae615..f028d47898 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -13,7 +13,7 @@ use super::{ is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; use crate::justify::is_format_control; -use crate::shape::{keep_inseparable_pairs, keep_korean_words}; +use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeated_char, shape_range}; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? @@ -213,6 +213,9 @@ struct ParagraphData<'a, 'text> { bidi: Option>, rtl: bool, continued: bool, + /// Kurikaeshi Moji Shori: the character before a `continued` paragraph in the frames before + /// ([`TextObject::first_para_lead`]). + lead: Option, sg: Vec, compressed: Vec, wakan: Vec, @@ -331,6 +334,7 @@ fn prepare_paragraph<'a, 'text>( bidi, rtl, continued, + lead: t.first_para_lead.filter(|_| continued), sg, compressed, wakan, @@ -1272,6 +1276,40 @@ fn emit_line_glyph( cx.emit(glyph, Affine::translate(at.to_vec2()), at, 0.0, w.advance, line_index); } +/// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of +/// a line of the paragraph starting at byte `para_start`, when `g` is a repeat mark, and the +/// character it shows: the character [`repeated_char`] gives, shaped in the mark's style with the +/// type's features (so vertical type gets the font's vertical forms), from the same face, with the +/// mark's advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, +/// belongs to a tate-chu-yoko or warichu block, nothing before it in the paragraph fits, or the face +/// draws the character with no glyph or with more than one. `lead` stands before a paragraph that +/// continues from the frame before ([`TextObject::first_para_lead`]). +fn repeat_mark_glyph(cx: &Ctx<'_>, para_start: usize, lead: Option, g: &SGlyph) -> Option<(SGlyph, char)> { + if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() { + return None; + } + let c = repeated_char(lead, cx.text.get(para_start..g.byte)?, g.ch)?; + let mut buf = [0; 4]; + let s: &str = c.encode_utf8(&mut buf); + let mut shaped = Vec::with_capacity(1); + shape_range(cx.db, s, 0..s.len(), &[(0..s.len(), cx.style_at(g.byte))], &[], &cx.opts.features, &[], &mut shaped); + let [one] = shaped.as_slice() else { return None }; + (one.gid != 0 && one.face.id() == g.face.id()).then(|| (SGlyph { gid: one.gid, ..g.clone() }, c)) +} + +/// Kurikaeshi Moji Shori: the glyph drawn in place of glyph `first` of `paragraph`, the first +/// character of a line that ends before glyph `end`, when the paragraph has the setting on and +/// [`repeat_mark_glyph`] gives one; it is recorded in [`crate::TextLayout::repeat_marks`]. +fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: usize, end: usize) -> Option { + if !paragraph.para.kurikaeshi_moji_shori || first >= end { + return None; + } + let g = paragraph.sg.get(first)?; + let (glyph, c) = repeat_mark_glyph(cx, paragraph.pr.start, paragraph.lead, g)?; + cx.out.repeat_marks.push((g.byte, c)); + Some(glyph) +} + /// Lay out `line` of `paragraph` as `justification` aligns it: each glyph placed along the /// baseline (tabs as [`tab_glyph`] sets them), its hyphen, and the line's record, then the pen /// moved on past it. @@ -1306,9 +1344,14 @@ fn emit_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, paragraph: &ParagraphData let mut marker_tab = 0; // The warichu blocks drawn on the line: the byte that names each and where it starts. let mut wari_blocks: Vec<(usize, f64)> = Vec::new(); + // Kurikaeshi Moji Shori: the line's first character after any list marker, drawn as the + // character it repeats when it is a repeat mark. + let first = index.max(paragraph.marker); + let repeat = line_start_repeat(cx, paragraph, first, position.end); for (order_index, &offset) in order.iter().enumerate() { let glyph_index = index + offset; let Some(glyph) = sg.get(glyph_index) else { continue }; + let glyph = if glyph_index == first { repeat.as_ref().unwrap_or(glyph) } else { glyph }; let mut advance = glyph.adv; if glyph_index + 1 == trimmed { advance -= line.end_trim; diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 07d761926b..506b7e5b03 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -54,7 +54,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled}; -pub use shape::{aki_space, inseparable, line_start_space, spacing_scale}; +pub use shape::{aki_space, inseparable, line_start_space, repeat_base, spacing_scale}; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; @@ -401,6 +401,10 @@ pub struct TextLayout { pub inlines: Vec, /// List markers, in text order. pub markers: Vec, + /// Kurikaeshi Moji Shori: the repeat marks drawn as the character they stand for, as (the + /// mark's byte offset in the plain text, the character drawn), in text order. Writers that put + /// characters in place of glyphs (live SVG text) write that character. + pub repeat_marks: Vec<(usize, char)>, } impl Default for TextLayout { @@ -419,6 +423,7 @@ impl Default for TextLayout { path_fill: None, inlines: Vec::new(), markers: Vec::new(), + repeat_marks: Vec::new(), } } } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 13cd2e06de..9d09ce076e 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -450,6 +450,65 @@ pub fn inseparable(a: char, b: char) -> bool { ) } +/// Kurikaeshi Moji Shori: the last character of `text` that a repeat mark after it could stand for: +/// the last one that is neither a repeat mark, a soft return (U+2028) nor a combining voicing mark +/// (U+3099, U+309A), or None when there is none. The engine gives a threaded frame whose first +/// paragraph continues from the frame before the result for the text before it +/// (`TextObject::first_para_lead`). +pub fn repeat_base(text: &str) -> Option { + text.chars().rev().find(|&c| !matches!(c, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ' | '\u{2028}' | '\u{3099}' | '\u{309A}')) +} + +/// Kurikaeshi Moji Shori: the character the repeat mark `mark` stands for after the text `before` +/// it, or None when `mark` is not a repeat mark or nothing before it fits. `lead` stands before +/// `before` (the text of a threaded paragraph in the frames before). VectorCraft's rules: the +/// repeated character is the last one before the mark that is neither a repeat mark, a soft return +/// (U+2028) nor a combining voicing mark ([`repeat_base`]); 々 repeats a Han ideograph, ゝ and ゞ a +/// hiragana and ヽ and ヾ a katakana. ゝ and ヽ give the kana without its voicing marks, and ゞ and +/// ヾ its voiced form, or the plain kana when it has none. +pub(crate) fn repeated_char(lead: Option, before: &str, mark: char) -> Option { + let script = match mark { + '々' => Script::Han, + 'ゝ' | 'ゞ' => Script::Hiragana, + 'ヽ' | 'ヾ' => Script::Katakana, + _ => return None, + }; + let base = repeat_base(before).or(lead)?; + if base.script() != script || (script != Script::Han && !matches!(base as u32, 0x3041..=0x3096 | 0x30A1..=0x30F6)) { + return None; + } + if script == Script::Han { + return Some(base); + } + // Katakana from U+30A1 to U+30F6 lie 0x60 past their hiragana, so one table serves both. + let shift = if script == Script::Katakana { 0x60 } else { 0 }; + let plain = unvoiced(base as u32 - shift); + let kana = if matches!(mark, 'ゞ' | 'ヾ') { voiced(plain).unwrap_or(plain) } else { plain }; + char::from_u32(kana + shift) +} + +/// The hiragana `h` (a code point) without its dakuten or handakuten. +fn unvoiced(h: u32) -> u32 { + match h { + 0x304C..=0x3062 if h.is_multiple_of(2) => h - 1, + 0x3065 | 0x3067 | 0x3069 => h - 1, + 0x3070..=0x307D => h - (h - 0x306F) % 3, + 0x3094 => 0x3046, + _ => h, + } +} + +/// The voiced form (with dakuten) of the plain hiragana `h`, if it has one. +fn voiced(h: u32) -> Option { + match h { + 0x304B..=0x3061 if !h.is_multiple_of(2) => Some(h + 1), + 0x3064 | 0x3066 | 0x3068 => Some(h + 1), + 0x306F..=0x307B if (h - 0x306F).is_multiple_of(3) => Some(h + 1), + 0x3046 => Some(0x3094), + _ => None, + } +} + /// Is `c` Hangul: a syllable, a jamo or a compatibility jamo (full or half width)? pub(crate) fn is_hangul(c: char) -> bool { c.script() == Script::Hangul diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d17ce78603..4a4297c33a 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -484,6 +484,59 @@ pub fn full_width_font() -> Option> { Some(builder.build()) } +/// The family of [`repeat_mark_font`]. +pub const REPEAT_MARK_FAMILY: &str = "Repeattest Sans"; + +/// The Japanese characters [`repeat_mark_font`] maps, each to the glyph of the Latin capital beside +/// it: an ideograph, the repeat marks, and kana with and without their voicing marks. +pub const REPEAT_MARK_CHARS: [(char, char); 11] = + [('時', 'A'), ('々', 'B'), ('す', 'C'), ('ず', 'D'), ('ゝ', 'E'), ('ゞ', 'F'), ('サ', 'G'), ('ザ', 'H'), ('ヽ', 'I'), ('ヾ', 'J'), ('あ', 'K')]; + +/// A test-only cmap over bundled Source Sans 3: each of [`REPEAT_MARK_CHARS`] uses the glyph of its +/// Latin capital, so the glyph drawn for a repeat mark tells which character was drawn; the space +/// keeps its own glyph. +pub fn repeat_mark_font() -> Option> { + repeat_font(REPEAT_MARK_FAMILY, &REPEAT_MARK_CHARS) +} + +/// The family of [`rare_repeat_mark_font`]. +pub const RARE_REPEAT_MARK_FAMILY: &str = "Raretest Sans"; + +/// [`repeat_mark_font`] for tests that add it to the shared [`crate::FontDb::global`]: it maps +/// only 龘 (to the glyph of A) and 々 (to the glyph of B), characters no other text in those tests +/// uses, so other tests' Japanese text does not fall back to it. +pub fn rare_repeat_mark_font() -> Option> { + repeat_font(RARE_REPEAT_MARK_FAMILY, &[('龘', 'A'), ('々', 'B')]) +} + +/// A font named `family` over bundled Source Sans 3 whose cmap maps each of `chars` to the glyph of +/// the Latin capital beside it, and the space to its own glyph. +fn repeat_font(family: &str, chars: &[(char, char)]) -> Option> { + use write_fonts::tables::cmap::Cmap; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let mut mappings: Vec<(char, write_fonts::types::GlyphId)> = Vec::new(); + for &(c, latin) in chars.iter().chain(&[(' ', ' ')]) { + mappings.push((c, write_fonts::types::GlyphId::new(charmap.map(latin)?.to_u32()))); + } + let cmap = Cmap::from_mappings(mappings).ok()?; + let full = format!("{family} Regular"); + let postscript = format!("{}-Regular", family.replace(' ', "")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &postscript)])?; + let mut builder = FontBuilder::new(); + builder.add_table(&cmap).ok()?; + builder.add_raw(Tag::new(b"name"), name); + for r in font.table_directory.table_records() { + let tag = Tag::new(&r.tag().to_be_bytes()); + if tag != Tag::new(b"GSUB") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`half_form_font`]. pub const HALF_FORM_FAMILY: &str = "Halftest Sans"; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 4bab8aa561..477c3e3392 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2693,6 +2693,123 @@ fn bunri_kinshi_keeps_two_em_dashes_on_one_line() { assert_eq!(ends(&t), [kept, text.len(), second + split, second + text.len()]); } +/// Kurikaeshi Moji Shori: the character a repeat mark stands for is the last one before it that is +/// not a repeat mark, in the mark's script; ゝ and ヽ give it without voicing marks, ゞ and ヾ give +/// its voiced form when it has one. +#[test] +fn repeat_marks_stand_for_the_character_before_them() { + use crate::shape::repeated_char; + for (before, mark, want) in [ + ("時", '々', Some('時')), + ("時々", '々', Some('時')), + ("時\u{2028}", '々', Some('時')), + ("す", 'ゝ', Some('す')), + ("ず", 'ゝ', Some('す')), + ("す", 'ゞ', Some('ず')), + ("ず", 'ゞ', Some('ず')), + ("ぱ", 'ゝ', Some('は')), + ("は", 'ゞ', Some('ば')), + ("ぽ", 'ゞ', Some('ぼ')), + ("つ", 'ゞ', Some('づ')), + ("う", 'ゞ', Some('ゔ')), + ("あ", 'ゞ', Some('あ')), + ("サ", 'ヽ', Some('サ')), + ("ザ", 'ヽ', Some('サ')), + ("サ", 'ヾ', Some('ザ')), + ("ウ", 'ヾ', Some('ヴ')), + ("ピ", 'ヾ', Some('ビ')), + ("サ", 'ゝ', None), + ("す", 'ヽ', None), + ("す", '々', None), + ("時", 'ゝ', None), + ("A", '々', None), + ("", '々', None), + ("々ゝ", '々', None), + ("時", 'x', None), + // A kana followed by a combining voicing mark is that kana. + ("か\u{3099}\u{2028}", 'ゝ', Some('か')), + ("か\u{3099}", 'ゞ', Some('が')), + ("ハ\u{309A}", 'ヽ', Some('ハ')), + ] { + assert_eq!(repeated_char(None, before, mark), want, "{before:?} {mark}"); + } + // The character before a paragraph that continues from the frame before stands in when the text + // before the mark in this frame has none. + assert_eq!(repeated_char(Some('時'), "", '々'), Some('時')); + assert_eq!(repeated_char(Some('時'), "\u{2028}々", '々'), Some('時')); + assert_eq!(repeated_char(Some('時'), "日", '々'), Some('日')); + assert_eq!(repeated_char(Some('す'), "", '々'), None); +} + +/// Kurikaeshi Moji Shori (a paragraph attribute): on, a repeat mark that starts a line is drawn as +/// the character it repeats, in point and area type, horizontal and vertical, at a soft return or +/// where a line wraps; a mark inside a line, one starting a paragraph and every mark with the +/// setting off keep their own glyph. The line breaks and the glyphs' bytes do not change. Uses a test +/// font that draws each character with a different Latin glyph. +#[test] +fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let glyph = |c: char| Some(face.glyph_for(c)); + let gid_of = |l: &TextLayout, b: usize| l.glyphs.iter().find(|g| g.byte == b).map(|g| g.gid); + let ends = |l: &TextLayout| l.lines.iter().map(|line| line.end).collect::>(); + // 時 | 々す | ゞ時々ザ | ヽ, then a paragraph that starts with 々. + let text = "時\u{2028}々す\u{2028}ゞ時々ザ\u{2028}ヽ\n々"; + let at = |s: &str| text.find(s).unwrap(); + let (first_mark, voiced, inner, katakana, para_start) = (at("々す"), at("ゞ"), at("時々ザ") + "時".len(), at("ヽ"), text.len() - "々".len()); + for vertical in [false, true] { + let mut t = TextObject::point(Point::ZERO, text, st.clone()); + t.vertical = vertical; + let off = layout(&db, &t); + t.set_paragraph_styles(vec![ + vectorcraft_doc::ParaStyle { kurikaeshi_moji_shori: true, ..t.para.clone() }, + vectorcraft_doc::ParaStyle { kurikaeshi_moji_shori: true, ..t.para.clone() }, + ]); + let on = layout(&db, &t); + assert_eq!(ends(&on), ends(&off), "vertical {vertical}"); + let bytes = |l: &TextLayout| l.glyphs.iter().map(|g| g.byte).collect::>(); + assert_eq!(bytes(&on), bytes(&off), "vertical {vertical}"); + // Off, each mark has its own glyph. + for (b, mark) in [(first_mark, '々'), (voiced, 'ゞ'), (inner, '々'), (katakana, 'ヽ'), (para_start, '々')] { + assert_eq!(gid_of(&off, b), glyph(mark), "vertical {vertical}: off, {mark} at {b}"); + } + assert_eq!(gid_of(&on, first_mark), glyph('時'), "vertical {vertical}: 々 drawn as 時"); + assert_eq!(gid_of(&on, voiced), glyph('ず'), "vertical {vertical}: ゞ after す drawn as ず"); + assert_eq!(gid_of(&on, katakana), glyph('サ'), "vertical {vertical}: ヽ after ザ drawn as サ"); + assert_eq!(gid_of(&on, inner), glyph('々'), "vertical {vertical}: a mark inside a line keeps its glyph"); + assert_eq!(gid_of(&on, para_start), glyph('々'), "vertical {vertical}: a paragraph's first mark keeps its glyph"); + assert!(off.repeat_marks.is_empty()); + assert_eq!(on.repeat_marks, [(first_mark, '時'), (voiced, 'ず'), (katakana, 'サ')], "vertical {vertical}"); + } + // Where area type wraps: each line holds one character, so 々 starts the second line. + let mut t = TextObject::point(Point::ZERO, "時々", st.clone()); + let both: f64 = layout(&db, &t).glyphs.iter().map(|g| g.advance).sum(); + t.xf = Affine::IDENTITY; + // The Soft set lets 々 start a line. + t.para.kinsoku = vectorcraft_doc::Kinsoku::Soft; + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, both - 1.0, 200.0).to_path(0.1)) }; + let off = layout(&db, &t); + assert_eq!(ends(&off), ["時".len(), "時々".len()]); + t.para.kurikaeshi_moji_shori = true; + let on = layout(&db, &t); + assert_eq!(ends(&on), ends(&off)); + assert_eq!(gid_of(&off, "時".len()), glyph('々')); + assert_eq!(gid_of(&on, "時".len()), glyph('時'), "a wrapped line's 々 is drawn as 時"); + // A threaded frame whose first paragraph continues: a mark that starts the frame is drawn as the + // character before it in the frame before, only while the paragraph continues. + let mut t = TextObject::point(Point::ZERO, "々す\n々", st.clone()); + t.para.kurikaeshi_moji_shori = true; + t.first_para_lead = Some('時'); + assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "a frame that does not continue"); + t.first_para_continues = true; + let on = layout(&db, &t); + assert_eq!(gid_of(&on, 0), glyph('時'), "the frame's first 々 is drawn as 時"); + assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..466bf21b1b 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2978,6 +2978,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Латинска висяща пунктуация Korean Line Break Anywhere Пренасяне на корейски текст навсякъде Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Настройки за източноазиатска композиция Korean Composition Settings Настройки за корейска композиция Rotate Завъртане diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..b0d3668edf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2076,6 +2076,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Latinična viseća interpunkcija Korean Line Break Anywhere Prelom korejskog reda bilo gdje Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Postavke istočnoazijske kompozicije Korean Composition Settings Postavke korejske kompozicije Select a text object to edit its paragraph attributes. Odaberite tekstualni objekat da uredite njegove atribute pasusa. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..e9c8189f1e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3810,6 +3810,7 @@ digits Malayalam Malaiàlam Roman Hanging Punctuation Puntuació penjant romana Korean Line Break Anywhere Salt de línia coreà a qualsevol lloc Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Configuració de composició de l’Àsia oriental Korean Composition Settings Configuració de composició coreana Rotate Gira diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..7cac30c893 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2147,6 +2147,7 @@ digits Malayalam Malajálamské Roman Hanging Punctuation Visící latinková interpunkce Korean Line Break Anywhere Zalomení korejského řádku kdekoli Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Nastavení východoasijské sazby Korean Composition Settings Nastavení korejské sazby Select a text object to edit its paragraph attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho odstavce. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..6b97db1903 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2565,6 +2565,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Romersk hængende tegnsætning Korean Line Break Anywhere Koreansk linjeskift hvor som helst Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Indstillinger for østasiatisk komposition Korean Composition Settings Indstillinger for koreansk komposition Select a text object to edit its paragraph attributes. Markér et tekstobjekt for at redigere dets afsnitsattributter. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..fbb09e5340 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3021,6 +3021,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Hängende Interpunktion (lateinisch) Korean Line Break Anywhere Koreanischer Zeilenumbruch überall Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Einstellungen für ostasiatischen Satz Korean Composition Settings Einstellungen für koreanischen Satz Rotate Drehen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..b71d14db76 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2073,6 +2073,7 @@ font-technology Variable Μεταβλητές Roman Hanging Punctuation Κρεμαστή στίξη όρθιας γραφής Korean Line Break Anywhere Αλλαγή γραμμής κορεατικών οπουδήποτε Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ρυθμίσεις σύνθεσης ανατολικής Ασίας Korean Composition Settings Ρυθμίσεις κορεατικής σύνθεσης Rotate Περιστροφή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..eb281bb92e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3057,6 +3057,7 @@ digits Malayalam Malayálam Roman Hanging Punctuation Puntuación colgante romana Korean Line Break Anywhere Salto de línea coreano en cualquier lugar Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ajustes de composición de Asia oriental Korean Composition Settings Ajustes de composición coreana Rotate Rotar diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..d50fbf4ad3 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2110,6 +2110,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Latinalaiset riippuvat välimerkit Korean Line Break Anywhere Korean rivinvaihto missä tahansa Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Itäaasialaisen ladonnan asetukset Korean Composition Settings Korean ladonnan asetukset Select a text object to edit its paragraph attributes. Valitse tekstiobjekti, jonka kappalemääritteitä haluat muokata. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..d04586aa05 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3049,6 +3049,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Ponctuation romaine hors justification Korean Line Break Anywhere Saut de ligne coréen n’importe où Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Paramètres de composition d’Asie orientale Korean Composition Settings Paramètres de composition coréenne Rotate Rotation diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..108352cc12 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4465,6 +4465,7 @@ antiAlias Sharp શાર્પ Save Prominent Colors મુખ્ય રંગો સાચવો Korean Line Break Anywhere કોરિયન લાઇન ગમે ત્યાં તોડો Bunri-Kinshi બુનરી-કિન્શી + Kurikaeshi Moji Shori કુરિકાએશી મોજી શોરી East Asian Composition Settings પૂર્વ એશિયાઈ કમ્પોઝિશન સેટિંગ્સ Korean Composition Settings કોરિયન કમ્પોઝિશન સેટિંગ્સ Show Bounding Box While Moving and Drawing ખસેડતી અને દોરતી વખતે બાઉન્ડિંગ બોક્સ બતાવો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..0d5de80b4e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4187,6 +4187,7 @@ antiAlias Sharp शार्प Roman Hanging Punctuation रोमन हैंगिंग विराम चिह्न Korean Line Break Anywhere कोरियाई लाइन ब्रेक कहीं भी Bunri-Kinshi बुनरी-किंशी + Kurikaeshi Moji Shori कुरिकाएशी मोजी शोरी East Asian Composition Settings पूर्वी एशियाई संरचना सेटिंग्स Korean Composition Settings कोरियाई संरचना सेटिंग्स Rotate घुमाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..f94014cb6f 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3645,6 +3645,7 @@ mark-style Japanese Japán Roman Hanging Punctuation Latin függő írásjelek Korean Line Break Anywhere Koreai sortörés bárhol Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Kelet-ázsiai szedési beállítások Korean Composition Settings Koreai szedési beállítások Rotate Elforgatás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..0d369293a0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1899,6 +1899,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Tanda baca gantung Romawi Korean Line Break Anywhere Putus baris Korea di mana saja Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Pengaturan komposisi Asia Timur Korean Composition Settings Pengaturan komposisi Korea Select a text object to edit its paragraph attributes. Pilih objek teks untuk mengedit atribut paragrafnya. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..70d3026e6a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3098,6 +3098,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Punteggiatura sporgente romana Korean Line Break Anywhere Interruzione di riga coreana ovunque Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Impostazioni di composizione dell’Asia orientale Korean Composition Settings Impostazioni di composizione coreana Rotate Ruota diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..563a2b1966 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3064,6 +3064,7 @@ mark-style Japanese 日本式 Roman Hanging Punctuation 欧文ぶら下がり Korean Line Break Anywhere 韓国語の任意位置での改行 Bunri-Kinshi 分離禁止 + Kurikaeshi Moji Shori 繰り返し文字処理 East Asian Composition Settings 東アジア言語の組版設定 Korean Composition Settings 韓国語の組版設定 Rotate 回転 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 358960bd37..12be5345a9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3955,6 +3955,7 @@ digits Malayalam მალაიალამური Roman Hanging Punctuation რომაული გამოწეული პუნქტუაცია Korean Line Break Anywhere კორეული სტრიქონის გადატანა ნებისმიერ ადგილას Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings აღმოსავლეთ აზიური აწყობის პარამეტრები Korean Composition Settings კორეული აწყობის პარამეტრები Select a text object to edit its paragraph attributes. აბზაცის ატრიბუტების რედაქტირებისთვის მონიშნეთ ტექსტური ობიექტი. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..ca1687819b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3053,6 +3053,7 @@ mark-style Japanese 일본식 Roman Hanging Punctuation 로마자 걸림 문장 부호 Korean Line Break Anywhere 한글 어디서나 줄 바꿈 Bunri-Kinshi 분리 금지 + Kurikaeshi Moji Shori 반복 문자 처리 East Asian Composition Settings 동아시아 조판 설정 Korean Composition Settings 한글 조판 설정 Rotate 회전 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..513cb35895 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2461,6 +2461,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Romeinse hangende leestekens Korean Line Break Anywhere Koreaans regeleinde overal Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Instellingen voor Oost-Aziatische zetting Korean Composition Settings Instellingen voor Koreaanse zetting Select a text object to edit its paragraph attributes. Selecteer een tekstobject om de alineakenmerken ervan te bewerken. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..61b9465dec 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2065,6 +2065,7 @@ digits Malayalam Malajalam Roman Hanging Punctuation Wysunięta interpunkcja łacińska Korean Line Break Anywhere Koreański podział wiersza w dowolnym miejscu Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Ustawienia składu wschodnioazjatyckiego Korean Composition Settings Ustawienia składu koreańskiego Select a text object to edit its paragraph attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty akapitu. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..460e581b15 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2544,6 +2544,7 @@ digits Malayalam Malaiala Roman Hanging Punctuation Pontuação Pendurada Romana Korean Line Break Anywhere Quebra de Linha Coreana em Qualquer Lugar Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Configurações de Composição do Leste Asiático Korean Composition Settings Configurações de Composição Coreana Rotate Girar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..dca47d1e4c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3087,6 +3087,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Римская висячая пунктуация Korean Line Break Anywhere Перенос корейского текста в любом месте Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Параметры восточноазиатского набора Korean Composition Settings Параметры корейского набора Rotate Повернуть diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..e7f7555c6a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2991,6 +2991,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Hängande interpunktion (roman) Korean Line Break Anywhere Koreansk radbrytning var som helst Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Inställningar för östasiatisk sättning Korean Composition Settings Inställningar för koreansk sättning Rotate Rotera diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..4aca424124 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2826,6 +2826,7 @@ digits Malayalam Malayalam Roman Hanging Punctuation Roma Asılı Noktalama İşaretleri Korean Line Break Anywhere Korece Satırı Her Yerde Kes Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Doğu Asya Dizgi Ayarları Korean Composition Settings Korece Dizgi Ayarları Rotate Döndür diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..704309b261 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3090,6 +3090,7 @@ digits Malayalam Малаялам Roman Hanging Punctuation Римська висяча пунктуація Korean Line Break Anywhere Перенесення корейського тексту будь-де Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Параметри східноазійського набору Korean Composition Settings Параметри корейського набору Rotate Повернути diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..b2b5b8f0da 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3407,6 +3407,7 @@ mark-style Japanese Kiểu Nhật Roman Hanging Punctuation Dấu câu treo Roman Korean Line Break Anywhere Ngắt dòng tiếng Hàn ở bất kỳ đâu Bunri-Kinshi Bunri-Kinshi + Kurikaeshi Moji Shori Kurikaeshi Moji Shori East Asian Composition Settings Cài đặt dàn trang Đông Á Korean Composition Settings Cài đặt dàn trang tiếng Hàn Rotate Xoay diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..6105919a37 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2948,6 +2948,7 @@ digits Malayalam 马拉雅拉姆数字 Roman Hanging Punctuation 西文悬挂标点 Korean Line Break Anywhere 韩文任意位置换行 Bunri-Kinshi 分离禁止 + Kurikaeshi Moji Shori 重复字符处理 East Asian Composition Settings 东亚排版设置 Korean Composition Settings 韩文排版设置 Rotate 旋转 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..cae679bd47 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4176,6 +4176,7 @@ digits Malayalam 馬來亞拉姆數字 Roman Hanging Punctuation 羅馬懸掛標點 Korean Line Break Anywhere 韓文任意位置換行 Bunri-Kinshi 分離禁止 + Kurikaeshi Moji Shori 重複字元處理 East Asian Composition Settings 東亞排版設定 Korean Composition Settings 韓文排版設定 Rotate 旋轉 diff --git a/crates/ui-egui/src/panels/paragraph.rs b/crates/ui-egui/src/panels/paragraph.rs index 3f1a56cee5..52b3135cc2 100644 --- a/crates/ui-egui/src/panels/paragraph.rs +++ b/crates/ui-egui/src/panels/paragraph.rs @@ -859,6 +859,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); + // A repeat mark starting a line is drawn as the character it repeats. + let repeat = shared_para(app, |p| p.kurikaeshi_moji_shori) == Some(true); + if menu_item(ui, tl!("Kurikaeshi Moji Shori"), has, repeat) { + toggle_kurikaeshi_moji_shori(app); + } // How a line keeps the kinsoku characters off its ends: the selected paragraphs' type is // checked, and none is when they differ. let kinsoku_type = shared_para(app, |p| p.kinsoku_type); @@ -937,6 +942,14 @@ fn toggle_bunri_kinshi(app: &mut VectorcraftApp) { format(app, json!({"bunriKinshi": !on})); } +/// Kurikaeshi Moji Shori (Paragraph panel menu): the menu item is checked when every paragraph the +/// panel acts on ([`format`]) has it, and a click turns it off for all of them then, and on for all +/// of them otherwise, in one undo step. +fn toggle_kurikaeshi_moji_shori(app: &mut VectorcraftApp) { + let on = shared_para(app, |p| p.kurikaeshi_moji_shori) == Some(true); + format(app, json!({"kurikaeshiMojiShori": !on})); +} + /// Korean Line Break Anywhere (Paragraph panel menu): the menu item is checked when every paragraph /// the panel acts on ([`format`]) has it, and a click turns it off for all of them then, and on for /// all of them otherwise, in one undo step. @@ -949,7 +962,7 @@ fn toggle_korean_line_break_anywhere(app: &mut VectorcraftApp) { /// indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification /// options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi /// Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, -/// Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo +/// Kurikaeshi Moji Shori, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo /// step named Reset Panel (inside an undo group that is already open, as part of its step). fn reset_panel(app: &mut VectorcraftApp) { let h = HyphenationOptions::default(); @@ -971,7 +984,7 @@ fn reset_panel(app: &mut VectorcraftApp) { "autoLeading": j.auto_leading, "singleWordJustification": "fullJustify", "direction": "auto", "leadingModel": "romanBaseline", "mojikumi": "lineEndHalf", "burasagari": "standard", "kinsoku": "hard", "kinsokuType": "pushOutOnly", "composer": "everyLine", "romanHangingPunctuation": false, "koreanLineBreakAnywhere": false, - "bunriKinshi": false + "bunriKinshi": false, "kurikaeshiMojiShori": false }), ); para_cmd(app, "text.tabs.clear", json!({})); diff --git a/crates/ui-egui/src/panels/paragraph/tests.rs b/crates/ui-egui/src/panels/paragraph/tests.rs index 11fd7fbafc..aebdbbf1cf 100644 --- a/crates/ui-egui/src/panels/paragraph/tests.rs +++ b/crates/ui-egui/src/panels/paragraph/tests.rs @@ -324,6 +324,37 @@ fn bunri_kinshi_toggle_follows_kinsoku_and_the_selected_paragraphs() { assert_eq!(flags(&app), (false, false), "Reset Panel turns it off"); } +/// Kurikaeshi Moji Shori: new type has it off; the menu item turns it on for the paragraphs the Type +/// tool's selection touches in one undo step, a click while the selected paragraphs differ turns it +/// on for all of them, and a click while all have it turns it off. Reset Panel turns it off. +#[test] +fn kurikaeshi_moji_shori_toggle_follows_the_selected_paragraphs() { + let (mut app, id) = editing_text("時々\nすゝ\n"); + app.session.prefs.show_east_asian_options = true; + let flags = |app: &VectorcraftApp| { + let node = app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap(); + let NodeKind::Text(text) = &node.kind else { panic!("text") }; + (text.para_at(0).kurikaeshi_moji_shori, text.para_at(1).kurikaeshi_moji_shori) + }; + assert_eq!(flags(&app), (false, false), "new type has it off"); + select_range(&mut app, 0, 3); + let history = app.session.active().unwrap().history.undo.len(); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (true, false)); + assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (true, true), "mixed: a click turns it on for all"); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + assert_eq!(flags(&app), (false, false), "all on: a click turns it off"); + app.session.set_tool_option("selectAll", &json!(true)); + toggle_kurikaeshi_moji_shori(&mut app); + app.session.set_tool_option("selectAll", &json!(true)); + reset_panel(&mut app); + assert_eq!(flags(&app), (false, false), "Reset Panel turns it off"); +} + #[test] fn paragraph_mixed_indent_fields_show_blank() { let (mut app, id) = editing_text("A\nB\n"); diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..ba9e16985d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9451,6 +9451,30 @@ https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html {"name":"run_command","arguments":{"command":"text.setFormat","params":{"bunriKinshi":true}}} ``` +## Kurikaeshi Moji Shori + +`text.setFormat {kurikaeshiMojiShori: bool}` (Paragraph panel menu › Kurikaeshi Moji Shori, shown with the East Asian +options) turns it on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a `start` / `end` +range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, is drawn as the +character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, +searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. +SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. +VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the +repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a +combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph +from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the +plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a +paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph +(`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph +style's attributes), and Reset Panel turns it off. A value that is not true or false is refused, and a call that gives +the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a +save reports a paragraph with it on as left out. The help page: +https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html + +```json +{"name":"run_command","arguments":{"command":"text.setFormat","params":{"kurikaeshiMojiShori":true}}} +``` + ## Korean Line Break Anywhere `text.setFormat {koreanLineBreakAnywhere: bool}` (Paragraph panel menu › Korean Line Break Anywhere, shown with the diff --git a/docs/type-parity.md b/docs/type-parity.md index 5b332efd5e..419ccc7717 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -67,6 +67,7 @@ against Illustrator's public documentation; **estimated** unless noted. | 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 | | CJK: Kinsoku Shori Type (Push In First, Push Out First, Push Out Only) | done | Paragraph panel menu › Kinsoku Shori Type (`text.setFormat {kinsokuType}`), with the East Asian options ([Formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); Push Out Only is the default, and a push-in closes the line's gaps next to CJK characters by at most a tenth of an em each (VectorCraft's own limit). Evidence: `layout::wrapping_tests::kinsoku_shori_type_pushes_a_closing_bracket_in_or_out`, `tests::vertical::kinsoku_shori_type_pushes_a_closing_bracket_in_or_out`, `typecmd::area_tests::kinsoku_shori_type_is_set_per_paragraph_and_saved_only_when_not_push_out_only` | +| CJK: Kurikaeshi Moji Shori | done | Paragraph panel menu › Kurikaeshi Moji Shori (`text.setFormat {kurikaeshiMojiShori}`), with the East Asian options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): a repeat mark (々, ゝ, ゞ, ヽ, ヾ) that starts a line of point or area type is drawn as the character it repeats, and the text keeps the mark; SVG export with live type writes the drawn character. The set of marks and the voicing rules are VectorCraft's own. Off by default, saved natively only when on, carried by paragraph styles. Evidence: `tests::repeat_marks_stand_for_the_character_before_them`, `tests::kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start`, `typecmd::area_tests::kurikaeshi_moji_shori_is_set_per_paragraph_and_saved_only_when_on`, `threads::tests::a_continued_frame_carries_the_character_a_repeat_mark_stands_for`, `panels::paragraph::tests::kurikaeshi_moji_shori_toggle_follows_the_selected_paragraphs`, `text_layout::a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws` | | CJK: Proportional Metrics (`palt` in horizontal type, `vpal` in vertical type) | done | #966 | | CJK: East Asian Type units (Q, Ha) | done | Preferences › Units › East Asian Type (`unitsAsianType`, Points by default) offers every unit and Q and Ha, a quarter of a millimetre each ([Scripting Guide](https://ai-scripting.docsforadobe.dev/scripting/measurementUnits/): 0.709 pt per Q; [InDesign's unit notation](https://helpx.adobe.com/in/indesign/desktop/layout-and-grid-tools/rulers-and-measure-tools/change-ruler-measurement-units.html): `q`, `h`). The public pages do not say which fields follow it, so no field uses it yet and that waits for a source. Evidence: `q_and_ha_are_a_quarter_millimetre`, `east_asian_type_unit_*` | | CJK: manual tate-chu-yoko | done | Character panel menu › Tate-chu-yoko (`text.setFormat` / `text.setRangeStyle {tateChuYoko}`), with Show East Asian Options: marked characters stand side by side across one em of a vertical column, squeezed to the em when wider; two or three half-width digits still do so without the mark; horizontal type keeps the mark and does not move them. Tate-chu-yoko Settings… (`ui.tateChuYokoSettings`, `{tcyUpDown, tcyLeftRight}` in points) moves a marked block up or down and right or left as one piece. Evidence: `tests_vertical::manual_tate_chu_yoko_sets_marked_characters_across_one_em`, `tests_vertical::tate_chu_yoko_settings_move_a_marked_block_up_down_left_and_right`, `typecmd::tate_chu_yoko_is_a_character_attribute_saved_only_when_on`, `typecmd::tate_chu_yoko_settings_are_character_attributes_saved_only_when_set`, `dialogs::tate_chu_yoko::tests` | From 411310a75789182880028044d808e461f5e44da3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:28:29 -0800 Subject: [PATCH 26/77] PDF export: Preserve Numbers converts tagged images from their profile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Output › Convert to Destination (Preserve Numbers), and in PDF/X-1a, which converts the same way, a gray or RGB image that carries an ICC profile had its numbers read as sRGB: converted as sRGB to a CMYK destination, and kept as they were in an RGB one. Preserve Numbers keeps the numbers of untagged content only, so such an image is now converted from its profile to sRGB with the color settings' intent, and then to a CMYK or other RGB destination, the document's own RGB profile included. - An untagged RGB image keeps its numbers in an RGB destination and converts from sRGB to a CMYK one, as before. - A gray image is converted to sRGB grays in an sRGB destination and keeps its profile in the others. - With RGB colors ICC-tagged as sRGB, the image is written as sRGB. - A profile the color engine can't read leaves the image as it is in an RGB destination, and its numbers read as sRGB in a CMYK one, with a warning each. - The table for an RGB destination is built only when the first tagged image needs it. --- crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/pdf/src/export/images.rs | 3 +- crates/pdf/src/images.rs | 32 ++++--- crates/pdf/src/output.rs | 50 +++++++++-- crates/pdf/src/tests/compression.rs | 124 +++++++++++++++++++++++++++- docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + 7 files changed, 199 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 77902b4a15..90b3401821 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; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; 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", has_doc, export_pdf ), diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 04a3a811f3..70cc868c23 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -139,7 +139,8 @@ impl Exporter<'_> { let doc = self.doc; let out = self.out.clone(); let profiles = !out.standard.cmyk_only(); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit }); + let then = out.converts_tagged_pixels().then_some(&*out); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then }); let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index ac1d77f372..2f81d84571 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -12,7 +12,9 @@ //! conversion leaves unchanged (an sRGB profile) keeps its JPEG data. A black-and-white image whose //! converted levels are grey is compressed as greyscale. A colour image the Output settings also //! convert to their destination ([`Pixels`]) goes from its profile to sRGB, then to the -//! destination; a grey one keeps its profile there, as grey pixels are not converted. +//! destination, and so does one converted from its profile to an RGB destination whose untagged +//! images keep their numbers (Preserve Numbers); a grey one keeps its profile there, as grey +//! pixels are not converted. //! //! CMYK images ([`ImageBlob::cmyk`]) stay CMYK: a CMYK JPEG already as asked is embedded as it is //! when its numbers are kept; the others' ink amounts are resampled, converted when the Output @@ -319,15 +321,20 @@ pub(crate) struct Recoded { pub note: Option<&'static str>, } -/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB (Convert to -/// Destination, [`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, -/// else the step before the image's [`Pixels`] conversion. -#[derive(Clone, Copy, Debug)] -pub(crate) struct ToSrgb { +/// How [`recode`] converts a gray or RGB image that carries an ICC profile to sRGB +/// ([`crate::output::ColorOut::image_srgb_intent`]): the destination when it is sRGB, else the +/// step before the image's [`Pixels`] conversion. +#[derive(Clone, Copy)] +pub(crate) struct ToSrgb<'a> { /// The rendering intent of the conversion. pub intent: Intent, /// 16-bit samples may be written (PDF 1.5 and later). pub sixteen_bit: bool, + /// The colour output whose [`crate::output::ColorOut::tagged_pixels`] then convert a colour + /// image converted from its profile, when other colour images are not converted (`recode`'s + /// `convert`): to an RGB destination whose untagged images keep their numbers (Preserve + /// Numbers). Its table is built when the first such image needs it. + pub then: Option<&'a crate::output::ColorOut>, } /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of @@ -476,8 +483,8 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// 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 -/// 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 +/// instead ([`ToSrgb`]), and colour ones then by `convert`, or without it by the conversion +/// `to_srgb` gives ([`ToSrgb::then`]); grey ones that either 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. pub(crate) fn recode( bytes: &[u8], @@ -497,7 +504,8 @@ pub(crate) fn recode( let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. // Grey pixels, which `convert` leaves as they are, keep their profile when it converts. - let to_srgb = to_srgb.filter(|_| !(grey && convert.is_some())); + let then = to_srgb.and_then(|t| t.then); + let to_srgb = to_srgb.filter(|_| !(grey && (convert.is_some() || then.is_some()))); // Converted to the destination as sRGB, as before, when the profile can't be read. let mut note = None; let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) { @@ -533,6 +541,8 @@ pub(crate) fn recode( return Recoded { image: None, warning: rule.instead, note: None }; } let Some(mut img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + // Converted from its profile: then by `convert`, else by the conversion `to_srgb` gives. + let mut from_profile = false; if let Some((p, t)) = &source { let srgb = match into_srgb(img, p, t.intent) { Some(s) => Some(s), @@ -550,8 +560,9 @@ pub(crate) fn recode( if kind == Kind::Mono && !bilevel(&srgb) { (kind, rule) = (Kind::Gray, self::rule(c, Kind::Gray)); } + from_profile = true; // Written as it is only when nothing converts it further. - let as_is = kept(&rule, dims, size, jpeg) && convert.is_none(); + let as_is = kept(&rule, dims, size, jpeg) && convert.is_none() && then.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 { @@ -570,6 +581,7 @@ pub(crate) fn recode( } }; } + let convert = if from_profile { convert.or_else(|| then.and_then(crate::output::ColorOut::tagged_pixels)) } else { convert }; // 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" }; diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index 92381e1628..dce763e9d6 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -14,7 +14,10 @@ //! that carries an ICC profile is converted from it to sRGB with the same intent and written //! without it ([`ColorOut::image_srgb_intent`]); with `destination` and a destination its //! pixels are converted to (CMYK, another RGB space), a colour image is converted from its -//! profile to sRGB and then to the destination. Without conversion it keeps its profile. The +//! profile to sRGB and then to the destination. With `preserveNumbers` (and PDF/X-1a), which +//! keeps the numbers of untagged colours only, such an image is converted from its profile +//! whatever the destination: to sRGB, and then to a CMYK or other RGB destination +//! ([`ColorOut::tagged_pixels`]). Without conversion it keeps its profile. The //! destination is a profile name; empty, the document's profile for its colour mode. //! - Profiles ([`ProfileInclusion`]): with `all`, with `destination`, and with `taggedSource` on a //! document that was assigned profiles, colours are written in ICC-based colour spaces: CMYK @@ -77,6 +80,9 @@ pub(crate) struct ColorOut { pub srgb_note: Option, /// The image transform, built when the first image needs it. pixels: OnceLock>, + /// The transform of images converted from their profile, when it isn't `pixels` + /// ([`Self::tagged_pixels`]). + tagged_pixels: OnceLock>, /// The CMYK image transform, built when the first CMYK image needs it. cmyk_pixels: OnceLock>, intent: Intent, @@ -120,6 +126,7 @@ impl Default for ColorOut { cmyk_profile, srgb_note: None, pixels: OnceLock::new(), + tagged_pixels: OnceLock::new(), cmyk_pixels: OnceLock::new(), intent, catalog: None, @@ -348,13 +355,42 @@ impl ColorOut { /// The intent a gray or RGB image that carries an ICC profile is converted from it to sRGB /// with ([`crate::images::recode`]): the colour settings' intent, with Convert to Destination /// and an sRGB destination, also when the document's RGB space is sRGB, or a destination - /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space). - /// `None` otherwise, Preserve Numbers and an RGB destination that is the document's own RGB - /// profile (which leaves RGB colours and RGB images as they are) included: such an image - /// keeps its profile, or its numbers are converted as sRGB ones. + /// colour images' pixels are then converted to ([`Self::pixels`]: CMYK, another RGB space); + /// and with Preserve Numbers (and PDF/X-1a's own conversion), whatever the destination, as + /// only untagged colours of the destination's model keep their numbers. The pixels are then + /// converted by [`Self::tagged_pixels`]. `None` otherwise, an RGB destination that is the + /// document's own RGB profile with Convert to Destination (which leaves RGB colours and RGB + /// images as they are) included: such an image keeps its profile. pub(crate) fn image_srgb_intent(&self) -> Option { - let d = self.dest.as_ref().filter(|d| d.destination)?; - ((d.model == Model::Rgb && d.srgb) || self.pixels().is_some()).then_some(self.intent) + let d = self.dest.as_ref()?; + let rgb = d.model == Model::Rgb && (d.srgb || !d.destination); + (rgb || self.pixels().is_some()).then_some(self.intent) + } + + /// The destination a colour image converted from its ICC profile to sRGB + /// ([`Self::image_srgb_intent`]) is then converted to when other colour images are not + /// ([`Self::pixels`]): with Preserve Numbers, an RGB destination other than sRGB, whose + /// untagged RGB images keep their numbers (unless RGB is tagged as sRGB). + fn tagged_rgb_dest(&self) -> Option<&Dest> { + self.dest.as_ref().filter(|d| !d.destination && d.model == Model::Rgb && !d.srgb && !self.tagged) + } + + /// Are colour images converted from their ICC profile then converted by + /// [`Self::tagged_pixels`]? + pub(crate) fn converts_tagged_pixels(&self) -> bool { + self.tagged_rgb_dest().is_some() + } + + /// How a colour image converted from its ICC profile to sRGB is then converted into that + /// destination's RGB space ([`Self::converts_tagged_pixels`]), built when the first such image + /// needs it; `None` when there is no such destination. + pub(crate) fn tagged_pixels(&self) -> Option<&Pixels> { + self.tagged_pixels + .get_or_init(|| { + let d = self.tagged_rgb_dest()?; + Some(Pixels::Rgb(Box::new(ProofLut::build(|rgb| d.cms.srgb_to_rgb(rgb))))) + }) + .as_ref() } /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index f36cb88e4b..8ad11de270 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -776,7 +776,7 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { png }; let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); - let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true }); + let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None }); 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); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); @@ -980,3 +980,125 @@ fn convert_to_destination_converts_tagged_images_from_their_profile() { let as_srgb = converted_samples(&img, to_cmyk); assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile: converted as sRGB"); } + +/// With Preserve Numbers, an RGB image that carries an ICC profile is converted from that profile +/// whatever the destination, while an untagged one keeps its numbers in an RGB destination (and +/// converts from sRGB to a CMYK one, as before): to Generic CMYK, sRGB, Wide Gamut RGB, and Wide +/// Gamut RGB that is also the document's RGB profile, and in PDF/X-1a, which converts the same way. +/// A gray image keeps its profile, except in an sRGB destination, where it is converted to sRGB +/// grays. An RGB profile the CMS can't read leaves the image as it is in an RGB destination, and +/// its numbers converted as sRGB ones to a CMYK destination, with a warning. +#[test] +fn preserve_numbers_converts_tagged_images_from_their_profile() { + use vectorcraft_color::cms::{self, ColorSettings, DISPLAY_P3, GENERIC_CMYK, Intent, SRGB, WIDE_GAMUT_RGB, icc_bytes}; + let intent = Intent::RelativeColorimetric; + let settings_with = + |rgb: &str| std::sync::Arc::new(cms::Cms::new(&ColorSettings { intent, rgb: rgb.into(), ..ColorSettings::default() }).unwrap()); + let (active, own) = (settings_with(SRGB), settings_with(WIDE_GAMUT_RGB)); + let mut p3 = icc_bytes(DISPLAY_P3).unwrap().to_vec(); + p3[8..12].copy_from_slice(&[4, 0x20, 0, 0]); + let p3_profile = cms::IccProfile::from_bytes(None, &p3).unwrap(); + let from_p3 = |rgb: [u8; 3]| p3_profile.to_srgb(&rgb.map(|v| f32::from(v) / 255.0), intent).unwrap().map(|v| (v * 255.0).round() as u8); + let img = colour_blocks(); + let tagged_png = doc(tagged(&img, &p3, ImageFormat::Png), "image/png"); + let untagged_png = doc(encoded(img.clone(), ImageFormat::Png), "image/png"); + let device = |space: &str| vec![Written { space: space.into(), icc: None, bits: 8, filter: "FlateDecode".into(), smask: false }]; + let cmyk = cms::Cms::new(&ColorSettings { intent, cmyk: GENERIC_CMYK.into(), ..ColorSettings::default() }).unwrap(); + let cmy = cms::ProofLut::build(|rgb| { + let v = cmyk.srgb_to_cmyk(rgb, intent); + [v[0], v[1], v[2]] + }); + let black = cms::ProofLut::build(|rgb| [cmyk.srgb_to_cmyk(rgb, intent)[3], 0.0, 0.0]); + let wide_lut = cms::ProofLut::build(|rgb| own.srgb_to_rgb(rgb)); + let to_cmyk = |rgb: [u8; 3]| [cmy.apply8(rgb).as_slice(), &black.apply8(rgb)[..1]].concat(); + let to_wide = |rgb: [u8; 3]| wide_lut.apply8(rgb).to_vec(); + let to_srgb = |rgb: [u8; 3]| rgb.to_vec(); + type ToDest<'a> = &'a dyn Fn([u8; 3]) -> Vec; + // Each case: what, the color settings, the export settings, the space images are written in, + // how an sRGB pixel converts to the destination, and whether untagged images keep their numbers. + type Case<'a> = (&'a str, &'a std::sync::Arc, Value, &'a str, ToDest<'a>, bool); + let cases: [Case<'_>; 5] = [ + ("CMYK", &active, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}}), "DeviceCMYK", &to_cmyk, false), + ("sRGB", &active, json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}), "DeviceRGB", &to_srgb, true), + ("Wide Gamut", &active, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ("own RGB", &own, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}}), "DeviceRGB", &to_wide, true), + ( + "PDF/X-1a", + &active, + json!({"standard": "pdfX1a", "compatibility": "1.3", "output": {"destination": GENERIC_CMYK}}), + "DeviceCMYK", + &to_cmyk, + false, + ), + ]; + for (what, color, settings, space, to_dest, keeps) in cases { + let export = |d: &Document| { + let mut s: PdfSettings = serde_json::from_value(settings.clone()).unwrap(); + s.compression.compress_text = false; + let r = cms::with_active((*color).clone(), || export_with_report(d, &PdfOptions { settings: s, ..Default::default() })).unwrap(); + assert!(r.warnings.is_empty(), "{what}: {:?}", r.warnings); + if what == "PDF/X-1a" { + crate::pdfx::verify(&r.bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("{what}: {e}")); + } + (image_spaces(&r.bytes), image_samples(&r.bytes)) + }; + let (spaces, samples) = export(&tagged_png); + assert_eq!(spaces, device(space), "{what}: tagged"); + let want = converted_samples(&img, |rgb| to_dest(from_p3(rgb))); + let as_numbers = converted_samples(&img, to_dest); + assert!( + samples.len() == 1 && samples_close(&samples[0], &want, false, 1), + "{what}: converted from the profile, {}", + max_diff(&samples[0], &want) + ); + assert!(!samples_close(&samples[0], &as_numbers, false, 8), "{what}: not converted as its numbers"); + let (spaces, samples) = export(&untagged_png); + assert_eq!(spaces, device(space), "{what}: untagged"); + let untagged = if keeps { img.to_rgb8().into_raw() } else { as_numbers }; + assert!(samples.len() == 1 && samples_close(&samples[0], &untagged, false, 1), "{what}: untagged, {}", max_diff(&samples[0], &untagged)); + } + // With RGB colours ICC-tagged as sRGB, the tagged image is written as its sRGB samples, in an + // ICC-based colour space with the sRGB profile. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}}); + let (spaces, pdf) = cms::with_active(active.clone(), || export_images(&tagged_png, settings)); + let is_srgb = |icc: &[u8]| { + let p = cms::IccProfile::from_bytes(None, icc).unwrap(); + [[0.2, 0.5, 0.9], [0.9, 0.1, 0.4]].iter().all(|v| p.to_srgb(v, intent).unwrap().iter().zip(v).all(|(a, b)| (a - b).abs() < 0.01)) + }; + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref().is_some_and(is_srgb), "tagged as sRGB: {spaces:?}"); + let samples = image_samples(&pdf); + let want = converted_samples(&img, |rgb| from_p3(rgb).to_vec()); + assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "tagged as sRGB, {}", max_diff(&samples[0], &want)); + // A gray image keeps its gray profile, in a CMYK and in an RGB destination. + let gray = gray_profile(&[0x01CD]); + let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff"); + for destination in [GENERIC_CMYK, WIDE_GAMUT_RGB] { + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": destination}}); + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!( + spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), + "gray, {destination}: {spaces:?}" + ); + } + // In an sRGB destination it is converted to sRGB grays and written without it. + let settings = json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}); + let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); + assert!(spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none(), "gray, sRGB: {spaces:?}"); + // A profile the CMS can't read: the image keeps it and its numbers in an RGB destination, and + // its numbers are converted as sRGB ones to a CMYK destination, with a warning each. + let unread = icc_profile(b"RGB ", 600); + let unread_doc = doc(tagged(&img, &unread, ImageFormat::Png), "image/png"); + let unread_export = |destination: &str| { + let mut s: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "preserveNumbers", "destination": destination}})).unwrap(); + s.compression.compress_text = false; + cms::with_active(active.clone(), || export_with_report(&unread_doc, &PdfOptions { settings: s, ..Default::default() })).unwrap() + }; + let r = unread_export(WIDE_GAMUT_RGB); + assert!(r.warnings.iter().any(|w| w.contains("the image keeps it")), "{:?}", r.warnings); + let spaces = image_spaces(&r.bytes); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(unread.as_slice()), "unread profile: {spaces:?}"); + let r = unread_export(GENERIC_CMYK); + assert!(r.warnings.iter().any(|w| w.contains("converted to the destination as sRGB")), "{:?}", r.warnings); + let as_srgb = converted_samples(&img, to_cmyk); + assert!(image_samples(&r.bytes).first().is_some_and(|s| samples_close(s, &as_srgb, false, 1)), "unread profile, CMYK: converted as sRGB"); +} diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..6cdd88a9e1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5911,7 +5911,13 @@ and then to the destination, instead of having its numbers read as sRGB (a profi them read as sRGB, with a warning); a gray image keeps its profile, as gray is not converted. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there. -`preserveNumbers` still reads an image's numbers as sRGB. The destination is any profile `edit.colorSettings` lists (default: the document's +`preserveNumbers` (and PDF/X-1a, which converts the same way) keeps the numbers of untagged content only: an RGB image +that carries an ICC profile is converted from that profile to sRGB with the same intent, and then to a CMYK or other +RGB destination, the document's own RGB profile included (written as sRGB when colours are ICC-tagged), while an untagged RGB image keeps its numbers in an RGB +destination and converts from sRGB to a CMYK one. A gray image that carries one is converted to sRGB grays in an +sRGB destination and keeps its profile in the others, and a profile the color engine can't +read leaves the image as it is in an RGB destination, with a warning, and its numbers read as sRGB in a CMYK one. +The destination is any profile `edit.colorSettings` lists (default: the document's for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c8b2d43f8..35bce4927e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1935,6 +1935,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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`). - PDF export with Output › Convert to Destination and an sRGB destination converts a gray or RGB image that carries an ICC profile from that profile to sRGB, with the color settings' rendering intent, and writes it without the profile, as the conversion applies to every color ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)): 8-bit and 16-bit TIFFs (16 bits a sample from PDF 1.5 on when not resampled or recompressed), PNGs, JPEGs (kept as JPEG) and resampled images. A JPEG in an sRGB profile keeps its JPEG data, a black-and-white image whose converted levels are gray is written as grayscale, and without conversion every image keeps its profile. An image whose profile the color engine can't read, or whose pixels can't be decoded, is not converted: it keeps its profile, with a warning (`crates/pdf/src/tests/compression.rs`). - PDF export with Output › Convert to Destination and a CMYK destination, or an RGB destination other than sRGB that images are converted to, converts an RGB image that carries an ICC profile from that profile to sRGB and then to the destination, with the color settings' rendering intent, instead of reading its numbers as sRGB ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)). An untagged image converts from sRGB as before, a gray image keeps its profile, and a profile the color engine can't read leaves the numbers read as sRGB, with a warning. An RGB destination other than sRGB that is the document's own RGB profile leaves RGB colors and RGB images as they are, so a tagged RGB image keeps its profile there (`convert_to_destination_converts_tagged_images_from_their_profile` in `crates/pdf/src/tests/compression.rs`). + - PDF export with Output › Convert to Destination (Preserve Numbers), and PDF/X-1a, keeps the numbers of untagged content only, as the option describes ([PDF options](https://helpx.adobe.com/illustrator/using/pdf-options.html)): an RGB image that carries an ICC profile is converted from that profile to sRGB with the color settings' rendering intent, and then to a CMYK or other RGB destination, the document's own RGB profile included, while an untagged RGB image keeps its numbers in an RGB destination. A gray image is converted to sRGB grays in an sRGB destination and keeps its profile in the others, and a profile the color engine can't read leaves the image as it is in an RGB destination, with a warning (`preserve_numbers_converts_tagged_images_from_their_profile` in `crates/pdf/src/tests/compression.rs`). - SVG import shows a raster `` whose EXIF orientation or TIFF Orientation tag turns or flips it upright, linked or as a data URL, and inside an SVG shown as an image: the pixels are stored turned, the width and height swap, and the `` box fits the turned image under `preserveAspectRatio`, as CSS `image-orientation: from-image` describes (). A turned CMYK JPEG or TIFF keeps its inks as a CMYK TIFF, as does a CMYK TIFF that is not turned. TIFF data URLs (`image/tiff`, or untyped TIFF bytes) are read, and TIFFs with an alpha or other extra channel, CCITT Group 3 TIFFs and CMYK TIFFs stored one plane per ink are read as Open and Place read them. The pixels are decoded within the decode allowance, and a TIFF claiming more strips or tiles than the decoder can count is refused before it is decoded (`crates/svg/tests/it/image_orientation.rs`). - An image that SVG import stores again, as PNG or as a CMYK TIFF, keeps the resolution its PNG, JPEG, TIFF, WebP or BMP file declares, as Open and Place keep it: in a PNG `pHYs` chunk () or the TIFF's resolution tags, with the horizontal and vertical values swapped when the image turns a quarter. An image that declares no resolution is stored without one (`a_turned_raster_keeps_its_resolution`, `an_upright_tiff_keeps_its_resolution` and `a_cmyk_tiff_keeps_its_resolution_turned_or_not` in `crates/svg/tests/it/image_orientation.rs`). - SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`). From a230ea470d5ea96b358238d8a5f06fee532d49c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:31:15 -0800 Subject: [PATCH 27/77] 3D (Classic): the Black Overprint shading color shades with overprinting black over the fill Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) take shadingColor blackOverprint. Each face keeps its paint unchanged, and a face that darkens gets black over it, as strong as the darkening of the shading color Black: a fill multiplied and overprinting, and a seam stroke overprinting with Darken. The black is on the black plate in Separations Preview and is written to PDF as overprinting fills. The Plastic highlight is not drawn with it. Preserve Spot Colors draws its black with the same helper, so its seam stroke no longer multiplies the black a second time along face edges. The dialogs list the choice, with catalog rows next to Shading Color. Params text, docs/mcp.md, docs/three-d.md and docs/effects-parity.md describe it. --- crates/effects/src/catalog.rs | 6 +- crates/effects/src/revolve/classic.rs | 35 +++++++++++ crates/effects/src/solids/classic.rs | 69 ++++++++++++++------ crates/effects/src/solids/tests.rs | 91 ++++++++++++++++++++++++++- crates/engine/src/tests/overprint.rs | 58 +++++++++++++++++ crates/ui-egui/src/dialogs/effect.rs | 2 +- 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/effects-parity.md | 2 +- docs/mcp.md | 16 +++-- docs/three-d.md | 6 +- 37 files changed, 282 insertions(+), 31 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 8e0d63e9d0..7a93ab079e 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -210,21 +210,21 @@ pub fn effect_catalog() -> Vec { CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}), ), g( CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( CLASSIC_ROTATE, "Rotate (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.", json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), ), g( diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 8dc013e9dc..4aefb13eef 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -164,6 +164,41 @@ mod tests { } } + /// With Black Overprint every face keeps the blue, and the faces that darken get black over it, + /// overprinting, as strong as the darkening of the shading color Black. + #[test] + fn black_overprint_keeps_the_blue_under_overprinting_black() { + let darkened = revolved(json!({"surface": "diffuse"})); + let art = revolved(json!({"surface": "diffuse", "shadingColor": "blackOverprint"})); + let (darkened, drawn) = (faces(&darkened), faces(&art)); + assert_eq!(darkened.len(), drawn.len()); + let mut shaded = 0; + for (face, black) in drawn.iter().zip(&darkened) { + let fills: Vec<&vectorcraft_doc::FillLayer> = face + .appearance + .items + .iter() + .filter_map(|i| match i { + AppearanceItem::Fill(f) => Some(f), + AppearanceItem::Stroke(_) => None, + }) + .collect(); + assert_eq!((fills[0].paint.color(), fills[0].overprint), (Some(BLUE), false)); + let k = match fills.get(1) { + Some(shadow) => { + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint), (vectorcraft_doc::color::BlendMode::Multiply, true)); + shaded += 1; + k + } + None => 0.0, + }; + let b = fill(black).unwrap().to_rgb()[2]; + assert!((b - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened blue {b}"); + } + assert!(shaded > 0, "faces turned from the light get black"); + } + #[test] fn angle_offset_edge_and_cap_shape_the_surface() { let full = revolved(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0})).visual_bounds().unwrap(); diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index f48b94bce9..e2c3347efa 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -20,8 +20,8 @@ pub const ROTATE_SURFACES: [&str; 2] = ["none", "diffuse"]; /// The width of a Wireframe edge, in points. const WIRE: f64 = 0.5; -/// The Shading Color choices: black, a custom color, or none. -pub const SHADING_COLORS: [&str; 3] = ["black", "custom", "none"]; +/// The Shading Color choices: black, a custom color, none, or black overprinting the paint. +pub const SHADING_COLORS: [&str; 4] = ["black", "custom", "none", "blackOverprint"]; /// The surface settings of Extrude & Bevel (Classic)'s parameters. pub fn classic_shading(p: &Value) -> ClassicShading { @@ -55,8 +55,8 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { } } -/// The color faces darken toward: black, the custom color, or none (faces keep their paint and only -/// the highlight lightens them). +/// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces +/// keep their paint and only the highlight lightens them). fn shading_color(p: &Value) -> Option { match text(p, "shadingColor", "black") { "none" => None, @@ -200,27 +200,54 @@ fn preserves_spot_colors(p: &Value) -> bool { /// A face of `paint`, a color linked to a swatch, with Preserve Spot Colors: the swatch at a lower /// tint for the highlight `spec`, its link kept so a spot color stays on its own plate, and, where -/// tone `tone` is below full light and the faces darken (`shade`), black over it at `1 - tone`, -/// multiplied and overprinting, so it prints on the black plate. `seam` is the width of the seam +/// tone `tone` is below full light and the faces darken (`shade`), black over it as +/// [`overprinting_black`] draws it, so it prints on the black plate. `seam` is the width of the seam /// stroke each layer draws around the face. fn linked_face(paint: &Paint, tone: f64, spec: f64, shade: Option, seam: f64) -> Vec { let Paint::Solid { color, swatch, tint } = paint else { return vec![] }; let keep = (1.0 - spec).clamp(0.0, 1.0) as f32; let fill = Paint::Solid { color: color.tinted(keep), swatch: swatch.clone(), tint: tint * keep }; let mut items = vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))]; - if shade.is_some() && tone < 1.0 { - let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); - let mut layer = FillLayer::new(black.clone()); - layer.blend = BlendMode::Multiply; - layer.overprint = true; - let mut edge = crate::lighting::seam_stroke(black, seam); - edge.blend = BlendMode::Multiply; - edge.overprint = true; - items.extend([AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)]); + if shade.is_some() { + items.extend(overprinting_black(tone, seam)); } items } +/// The black that shades a face at tone `tone` on the black plate, when the tone is below full +/// light: a fill of black at `1 - tone`, multiplied and overprinting, and its seam stroke `seam` +/// wide, overprinting with Darken, so where the stroke lies over the face's own black, or over a +/// neighbor's, the face is not darkened twice. +fn overprinting_black(tone: f64, seam: f64) -> Vec { + if tone >= 1.0 { + return vec![]; + } + let black = Paint::solid(Color::gray((1.0 - tone).clamp(0.0, 1.0) as f32)); + let mut layer = FillLayer::new(black.clone()); + layer.blend = BlendMode::Multiply; + layer.overprint = true; + let mut edge = crate::lighting::seam_stroke(black, seam); + edge.blend = BlendMode::Darken; + edge.overprint = true; + vec![AppearanceItem::Fill(layer), AppearanceItem::Stroke(edge)] +} + +/// Whether the shading color of parameters `p` is Black Overprint. +fn black_overprint(p: &Value) -> bool { + text(p, "shadingColor", "black") == "blackOverprint" +} + +/// A face of `paint` with Black Overprint: the paint unchanged, and where tone `tone` is below full +/// light, black over it as [`overprinting_black`] draws it, so the paint's own inks print as they +/// are and the shading prints on the black plate. The highlight is not drawn. `seam` is the width of +/// the seam stroke each layer draws around the face. +fn overprinted_face(paint: &Paint, tone: f64, seam: f64) -> Vec { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]; + items.extend(overprinting_black(tone, seam)); + items +} + /// The width of the stroke [`surface`] draws around `face` with parameters `p`: a wire edge on /// Wireframe, else the seam between faces. pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { @@ -229,14 +256,16 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// One solid's faces in paint `paint`, as a group with the paint's opacity and blend mode, one child /// for each facet: the edges of the faces on Wireframe, else each face filled in its paint shaded by -/// its tone and highlight (with Preserve Spot Colors, a color linked to a swatch as [`linked_face`] -/// draws it). A gradient with transparent stops is shaded opaque and then masked by -/// its own transparency, so the shading follows the gradient's coverage. +/// its tone and highlight (with Black Overprint, as [`overprinted_face`] draws it; with Preserve Spot +/// Colors, a color linked to a swatch as [`linked_face`] draws it). A gradient with transparent stops +/// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's +/// coverage. pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); + let overprint = black_overprint(p); let wire = shading.surface == ClassicSurface::Wireframe; let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_paint(source) }; let paint = &paint; @@ -251,6 +280,10 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let (tone, spec) = shading.tone(face.normal, &lights); // A narrow stroke of the face's own paint closes the hairline seams between faces. let seam = super::seam_width(&face); + if overprint { + let items = overprinted_face(paint, tone, seam); + return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })); + } let items = match paint.color() { // Unshaded (No Shading, no shading color, or a face in full light) with no // highlight: the paint itself, its color space and swatch kept. diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index de1ec75de3..17e746d1aa 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1902,6 +1902,89 @@ fn classic_shading_color_blend_steps_and_lights() { assert_eq!(with(json!({"drawHiddenFaces": true})).len(), 6); } +/// The fills, then the strokes, of face `face`. +fn layers_of(face: &Node) -> (Vec<&vectorcraft_doc::FillLayer>, Vec<&StrokeLayer>) { + let fills = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }).collect(); + let strokes = face.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }).collect(); + (fills, strokes) +} + +/// The black over face `face` with Black Overprint, checked to be opaque and overprinting in +/// both its fill (multiplied) and its seam stroke (Darken, so it does not darken the face twice); +/// `None` when the face has none. +fn overprinted_black(face: &Node) -> Option { + let (fills, strokes) = layers_of(face); + assert_eq!(fills.len(), strokes.len(), "each fill has its seam stroke"); + let shadow = fills.get(1)?; + let Some(Color::Gray { k }) = shadow.paint.color() else { panic!("black shading: {:?}", shadow.paint) }; + assert_eq!((shadow.blend, shadow.overprint, shadow.opacity), (BlendMode::Multiply, true, 1.0)); + assert_eq!((strokes[1].paint.clone(), strokes[1].blend, strokes[1].overprint), (shadow.paint.clone(), BlendMode::Darken, true)); + assert!(!fills[0].overprint && !strokes[0].overprint, "the paint itself knocks out"); + Some(k) +} + +/// Black Overprint keeps the paint on every face and draws the shading over it as black, +/// overprinting, as strong as the darkening of the shading color Black; the +/// highlight is not drawn, and No Shading adds no black. +#[test] +fn classic_black_overprint_keeps_the_paint_under_overprinting_black() { + let diffuse = json!({"surface": "diffuse", "ambient": 20}); + let mut over = diffuse.clone(); + over["shadingColor"] = json!("blackOverprint"); + let darkened: Vec<[f32; 3]> = classic_faces(diffuse).iter().map(fill_rgb).collect(); + let faces = classic_faces(over); + assert_eq!(faces.len(), darkened.len()); + let mut shaded = 0; + for (face, rgb) in faces.iter().zip(&darkened) { + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED), "the paint is kept"); + let k = overprinted_black(face).unwrap_or(0.0); + assert!((rgb[0] - 0.8 * (1.0 - k)).abs() < 1e-3, "black at {k} matches the darkened {rgb:?}"); + shaded += usize::from(k > 0.0); + } + assert!(shaded > 0, "faces turned from the light get black"); + // Plastic: no white layer for the highlight. + let shiny = json!({"shadingColor": "blackOverprint", "highlightIntensity": 100, "highlightSize": 100, "lightHeight": 60}); + for face in classic_faces(shiny) { + let (fills, _) = layers_of(&face); + assert_eq!(fills[0].paint, Paint::solid(RED)); + assert!(fills.len() <= 2 && overprinted_black(&face).is_none_or(|k| k > 0.0), "{fills:?}"); + } + // No Shading: the paint alone. + for face in classic_faces(json!({"surface": "none", "shadingColor": "blackOverprint"})) { + assert_eq!(overprinted_black(&face), None); + assert_eq!(layers_of(&face).0[0].paint, Paint::solid(RED)); + } +} + +/// Black Overprint keeps a gradient fill on every face, with the black over it, and Rotate +/// (Classic) draws its plane the same way. +#[test] +fn classic_black_overprint_keeps_gradients_and_shades_rotate() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint}; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new( + GradientKind::Linear, + vec![vectorcraft_doc::color::GradientStop::new(0.0, RED), vectorcraft_doc::color::GradientStop::new(1.0, BLUE)], + )))); + let mut n = classic(json!({"shadingColor": "blackOverprint", "surface": "diffuse"})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = gradient.clone(); + } + let art = solid_art(&n).unwrap(); + let mut shaded = 0; + for face in faces(&art) { + assert_eq!(layers_of(face).0[0].paint, gradient); + shaded += usize::from(overprinted_black(face).is_some()); + } + assert!(shaded > 0); + // Rotate (Classic), turned from the light: red with black over it; facing it: red alone. + let turned = classic_rotate(json!({"rotationX": 0, "rotationY": 70, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + let face = &turned[0].children().unwrap()[0]; + assert_eq!(layers_of(face).0[0].paint, Paint::solid(RED)); + assert!(overprinted_black(face).is_some_and(|k| k > 0.05)); + let lit = classic_rotate(json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "lightHeight": 90, "shadingColor": "blackOverprint"})); + assert_eq!(overprinted_black(&lit[0].children().unwrap()[0]), None); +} + #[test] fn classic_bevel_height_extent_and_cap_shape_the_solid() { let bounds = |p: Value| solid_art(&classic(p)).unwrap().visual_bounds().unwrap(); @@ -2077,9 +2160,12 @@ fn classic_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_EXTRUDE, &crate::merged_params(CLASSIC_EXTRUDE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "wireframe", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 256, "bevel": "ogee"})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "glossy"}), "`surface` must be one of wireframe, none, diffuse, plastic"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), + (json!({"shadingColor": "blackoverprint"}), "`shadingColor` must be one of"), + (json!({"shadingColor": true}), "`shadingColor` must be one of"), (json!({"shadingCustom": "blue"}), "`shadingCustom` must be a #rrggbb color"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"depth": 2001}), "`depth` must be between 0 and 2000 (got 2001)"), @@ -2156,11 +2242,12 @@ fn classic_rotate_parameters_are_checked() { let check = |p: Value| validate_solid(&n, CLASSIC_ROTATE, &crate::merged_params(CLASSIC_ROTATE, &p)); assert!(check(json!({})).is_ok()); assert!(check(json!({"surface": "none", "shadingColor": "custom", "shadingCustom": "#12aBcd", "blendSteps": 1})).is_ok()); + assert!(check(json!({"shadingColor": "blackOverprint"})).is_ok()); for (p, says) in [ (json!({"surface": "plastic"}), "`surface` must be one of none, diffuse"), (json!({"surface": "wireframe"}), "`surface` must be one of none, diffuse"), (json!({"surface": 2}), "`surface` must be one of"), - (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none"), + (json!({"shadingColor": "red"}), "`shadingColor` must be one of black, custom, none, blackOverprint"), (json!({"shadingCustom": "#fff"}), "`shadingCustom` must be a #rrggbb color"), (json!({"rotationX": 181}), "`rotationX` must be between -180 and 180 (got 181)"), (json!({"perspectiveAngle": 161}), "`perspectiveAngle` must be between 0 and 160 (got 161)"), diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index 15fbb721e2..3f18ddf644 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -276,3 +276,61 @@ fn overprint_black_covers_type_gradients_spots_and_groups() { s.execute("edit.colors.overprintBlack", &json!({"includeCmyBlacks": true, "includeSpotBlacks": true})).unwrap(); assert!(fill(&s, g) && fill(&s, spot)); } + +/// The plate `plate` of `doc`, drawn as Separations Preview draws one plate, as one gray value per +/// pixel (0 full ink, 255 none). +fn plate(doc: &Document, plate: &str) -> Vec { + let mut r = Renderer::new(); + r.threads = 0; + let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() }; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() }; + let image = r.render(doc, 100, 100, Affine::IDENTITY, &opts); + (0..100 * 100).map(|i| image.pixel(i % 100, i / 100)[0]).collect() +} + +/// 3D (Classic) with the shading color Black Overprint puts the shading on the black plate, shows +/// it as the cyan darkened, and writes it to PDF as overprinting fills. +#[test] +fn classic_3d_black_overprint_shades_on_the_black_plate() { + let doc = |params: Value| { + let mut s = session(); + rect(&mut s, [30.0, 30.0, 40.0, 40.0], cyan_ink(), None, 0.0); + s.execute("effect.apply", &json!({"effect": "threeD.classicExtrude", "item": null, "params": params})).unwrap(); + s + }; + let over = doc(json!({"surface": "diffuse", "depth": 20, "shadingColor": "blackOverprint"})); + let flat = doc(json!({"surface": "none", "depth": 20, "shadingColor": "blackOverprint"})); + let black = doc(json!({"surface": "diffuse", "depth": 20})); + let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc); + let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count(); + assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn"); + assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate"); + assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black"); + // On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan. + let image = |d: &Document| { + let mut r = Renderer::new(); + r.threads = 0; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + r.render(d, 100, 100, Affine::IDENTITY, &opts) + }; + let (shaded, unshaded) = (image(over_doc), image(flat_doc)); + let mut darker = 0; + for (x, y) in (0..100u32).flat_map(|y| (0..100u32).map(move |x| (x, y))) { + let (s, u) = (shaded.pixel(x, y), unshaded.pixel(x, y)); + // Inside the solid (no white mixed in at an antialiased edge) where the shading darkens it. + if u[0] < 30 && (s[1] as i32) + 20 < u[1] as i32 { + darker += 1; + assert!(s[2] as i32 > s[0] as i32 + 20, "a shaded face keeps its cyan at ({x}, {y}): {s:?}"); + } + } + assert!(darker > 100, "the faces turned from the light are darker"); + + let pdf_overprints = |s: &mut Session| { + let v = s.execute("document.exportPdf", &json!({"compression": {"compressText": false}, "preserveEditing": false})).unwrap(); + let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); + String::from_utf8_lossy(&bytes).matches("/OP true/op true/OPM 1").count() + }; + let (mut over, mut black) = (over, black); + assert!(pdf_overprints(&mut over) > 0, "the black is written overprinting"); + assert_eq!(pdf_overprints(&mut black), 0); +} diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index cd089e04bd..82309cf1a0 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -542,7 +542,7 @@ pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option vec![(tl!("No Shading"), "none"), (tl!("Diffuse"), "diffuse")], (vectorcraft_effects::CLASSIC_EXTRUDE | vectorcraft_effects::CLASSIC_REVOLVE | vectorcraft_effects::CLASSIC_ROTATE, "shadingColor") => { - vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none")] + vec![(tl!("Black"), "black"), (tl!("Custom"), "custom"), (tl!("None"), "none"), (tl!("Black Overprint"), "blackOverprint")] } (vectorcraft_effects::EXTRUDE | vectorcraft_effects::CLASSIC_EXTRUDE, "bevel") => vec![ (tl!("None"), "none"), diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..79c9b2230c 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1162,6 +1162,7 @@ font-technology Variable Променливи Highlight Size Размер на отблясъка Blend Steps Стъпки на преливане Shading Color Цвят на засенчването + Black Overprint Черно с напечатване Draw Hidden Faces Изчертаване на скритите страни Eyedropper Пипета Eyedropper Applies: Пипетата прилага: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..c328ae9a05 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -520,6 +520,7 @@ Highlight Size Veličina odsjaja Blend Steps Koraci prelaza Shading Color Boja sjenčenja + Black Overprint Crni pretisak Draw Hidden Faces Crtaj skrivene strane Revolve… Rotaciono tijelo… Inflate… Napuhni… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..221fde4557 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1642,6 +1642,7 @@ antiAlias Sharp Nítid Highlight Size Mida de la brillantor Blend Steps Passos de fusió Shading Color Color de l’ombra + Black Overprint Negre en sobreimpressió Draw Hidden Faces Dibuixa les cares ocultes Eyedropper Comptagotes Eyedropper Applies: El comptagotes aplica: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..49255c036a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -533,6 +533,7 @@ Highlight Size Velikost odlesku Blend Steps Kroky prolnutí Shading Color Barva stínování + Black Overprint Přetisk černou Draw Hidden Faces Kreslit skryté stěny Revolve… Rotační těleso… Inflate… Nafouknutí… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..c84c49dfa0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1111,6 +1111,7 @@ Highlight Size Højlysstørrelse Blend Steps Overgangstrin Shading Color Skyggefarve + Black Overprint Sort overprint Draw Hidden Faces Tegn skjulte flader Revolve… Omdrej… Inflate… Pust op… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..e420257131 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1173,6 +1173,7 @@ font-technology Variable Variabel Highlight Size Glanzpunktgröße Blend Steps Angleichungsstufen Shading Color Schattierungsfarbe + Black Overprint Überdruckendes Schwarz Draw Hidden Faces Verdeckte Flächen zeichnen Eyedropper Pipette Sample Color from Screen Farbe vom Bildschirm aufnehmen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..f3fa7aea6b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1140,6 +1140,7 @@ font-technology Variable Μεταβλητές Highlight Size Μέγεθος ανταύγειας Blend Steps Βήματα ανάμειξης Shading Color Χρώμα σκίασης + Black Overprint Μαύρο με υπερεκτύπωση Draw Hidden Faces Σχεδίαση κρυφών εδρών Eyedropper Σταγονόμετρο (Eyedropper Tool) Eyedropper Applies: Το σταγονόμετρο εφαρμόζει: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..f0c90a60a0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1196,6 +1196,7 @@ font-technology Variable Variables Highlight Size Tamaño del brillo Blend Steps Pasos de fusión Shading Color Color de sombreado + Black Overprint Negro sobreimpreso Draw Hidden Faces Dibujar caras ocultas Eyedropper Cuentagotas Sample Color from Screen Tomar color de la pantalla diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..c42f5a9c3c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -530,6 +530,7 @@ Highlight Size Kiillon koko Blend Steps Sulautusvaiheet Shading Color Varjostusväri + Black Overprint Päällepainettu musta Draw Hidden Faces Piirrä piilotetut pinnat Revolve… Pyöräytä… Inflate… Täytä ilmalla… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..792514e69f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1191,6 +1191,7 @@ font-technology Variable Variables Highlight Size Taille de la brillance Blend Steps Étapes de transition Shading Color Couleur d’ombrage + Black Overprint Noir en surimpression Draw Hidden Faces Dessiner les faces cachées Eyedropper Pipette Sample Color from Screen Prélever une couleur à l’écran diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..b1d6b7e124 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3462,6 +3462,7 @@ Setup… સેટઅપ… Shading શેડિંગ Shading Color શેડિંગ રંગ + Black Overprint કાળો ઓવરપ્રિન્ટ Shadows and Glows પડછાયા અને ગ્લો Shape શેપ Shape Builder શેપ બિલ્ડર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..79781c16dd 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1840,6 +1840,7 @@ antiAlias Sharp शार्प Highlight Size हाइलाइट आकार Blend Steps ब्लेंड चरण Shading Color शेडिंग रंग + Black Overprint काला ओवरप्रिंट Draw Hidden Faces छिपे हुए फलक बनाएँ Eyedropper आईड्रॉपर Eyedropper Applies: आईड्रॉपपर लागू होता है: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..e126652d26 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1495,6 +1495,7 @@ font-technology Variable Változó Highlight Size Csillanás mérete Blend Steps Átmenetlépések Shading Color Árnyékolás színe + Black Overprint Felülnyomó fekete Draw Hidden Faces Rejtett lapok rajzolása Eyedropper Pipetta Sample Color from Screen Szín mintavétele a képernyőről diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..88a5d92366 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -487,6 +487,7 @@ Highlight Size Ukuran kilau Blend Steps Langkah campuran Shading Color Warna pengarsiran + Black Overprint Hitam overprint Draw Hidden Faces Gambar sisi tersembunyi Revolve… Revolusi… Inflate… Gelembungkan… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..186a7181ee 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1203,6 +1203,7 @@ font-technology Variable Variabili Highlight Size Dimensione lucentezza Blend Steps Passaggi di fusione Shading Color Colore ombreggiatura + Black Overprint Nero in sovrastampa Draw Hidden Faces Disegna facce nascoste Eyedropper Contagocce Sample Color from Screen Campiona colore dallo schermo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..73c3670166 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -577,6 +577,7 @@ digits Malayalam マラヤーラム数字 Highlight Size ハイライトのサイズ Blend Steps ブレンドの階調 Shading Color 陰影のカラー + Black Overprint ブラックオーバープリント Draw Hidden Faces 隠れた面を描画 Revolve… 回転体… Inflate… 膨張… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 358960bd37..6e904cdb61 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2544,6 +2544,7 @@ Highlight Size ელვარების ზომა Blend Steps შერევის საფეხურები Shading Color დაჩრდილვის ფერი + Black Overprint ზედდაბეჭდილი შავი Draw Hidden Faces დამალული წახნაგების დახატვა Revolve… ბრუნვა… Inflate… გაბერვა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..b8116ec6d8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -570,6 +570,7 @@ digits Malayalam 말라얄람어 Highlight Size 하이라이트 크기 Blend Steps 혼합 단계 Shading Color 셰이딩 색상 + Black Overprint 검정 겹쳐찍기 Draw Hidden Faces 숨겨진 면 그리기 Revolve… 회전체… Inflate… 부풀리기… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..18484b6c1b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1007,6 +1007,7 @@ Highlight Size Glansgrootte Blend Steps Overvloeistappen Shading Color Arceringskleur + Black Overprint Zwart overprinten Draw Hidden Faces Verborgen vlakken tekenen Revolve… Draaien… Inflate… Opblazen… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..10d07baad9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -492,6 +492,7 @@ Highlight Size Rozmiar połysku Blend Steps Kroki przejścia Shading Color Kolor cieniowania + Black Overprint Czarny nadruk Draw Hidden Faces Rysuj ukryte ściany Revolve… Obrót… Inflate… Nadmuchanie… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..a8f5051c4e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1085,6 +1085,7 @@ antiAlias Sharp Nítido Highlight Size Tamanho do Realce Blend Steps Etapas de Mesclagem Shading Color Cor do Sombreamento + Black Overprint Preto em Sobreimpressão Draw Hidden Faces Desenhar Faces Ocultas Eyedropper Conta-gotas Eyedropper Applies: O Conta-gotas Aplica: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..5a83489ac0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1194,6 +1194,7 @@ font-technology Variable Вариативные Highlight Size Размер блика Blend Steps Шаги перехода Shading Color Цвет затенения + Black Overprint Чёрный с наложением Draw Hidden Faces Рисовать скрытые грани Eyedropper Пипетка Sample Color from Screen Взять цвет с экрана diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..c7c9cc79ca 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1173,6 +1173,7 @@ font-technology Variable Variabla Highlight Size Högdagerstorlek Blend Steps Övergångssteg Shading Color Skuggningsfärg + Black Overprint Svart övertryck Draw Hidden Faces Rita dolda ytor Eyedropper Pipett Eyedropper Applies: Pipetten tillämpar: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..7eac71007e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1167,6 +1167,7 @@ font-technology Variable Değişken Highlight Size Parlama Boyutu Blend Steps Karışım Adımları Shading Color Gölgeleme Rengi + Black Overprint Siyah Üst Baskı Draw Hidden Faces Gizli Yüzleri Çiz Eyedropper Damlalık Sample Color from Screen Ekrandan Örnek Renk diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..ba601bde45 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1197,6 +1197,7 @@ font-technology Variable Варіативні Highlight Size Розмір відблиску Blend Steps Кроки переходу Shading Color Колір затінення + Black Overprint Чорний із накладенням Draw Hidden Faces Малювати приховані грані Eyedropper Піпетка Sample Color from Screen Взяти колір з екрана diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..3042ae2089 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1380,6 +1380,7 @@ font-technology Variable Biến thiên Highlight Size Kích thước điểm sáng Blend Steps Số bước hòa trộn Shading Color Màu tô bóng + Black Overprint Đen in chồng Draw Hidden Faces Vẽ các mặt ẩn Eyedropper Ống hút màu Sample Color from Screen Lấy mẫu màu từ màn hình diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..6494b6b557 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1134,6 +1134,7 @@ antiAlias Sharp 锐利 Highlight Size 高光大小 Blend Steps 混合步骤 Shading Color 底纹颜色 + Black Overprint 黑色叠印 Draw Hidden Faces 绘制隐藏表面 Eyedropper 吸管 Sample Color from Screen 从屏幕取样颜色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..b4f286d3bf 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1167,6 +1167,7 @@ font-technology Variable 可變 Highlight Size 亮部大小 Blend Steps 漸變階數 Shading Color 網底顏色 + Black Overprint 黑色疊印 Draw Hidden Faces 繪製隱藏表面 Eyedropper 滴管 Sample Color from Screen 從螢幕取樣顏色 diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 290148b89d..e84973de83 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -181,7 +181,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; 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 | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); 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)) | diff --git a/docs/mcp.md b/docs/mcp.md index c38d6fc7a2..670b693021 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4359,16 +4359,24 @@ is tall), `bevelInside` (false adds the bevel around the shape, true carves it i `softness` are not used). `ambient` (0..100%, default 50) lights every face. - `highlightIntensity` (0..100%, default 60) and `highlightSize` (0..100%, default 90; 100 is broad) shape the Plastic highlight. `blendSteps` (whole number, 1..256, default 25) is how many levels the shading is rounded to. -- `shadingColor`: `black` (the default), `custom` (darkens toward `shadingCustom`, a `#rrggbb` color) or `none` (the - paint is kept and only the highlight lightens it). `drawHiddenFaces` also draws the faces turned away from the - viewer, behind the others. +- `shadingColor`: `black` (the default), `custom` (darkens toward `shadingCustom`, a `#rrggbb` color), `none` (the + paint is kept and only the highlight lightens it) or `blackOverprint`. With `blackOverprint` every face keeps the + paint unchanged, and each face that darkens gets overprinting black over it, as strong as `black` would darken it. + The paint's own inks print as they are and the shading prints on the black plate. On screen the black is multiplied + over the paint, Separations Preview shows it on the Black plate, and `document.exportPdf` writes it as overprinting + fills + ([Shading Color options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)). + The highlight is not drawn with `blackOverprint`; that rule is VectorCraft's own. On a pattern face the black covers + the whole face, transparent pattern cells included, as the shading of the other shading colors does. + `drawHiddenFaces` also draws the faces turned away from the viewer, behind the others. - `preserveSpotColors` (default false) is the Lighting tab's Preserve Spot Colors checkbox. When it is on, a fill or stroke linked to a spot or global swatch stays linked on every face, so a spot color prints on its own plate in separations and PDF. The highlight lowers the swatch's tint, and a face that darkens gets black at the shade's strength over the swatch, multiplied and overprinting. These rules for drawing the shading are VectorCraft's own. The option does nothing while `shadingColor` is `custom`, since a custom shading color cannot keep a spot color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)). - Unlinked colors, gradients, patterns and the Wireframe surface draw as they do with it off. + Unlinked colors, gradients, patterns and the Wireframe surface draw as they do with it off. With `blackOverprint` + every face keeps its paint, swatch link included, whether the option is on or off. The defaults are VectorCraft's own. An unknown parameter, a number out of range, a flag that is not true or false, or an unknown surface or shading color is refused with an error and the document is not changed. diff --git a/docs/three-d.md b/docs/three-d.md index 2861bee0b7..461bd2352f 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -553,8 +553,10 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. face that darkens gets black over it, multiplied and overprinting, so a spot color stays on its own plate. The checkbox is unavailable while Shading Color is Custom ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); how - the faces are shaded with it is VectorCraft's own. The track cube, map art, Turntable and 3D export are separate, - unbuilt items. + the faces are shaded with it is VectorCraft's own. The Black Overprint shading color keeps each face's paint and + draws the shading over it as overprinting black, without the highlight. The shading is on the black plate in + Separations Preview and PDF output. The track cube, map art, Turntable and 3D export are + separate, unbuilt items. Release measurements and a repeatable CLI scene are in [3D lighting performance](3d-lighting-performance.md). From d39334a7512b7035438e50558c88f25256e59271 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:09:42 -0800 Subject: [PATCH 28/77] Graphs: a row written to an axis line is kept for its kind appearance.addFill and appearance.addStroke on an axis line, tick mark or radar ring stored only the attributes the new row changed on the line, so a stroke the kind kept from another line came back when the graph was drawn again, although the line showed the new black stroke. They now store the row they add for the line's kind when it becomes the line's topmost visible row of its kind. An appearance.copyFrom of some attributes, appearance.setItem and stroke.set stored only what they changed, so a paint, stroke weight, row opacity or blend mode that the line already showed did not replace what its kind kept. What they write to the line's topmost visible rows is now stored for the kind, as paint.setStroke stores the paint it writes. Row opacity and blend mode are stored apart, so an edit of one leaves the other as the kind keeps it, and a null weight or opacity writes nothing. --- crates/engine/src/cmd/appearance.rs | 95 +++++++++++++++++-- crates/engine/src/cmd/graph.rs | 10 +- crates/engine/src/cmd/graph/series.rs | 57 ++++++++++-- crates/engine/src/cmd/graph/tests.rs | 128 ++++++++++++++++++++++++++ crates/engine/src/cmd/stroke.rs | 8 +- docs/mcp.md | 8 +- 6 files changed, 280 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index b2df4133f1..5e3a6b79ee 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, true) ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, false) ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Appearance Item", [], None, - "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `index` needs `aligned` and is a row of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, only what the edit changes)", + "{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels; when their rows differ, `index` needs `aligned` and is a row of the backmost one), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the paint, weight, opacity and blend mode it writes to the line's topmost visible row)", has_doc, set_item ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: only what it changes; with `append`: only the kinds of row it adds) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}", has_doc, copy_from ), @@ -695,6 +695,45 @@ pub(crate) fn edit_items_then( cmd: &str, label: &str, fill: bool, + f: impl FnMut(&mut Node, Option) -> Result<()>, + after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result, +) -> Result> { + edit_items_writing_then(s, ids, item, of, cmd, label, fill, super::graph::RowWrites::NONE, f, after) +} + +/// [`edit_items`] for an edit that writes the attributes `writes` says to the row of each target it edits: a graph line +/// keeps them for its kind when that row is its topmost visible one, also when the line already showed them +/// ([`super::graph::capture_line_row_writes`]). +#[allow(clippy::too_many_arguments)] +pub(crate) fn edit_items_writing( + s: &mut Session, + ids: &[NodeId], + item: ItemTarget, + of: Option, + cmd: &str, + label: &str, + fill: bool, + writes: super::graph::RowWrites, + f: impl FnMut(&mut Node, Option) -> Result<()>, +) -> Result> { + edit_items_writing_then(s, ids, item, of, cmd, label, fill, writes, f, |before, d, edited| { + let series = capture_series_changes(before, d, edited); + let labels = super::graph::capture_label_changes(before, d, edited, false, None); + Ok(series || labels) + }) +} + +/// [`edit_items_then`] with the attributes `writes` says, as [`edit_items_writing`] keeps them. +#[allow(clippy::too_many_arguments)] +fn edit_items_writing_then( + s: &mut Session, + ids: &[NodeId], + item: ItemTarget, + of: Option, + cmd: &str, + label: &str, + fill: bool, + writes: super::graph::RowWrites, mut f: impl FnMut(&mut Node, Option) -> Result<()>, mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result, ) -> Result> { @@ -720,6 +759,8 @@ pub(crate) fn edit_items_then( let mut rows = Vec::new(); // The objects where `f` wrote the topmost visible row of its kind. let mut wrote = Vec::new(); + // The row of each object `f` wrote: its index, else the topmost row of the kind. + let mut written = Vec::new(); for (id, item) in ids.iter().zip(&per) { let Some(item) = item else { continue }; let Some(n) = d.node_mut(*id) else { continue }; @@ -732,13 +773,18 @@ pub(crate) fn edit_items_then( if index.is_none_or(|i| is_top_shown(n, i)) { wrote.push(*id); } + written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at))); } let more = after(&before, d, &edited)?; - // A graph line keeps only the attributes of its rows that the edit changed: the others stay as its kind keeps - // them, which the line may not show yet. + // A graph line keeps only the attributes of its rows that the edit changed, and those it wrote (`writes`): the + // others stay as its kind keeps them, which the line may not show yet. rows.retain(|id| !super::graph::is_graph_line(d, *id)); let labels = super::graph::capture_label_rows(d, &shown_rows_edited(&before, d, rows, |id| wrote.contains(&id))); - let lines = super::graph::capture_line_changes(&before, d, &edited); + let mut lines = super::graph::capture_line_changes(&before, d, &edited); + if writes != super::graph::RowWrites::NONE { + let (on_fill, on_stroke) = if fill { (writes, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, writes) }; + lines |= super::graph::capture_line_row_writes(d, &written, on_fill, on_stroke); + } Ok(count_changed(d, &before, &edited) + usize::from(more || labels || lines)) })?; Ok(aimed) @@ -896,10 +942,13 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { } } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); + let lines: Vec = added.iter().map(|(id, _)| *id).collect(); let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); capture_row_edits(&before, d, &ids); + // A graph line keeps the row it got for its kind, also when it showed that row's paint, weight and transparency. + super::graph::capture_line_kind_rows(d, &lines, (fill, !fill), false); Ok(()) })?; // A fill added above the active row becomes the active row; otherwise the rows above the new @@ -1277,7 +1326,17 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let painted = super::graph::capture_series_top_paints(d, &rows); let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id)); let labels = capture_row_edits(&before, d, &reached); - Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels)) + // A graph line keeps what was written to its topmost visible row, also when it already showed it. + let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect(); + // Only the values the edit applied: a null weight or opacity leaves the row as it is. + let writes = super::graph::RowWrites { + paint: paint.is_some(), + weight: p.get("weight").and_then(Value::as_f64).is_some(), + opacity: p.get("opacity").and_then(Value::as_f64).is_some(), + blend: blend.is_some(), + }; + let lines = super::graph::capture_line_row_writes(d, &tops, super::graph::RowWrites { weight: false, ..writes }, writes); + Ok(count_changed(d, &before, &ids) + usize::from(kept || painted || labels || lines)) })?; if let Some(pa) = &paint { s.remember_paint(pa); @@ -1886,7 +1945,25 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { _ if append => super::graph::capture_line_kind_rows(d, &targets, paints, transparency), (true, true) => super::graph::capture_line_rows(d, &targets), (true, false) => super::graph::capture_line_fill_stroke_rows(d, &targets), - (false, _) => super::graph::capture_line_changes(&before, d, &targets), + (false, _) => { + // The topmost row of each kind, which the pick wrote: what it wrote is kept also when the line showed it. + let tops: Vec<(NodeId, usize)> = targets + .iter() + .filter_map(|id| d.node(*id).map(|n| (*id, &n.appearance.items))) + .flat_map(|(id, items)| { + [true, false].into_iter().filter_map(move |kind| items.iter().rposition(|it| it.is_fill() == kind).map(|at| (id, at))) + }) + .collect(); + // A transparency pick applies the row's opacity and blend mode together. + let on_fill = super::graph::RowWrites { paint: fill.color, weight: false, opacity: opacities.0, blend: opacities.0 }; + let on_stroke = super::graph::RowWrites { + paint: stroke.color, + weight: stroke.weight && source_has(false), + opacity: opacities.1, + blend: opacities.1, + }; + super::graph::capture_line_changes(&before, d, &targets) | super::graph::capture_line_row_writes(d, &tops, on_fill, on_stroke) + } }; Ok(count_changed(d, &before, &targets) + usize::from(kept || painted || object || rows || text || lines)) })?; diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 93e79e857e..f5a07715cf 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -48,12 +48,12 @@ use generate::generate; #[cfg(test)] use series::default_series_color; pub(crate) use series::{ - LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity, + LabelTextChange, RowWrites, capture_label_anti_alias, capture_label_changes, capture_label_kind_rows, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles, capture_label_styles_given, capture_label_text, capture_line_changes, - capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_rows, capture_series_object_opacity, - capture_series_opacity, capture_series_top_paints, graph_part_members, is_design_art, is_graph_line, label_object_opacity_differs, label_rows, - labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, - series_object_opacity_differs, shown_paint, + capture_line_fill_stroke_rows, capture_line_kind_rows, capture_line_paint_writes, capture_line_row_writes, capture_line_rows, + capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, graph_part_members, is_design_art, is_graph_line, + label_object_opacity_differs, label_rows, labels_in, paint_targets, plain_labels, series_group_marks, series_group_marks_where, + series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, }; #[cfg(test)] diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 98352fe809..3651c41a9a 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -1443,25 +1443,68 @@ pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: & /// of a kind take the frontmost one's paint. Called inside the same edit, so they undo together. Returns whether kept /// rows changed. pub(crate) fn capture_line_paint_writes(doc: &mut Document, written: &[(NodeId, usize)]) -> bool { + let paint = RowWrites { paint: true, ..RowWrites::NONE }; + capture_line_row_writes(doc, written, paint, paint) +} + +/// Which attributes of a fill or stroke row an edit wrote, for [`capture_line_row_writes`]. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct RowWrites { + /// The paint. + pub paint: bool, + /// The weight (a stroke row only). + pub weight: bool, + /// The row's opacity. + pub opacity: bool, + /// The row's blend mode. + pub blend: bool, +} + +impl RowWrites { + /// No attribute. + pub const NONE: RowWrites = RowWrites { paint: false, weight: false, opacity: false, blend: false }; +} + +/// [`capture_line_paint_writes`] for the attributes `fill` says of a written fill row and `stroke` says of a written +/// stroke row: each is kept for every line of the kind as the line shows it, also when the line already showed it, in +/// place of what its kind keeps from another line. +pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, usize)], fill: RowWrites, stroke: RowWrites) -> bool { let ids: Vec = written.iter().map(|(id, _)| *id).collect(); let mut changed = false; for (id, graph, line) in lines_of(doc, &ids) { let Some(n) = doc.node(id) else { continue }; let items = &n.appearance.items; - let wrote = |fill: bool| items.iter().rposition(|it| it.is_fill() == fill && it.visible()).is_some_and(|at| written.contains(&(id, at))); - let (fill, stroke) = (wrote(true), wrote(false)); - if !fill && !stroke { + let wrote = |kind: bool| items.iter().rposition(|it| it.is_fill() == kind && it.visible()).is_some_and(|at| written.contains(&(id, at))); + let on_fill = if wrote(true) { fill } else { RowWrites::NONE }; + let on_stroke = if wrote(false) { stroke } else { RowWrites::NONE }; + if on_fill == RowWrites::NONE && on_stroke == RowWrites::NONE { continue; } let shown = label_rows(n).unwrap_or_default().paint; let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; let slot = line_slot(&mut spec.label_styles, line); let mut rows = slot.clone().unwrap_or_else(|| line.default_rows()); - if fill { - rows.paint.fill = shown.fill; + let k = &mut rows.paint; + if on_fill.paint { + k.fill = shown.fill; } - if stroke { - rows.paint.stroke = shown.stroke; + if on_fill.opacity { + k.fill_opacity = shown.fill_opacity; + } + if on_fill.blend { + k.fill_blend = shown.fill_blend; + } + if on_stroke.paint { + k.stroke = shown.stroke; + } + if on_stroke.weight { + k.stroke_width = shown.stroke_width; + } + if on_stroke.opacity { + k.stroke_opacity = shown.stroke_opacity; + } + if on_stroke.blend { + k.stroke_blend = shown.stroke_blend; } let kept = (rows != line.default_rows()).then_some(rows); changed |= *slot != kept; diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 5775197535..7e51fd6456 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -8271,6 +8271,134 @@ fn a_stroke_written_to_an_axis_line_that_shows_it_is_kept() { }); } +/// A stroke added to an axis line whose stroke shows the paint the new one takes is kept for every axis line, in place of +/// the stroke the kind keeps from another line. +#[test] +fn a_stroke_added_to_an_axis_line_is_kept() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + assert_eq!(line_look(&line_nodes(&s, id)[1]).0, "#000000", "the other lines show black until the graph is drawn again"); + s.execute("appearance.addStroke", &json!({"ids": [lines[1].id.0]})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| (l.0.as_str(), l.1) == ("#000000", 1.0)), "the added 1 pt black stroke: {looks:?}"); +} + +/// An Eyedropper pick of the stroke color, weight or transparency alone onto an axis line that already shows what it +/// writes is kept for every axis line, in place of what the kind keeps from another line. +#[test] +fn an_eyedropper_pick_an_axis_line_already_shows_is_kept() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let cases = [("color", json!({"color": "#ff0000"})), ("weight", json!({"weight": 2})), ("transparency", json!({"opacity": 40}))]; + every_case(cases, |(attr, edit)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [rect.0], "weight": 0.5})).unwrap(); + let lines = line_nodes(&s, id); + let mut p = edit.clone(); + p["ids"] = json!([lines[0].id.0]); + match *attr { + "color" => s.execute("paint.setStroke", &p), + "weight" => s.execute("stroke.set", &p), + _ => { + p["index"] = json!(stroke_row(&lines[0])); + s.execute("appearance.setItem", &p) + } + } + .unwrap(); + let shown = line_nodes(&s, id)[1].clone(); + assert_eq!(line_look(&shown), ("#000000".into(), 0.5, 1.0), "{attr}: the other lines show the default until the graph is drawn again"); + let fill = json!({"color": false, "transparency": false, "overprint": false}); + let mut stroke = json!({"color": false, "transparency": false, "overprint": false, "weight": false, "cap": false, "join": false, "miter": false, "dash": false}); + stroke[*attr] = json!(true); + let apply = json!({"appearance": {"transparency": false, "fill": fill, "stroke": stroke}, "character": false, "paragraph": false}); + s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [lines[1].id.0], "apply": apply})).unwrap(); + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{attr}: {looks:?}"); + let opacities: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.items[stroke_row(n)].opacity()).collect(); + assert!(opacities.iter().all(|o| *o == 1.0), "{attr}: {opacities:?}"); + }); +} + +/// A stroke color, weight or opacity set with `appearance.setItem`, or a weight set with `stroke.set`, on an axis line +/// that already shows it is kept for every axis line, in place of what the kind keeps from another line. +#[test] +fn a_row_attribute_set_on_an_axis_line_that_shows_it_is_kept() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let cases = [ + ("appearance.setItem", json!({"color": "#ff0000"}), json!({"color": "#000000"})), + ("appearance.setItem", json!({"weight": 2}), json!({"weight": 0.5})), + ("appearance.setItem", json!({"opacity": 40}), json!({"opacity": 100})), + ("stroke.set", json!({"weight": 2}), json!({"weight": 0.5})), + ]; + every_case(cases, |(cmd, kept, shown)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + for (line, values) in [(&lines[0], kept), (&lines[1], shown)] { + let mut p = values.clone(); + p["ids"] = json!([line.id.0]); + if *cmd == "appearance.setItem" { + p["index"] = json!(stroke_row(line)); + } + s.execute(cmd, &p).unwrap(); + } + let looks = redrawn_line_looks(&mut s, id); + assert!(looks.iter().all(|l| *l == ("#000000".into(), 0.5, 1.0)), "{cmd} {shown}: {looks:?}"); + let opacities: Vec = line_nodes(&s, id).iter().map(|n| n.appearance.items[stroke_row(n)].opacity()).collect(); + assert!(opacities.iter().all(|o| *o == 1.0), "{cmd} {shown}: {opacities:?}"); + }); +} + +/// `appearance.setItem` of a row's opacity alone on an axis line keeps the blend mode the kind keeps from another line, +/// and of its blend mode alone the opacity; a null weight or opacity writes nothing and adds no undo step. +#[test] +fn a_row_attribute_set_on_an_axis_line_keeps_the_others_its_kind_keeps() { + let stroke_row = |n: &vectorcraft_doc::Node| n.appearance.items.iter().rposition(|it| !it.is_fill()).unwrap(); + let row = |n: &vectorcraft_doc::Node| { + let it = &n.appearance.items[stroke_row(n)]; + (it.opacity(), it.blend()) + }; + let cases = [ + (json!({"blend": "multiply"}), json!({"opacity": 100}), (1.0, BlendMode::Multiply)), + (json!({"opacity": 40}), json!({"blend": "normal"}), (0.4, BlendMode::Normal)), + ]; + every_case(cases, |(kept, shown, want)| { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + for (line, values) in [(&lines[0], kept), (&lines[1], shown)] { + let mut p = values.clone(); + p["ids"] = json!([line.id.0]); + p["index"] = json!(stroke_row(line)); + s.execute("appearance.setItem", &p).unwrap(); + } + redrawn_line_looks(&mut s, id); + let rows: Vec<(f32, BlendMode)> = line_nodes(&s, id).iter().map(row).collect(); + assert!(rows.iter().all(|r| *r == *want), "{shown}: {rows:?}"); + }); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let lines = line_nodes(&s, id); + s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "color": "#ff0000"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + for key in ["weight", "opacity"] { + let mut p = json!({"ids": [lines[1].id.0], "index": stroke_row(&lines[1])}); + p[key] = serde_json::Value::Null; + s.execute("appearance.setItem", &p).unwrap(); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a null value adds no undo step"); + assert!(redrawn_line_looks(&mut s, id).iter().all(|l| l.0 == "#ff0000")); +} + #[test] fn pie_names_and_wedge_labels_keep_their_style() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 00feae339a..e16dce9495 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -22,7 +22,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -304,8 +304,10 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { } }; let of = super::appearance::reference_of(s, p, item, C)?; - // The objects counted: with a design's art, those with a row equal to the art's. - let ids = edit_items(s, &ids, item, of, C, "Stroke", false, |n, index| { + // The objects counted: with a design's art, those with a row equal to the art's. A graph line keeps the weight + // given to it, also when it already showed it. + let writes = super::graph::RowWrites { weight: change.weight.is_some(), ..super::graph::RowWrites::NONE }; + let ids = super::appearance::edit_items_writing(s, &ids, item, of, C, "Stroke", false, writes, |n, index| { if index.is_none() && let NodeKind::Text(t) = &mut n.kind { diff --git a/docs/mcp.md b/docs/mcp.md index 47d14ac50f..644ddb802b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -972,11 +972,15 @@ The other commands store them when given the line itself, and the `appearance.*` `item` and `object.setProps` store only the object opacity and blend mode. `appearance.clear`, `appearance.transfer`, `graphicStyle.apply`, `graphicStyle.redefine`, and `appearance.copyFrom` with every attribute picked up and applied or with `append`, store a line's rows even when the line already showed them; `graphicStyle.apply` with `add` and -`appearance.copyFrom` with `append` store only the kinds of row they add. The other commands, an `appearance.copyFrom` +`appearance.copyFrom` with `append` store only the kinds of row they add. `appearance.addFill` and +`appearance.addStroke` store the row they add when it becomes the line's topmost visible row of its kind, also when the +line already showed its paint, weight and opacity. The other commands, an `appearance.copyFrom` of some attributes included, store only what they change on a line's rows; the kind keeps its other attributes, also when the line still shows different ones until the graph is drawn again. `paint.setFill`, `paint.setStroke`, `addon.color.fillToStroke` and `addon.color.strokeToFill` also store the paint they write on a line's topmost visible -fill or stroke row when the line already showed it. An `appearance.copyFrom` that does not apply +fill or stroke row when the line already showed it. `appearance.setItem` and an `appearance.copyFrom` of some +attributes store the paint, stroke weight, and row opacity and blend mode they write to that row in the same way, and +`stroke.set` stores the weight it writes there. An `appearance.copyFrom` that does not apply the object's transparency, and `graphicStyle.apply` with `add`, leave the object opacity and blend mode a kind keeps as they are, also when the line still shows other ones. `paint.default` stores the default fill and stroke rows for a line's kind even when the line already showed them, and leaves the object opacity and blend mode the kind keeps. Rows From c08b4d932f341fb7b2dd1e6cd127e5db693c9acf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:52:00 -0800 Subject: [PATCH 29/77] MCP docs: Kurikaeshi Moji Shori says null leaves the setting as it is --- docs/mcp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 7a8396740c..b0bdf2972e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9466,8 +9466,8 @@ from one frame into the next; ゝ and ヽ draw it without its voicing marks, and plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph -style's attributes), and Reset Panel turns it off. A value that is not true or false is refused, and a call that gives -the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a +style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the +setting as it is, and a call that gives the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a save reports a paragraph with it on as left out. The help page: https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html From be2f993c4b27b9010529a25622f9f384f70acde4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:56:03 -0800 Subject: [PATCH 30/77] PDF export: Preserve Numbers keeps a gray image's profile when RGB is tagged as sRGB With Preserve Numbers, a non-sRGB RGB destination and RGB colors ICC-tagged as sRGB (the `all` profiles setting, PDF/A-2b, PDF/X-3 and PDF/X-4), a gray image that carries an ICC profile was converted to sRGB grays and lost its profile. It now keeps its profile there, as in the other destinations other than sRGB. --- crates/pdf/src/export/images.rs | 3 ++- crates/pdf/src/images.rs | 12 ++++++++---- crates/pdf/src/output.rs | 7 +++++++ crates/pdf/src/tests/compression.rs | 18 ++++++++++-------- 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 70cc868c23..a91e6f8a0f 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -140,7 +140,8 @@ impl Exporter<'_> { let out = self.out.clone(); let profiles = !out.standard.cmyk_only(); let then = out.converts_tagged_pixels().then_some(&*out); - let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then }); + let grey = out.converts_grey_images(); + let to_srgb = out.image_srgb_intent().map(|intent| crate::images::ToSrgb { intent, sixteen_bit: self.sixteen_bit, then, grey }); let img = doc.image_blob(im).filter(|_| !self.left_out.contains(key)).and_then(|blob| { let cmyk_image = blob.is_cmyk(); if !cmyk_image && self.convert && doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index 2f81d84571..c578c23176 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -335,6 +335,9 @@ pub(crate) struct ToSrgb<'a> { /// `convert`): to an RGB destination whose untagged images keep their numbers (Preserve /// Numbers). Its table is built when the first such image needs it. pub then: Option<&'a crate::output::ColorOut>, + /// Gray images are converted too: with an sRGB destination + /// ([`crate::output::ColorOut::converts_grey_images`]). In the others they keep their profile. + pub grey: bool, } /// The ICC profile image `bytes` carries ([`source_icc`]), when it is a well-formed profile of @@ -484,8 +487,9 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// 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 /// instead ([`ToSrgb`]), and colour ones then by `convert`, or without it by the conversion -/// `to_srgb` gives ([`ToSrgb::then`]); grey ones that either 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. +/// `to_srgb` gives ([`ToSrgb::then`]); grey ones keep their profile unless the destination is +/// sRGB ([`ToSrgb::grey`]). `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. pub(crate) fn recode( bytes: &[u8], size: (f64, f64), @@ -503,9 +507,9 @@ pub(crate) fn recode( use ExtendedColorType as T; let grey = matches!(decoder.original_color_type(), T::L1 | T::La1 | T::L2 | T::La2 | T::L4 | T::La4 | T::L8 | T::La8 | T::L16 | T::La16); // Pixels in a profile they are converted from are decoded, whatever the Compression settings. - // Grey pixels, which `convert` leaves as they are, keep their profile when it converts. + // Grey pixels keep their profile unless the destination is sRGB ([`ToSrgb::grey`]). let then = to_srgb.and_then(|t| t.then); - let to_srgb = to_srgb.filter(|_| !(grey && (convert.is_some() || then.is_some()))); + let to_srgb = to_srgb.filter(|t| !grey || t.grey); // Converted to the destination as sRGB, as before, when the profile can't be read. let mut note = None; let source = match to_srgb.and_then(|t| Some((source_profile(bytes, if grey { *b"GRAY" } else { *b"RGB " })?, t))) { diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index dce763e9d6..d1365dc8d9 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -367,6 +367,13 @@ impl ColorOut { (rgb || self.pixels().is_some()).then_some(self.intent) } + /// Are gray images that carry an ICC profile converted from it to sRGB grays too + /// ([`Self::image_srgb_intent`])? Only with an sRGB destination; in the others, RGB tagged as + /// sRGB included, grey pixels are not converted and keep their profile. + pub(crate) fn converts_grey_images(&self) -> bool { + self.dest.as_ref().is_some_and(|d| d.model == Model::Rgb && d.srgb) + } + /// The destination a colour image converted from its ICC profile to sRGB /// ([`Self::image_srgb_intent`]) is then converted to when other colour images are not /// ([`Self::pixels`]): with Preserve Numbers, an RGB destination other than sRGB, whose diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 8ad11de270..871ab42bcb 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -776,7 +776,7 @@ fn convert_to_srgb_converts_tagged_images_from_their_profile() { png }; let c: CompressionSettings = serde_json::from_value(json!({})).unwrap(); - let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None }); + let srgb_out = Some(crate::images::ToSrgb { intent: Intent::RelativeColorimetric, sixteen_bit: true, then: None, grey: 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); assert!(r.image.is_none() && r.warning.is_some_and(|w| w.contains("not converted to sRGB")), "{what}: {:?}", r.warning); @@ -1069,16 +1069,18 @@ fn preserve_numbers_converts_tagged_images_from_their_profile() { let samples = image_samples(&pdf); let want = converted_samples(&img, |rgb| from_p3(rgb).to_vec()); assert!(samples.len() == 1 && samples_close(&samples[0], &want, false, 1), "tagged as sRGB, {}", max_diff(&samples[0], &want)); - // A gray image keeps its gray profile, in a CMYK and in an RGB destination. + // A gray image keeps its gray profile, in a CMYK and in an RGB destination, and in an RGB one + // with RGB colours ICC-tagged as sRGB (`all` profiles, PDF/A-2b). let gray = gray_profile(&[0x01CD]); let gray_doc = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Tiff), "image/tiff"); - for destination in [GENERIC_CMYK, WIDE_GAMUT_RGB] { - let settings = json!({"output": {"conversion": "preserveNumbers", "destination": destination}}); + for (what, settings) in [ + (GENERIC_CMYK, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}})), + (WIDE_GAMUT_RGB, json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ("all profiles", json!({"output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB, "profiles": "all"}})), + ("PDF/A-2b", json!({"standard": "pdfA2b", "output": {"conversion": "preserveNumbers", "destination": WIDE_GAMUT_RGB}})), + ] { let (spaces, _) = cms::with_active(active.clone(), || export_images(&gray_doc, settings)); - assert!( - spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), - "gray, {destination}: {spaces:?}" - ); + assert!(spaces.len() == 1 && spaces[0].space == "ICCBased" && spaces[0].icc.as_deref() == Some(gray.as_slice()), "gray, {what}: {spaces:?}"); } // In an sRGB destination it is converted to sRGB grays and written without it. let settings = json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}}); From b6463e53cc6c2a026a172866d6d7979048f43924 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:13:16 -0800 Subject: [PATCH 31/77] Paragraph: threaded Kurikaeshi Moji Shori leads come from one pass over the frames A thread of frames that hold only repeat marks or soft returns made each frame look back through every frame before it, so opening or flowing such a story took quadratic time, with the setting off as well. The leads are now carried forward in one pass. --- crates/engine/src/cmd/threads.rs | 39 +++++++++++++++----------- crates/engine/src/cmd/threads/tests.rs | 18 ++++++++++++ 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index 7ccf26d3de..f4f807cb15 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -404,23 +404,22 @@ pub(crate) fn mark_continued(doc: &mut Document) { /// [`TextObject::first_para_lead`] for each frame of a thread, from the frames' plain `texts` and /// whether each one's first paragraph `continues` from the frame before: the last character of -/// that paragraph in the frames before that a repeat mark could stand for, or None. +/// that paragraph in the frames before that a repeat mark could stand for, or None. One pass over +/// the frames: each frame's lead is carried forward to the next. fn first_para_leads(texts: &[String], continues: &[bool]) -> Vec> { - (0..texts.len()) - .map(|k| { - let mut j = k; - while continues.get(j) == Some(&true) && j > 0 { - j -= 1; - let text = texts.get(j)?; - let tail = text.rfind('\n').map_or(Some(text.as_str()), |at| text.get(at + 1..))?; - if let Some(c) = vectorcraft_text::repeat_base(tail) { - return Some(c); - } - if tail.len() != text.len() { - return None; - } - } - None + // The lead the next frame takes when its first paragraph continues from this one. + let mut carry = None; + texts + .iter() + .enumerate() + .map(|(k, text)| { + #[cfg(test)] + LEAD_SCANS.with(|c| c.set(c.get() + 1)); + let lead = carry.filter(|_| continues.get(k) == Some(&true)); + let tail = text.rsplit('\n').next().unwrap_or(text); + // A paragraph break in this frame ends the paragraph the lead came from. + carry = vectorcraft_text::repeat_base(tail).or(lead.filter(|_| tail.len() == text.len())); + lead }) .collect() } @@ -432,6 +431,8 @@ thread_local! { static THREAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many times [`story_in`] went through a thread's frames on this thread. static STORY_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many frame texts [`first_para_leads`] went through on this thread. + static LEAD_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Tests: how many times [`story_of`] and [`ThreadIndex::of`] have gone through the document's @@ -447,6 +448,12 @@ pub(crate) fn story_builds() -> usize { STORY_BUILDS.with(std::cell::Cell::get) } +/// Tests: how many frame texts [`first_para_leads`] has gone through on this thread. +#[cfg(test)] +pub(crate) fn lead_scans() -> usize { + LEAD_SCANS.with(std::cell::Cell::get) +} + /// The frames of the thread that `id` is a frame of, in thread order, each area type or type on a /// path; empty when `id` is in no thread or the thread has fewer than two such frames. pub(crate) fn story_of(d: &Document, id: NodeId) -> Vec { diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index ba2cbaa1d4..82ac2f9f76 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -2262,3 +2262,21 @@ fn a_continued_frame_carries_the_character_a_repeat_mark_stands_for() { assert!(tb.first_para_continues); assert_eq!(tb.first_para_lead, vectorcraft_text::repeat_base(&ta.plain_text())); } + +/// Kurikaeshi Moji Shori: the leads of a thread whose frames hold only repeat marks come from one +/// pass over the frames, each frame's text gone through once, not once for every frame after it. +#[test] +fn continued_frame_leads_go_through_each_frame_once() { + let n = 2000; + let mut texts = vec!["時".to_string()]; + texts.extend(std::iter::repeat_n("々\u{2028}".to_string(), n - 1)); + let continues: Vec = (0..n).map(|k| k > 0).collect(); + let before = lead_scans(); + let leads = first_para_leads(&texts, &continues); + assert!(lead_scans() - before <= n, "{} frame texts gone through for {n} frames", lead_scans() - before); + assert_eq!(leads.first(), Some(&None)); + assert!(leads.iter().skip(1).all(|l| *l == Some('時'))); + // A paragraph break stops the carry, and a frame that starts a paragraph carries nothing. + let leads = first_para_leads(&["時".into(), "々\nす".into(), "々".into(), "日".into(), "々".into()], &[false, true, true, false, true]); + assert_eq!(leads, [None, Some('時'), Some('す'), None, Some('日')]); +} From 74f139062b468992fb79d76d2e0277a46702861c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:31:23 -0800 Subject: [PATCH 32/77] Paragraph: Kurikaeshi Moji Shori scans a paragraph once while laying it out Each line that started with a repeat mark scanned the paragraph's text from its start for the character the mark stands for, so a paragraph with marks at the start of many lines took quadratic time to lay out. The scan now goes on from the line before. --- crates/text/src/layout/flow.rs | 47 ++++++++++++++++++++++++---------- crates/text/src/shape.rs | 14 ++++++++++ crates/text/src/tests.rs | 22 ++++++++++++++++ 3 files changed, 70 insertions(+), 13 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index f028d47898..3999401a05 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -13,7 +13,8 @@ use super::{ is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, }; use crate::justify::is_format_control; -use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeated_char, shape_range}; +use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeat_base, repeated_char, shape_range}; +use std::cell::Cell; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? @@ -216,6 +217,9 @@ struct ParagraphData<'a, 'text> { /// Kurikaeshi Moji Shori: the character before a `continued` paragraph in the frames before /// ([`TextObject::first_para_lead`]). lead: Option, + /// Kurikaeshi Moji Shori: the byte the paragraph's text has been scanned to for the character a + /// repeat mark could stand for, and that character so far ([`ParagraphData::repeat_base_before`]). + repeat_scan: Cell<(usize, Option)>, sg: Vec, compressed: Vec, wakan: Vec, @@ -234,6 +238,21 @@ struct ParagraphData<'a, 'text> { regions: Option<&'a [Region]>, } +impl ParagraphData<'_, '_> { + /// Kurikaeshi Moji Shori: the character a repeat mark at byte `at` of `text` could stand for, + /// the last one before it in the paragraph that [`repeat_base`] takes, or else the paragraph's + /// `lead`. Lines are laid out in order, so each call scans on from where the call before it + /// stopped; a byte before that starts the scan again at the paragraph's start. None when `at` + /// does not fall on a character boundary after the paragraph's start. + fn repeat_base_before(&self, text: &str, at: usize) -> Option> { + let (from, base) = self.repeat_scan.get(); + let (from, base) = if from <= at { (from, base) } else { (self.pr.start, self.lead) }; + let base = repeat_base(text.get(from..at)?).or(base); + self.repeat_scan.set((at, base)); + Some(base) + } +} + fn prepare_paragraph<'a, 'text>( cx: &mut Ctx<'text>, pen: &mut Pen<'_>, @@ -327,14 +346,16 @@ fn prepare_paragraph<'a, 'text>( let zone = if cx.opts.composer.unwrap_or(para.composer).is_single_line() { para.hyphenation.zone } else { 0.0 }; let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX); let mirror = mirrors_indents(para, rtl, cx.vertical); + let lead = t.first_para_lead.filter(|_| continued); ParagraphData { para, + repeat_scan: Cell::new((pr.start, lead)), pr, marker_text, bidi, rtl, continued, - lead: t.first_para_lead.filter(|_| continued), + lead, sg, compressed, wakan, @@ -1277,18 +1298,18 @@ fn emit_line_glyph( } /// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of -/// a line of the paragraph starting at byte `para_start`, when `g` is a repeat mark, and the -/// character it shows: the character [`repeated_char`] gives, shaped in the mark's style with the -/// type's features (so vertical type gets the font's vertical forms), from the same face, with the -/// mark's advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, -/// belongs to a tate-chu-yoko or warichu block, nothing before it in the paragraph fits, or the face -/// draws the character with no glyph or with more than one. `lead` stands before a paragraph that -/// continues from the frame before ([`TextObject::first_para_lead`]). -fn repeat_mark_glyph(cx: &Ctx<'_>, para_start: usize, lead: Option, g: &SGlyph) -> Option<(SGlyph, char)> { - if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() { +/// a line of `paragraph`, when `g` is a repeat mark, and the character it shows: the character +/// [`repeated_char`] gives, shaped in the mark's style with the type's features (so vertical type +/// gets the font's vertical forms), from the same face, with the mark's advance and place, so the +/// line breaks stay as they are. None when `g` is no repeat mark, belongs to a tate-chu-yoko or +/// warichu block, nothing before it in the paragraph fits, or the face draws the character with no +/// glyph or with more than one. The paragraph's `lead` stands before a paragraph that continues +/// from the frame before ([`TextObject::first_para_lead`]). +fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph) -> Option<(SGlyph, char)> { + if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(lead, cx.text.get(para_start..g.byte)?, g.ch)?; + let c = repeated_char(paragraph.repeat_base_before(cx.text, g.byte)?, "", g.ch)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1305,7 +1326,7 @@ fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: return None; } let g = paragraph.sg.get(first)?; - let (glyph, c) = repeat_mark_glyph(cx, paragraph.pr.start, paragraph.lead, g)?; + let (glyph, c) = repeat_mark_glyph(cx, paragraph, g)?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index 9d09ce076e..097b056d7d 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -456,9 +456,23 @@ pub fn inseparable(a: char, b: char) -> bool { /// paragraph continues from the frame before the result for the text before it /// (`TextObject::first_para_lead`). pub fn repeat_base(text: &str) -> Option { + #[cfg(test)] + REPEAT_SCANNED.with(|c| c.set(c.get() + text.len())); text.chars().rev().find(|&c| !matches!(c, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ' | '\u{2028}' | '\u{3099}' | '\u{309A}')) } +#[cfg(test)] +thread_local! { + /// Tests: how many bytes of text [`repeat_base`] was given on this thread. + static REPEAT_SCANNED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Tests: how many bytes of text [`repeat_base`] has been given on this thread. +#[cfg(test)] +pub(crate) fn repeat_scanned() -> usize { + REPEAT_SCANNED.get() +} + /// Kurikaeshi Moji Shori: the character the repeat mark `mark` stands for after the text `before` /// it, or None when `mark` is not a repeat mark or nothing before it fits. `lead` stands before /// `before` (the text of a threaded paragraph in the frames before). VectorCraft's rules: the diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 477c3e3392..b15b0757be 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2810,6 +2810,28 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); } +/// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid +/// out in one scan of its text, not one scan of everything before each line. +#[test] +fn kurikaeshi_moji_shori_scans_a_paragraph_once() { + use crate::shape::repeat_scanned; + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let text = format!("時{}", "\u{2028}々".repeat(2000)); + let mut t = TextObject::point(Point::ZERO, &text, st); + t.para.kurikaeshi_moji_shori = true; + let before = repeat_scanned(); + let l = layout(&db, &t); + let scanned = repeat_scanned() - before; + assert!(scanned <= 2 * text.len(), "{scanned} bytes scanned for a paragraph of {}", text.len()); + // Every line's 々 is still drawn as 時. + assert_eq!(l.repeat_marks.len(), 2000); + assert!(l.glyphs.iter().filter(|g| g.byte > 0 && text.get(g.byte..).is_some_and(|s| s.starts_with('々'))).all(|g| g.gid == face.glyph_for('時'))); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] From a5b84d8e2ae997a1059ce4ce22573de0e1d13ff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:38:15 -0800 Subject: [PATCH 33/77] Paragraph: Kurikaeshi Moji Shori keeps one record per mark when area type flows again Vertically aligned area type in a frame that is not a rectangle flows its text again until it settles, and each pass added the line-start repeat marks to the layout's records once more, so SVG export could look up the wrong character. Each pass now starts from empty records, and an undone pass restores the ones before it. --- crates/text/src/layout/vertical.rs | 3 ++- crates/text/src/tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/text/src/layout/vertical.rs b/crates/text/src/layout/vertical.rs index 30f12139a2..3262362fae 100644 --- a/crates/text/src/layout/vertical.rs +++ b/crates/text/src/layout/vertical.rs @@ -529,13 +529,14 @@ pub(super) fn align_vertically(cx: &mut Ctx<'_>, paras: &[Range], t: &Tex std::mem::take(&mut cx.out.lines), std::mem::take(&mut cx.out.inlines), std::mem::take(&mut cx.out.markers), + std::mem::take(&mut cx.out.repeat_marks), std::mem::replace(&mut cx.out.overflow, false), ); flow(cx, paras, t, Some(regions)); if laid_out(&cx.out) < before { // Text no longer fits (lines got narrower, or flow around a wrap object): undo the // pass and try a smaller step. - (cx.out.glyphs, cx.out.lines, cx.out.inlines, cx.out.markers, cx.out.overflow) = prev; + (cx.out.glyphs, cx.out.lines, cx.out.inlines, cx.out.markers, cx.out.repeat_marks, cx.out.overflow) = prev; for (r, (shift, gap)) in regions.iter_mut().zip(saved) { r.shift = shift; r.gap = gap; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index b15b0757be..d2940f83b5 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2832,6 +2832,29 @@ fn kurikaeshi_moji_shori_scans_a_paragraph_once() { assert!(l.glyphs.iter().filter(|g| g.byte > 0 && text.get(g.byte..).is_some_and(|s| s.starts_with('々'))).all(|g| g.gid == face.glyph_for('時'))); } +/// Kurikaeshi Moji Shori: area type in a frame that isn't a rectangle, centered vertically, flows +/// again until it settles, and keeps one record for each repeat mark it draws as another character. +#[test] +fn vertically_centered_repeat_marks_in_a_round_frame_are_recorded_once() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + use vectorcraft_doc::VerticalAlign; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let text = format!("時{}", "\u{2028}々".repeat(5)); + let frame = kurbo::Ellipse::new((150.0, 150.0), (150.0, 150.0), 0.0).to_path(0.1); + let mut t = area(&text, st, Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left); + t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) }; + t.para.kurikaeshi_moji_shori = true; + let top = layout(&db, &t); + let marks: Vec<(usize, char)> = text.match_indices('々').map(|(b, _)| (b, '時')).collect(); + assert_eq!(top.repeat_marks, marks); + t.area.vertical_align = VerticalAlign::Center; + let lay = layout(&db, &t); + assert!(lay.lines[0].baseline > top.lines[0].baseline + 1.0, "the text moves down"); + assert_eq!(lay.repeat_marks, marks); +} + /// Bunri-Kinshi: a justified line spreads its room over the gaps between its CJK characters but not /// over the gap inside a vertical kana repeat mark, and still fills its width. #[test] From 63451f5d78ff705e7fec43864d078432705dbed4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:48:02 -0800 Subject: [PATCH 34/77] Command Palette: a Recent Commands list beside the search field runs the last five picks again MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A button beside the Help › Search Commands field opens a Recent Commands list: the last five commands and tools picked from the palette, most recent first. A command picked again moves to the top, so it takes one place. Choosing a row closes the palette and runs it the way a pick of the same result does, so dialogs, a dimmed item's reason and tool picks work as before. With nothing picked yet, the list shows a dimmed No recent commands row. A command that is not available now, such as a filter of a plug-in that is not loaded, is left out of the list but stays in the saved ids, so it shows again when it comes back. The saved list keeps the last five available picks and at most 20 ids in all. It is saved with the UI state next to Recent Fonts. While the list is open, its first row takes the keyboard, Up and Down move through its rows and wrap at the ends, Enter runs the row, and Escape closes the list before the palette. Docs: docs/target-app-parity.md (command palette). Fixes #6376 --- 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/palette.rs | 328 +++++++++++++++++++++++++++- crates/ui-egui/src/shortcuts.rs | 6 +- crates/ui-egui/src/state.rs | 4 + docs/target-app-parity.md | 1 + 32 files changed, 382 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..5c0d251097 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3158,6 +3158,8 @@ digits Malayalam Малаялам Search All Търсене във всички Search commands and tools Търсене на команди и инструменти Search commands and tools… Търсене на команди и инструменти… + Recent Commands Последни команди + No recent commands Няма последни команди Search Commands… Търсене на команди… Secondary Вторичен Section Symbol Символ за раздел diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..a241f7b7b5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4352,6 +4352,8 @@ font-technology Variable Varijabilni Saving Čuvanje Saving {} Čuvanje {} Search commands and tools… Pretraži naredbe i alate… + Recent Commands Nedavne naredbe + No recent commands Nema nedavnih naredbi Dashed Line Isprekidana linija Panel menu Meni panela Unembed… Poništi ugrađivanje… diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..97faf4ae00 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4074,6 +4074,8 @@ digits Malayalam Malaiàlam Search All Cerca a tot Search commands and tools Cerca ordres i eines Search commands and tools… Cerca ordres i eines… + Recent Commands Ordres recents + No recent commands No hi ha ordres recents Search Commands… Cerca ordres… Search Fonts Folder Cerca a la carpeta de tipus de lletra Searching… Cercant… diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..501d984ad7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4450,6 +4450,8 @@ font-technology Variable Variabilní Saving Ukládání Saving {} Ukládání {} Search commands and tools… Hledat příkazy a nástroje… + Recent Commands Nedávné příkazy + No recent commands Žádné nedávné příkazy Dashed Line Čárkovaná čára Panel menu Nabídka panelu Unembed… Zrušit vložení… diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..9d0108a02a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4774,6 +4774,8 @@ font-technology Variable Variable Saving Gemmer Saving {} Gemmer {} Search commands and tools… Søg i kommandoer og værktøjer… + Recent Commands Seneste kommandoer + No recent commands Ingen seneste kommandoer Dashed Line Stiplet linje Panel menu Panelmenu Unembed… Ophæv integrering… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..43d8b305ad 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3215,6 +3215,8 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` muss ein Array mit diesen Namen sein: {_1} Search commands and tools Befehle und Werkzeuge suchen Search commands and tools… Befehle und Werkzeuge suchen… + Recent Commands Zuletzt verwendete Befehle + No recent commands Keine zuletzt verwendeten Befehle Search Commands… Befehle suchen… Secondary Sekundär Section Symbol Paragrafenzeichen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..a0462d5c7a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3853,6 +3853,8 @@ digits Malayalam Μαλαγιάλαμ Search All Αναζήτηση όλων Search commands and tools Αναζήτηση εντολών και εργαλείων Search commands and tools… Αναζήτηση εντολών και εργαλείων… + Recent Commands Πρόσφατες εντολές + No recent commands Δεν υπάρχουν πρόσφατες εντολές Search Commands… Αναζήτηση εντολών… Secondary Δευτερεύον Section Symbol Σύμβολο ενότητας diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..118c452f14 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3249,6 +3249,8 @@ digits Malayalam Malayálam @msg `{key}` must be an array of these names: {_1} `{key}` debe ser una lista de estos nombres: {_1} Search commands and tools Buscar comandos y herramientas Search commands and tools… Buscar comandos y herramientas… + Recent Commands Comandos recientes + No recent commands No hay comandos recientes Search Commands… Buscar comandos… Secondary Secundario Section Symbol Símbolo de sección diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..0ec8f7852b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4369,6 +4369,8 @@ font-technology Variable Muuttuvat Saving Tallennetaan Saving {} Tallennetaan {} Search commands and tools… Hae komentoja ja työkaluja… + Recent Commands Viimeisimmät komennot + No recent commands Ei viimeisimpiä komentoja Dashed Line Katkoviiva Panel menu Paneelivalikko Unembed… Poista upotus… diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..95cff2e4cb 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3241,6 +3241,8 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` doit être un tableau de noms parmi {_1} Search commands and tools Chercher commandes et outils Search commands and tools… Chercher commandes et outils… + Recent Commands Commandes récentes + No recent commands Aucune commande récente Search Commands… Rechercher des commandes… Secondary Secondaire Section Symbol Symbole de section diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..d22c686b34 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3347,6 +3347,8 @@ Search Preferences પસંદગીઓ શોધો Search commands and tools આદેશો અને ટૂલ્સ શોધો Search commands and tools… આદેશો અને ટૂલ્સ શોધો… + Recent Commands તાજેતરના આદેશો + No recent commands કોઈ તાજેતરના આદેશો નથી Search images છબીઓ શોધો Searching… શોધી રહ્યા છીએ… Secondary ગૌણ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..5723999158 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4426,6 +4426,8 @@ antiAlias Sharp शार्प Search artboards खोज आर्टबोर्ड Search commands and tools खोज आदेश और टूल Search commands and tools… आदेश और टूल खोजें… + Recent Commands हाल के आदेश + No recent commands कोई हाल का आदेश नहीं Search Commands… कमांड खोजें… Search Fonts Folder खोज फ़ॉन्ट फ़ोल्डर Search images इमेज खोजना diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..7979496ee9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3866,6 +3866,8 @@ mark-style Japanese Japán @msg `{key}` must be an array of these names: {_1} `{key}`: ezen nevek tömbje kell: {_1} Search commands and tools Parancsok és eszközök keresése Search commands and tools… Parancsok és eszközök keresése… + Recent Commands Legutóbbi parancsok + No recent commands Nincsenek legutóbbi parancsok Search Commands… Parancsok keresése… Search Fonts Folder Keresés betűtípusmappában Searching… Keresés… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..b76f7994df 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4108,6 +4108,8 @@ font-technology Variable Variabel Saving Menyimpan Saving {} Menyimpan {} Search commands and tools… Cari perintah dan alat… + Recent Commands Perintah terbaru + No recent commands Tidak ada perintah terbaru Dashed Line Garis putus-putus Panel menu Menu panel Unembed… Lepaskan sematan… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..6a68dcb67c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3292,6 +3292,8 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` deve essere un array di questi nomi: {_1} Search commands and tools Cerca comandi e strumenti Search commands and tools… Cerca comandi e strumenti… + Recent Commands Comandi recenti + No recent commands Nessun comando recente Search Commands… Cerca comandi… Secondary Secondario Section Symbol Simbolo di sezione diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..19d5cff210 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3172,6 +3172,8 @@ mark-style Japanese 日本式 @msg `{key}` must be an array of these names: {_1} `{key}` には {_1} の中の名前の配列を指定してください Search commands and tools コマンドとツールを検索 Search commands and tools… コマンドとツールを検索… + Recent Commands 最近使ったコマンド + No recent commands 最近使ったコマンドはありません Secondary セカンダリ Select All Art on Layer レイヤー上のすべてのアートを選択 Select All Assets すべてのアセットを選択 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 2864881e87..6dc81153d4 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6053,6 +6053,8 @@ font-technology Variable ცვლადი Saving შენახვა Saving {} ინახება: {} Search commands and tools… ბრძანებებისა და ხელსაწყოების ძიება… + Recent Commands ბოლო ბრძანებები + No recent commands ბოლო ბრძანებები არ არის Dashed Line ტირეებიანი ხაზი Panel menu პანელის მენიუ Unembed… ჩაშენების მოხსნა… diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..da324398fc 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3161,6 +3161,8 @@ mark-style Japanese 일본식 @msg `{key}` must be an array of these names: {_1} `{key}`은(는) 다음 이름의 배열이어야 합니다: {_1} Search commands and tools 명령 및 도구 검색 Search commands and tools… 명령 및 도구 검색… + Recent Commands 최근 명령 + No recent commands 최근 명령 없음 Secondary 보조 Select All Art on Layer 레이어의 모든 아트웍 선택 Select All Assets 모든 에셋 선택 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..17a2aef1ad 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4670,6 +4670,8 @@ font-technology Variable Variabel Saving Bezig met opslaan Saving {} {} wordt opgeslagen Search commands and tools… Opdrachten en gereedschappen zoeken… + Recent Commands Recente opdrachten + No recent commands Geen recente opdrachten Dashed Line Streepjeslijn Panel menu Paneelmenu Unembed… Insluiten ongedaan maken… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..bc3b7c4027 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4291,6 +4291,8 @@ font-technology Variable Zmienne Saving Zapisywanie Saving {} Zapisywanie {} Search commands and tools… Szukaj poleceń i narzędzi… + Recent Commands Ostatnie polecenia + No recent commands Brak ostatnich poleceń Dashed Line Linia przerywana Panel menu Menu panelu Unembed… Wyodrębnij… diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..0429e8a9b8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2709,6 +2709,8 @@ digits Malayalam Malaiala Search Commands… Pesquisar Comandos… Search commands and tools Pesquisar comandos e ferramentas Search commands and tools… Pesquisar comandos e ferramentas… + Recent Commands Comandos recentes + No recent commands Nenhum comando recente Secondary Secundária Section Symbol Símbolo de Seção Select Selecionar diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..85b2c27e45 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3281,6 +3281,8 @@ digits Malayalam Малаялам @msg `{key}` must be an array of these names: {_1} `{key}` должно быть массивом из этих имён: {_1} Search commands and tools Поиск команд и инструментов Search commands and tools… Поиск команд и инструментов… + Recent Commands Недавние команды + No recent commands Нет недавних команд Search Commands… Поиск команд… Secondary Вторичный Section Symbol Символ параграфа diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..5b8d6a9599 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3171,6 +3171,8 @@ digits Malayalam Malayalam Search All Sök i alla Search commands and tools Sök kommandon och verktyg Search commands and tools… Sök kommandon och verktyg… + Recent Commands Senaste kommandon + No recent commands Inga senaste kommandon Search Commands… Sök kommandon… Secondary Sekundär Section Symbol Paragraftecken diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..a7b4ba34a7 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3042,6 +3042,8 @@ digits Malayalam Malayalam @msg `{key}` must be an array of these names: {_1} `{key}` şu adlardan oluşan bir dizi olmalıdır: {_1} Search commands and tools Komutları ve araçları arayın Search commands and tools… Komutları ve araçları arayın… + Recent Commands Son komutlar + No recent commands Son komut yok Search Commands… Arama Komutları… Secondary İkincil Section Symbol Bölüm Sembolü diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..87f67c5fee 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3284,6 +3284,8 @@ digits Malayalam Малаялам @msg `{key}` must be an array of these names: {_1} `{key}` має бути масивом цих назв: {_1} Search commands and tools Пошук команд та інструментів Search commands and tools… Пошук команд та інструментів… + Recent Commands Нещодавні команди + No recent commands Немає нещодавніх команд Search Commands… Пошук команд… Secondary Вторинний Section Symbol Символ параграфа diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..f45da3a4e2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3623,6 +3623,8 @@ mark-style Japanese Kiểu Nhật @msg `{key}` must be an array of these names: {_1} `{key}` phải là một mảng gồm các tên sau: {_1} Search commands and tools Tìm kiếm lệnh và công cụ Search commands and tools… Tìm kiếm lệnh và công cụ… + Recent Commands Lệnh gần đây + No recent commands Không có lệnh gần đây Search Commands… Tìm kiếm lệnh… Search Fonts Folder Tìm kiếm thư mục phông chữ Searching… Đang tìm kiếm… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..6b1ceffb87 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3111,6 +3111,8 @@ digits Malayalam 马拉雅拉姆数字 Filter Layers Panel Rows 筛选图层面板行 Search commands and tools 搜索命令和工具 Search commands and tools… 搜索命令和工具… + Recent Commands 最近使用的命令 + No recent commands 没有最近使用的命令 Search Commands… 搜索命令… Secondary 次要 Section Symbol 章节符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..cf2995c068 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4368,6 +4368,8 @@ digits Malayalam 馬來亞拉姆數字 Filter Layers Panel Rows 篩選圖層面板列 Search commands and tools 搜尋指令與工具 Search commands and tools… 搜尋指令與工具… + Recent Commands 最近使用的指令 + No recent commands 沒有最近使用的指令 Search Commands… 搜尋指令… Secondary 次要 Section Symbol 章節符號 diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 3e7fb53316..52eeed236e 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -136,6 +136,45 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } +/// How many picks the Recent Commands list beside the search field holds. +pub(crate) const MAX_RECENT_COMMANDS: usize = 5; + +/// How many ids the saved Recent Commands list holds at most, unavailable ones included. +const MAX_SAVED_RECENT_COMMANDS: usize = 4 * MAX_RECENT_COMMANDS; + +/// Puts `id` first in the Recent Commands ids `list`, removing its earlier place, and keeps the +/// newest [`MAX_RECENT_COMMANDS`] ids that are `known`. An id that is not `known` now (a plug-in +/// that is disabled or not loaded yet) keeps its place among them, so it shows again when its +/// command comes back. The list never holds more than [`MAX_SAVED_RECENT_COMMANDS`] ids. +fn remember(list: &mut Vec, id: &str, known: impl Fn(&str) -> bool) { + list.retain(|c| c != id); + list.insert(0, id.to_string()); + let mut kept = 0; + let end = list.iter().position(|c| { + if known(c) { + kept += 1; + } + kept > MAX_RECENT_COMMANDS + }); + list.truncate(end.unwrap_or(list.len()).min(MAX_SAVED_RECENT_COMMANDS)); +} + +/// The entries the Recent Commands list shows for the ids `ids`, most recent first. An id with no +/// entry (a removed plug-in) is skipped. +fn recent<'a>(entries: &'a [Entry], ids: &[String]) -> Vec<&'a Entry> { + ids.iter().take(MAX_SAVED_RECENT_COMMANDS).filter_map(|id| entries.iter().find(|e| e.id == *id)).take(MAX_RECENT_COMMANDS).collect() +} + +/// The id of the Recent Commands list's popup. +fn recent_list_id() -> egui::Id { + egui::Id::unique("palette-recent-commands") +} + +/// Is the palette's Recent Commands list open? +pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool { + egui::Popup::is_id_open(ctx, recent_list_id()) +} + pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if !app.ui.palette_open { return; @@ -145,6 +184,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let q = app.ui.palette_query.to_lowercase(); let entries = entries(ctx, crate::i18n::current()); let matches: Vec<&Entry> = entries.iter().filter(|e| q.split_whitespace().all(|w| e.haystack.contains(w))).take(14).collect(); + let recent = recent(&entries, &app.ui.recent_commands); + // While the Recent Commands list is open, the arrow keys and Enter go to its rows, and the + // search field leaves them the keyboard. + let list_open = recent_list_open(ctx); let mut run: Option = None; // The highlighted result (#1757): Up and Down move it (wrapping), the pointer over a result // takes it, and a new query starts again from the first. @@ -153,8 +196,24 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if last_q != q { sel = 0; } + // The Recent Commands row with the keyboard: Up and Down move it, wrapping at the ends, so the + // keys never leave the list for the results below it. + let rsel_id = egui::Id::unique("palette-recent-selected"); + let mut rsel = if list_open { ctx.data(|d| d.get_temp::(rsel_id)).unwrap_or(0) } else { 0 }; + if list_open && !recent.is_empty() { + let rn = recent.len(); + let (down, up) = + ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown), i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp))); + if down { + rsel = (rsel + 1) % rn; + } + if up { + rsel = (rsel + rn - 1) % rn; + } + rsel = rsel.min(rn - 1); + } let n = matches.len(); - if n > 0 { + if n > 0 && !list_open { let (down, up) = ctx.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowDown), i.consume_key(egui::Modifiers::NONE, egui::Key::ArrowUp))); if down { @@ -168,13 +227,35 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { egui::Area::new(egui::Id::unique("palette")).order(egui::Order::Foreground).anchor(egui::Align2::CENTER_TOP, [0.0, 90.0]).show(ctx, |ui| { egui::Frame::popup(ui.style()).fill(t.panel).inner_margin(egui::Margin::same(10)).show(ui, |ui| { ui.set_width(520.0); - let r = ui.add( - egui::TextEdit::singleline(&mut app.ui.palette_query) - .align(egui::Align2::LEFT_CENTER) - .hint_text(tl!("Search commands and tools…")) - .desired_width(500.0), - ); - r.request_focus(); + ui.horizontal(|ui| { + let r = ui.add( + egui::TextEdit::singleline(&mut app.ui.palette_query) + .align(egui::Align2::LEFT_CENTER) + .hint_text(tl!("Search commands and tools…")) + .desired_width(470.0), + ); + if !list_open { + r.request_focus(); + } + // Recent Commands: the last picks, most recent first. A choice runs as a pick of + // the same result does. The first row takes the keyboard when the list opens, and + // the row with the keyboard keeps it while the list is open. + let button = crate::widgets::icon_button(ui, "history", tl!("Recent Commands"), false, 24.0); + egui::Popup::menu(&button).id(recent_list_id()).show(|ui| { + if recent.is_empty() { + ui.add_enabled(false, egui::Button::new(tl!("No recent commands"))); + } + for (i, e) in recent.iter().enumerate() { + let row = ui.add(egui::Button::new(e.shown.as_str()).shortcut_text(menus::shown_shortcut(&e.shortcut))); + if i == rsel { + row.request_focus(); + } + if row.clicked() { + run = Some(e.id.clone()); + } + } + }); + }); ui.add_space(6.0); for (i, e) in matches.iter().enumerate() { let resp = ui.add( @@ -190,16 +271,21 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { run = Some(e.id.clone()); } } - if ui.input(|i| i.key_pressed(egui::Key::Enter)) + if !list_open + && ui.input(|i| i.key_pressed(egui::Key::Enter)) && let Some(e) = matches.get(sel) { run = Some(e.id.clone()); } }); }); - ctx.data_mut(|d| d.insert_temp(sel_id, (sel, q))); + ctx.data_mut(|d| { + d.insert_temp(sel_id, (sel, q)); + d.insert_temp(rsel_id, rsel); + }); if let Some(id) = run { app.ui.palette_open = false; + remember(&mut app.ui.recent_commands, &id, |c| entries.iter().any(|e| e.id == c)); run_pick(app, &id); } } @@ -512,6 +598,228 @@ mod tests { } } + /// #6376: a pick goes first in Recent Commands, and a pick of a command already listed moves it + /// to the top, so each command takes one place. The list is saved with the UI state. + #[test] + fn recent_commands_put_the_latest_pick_first_and_list_each_command_once() { + let mut list = vec![]; + for id in ["object.group", "paint.swap", "object.group"] { + remember(&mut list, id, |_| true); + } + assert_eq!(list, ["object.group", "paint.swap"]); + // A pick with Enter in the open palette is remembered. + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui.recent_commands = list; + app.ui.palette_open = true; + app.ui.palette_query = "paint.swap".into(); + let first = build(crate::i18n::current()).into_iter().find(|e| e.haystack.contains("paint.swap")).unwrap().id; + let ctx = egui::Context::default(); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + ctx.run_ui(egui::RawInput { events: vec![enter], ..Default::default() }, |ui| show(&mut app, ui.ctx())).textures_delta.clear(); + assert!(!app.ui.palette_open); + assert_eq!(app.ui.recent_commands.first(), Some(&first)); + assert_eq!(app.ui.recent_commands.iter().filter(|c| **c == first).count(), 1, "{:?}", app.ui.recent_commands); + let restored: crate::state::UiState = serde_json::from_str(&serde_json::to_string(&app.ui).unwrap()).unwrap(); + assert_eq!(restored.recent_commands, app.ui.recent_commands); + } + + /// #6376: Recent Commands keeps the last five picks. + #[test] + fn recent_commands_keep_the_last_five_picks() { + let mut list = vec![]; + let ids = ["a", "b", "c", "d", "e", "f", "g"]; + for id in ids { + remember(&mut list, id, |_| true); + } + assert_eq!(list, ["g", "f", "e", "d", "c"]); + let entries = build(Lang::EN); + let many: Vec = entries.iter().take(MAX_RECENT_COMMANDS + 2).map(|e| e.id.clone()).collect(); + assert_eq!(recent(&entries, &many).len(), MAX_RECENT_COMMANDS); + } + + /// #6376: a command that does not exist now, such as a plug-in's filter while the plug-in is + /// not loaded, is left out of Recent Commands. A pick keeps it in the saved list, so it shows + /// again when the command comes back; five other commands picked after it push it out. + #[test] + fn recent_commands_skip_ids_that_no_longer_exist() { + let entries = build(Lang::EN); + let known = |c: &str| entries.iter().any(|e| e.id == c); + let saved: Vec = ["plugin:test.UI.palette_removed", "object.group", "tool:no-such-tool"].map(str::to_string).into(); + let shown: Vec<&str> = recent(&entries, &saved).iter().map(|e| e.id.as_str()).collect(); + assert_eq!(shown, ["object.group"]); + let mut list = saved; + remember(&mut list, "paint.swap", known); + assert_eq!(list, ["paint.swap", "plugin:test.UI.palette_removed", "object.group", "tool:no-such-tool"]); + let four: Vec = entries.iter().filter(|e| e.id != "paint.swap" && e.id != "object.group").take(4).map(|e| e.id.clone()).collect(); + for id in &four { + remember(&mut list, id, known); + } + let expected: Vec = + four.iter().rev().cloned().chain(["paint.swap".to_string(), "plugin:test.UI.palette_removed".to_string()]).collect(); + assert_eq!(list, expected, "object.group, the sixth known id, and the ids after it go"); + // Unavailable ids are capped too. + let mut list: Vec = (0..50).map(|i| format!("plugin:test.UI.gone{i}")).collect(); + remember(&mut list, "paint.swap", known); + assert_eq!(list.len(), MAX_SAVED_RECENT_COMMANDS); + assert_eq!(list.first().map(String::as_str), Some("paint.swap")); + } + + /// The open palette drawn over `app`, after the frame's keys go to the shortcuts as in the app, + /// with a query no result matches, so the only command buttons are the Recent Commands list's. + fn palette_harness(mut app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> { + app.ui.palette_open = true; + app.ui.palette_query = "zzqqxxjj".into(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 700.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::shortcuts::handle(app, ui.ctx()); + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(3); + h + } + + /// #6376: the open Recent Commands list has the keyboard: its first row takes it, Down moves to + /// the next row and Enter runs that row, not the highlighted search result. + #[test] + fn the_keyboard_moves_through_recent_commands_and_enter_runs_a_row() { + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.ui.recent_commands = vec!["object.group".into(), "paint.swap".into()]; + let mut h = palette_harness(app); + h.state_mut().ui.palette_query = "zoom".into(); + h.run_steps(1); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + h.key_press(egui::Key::ArrowDown); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(!h.state().ui.palette_open, "the palette closes"); + assert_eq!(h.state().ui.recent_commands, ["paint.swap", "object.group"]); + } + + /// #6376: Down on the last Recent Commands row wraps to the first row, and Up on the first + /// wraps to the last, so the keys never reach the search results below the list. + #[test] + fn the_keys_wrap_within_recent_commands() { + use egui_kittest::kittest::Queryable; + // (keys pressed after the list opens, the command Enter then runs) + let cases = [(vec![egui::Key::ArrowDown, egui::Key::ArrowDown], "object.group"), (vec![egui::Key::ArrowUp], "paint.swap")]; + for (keys, ran) in cases { + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.ui.recent_commands = vec!["object.group".into(), "paint.swap".into()]; + let mut h = palette_harness(app); + h.state_mut().ui.palette_query = "zoom".into(); + h.run_steps(1); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + for key in &keys { + h.key_press(*key); + h.run_steps(2); + } + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert!(!h.state().ui.palette_open, "{keys:?}: the palette closes"); + assert_eq!(h.state().ui.recent_commands.first().map(String::as_str), Some(ran), "{keys:?}: {:?}", h.state().ui.recent_commands); + assert_eq!(h.state().ui.recent_commands.len(), 2, "{keys:?}: no search result ran"); + } + } + + /// #6376: another open popup leaves the palette's keys alone: Enter still runs the highlighted + /// result. Only the Recent Commands list takes them. + #[test] + fn another_popup_leaves_enter_to_the_palette() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui.palette_open = true; + app.ui.palette_query = "paint.swap".into(); + let first = build(crate::i18n::current()).into_iter().find(|e| e.haystack.contains("paint.swap")).unwrap().id; + let ctx = egui::Context::default(); + let other = egui::Id::unique("another popup"); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + for events in [vec![], vec![enter]] { + ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + egui::Popup::open_id(ui.ctx(), other); + show(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + } + assert!(egui::Popup::is_id_open(&ctx, other) && !recent_list_open(&ctx)); + assert!(!app.ui.palette_open, "Enter runs the highlighted result"); + assert_eq!(app.ui.recent_commands, [first]); + } + + /// #6376: Escape with the Recent Commands list open closes the list and leaves the palette + /// open; the next Escape closes the palette. + #[test] + fn escape_closes_recent_commands_before_the_palette() { + use egui_kittest::kittest::Queryable; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.ui.recent_commands = vec!["object.group".into()]; + let mut h = palette_harness(app); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + let shown = build(crate::i18n::current()).into_iter().find(|e| e.id == "object.group").unwrap().shown; + let row = |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.query_by(|n| n.label().is_some_and(|l| l.starts_with(&shown))).is_some(); + assert!(row(&h), "the list is open"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(!row(&h), "the list closes"); + assert!(h.state().ui.palette_open, "the palette stays open"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(!h.state().ui.palette_open, "the next Escape closes the palette"); + } + + /// #6376: a choice in Recent Commands closes the palette and runs what a pick of the same + /// result runs (here Clean Up… opens its dialog), and moves the command to the top. + #[test] + fn a_recent_command_runs_what_its_pick_runs() { + use egui_kittest::kittest::Queryable; + let id = "object.path.cleanUp"; + let session = || vectorcraft_testkit::fixtures::Fixture::Single.session(); + let mut picked = VectorcraftApp::new(session(), crate::Services::default()); + picked.ui.status.clear(); + run_pick(&mut picked, id); + assert!(picked.ui.dialog.is_some(), "{}", picked.ui.status); + + let mut app = VectorcraftApp::new(session(), crate::Services::default()); + app.ui.status.clear(); + app.ui.recent_commands = vec!["object.group".into(), id.into()]; + // A result's button is named by its label and its shortcut. + let e = build(crate::i18n::current()).into_iter().find(|e| e.id == id).unwrap(); + let name = format!("{} {}", e.shown, menus::shown_shortcut(&e.shortcut)); + let mut h = palette_harness(app); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + h.get_by_label(&name).click(); + h.run_steps(2); + let app = h.state(); + assert!(!app.ui.palette_open, "the palette closes"); + assert_eq!(outcome(app), outcome(&picked)); + assert_eq!(app.ui.recent_commands, [id, "object.group"]); + } + + /// #6376: with nothing picked yet, Recent Commands shows a dimmed No recent commands row. + #[test] + fn recent_commands_without_picks_show_a_dimmed_row() { + use egui_kittest::kittest::{NodeT, Queryable}; + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut h = palette_harness(app); + assert!(h.query_by_label(tl!("No recent commands")).is_none(), "the list opens on a click"); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + assert!(h.get_by_label(tl!("No recent commands")).accesskit_node().is_disabled()); + assert!(h.state().ui.palette_open); + } + /// #1757: Up and Down move the highlighted result, wrapping at the ends; a new query starts /// from the first again. #[test] diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index d102c40d7e..6329f489b1 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -223,9 +223,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { if crate::shortcut_editor::is_recording(app) { return; } - // Escape closes a dropdown list or popover open in the dialog (each closes itself on it) and - // leaves the dialog open. - let popup = app.ui.dialog.as_ref().is_some_and(|d| { + // Escape closes a dropdown list or popover open in the dialog, or the palette's Recent + // Commands list (each closes itself on it), and leaves the dialog or the palette open. + let popup = app.ui.dialog.as_ref().map_or(crate::palette::recent_list_open(ctx), |d| { egui::Popup::is_any_open(ctx) || crate::dialogs::brush_options::tips_open(d) || crate::dialogs::new_document_popup_open(d) diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 26d3753b51..9f2ecc113d 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -691,6 +691,9 @@ pub struct UiState { /// Type → Recent Fonts, most recent first. #[serde(default)] pub recent_fonts: Vec, + /// Help › Search Commands' Recent Commands list: the ids of the last picks, most recent first. + #[serde(default)] + pub recent_commands: Vec, /// Families starred in the font menus (the ★ filter shows only these). #[serde(default)] pub favorite_fonts: Vec, @@ -1227,6 +1230,7 @@ impl Default for UiState { workspace_changes: vec![], recent_files: vec![], recent_fonts: vec![], + recent_commands: vec![], favorite_fonts: vec![], engine_prefs: Value::Null, color_guide: Default::default(), diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eed107bf24..a36da05b0d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -986,6 +986,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). + - A Recent Commands button beside the Help › Search Commands field lists the last five commands and tools picked from the palette, most recent first, with a command picked again moved to the top. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`). - The Learn panel (Window › Learn, or Explore tutorials beside the search icon on the app bar) has a For you tab with a Get started section and a Quick skill guide card, and a Skills tab that lists VectorCraft's own skills with their progress rings and counts of tutorials finished; a skill lists its tutorials, a tutorial shows its numbered steps, and Back goes up a level; `learn.list`, `learn.tab {tab}`, `learn.skill {skill}`, `learn.show {tutorial}` and `learn.back` script it, and the tab buttons, the rows and Back run them ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`). - A tool's name in a Learn tutorial step is a blue link that shows where the tool is without choosing it (`learn.locateTool {tool}`): its toolbar button is marked, a collapsed group's flyout opens with the tool's row marked, a torn-off strip comes to the front, and a tool no shown toolbar holds is marked in the All Tools drawer. The mark, its 3 seconds and the hidden-toolbar cases are VectorCraft's own rules ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`, the `a_learn_link_*` tests in `toolbar::tests`). - Under a tutorial's steps, View more opens the tutorial's own practice sample as a new untitled document, and once the tutorial is finished, Next Up moves to the next tutorial in the same skill, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). The samples are VectorCraft's own drawings. A Finish tutorial button that shows once the sample is open, the untitled copy, Back to skills in place of Next Up after a skill's last tutorial, and Next Up showing the next tutorial without opening its sample are VectorCraft's own rules. `learn.openSample`, `learn.finish`, `learn.next` and `learn.skills` (Back to skills) script them. Not done: the help page's short video. Regression tests: `view_more_opens_the_tutorial_s_sample_as_a_new_untitled_document`, `finishing_a_tutorial_offers_next_up_in_its_skill`, `the_practice_controls_work_from_the_keyboard`, `the_last_tutorial_of_a_skill_offers_back_to_skills`, `learn_finish_and_learn_next_follow_the_practice`, `learn_skills_shows_the_list_of_skills`, `the_practice_commands_reject_a_missing_or_unknown_tutorial`, `every_tutorial_has_its_own_readable_sample` and `the_next_tutorial_is_the_next_one_in_the_same_skill` in `crates/ui-egui/src/panels/learn/tests.rs`. From fcaed952fb9825420cbc99d6b7848f47e4092cef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:50:38 -0800 Subject: [PATCH 35/77] Paragraph: Kurikaeshi Moji Shori draws a threaded type-on-path frame's first repeat mark A frame of type on a path whose first paragraph continues from the frame before now draws a repeat mark at its start as the character before it in the frames before, as area and point type do. The mark keeps its advance, so the glyphs stay where they were, and live SVG text writes the character drawn. --- crates/text/src/layout/flow.rs | 24 +++++++++++++----------- crates/text/src/layout/on_path.rs | 22 +++++++++++++++++++++- crates/text/src/tests.rs | 18 ++++++++++++++++++ 3 files changed, 52 insertions(+), 12 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 3999401a05..50f0cef433 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -1298,18 +1298,17 @@ fn emit_line_glyph( } /// Kurikaeshi Moji Shori (Paragraph panel menu): the glyph drawn in place of `g`, the first glyph of -/// a line of `paragraph`, when `g` is a repeat mark, and the character it shows: the character -/// [`repeated_char`] gives, shaped in the mark's style with the type's features (so vertical type -/// gets the font's vertical forms), from the same face, with the mark's advance and place, so the -/// line breaks stay as they are. None when `g` is no repeat mark, belongs to a tate-chu-yoko or -/// warichu block, nothing before it in the paragraph fits, or the face draws the character with no -/// glyph or with more than one. The paragraph's `lead` stands before a paragraph that continues -/// from the frame before ([`TextObject::first_para_lead`]). -fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph) -> Option<(SGlyph, char)> { +/// a line, when `g` is a repeat mark, and the character it shows: the character [`repeated_char`] +/// gives for the character `base` finds before the mark, shaped in the mark's style with the type's +/// features (so vertical type gets the font's vertical forms), from the same face, with the mark's +/// advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, belongs +/// to a tate-chu-yoko or warichu block, `base` gives None, nothing before it fits, or the face draws +/// the character with no glyph or with more than one. `base` runs only for a repeat mark. +pub(super) fn repeat_mark_glyph(cx: &Ctx<'_>, g: &SGlyph, base: impl FnOnce() -> Option>) -> Option<(SGlyph, char)> { if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(paragraph.repeat_base_before(cx.text, g.byte)?, "", g.ch)?; + let c = repeated_char(base()?, "", g.ch)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1320,13 +1319,16 @@ fn repeat_mark_glyph(cx: &Ctx<'_>, paragraph: &ParagraphData<'_, '_>, g: &SGlyph /// Kurikaeshi Moji Shori: the glyph drawn in place of glyph `first` of `paragraph`, the first /// character of a line that ends before glyph `end`, when the paragraph has the setting on and -/// [`repeat_mark_glyph`] gives one; it is recorded in [`crate::TextLayout::repeat_marks`]. +/// [`repeat_mark_glyph`] gives one for the character before it in the paragraph, or the paragraph's +/// `lead` before a paragraph that continues from the frame before ([`TextObject::first_para_lead`]); +/// it is recorded in [`crate::TextLayout::repeat_marks`]. fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: usize, end: usize) -> Option { if !paragraph.para.kurikaeshi_moji_shori || first >= end { return None; } let g = paragraph.sg.get(first)?; - let (glyph, c) = repeat_mark_glyph(cx, paragraph, g)?; + let text = cx.text; + let (glyph, c) = repeat_mark_glyph(cx, g, || paragraph.repeat_base_before(text, g.byte))?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index ecb1377d10..80aaa5ea9a 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -1,6 +1,6 @@ use super::bidi::{is_rtl, para_bidi_with, visual_order}; use super::breaking::{Metrics, optical_hangs, optical_hangs_rtl, optical_share, roman_share}; -use super::flow::list_markers; +use super::flow::{list_markers, repeat_mark_glyph}; use super::region::in_range; use super::{ Affine, ArcPath, BezPath, Ctx, GlyphBend, Justify, LineInfo, ListMarker, ParamCurve, PathAlign, PathData, PathEffect, PathEl, Point, Range, @@ -409,6 +409,21 @@ fn hide_before_open_path(cx: &mut Ctx<'_>, ap: &ArcPath, lead: bool, at: usize, true } +/// Kurikaeshi Moji Shori: type on a path is one line, which starts with the first character of its +/// first paragraph `pr` (shaped as `glyphs`). When that paragraph continues from the frame before +/// and has the setting on, a repeat mark there is drawn as the character before it in the frames +/// before ([`TextObject::first_para_lead`]): its glyph in `glyphs` is replaced, and the mark's byte +/// and the character drawn are returned. +fn line_start_repeat(cx: &Ctx<'_>, t: &TextObject, pr: &Range, glyphs: &mut [SGlyph]) -> Option<(usize, char)> { + if !t.first_para_continues || !t.para_at(0).kurikaeshi_moji_shori { + return None; + } + let g = glyphs.iter_mut().find(|g| g.len > 0 && g.byte == pr.start)?; + let (glyph, c) = repeat_mark_glyph(cx, g, || Some(t.first_para_lead))?; + *g = glyph; + Some((g.byte, c)) +} + /// Lay type on a path out along `path` (text space), between its brackets. pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, path: &PathData) { cx.out.on_path = true; @@ -431,6 +446,8 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, } shaped.push((pr.clone(), bidi.filter(|b| b.has_rtl() && !cx.vertical), glyphs)); } + // Kurikaeshi Moji Shori: the repeat mark that starts the line, recorded when its glyph is drawn. + let mut repeat = shaped.first_mut().and_then(|(pr, _, glyphs)| line_start_repeat(cx, t, pr, glyphs)); let rtl = rtl.unwrap_or(false); // The text before byte `cut` in visual order, as area type reorders each line it breaks. let visual = |cut: usize| { @@ -710,6 +727,9 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, let at = cx.out.glyphs.len(); cx.emit(g, pre, origin, angle, g.adv, 0); let hidden = hide_before_open_path(cx, &ap, lead, at, s + step * 0.5, rise); + if !hidden && let Some(mark) = repeat.take_if(|&mut (byte, _)| g.len > 0 && g.byte == byte) { + cx.out.repeat_marks.push(mark); + } // A glyph of a script whose letters join is bent along a curved path (Rainbow), so its // joining strokes meet its neighbours' instead of standing off the curve. if !hidden && t.path_effect == PathEffect::Rainbow && g.cursive && !cx.vertical && g.inline.is_none() { diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index d2940f83b5..147b6a4818 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2808,6 +2808,24 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { let on = layout(&db, &t); assert_eq!(gid_of(&on, 0), glyph('時'), "the frame's first 々 is drawn as 時"); assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "the next paragraph's first mark keeps its glyph"); + assert_eq!(on.repeat_marks, [(0, '時')]); + // Type on a path is one line: a threaded frame on a path starts it the same way. + let mut line = BezPath::new(); + line.move_to((0.0, 50.0)); + line.line_to((500.0, 50.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + let on = layout(&db, &t); + assert!(on.on_path); + assert_eq!(gid_of(&on, 0), glyph('時'), "type on a path: the frame's first 々 is drawn as 時"); + assert_eq!(gid_of(&on, "々す\n".len()), glyph('々'), "type on a path: the next paragraph's first mark keeps its glyph"); + assert_eq!(on.repeat_marks, [(0, '時')]); + t.para.kurikaeshi_moji_shori = false; + let off = layout(&db, &t); + assert_eq!(gid_of(&off, 0), glyph('々'), "type on a path with the setting off"); + assert!(off.repeat_marks.is_empty()); + t.para.kurikaeshi_moji_shori = true; + t.first_para_continues = false; + assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "type on a path in a frame that does not continue"); } /// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid From 7d7c5918f3966364c21e29953138929686e9ee69 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:52:57 -0800 Subject: [PATCH 36/77] MCP docs: Kurikaeshi Moji Shori covers the first repeat mark of a frame of type on a path --- docs/mcp.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index b0bdf2972e..0769d0a97e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9455,8 +9455,8 @@ https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html `text.setFormat {kurikaeshiMojiShori: bool}` (Paragraph panel menu › Kurikaeshi Moji Shori, shown with the East Asian options) turns it on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a `start` / `end` -range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, is drawn as the -character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, +range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, or starts a frame +of type on a path (which holds one line), is drawn as the character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the @@ -9464,7 +9464,7 @@ repeated character is the last one before the mark in the paragraph that is not combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a -paragraph, inside tate-chu-yoko or warichu, and on type on a path. Off by default. It is saved with the paragraph +paragraph, and inside tate-chu-yoko or warichu. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the setting as it is, and a call that gives the value the paragraphs already have records no undo step. One undo step. `.ai` editing data does not hold it, and a From 3ca38f2237e73d24a87fbe7e13d3c6e12374df0c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:01:43 -0800 Subject: [PATCH 37/77] =?UTF-8?q?Paragraph:=20Kurikaeshi=20Moji=20Shori=20?= =?UTF-8?q?draws=20=E3=82=9D=20or=20=E3=83=BD=20with=20a=20combining=20voi?= =?UTF-8?q?cing=20mark=20as=20voiced?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ゝ or ヽ followed by U+3099, which a font draws as one glyph, is now drawn at a line start as ゞ or ヾ would be, instead of as the plain kana. A mark that shares its cluster with other glyphs, or with any other combining character, keeps its own glyphs. --- crates/text/src/layout/flow.rs | 28 ++++++++++++++++++++++------ crates/text/src/layout/on_path.rs | 5 +++-- crates/text/src/tests.rs | 23 +++++++++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 50 insertions(+), 9 deletions(-) diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 50f0cef433..36881e20d8 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -1301,14 +1301,30 @@ fn emit_line_glyph( /// a line, when `g` is a repeat mark, and the character it shows: the character [`repeated_char`] /// gives for the character `base` finds before the mark, shaped in the mark's style with the type's /// features (so vertical type gets the font's vertical forms), from the same face, with the mark's -/// advance and place, so the line breaks stay as they are. None when `g` is no repeat mark, belongs -/// to a tate-chu-yoko or warichu block, `base` gives None, nothing before it fits, or the face draws -/// the character with no glyph or with more than one. `base` runs only for a repeat mark. -pub(super) fn repeat_mark_glyph(cx: &Ctx<'_>, g: &SGlyph, base: impl FnOnce() -> Option>) -> Option<(SGlyph, char)> { +/// advance and place, so the line breaks stay as they are. ゝ or ヽ followed by a combining voicing +/// mark (U+3099) in one glyph counts as ゞ or ヾ. None when `g` is no repeat mark, belongs to a +/// tate-chu-yoko or warichu block, holds other characters with the mark, shares its cluster with the +/// glyph after it (`next`), `base` gives None, nothing before it fits, or the face draws the +/// character with no glyph or with more than one. `base` runs only for a repeat mark. +pub(super) fn repeat_mark_glyph( + cx: &Ctx<'_>, + g: &SGlyph, + next: Option<&SGlyph>, + base: impl FnOnce() -> Option>, +) -> Option<(SGlyph, char)> { if g.tcy.is_some() || g.wari.is_some() || g.inline.is_some() || !matches!(g.ch, '々' | 'ゝ' | 'ゞ' | 'ヽ' | 'ヾ') { return None; } - let c = repeated_char(base()?, "", g.ch)?; + if next.is_some_and(|n| n.byte == g.byte) { + return None; + } + let mark = match cx.text.get(g.byte..g.byte + g.len)? { + "ゝ\u{3099}" => 'ゞ', + "ヽ\u{3099}" => 'ヾ', + cluster if cluster.len() == g.ch.len_utf8() => g.ch, + _ => return None, + }; + let c = repeated_char(base()?, "", mark)?; let mut buf = [0; 4]; let s: &str = c.encode_utf8(&mut buf); let mut shaped = Vec::with_capacity(1); @@ -1328,7 +1344,7 @@ fn line_start_repeat(cx: &mut Ctx<'_>, paragraph: &ParagraphData<'_, '_>, first: } let g = paragraph.sg.get(first)?; let text = cx.text; - let (glyph, c) = repeat_mark_glyph(cx, g, || paragraph.repeat_base_before(text, g.byte))?; + let (glyph, c) = repeat_mark_glyph(cx, g, paragraph.sg.get(first + 1), || paragraph.repeat_base_before(text, g.byte))?; cx.out.repeat_marks.push((g.byte, c)); Some(glyph) } diff --git a/crates/text/src/layout/on_path.rs b/crates/text/src/layout/on_path.rs index 80aaa5ea9a..b69470b9d9 100644 --- a/crates/text/src/layout/on_path.rs +++ b/crates/text/src/layout/on_path.rs @@ -418,8 +418,9 @@ fn line_start_repeat(cx: &Ctx<'_>, t: &TextObject, pr: &Range, glyphs: &m if !t.first_para_continues || !t.para_at(0).kurikaeshi_moji_shori { return None; } - let g = glyphs.iter_mut().find(|g| g.len > 0 && g.byte == pr.start)?; - let (glyph, c) = repeat_mark_glyph(cx, g, || Some(t.first_para_lead))?; + let at = glyphs.iter().position(|g| g.len > 0 && g.byte == pr.start)?; + let (glyph, c) = repeat_mark_glyph(cx, glyphs.get(at)?, glyphs.get(at + 1), || Some(t.first_para_lead))?; + let g = glyphs.get_mut(at)?; *g = glyph; Some((g.byte, c)) } diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 147b6a4818..c04200a94f 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -2828,6 +2828,29 @@ fn kurikaeshi_moji_shori_draws_the_repeated_character_at_a_line_start() { assert_eq!(gid_of(&layout(&db, &t), 0), glyph('々'), "type on a path in a frame that does not continue"); } +/// Kurikaeshi Moji Shori: ゝ or ヽ typed with a combining voicing mark (U+3099) after it, which the +/// font draws as one glyph, is drawn as the voiced character at a line start, as ゞ and ヾ are. +#[test] +fn kurikaeshi_moji_shori_draws_a_decomposed_voiced_mark_voiced() { + use crate::test_fonts::{REPEAT_MARK_FAMILY, repeat_mark_font}; + let db = FontDb::with_font_dirs(vec![]); + db.add_font(repeat_mark_font().expect("test font")); + let st = CharStyle { size: 20.0, font_family: REPEAT_MARK_FAMILY.into(), font_style: "Regular".into(), ..CharStyle::default() }; + let face = db.style_face(&st).expect("face"); + let glyph = |c: char| Some(face.glyph_for(c)); + let gid_of = |l: &TextLayout, b: usize| l.glyphs.iter().find(|g| g.byte == b).map(|g| g.gid); + for (text, mark, want) in [("す\u{2028}ゝ\u{3099}", 'ゞ', 'ず'), ("サ\u{2028}ヽ\u{3099}", 'ヾ', 'ザ')] { + let at = text.find(['ゝ', 'ヽ']).expect("mark"); + let mut t = TextObject::point(Point::ZERO, text, st.clone()); + let off = layout(&db, &t); + assert_eq!(gid_of(&off, at), glyph(mark), "{text:?}: off, the font draws the voiced mark"); + t.para.kurikaeshi_moji_shori = true; + let on = layout(&db, &t); + assert_eq!(gid_of(&on, at), glyph(want), "{text:?}"); + assert_eq!(on.repeat_marks, [(at, want)], "{text:?}"); + } +} + /// Kurikaeshi Moji Shori: a paragraph with a repeat mark at the start of each of many lines is laid /// out in one scan of its text, not one scan of everything before each line. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 0769d0a97e..9dadf1c1d2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9463,7 +9463,8 @@ VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph from one frame into the next; ゝ and ヽ draw it without its voicing marks, and ゞ and ヾ draw its voiced form, or the -plain kana when it has none. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a +plain kana when it has none; ゝ or ヽ followed by a combining voicing mark (U+3099) counts as ゞ or ヾ when the font draws the +pair as one glyph, and is drawn as it is when the font draws two. A mark is drawn as it is when nothing before it in the paragraph fits, when the font has no glyph for the character, at the start of a paragraph, and inside tate-chu-yoko or warichu. Off by default. It is saved with the paragraph (`kurikaeshi_moji_shori` in `para`) only when on, paragraph styles carry it (`kurikaeshi_moji_shori` in a paragraph style's attributes), and Reset Panel turns it off. A value that is not true, false or null is refused, `null` leaves the From 9548a669a0e3c89435f4730a07cae2a0a2e3e7ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:17:36 -0800 Subject: [PATCH 38/77] SVG export: type on a path that starts with a drawn repeat mark is outlined Type on a path whose frame starts with a repeat mark drawn as the character it repeats is now written as outlines with a warning, as other type on a path that a cannot reproduce is. With Kurikaeshi Moji Shori off it stays live text. --- crates/svg/src/export/text.rs | 5 +++++ crates/svg/tests/it/text_layout.rs | 31 ++++++++++++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 5a1e811062..907068c56d 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -294,6 +294,11 @@ impl Writer<'_> { self.warn("type on a path with bullets or numbers is outlined to keep its look"); return self.text_outlines(n, t); } + // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). + if !lay.repeat_marks.is_empty() { + self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); + return self.text_outlines(n, t); + } return self.text_on_path(n, t, path, *start); } self.note_fonts(t, &lay); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index a190f21dea..ff27c96955 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -941,3 +941,34 @@ fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { } } } + +/// Kurikaeshi Moji Shori: a `` cannot draw a character in another character's width, so +/// type on a path whose threaded frame starts with a repeat mark drawn as the character it repeats +/// is outlined, with a warning; with the setting off it stays live text. +#[test] +fn a_repeat_mark_starting_a_frame_on_a_path_is_outlined() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), ..style(12.0) }; + let mut line = BezPath::new(); + line.move_to((20.0, 40.0)); + line.line_to((280.0, 40.0)); + for on in [false, true] { + let mut t = TextObject::point(Point::ZERO, "々龘々", st.clone()); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + t.para.kurikaeshi_moji_shori = on; + t.first_para_continues = true; + t.first_para_lead = Some('龘'); + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let out = vectorcraft_svg::export_full(&d, &ExportOptions::default(), None); + let warned = out.warnings.iter().any(|w| w.contains("repeat mark")); + if on { + assert!(!out.svg.contains("々龘々<") && !warned, "{:?}: {}", out.warnings, out.svg); + } + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 9dadf1c1d2..89393a9ae6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9458,7 +9458,8 @@ options) turns it on or off for the paragraphs of the selected type (or `ids`, o range touches). On, a repeat mark that starts a line of point or area type, horizontal or vertical, or starts a frame of type on a path (which holds one line), is drawn as the character it repeats, so both characters show when a line break separates them. The text keeps the mark: copying, searching, the caret and the line breaks stay as they were, and the drawn character takes the mark's place and width. -SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded. +SVG export with live type writes the drawn character, and embeds its glyph when fonts are embedded; it writes type on a +path that starts with such a mark as outlines, with a warning. VectorCraft's set of marks and its rules: 々 repeats a Han ideograph, ゝ and ゞ a hiragana, and ヽ and ヾ a katakana; the repeated character is the last one before the mark in the paragraph that is not a repeat mark, a soft return or a combining voicing mark (U+3099, U+309A), looking back into the frames before when threaded type continues a paragraph From 3607c70efe0f97404f11e13068e3b96482d24202 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:25:04 -0800 Subject: [PATCH 39/77] Glyphs: a cell's corner triangle opens a pop-up of its glyph's alternates A Glyphs panel cell whose glyph has alternates shows a small triangle in its lower right corner. A click on it opens a pop-up of that glyph and its alternates in the font's order. Picking one inserts the character at the Type tool's caret drawn with that glyph, or draws the selected character with it, in one undo step; the cell's own glyph inserts the character as a double-click does. In Entire Font a glyph no character maps has the triangle too, and a pick goes on the selected character as a double-click on that glyph's cell does. A pick is tried on a copy of the document first, so one the character cannot be drawn with (All Caps, for example) changes nothing and the status says why. A Select All over a threaded story is replaced as typing replaces it. The triangle's size and the pop-up's eight columns and six rows are VectorCraft's own. --- crates/text/src/fontdb/gsub.rs | 7 + crates/text/src/tests/alternates.rs | 19 + crates/ui-egui/src/panels/glyphs.rs | 572 +++++++++++++++++++++++++++- docs/type-parity.md | 2 +- 4 files changed, 591 insertions(+), 9 deletions(-) diff --git a/crates/text/src/fontdb/gsub.rs b/crates/text/src/fontdb/gsub.rs index a245efeea2..815eefd569 100644 --- a/crates/text/src/fontdb/gsub.rs +++ b/crates/text/src/fontdb/gsub.rs @@ -344,6 +344,13 @@ impl FontFace { self.gsub_index().by_input.get(&gid).cloned().unwrap_or_default() } + /// Do [`Self::substitutions`] of glyph `gid` give a glyph other than `gid` itself? It reads the + /// face's index without copying the substitutions, so the Glyphs panel asks it for each cell it + /// draws. + pub fn has_alternates(&self, gid: u32) -> bool { + self.gsub_index().by_input.get(&gid).is_some_and(|subs| subs.iter().any(|s| s.glyphs.iter().any(|&g| g != gid))) + } + /// The feature of the `GSUB` table that gives glyph `gid` as a substitute (by a single, /// multiple, alternate or ligature substitution), a listed feature ([`Self::substitutions`]) /// before another (`init`, `liga`), if any does. Not read through a contextual lookup. diff --git a/crates/text/src/tests/alternates.rs b/crates/text/src/tests/alternates.rs index cc70780eb3..48f621555d 100644 --- a/crates/text/src/tests/alternates.rs +++ b/crates/text/src/tests/alternates.rs @@ -40,6 +40,25 @@ fn alternates_come_in_feature_order_once_each() { assert!(bundled.alternates('a').iter().all(|a| a.gid < bundled.glyph_count())); } +/// A glyph has alternates when a listed feature gives it another glyph: `a` has them in both +/// faces, `b` and the alternates of `a` have none, and a glyph past the face has none. +#[test] +fn has_alternates_follows_the_listed_substitutions() { + let db = db(); + let [u1, ..] = unencoded_glyphs().expect("unencoded glyphs"); + for aalt in [true, false] { + let face = db.face(alternates_family(aalt), "Regular").expect("the test face"); + assert!(face.has_alternates(face.glyph_for('a')), "a, aalt {aalt}"); + assert!(!face.has_alternates(face.glyph_for('b')), "b, aalt {aalt}"); + assert!(!face.has_alternates(u1), "an alternate of a has none of its own, aalt {aalt}"); + assert!(!face.has_alternates(face.glyph_count() + 10), "a glyph past the face, aalt {aalt}"); + } + let bundled = db.face(FALLBACK_FAMILY, "Regular").expect("the bundled face"); + let with = bundled.chars().into_iter().filter(|(_, g)| bundled.has_alternates(*g)).count(); + let listed = bundled.chars().into_iter().filter(|(c, g)| bundled.alternates(*c).iter().any(|a| a.gid != *g)).count(); + assert_eq!(with, listed, "the same characters as the alternates lists say"); +} + /// The cap on lookups read in all leaves out the lowest ranked features: `salt` is read even when /// the `cv01` records before it list more lookups than the cap. #[test] diff --git a/crates/ui-egui/src/panels/glyphs.rs b/crates/ui-egui/src/panels/glyphs.rs index cac85259f3..ea26dfec76 100644 --- a/crates/ui-egui/src/panels/glyphs.rs +++ b/crates/ui-egui/src/panels/glyphs.rs @@ -2,6 +2,10 @@ //! outlines; Show › Entire Font adds the glyphs no character maps, by glyph id. Double-click //! inserts the character at the Type tool's caret (or appends it to the selected text objects). //! The character selected with the Type tool is highlighted in the grid. +//! A character whose glyph has alternates has a triangle in its cell's lower right corner, and a +//! click on it opens a pop-up of those alternates ([`alternates_popup`]); picking one inserts the +//! character drawn with it ([`insert_alternate`]). In Entire Font a glyph no character maps has the +//! triangle too, and a pick goes on the selected character as a double-click on its cell does. //! Show › Alternates for Current Selection lists that character's alternate glyphs instead (as it //! stands in its word), and a double-click applies the OpenType feature that draws one to that //! character alone, so the text stays real text that joins its neighbors. A double-click on a @@ -284,6 +288,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let row_h = cell + ui.spacing().item_spacing.y; area = area.vertical_scroll_offset((((i / cols) as f32 + 0.5) * row_h - list_h * 0.5).max(0.0)); } + // A pick in a cell's pop-up of alternates: the character (none for a glyph no character maps), + // the glyph of its cell, the glyph picked. + let mut popup_pick: Option<(Option, u32, u32)> = None; let shown = area.show_rows(ui, cell, rows, |ui, range| { for r in range.clone() { @@ -312,6 +319,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let ink = if matches!(pick, Some(None)) { t.text_disabled } else { t.text_strong }; let tex = glyph_texture(ui.ctx(), &face, gid, px); ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), ink); + // Only the cells drawn ask whether their glyph has alternates. + if face.has_alternates(gid) + && let Some(picked) = corner_popup(ui, &face, c, gid, rect, cell) + { + popup_pick = Some((c, gid, picked)); + } // The tooltip is made when it is shown: working out why a glyph cannot be // applied reads the font, which hundreds of cells cannot do each frame. let resp = resp.on_hover_ui(|ui| { @@ -354,6 +367,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { range }); ui.ctx().data_mut(|d| d.insert_temp(follow_id, (selected, shown.inner))); + match (popup_pick, &fit) { + (Some((Some(c), cell_gid, picked)), _) => insert_alternate(app, ui.ctx(), &face, c, cell_gid, picked), + // A glyph no character maps goes on the selected character as a double-click on its cell + // in Entire Font puts it. + (Some((None, _, picked)), Some(fit)) => match fit.pick(&face, picked) { + Some(pick) => fit.apply(app, pick), + None => app.status(fit.why(&face, picked)), + }, + _ => {} + } ui.add_space(4.0); let info = ui.ctx().data(|d| d.get_temp::<(Option, u32)>(hover_id)); let count = crate::i18n::tn(total as u64, "{n} glyph", "{n} glyphs"); @@ -541,15 +564,34 @@ fn alternates(app: &mut VectorcraftApp, ui: &mut Ui, w: f32) { /// goes through `text.setRangeStyle` on exactly the character (its other alternate features are /// turned off, a glyph choice is taken away); a glyph no feature draws through /// `text.setGlyphAlternate`. The default glyph, or a variant the character already has, changes -/// nothing. -fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), features: &[String], has_choice: bool, pick: Pick) { - let (cmd, params) = match pick { +/// nothing. Whether the command ran or nothing needed to change; a failed command's error goes to +/// the status. +fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), features: &[String], has_choice: bool, pick: Pick) -> bool { + let Some((cmd, params)) = alternate_command(id, bytes, features, has_choice, pick) else { return true }; + match app.run(cmd, params) { + Ok(_) => true, + Err(e) => { + app.status(e.to_string()); + false + } + } +} + +/// The command and parameters [`apply_alternate`] runs; `None` when nothing needs to change. +fn alternate_command( + id: NodeId, + bytes: (usize, usize), + features: &[String], + has_choice: bool, + pick: Pick, +) -> Option<(&'static str, serde_json::Value)> { + Some(match pick { Pick::Glyph(gid) => ("text.setGlyphAlternate", json!({"id": id.0, "start": bytes.0, "gid": gid})), Pick::Default | Pick::Feature(_) => { let tag = if let Pick::Feature(tag) = &pick { Some(tag.as_str()) } else { None }; let changes = vectorcraft_text::alternate_changes(features, tag); if changes.is_empty() && !has_choice { - return; + return None; } let mut params = json!({"id": id.0, "start": bytes.0, "end": bytes.1}); if !changes.is_empty() { @@ -560,10 +602,7 @@ fn apply_alternate(app: &mut VectorcraftApp, id: NodeId, bytes: (usize, usize), } ("text.setRangeStyle", params) } - }; - if let Err(e) = app.run(cmd, params) { - app.status(e.to_string()); - } + }) } /// The most alternate glyphs the canvas shows beside a selected character. Public behavior: at @@ -855,6 +894,250 @@ fn insert_character(app: &mut VectorcraftApp, ctx: &egui::Context, face: &vector } } +/// The side of the triangle in the lower right corner of a grid cell `cell` points wide whose glyph +/// has alternates: a quarter of the cell, from 5 to 10 points (VectorCraft's own size). +fn corner_side(cell: f32) -> f32 { + (cell * 0.25).clamp(5.0, 10.0) +} + +/// The most columns, and the most rows before it scrolls, of a cell's pop-up of alternates +/// (VectorCraft's own numbers). +const POPUP_COLUMNS: usize = 8; +const POPUP_ROWS: usize = 6; + +/// The triangle in the lower right corner of the grid cell `rect` of character `c` (none for a +/// glyph no character maps), whose glyph `gid` has alternates, and the pop-up a click on it opens +/// ([`alternates_popup`]). Public +/// behavior: a pop-up of alternate glyphs opens from the triangle in the lower right corner of a +/// glyph's box where the glyph has alternates +/// ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)). +/// Returns the glyph picked in the pop-up, in the frame it is picked. +fn corner_popup(ui: &mut Ui, face: &vectorcraft_text::FontFace, c: Option, gid: u32, rect: egui::Rect, cell: f32) -> Option { + let t = Tokens::get(ui.ctx()); + let side = corner_side(cell); + let corner = egui::Rect::from_min_max(rect.max - vec2(side + 1.0, side + 1.0), rect.max - vec2(1.0, 1.0)); + let resp = ui.interact(corner, egui::Id::unique(("gl-alternates-corner", face.id(), c, gid)), Sense::click()); + let fill = if resp.hovered() { t.accent } else { t.text_dim }; + ui.painter().add(egui::Shape::convex_polygon(vec![corner.right_top(), corner.right_bottom(), corner.left_bottom()], fill, Stroke::NONE)); + let resp = resp.on_hover_text(tl!("Show Character Alternates")); + let mut picked = None; + egui::Popup::menu(&resp).show(|ui| picked = alternates_popup(ui, face, c, gid, cell.max(CELL_STEPS[CELL_DEFAULT]))); + picked +} + +/// The pop-up of the alternates of glyph `gid`: that glyph first, then the alternates +/// [`vectorcraft_text::FontFace::alternates`] lists for character `c`, or for a glyph no character +/// maps the glyphs [`vectorcraft_text::FontFace::substitutions`] gives it, in the font's order, in +/// cells `cell` points wide, [`POPUP_COLUMNS`] to a row and [`POPUP_ROWS`] rows before it scrolls. +/// The glyph clicked. +fn alternates_popup(ui: &mut Ui, face: &vectorcraft_text::FontFace, c: Option, gid: u32, cell: f32) -> Option { + let t = Tokens::get(ui.ctx()); + let mut list: Vec<(u32, Option<[u8; 4]>)> = vec![(gid, None)]; + match c { + Some(c) => list.extend(face.alternates(c).into_iter().map(|a| (a.gid, Some(a.feature)))), + None => list.extend(face.substitutions(gid).into_iter().flat_map(|s| s.glyphs.into_iter().map(move |g| (g, Some(s.feature))))), + } + let mut seen = std::collections::HashSet::new(); + list.retain(|(g, _)| seen.insert(*g)); + let cols = list.len().clamp(1, POPUP_COLUMNS); + let rows = list.len().div_ceil(cols); + let px = (cell * ui.ctx().pixels_per_point()).round().clamp(8.0, 256.0) as u32; + let mut picked = None; + let area = egui::ScrollArea::vertical().id_salt(("gl-alternates-popup", face.id(), c, gid)).max_height(cell * POPUP_ROWS as f32); + area.show_rows(ui, cell, rows, |ui, range| { + for r in range { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + for &(g, feature) in list.iter().skip(r * cols).take(cols) { + let (rect, resp) = ui.allocate_exact_size(vec2(cell, cell), Sense::click()); + if resp.hovered() { + ui.painter().rect_filled(rect, 2, t.hover); + } + ui.painter().rect_stroke(rect.shrink(0.5), 0, Stroke::new(0.5, t.border), StrokeKind::Inside); + let tex = glyph_texture(ui.ctx(), face, g, px); + ui.painter().image(tex.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), t.text_strong); + let glyph = crate::i18n::fmt(tl!("glyph {id}"), &[("id", &g.to_string())]); + let tip = match feature { + Some(f) => format!("{glyph} ({})", String::from_utf8_lossy(&f)), + None => glyph, + }; + if resp.on_hover_text(tip).clicked() { + picked = Some(g); + } + } + }); + } + }); + picked +} + +/// A pick in the pop-up of character `c`'s cell, whose glyph is `gid` ([`alternates_popup`]). +/// The cell's own glyph inserts the character as a double-click on the cell does +/// ([`insert_character`]). An alternate needs the Type tool's caret or selection in text set in +/// `face`: when the selection is exactly one `c`, that character is drawn with the glyph; else `c` +/// goes in at the caret, in place of the selection, and is drawn with it, the two as one undo +/// step. The glyph goes on as a double-click in Show › Alternates for Current Selection puts it +/// ([`draw_selected_with`]). An Arabic presentation form goes in as its base letter, as a +/// double-click on its cell puts it, drawn with the glyph where the font gives it that glyph in its +/// word. Without a caret, with text in another font, or with a glyph the character cannot be drawn +/// with there, the status says why and nothing changes. +fn insert_alternate(app: &mut VectorcraftApp, ctx: &egui::Context, face: &vectorcraft_text::FontFace, c: char, gid: u32, picked: u32) { + if picked == gid { + return insert_character(app, ctx, face, c, gid); + } + let db = FontDb::global(); + let Some((editing, a, b)) = super::character::text_editing(app) else { + app.ui.status = "Select text or click into text with the Type tool to insert glyphs".into(); + return; + }; + let style = super::character::text_style(app).map(|(s, _)| s); + let text_face = style.as_ref().filter(|s| db.has_family(&s.font_family)).and_then(|s| db.style_face(s)); + if text_face.as_ref().map(|f| f.id()) != Some(face.id()) { + let text_font = match &text_face { + Some(f) => format!("{} {}", f.family, f.style), + None => style.map(|s| s.font_family).unwrap_or_default(), + }; + app.status(crate::i18n::fmt( + tl!("{glyph} is a glyph of {font}, not of the font the selected text is set in ({text_font})."), + &[("glyph", &glyph_label(face, picked)), ("font", &format!("{} {}", face.family, face.style)), ("text_font", &text_font)], + )); + return; + } + let c = base_letter(face, c, gid).unwrap_or(c); + // Typing in progress stays a step of its own. + super::character::end_typing(app); + let one = selected_target(app).is_some_and(|t| t.ch == c && (a.min(b), a.max(b)) == (t.byte, t.byte + c.len_utf8())); + if one { + draw_selected_with(app, face, c, picked); + return; + } + // Inside an undo group that is already open, the insertion and the glyph are part of that + // group's step; else they are one step of their own. + let open = app.session.active().is_some_and(|st| st.undo_group.is_some()); + if !open { + app.session.begin_named_undo_group(None); + } + // After Select All in a threaded story, the other frames' text goes too, as typing removes it. + let story = super::character::text_story(app).unwrap_or_default(); + put_alternate(app, face, c, picked, editing, (a.min(b), a.max(b)), &story); + if !open && let Some(st) = app.session.active_mut() { + st.undo_group = None; + } +} + +/// The insertion of [`insert_alternate`]: `c` takes the place of the Type tool's selection `lo..hi` +/// of text `id` (with the text of the other frames of `story` when the Type tool has the whole +/// threaded story selected), in the style of the selection's first character, and is drawn with +/// glyph `picked`. The edits are tried on a copy of the document first, and a pick the copy refuses +/// changes nothing, the undo history included. +fn put_alternate( + app: &mut VectorcraftApp, + face: &vectorcraft_text::FontFace, + c: char, + picked: u32, + id: NodeId, + (lo, hi): (usize, usize), + story: &[NodeId], +) { + let style = if lo < hi { + match app.run("text.getRange", json!({"id": id.0, "start": lo, "end": hi})) { + Ok(v) => v.pointer("/runs/0/style").cloned(), + Err(e) => { + app.status(e.to_string()); + return; + } + } + } else { + None + }; + let clear: Vec = story.iter().filter(|f| **f != id).map(|f| f.0).collect(); + let mut edit = json!({"id": id.0, "start": lo, "end": hi, "clear": clear}); + match style { + Some(style) => edit["runs"] = json!([{"text": c.to_string(), "style": style}]), + None => edit["insert"] = json!(c.to_string()), + } + if let Err(e) = try_on_a_copy(app, face, c, picked, (id, lo), &edit) { + app.status(e); + return; + } + if let Err(e) = app.run("text.editRange", edit) { + app.status(e.to_string()); + return; + } + app.session.set_tool_option("select", &json!({"start": lo, "end": lo + c.len_utf8()})); + if draw_selected_with(app, face, c, picked) { + app.session.set_tool_option("select", &json!({"start": lo + c.len_utf8(), "end": lo + c.len_utf8()})); + } +} + +/// The edits of [`put_alternate`] on a copy of the active document in a session of its own: `edit` +/// (`text.editRange`) puts `c` in at byte `at` of text `id`, and glyph `picked` of `face` goes on +/// it. The error of the step that fails; an error too when the character is not where the edit put +/// it. +fn try_on_a_copy( + app: &VectorcraftApp, + face: &vectorcraft_text::FontFace, + c: char, + picked: u32, + (id, at): (NodeId, usize), + edit: &serde_json::Value, +) -> Result<(), String> { + let Some(st) = app.session.active() else { return Ok(()) }; + let mut copy = vectorcraft_engine::Session::new(); + copy.add_document(vectorcraft_doc::Document::clone(&st.doc), None); + copy.execute("text.editRange", edit).map_err(|e| e.to_string())?; + let n = c.len_utf8(); + let step = match copy.active().and_then(|s| s.doc.node(id)).map(|node| &node.kind) { + Some(NodeKind::Text(text)) if text.plain_text().get(at..at + n) == Some(c.encode_utf8(&mut [0; 4])) => style_at(text, at).and_then(|style| { + alternate_command(id, (at, at + n), &style.features, style.glyph_alternate.is_some(), pick_for(text, at, face, picked)) + }), + _ => return Err("Select text or click into text with the Type tool to insert glyphs".into()), + }; + if let Some((cmd, params)) = step { + copy.execute(cmd, ¶ms).map_err(|e| e.to_string())?; + } + Ok(()) +} + +/// Draw the Type tool's selected character, `c` (a range's first character, else the one before +/// the caret), with glyph `picked` of `face`: through the OpenType feature that draws that glyph +/// on it in its word when one does, else as a glyph choice ([`apply_alternate`]). Whether it +/// worked; nothing changes when the character already has that glyph. +fn draw_selected_with(app: &mut VectorcraftApp, face: &vectorcraft_text::FontFace, c: char, picked: u32) -> bool { + let Some(t) = selected_target(app).filter(|t| t.ch == c) else { return false }; + let (id, byte, features, has_choice) = (t.id, t.byte, t.style.features.clone(), t.style.glyph_alternate.is_some()); + let pick = match app.session.active().and_then(|s| s.doc.node(id)).map(|node| &node.kind) { + Some(NodeKind::Text(text)) => pick_for(text, byte, face, picked), + _ => Pick::Glyph(picked), + }; + super::character::end_typing(app); + apply_alternate(app, id, (byte, byte + c.len_utf8()), &features, has_choice, pick) +} + +/// How glyph `picked` of `face` goes on the character at `byte` of `text`: the OpenType feature +/// that draws it there in its word, the default glyph, else a glyph choice. +fn pick_for(text: &vectorcraft_text::TextObject, byte: usize, face: &vectorcraft_text::FontFace, picked: u32) -> Pick { + match vectorcraft_text::alternates_in_context(FontDb::global(), text, byte).filter(|f| f.font_id == face.id()) { + Some(f) if f.default == picked => Pick::Default, + Some(f) => f.alternates.iter().find(|x| x.gid == picked).and_then(|x| x.apply.clone()).map_or(Pick::Glyph(picked), Pick::Feature), + None => Pick::Glyph(picked), + } +} + +/// The style of the character at `byte` of `text`. +fn style_at(text: &vectorcraft_text::TextObject, byte: usize) -> Option<&CharStyle> { + let mut start = 0; + text.runs + .iter() + .find(|run| { + let end = start + run.text.len(); + let found = (start..end).contains(&byte); + start = end; + found + }) + .map(|run| &run.style) +} + /// The tooltip of a glyph no character maps (Show › Entire Font): its name from the font, `gid N` /// when it has none, its id, and the feature that gives it, if one does. fn unencoded_tip(face: &vectorcraft_text::FontFace, gid: u32) -> String { @@ -1611,6 +1894,279 @@ mod tests { } } + /// The corner triangles of the grid cells whose glyph has alternates: right-angled, with the + /// right angle at the cell's lower right corner. + fn corner_triangles(shapes: &[Shape]) -> Vec { + fn walk(s: &Shape, out: &mut Vec) { + match s { + Shape::Path(p) if p.points.len() == 3 && p.points[0].x == p.points[1].x && p.points[1].y == p.points[2].y => { + out.push(Rect::from_points(&p.points)); + } + Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut out = vec![]; + shapes.iter().for_each(|s| walk(s, &mut out)); + out + } + + /// The Type tool editing `text` set in the alternates test font, the panel on Basic Latin, and + /// the egui context it is drawn in. + fn basic_latin_of_the_alternates_font(text: &str) -> (VectorcraftApp, serde_json::Value, egui::Context) { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font}; + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let (mut app, id) = editing(text); + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + (app, id, ctx) + } + + /// Click the one corner triangle of the grid, and return the glyph cells of the pop-up it + /// opens (drawn after the panel, on top of it). + fn open_corner_popup(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec { + let before = squares(&shapes(ctx, app, vec![])); + let corners = corner_triangles(&shapes(ctx, app, vec![])); + assert_eq!(corners.len(), 1, "only a has alternates among Basic Latin: {corners:?}"); + click(ctx, app, corners[0].center() + vec2(1.0, 1.0)); + let after = squares(&shapes(ctx, app, vec![])); + assert!(after.len() > before.len(), "the pop-up drew its glyphs: {} then {}", before.len(), after.len()); + after[after.len() - (after.len() - before.len())..].to_vec() + } + + /// A cell whose glyph has alternates has a corner triangle; a click on it opens a pop-up of the + /// glyph and its alternates in the font's order, and picking an alternate inserts the + /// character at the caret drawn with it, as one undo step. + #[test] + fn a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one() { + use vectorcraft_text::test_fonts::{alternates_family, unencoded_glyphs}; + let [u1, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xy"); + let face = FontDb::global().face(alternates_family(true), "Regular").expect("the test face"); + let a = face.glyph_for('a'); + assert!(face.has_alternates(a)); + let drawn = shapes(&ctx, &mut app, vec![]); + let (cells, triangle) = (squares(&drawn), corner_triangles(&drawn)); + assert_eq!(triangle.len(), 1); + assert!( + cells.iter().any(|c| c.contains(triangle[0].center()) && (c.max - triangle[0].max).length() < 2.0), + "in a cell's lower right corner: {triangle:?} among {cells:?}" + ); + select(&mut app, 1, 1); + let popup = open_corner_popup(&ctx, &mut app); + assert_eq!(popup.len(), 7, "a and its six alternates"); + let plain = glyph_ids(&app, &id); + let undo = app.session.active().unwrap().history.undo.len(); + // a, u1, b, u2: the fourth cell is ss01's u2. + click(&ctx, &mut app, popup[3].center()); + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + assert_eq!(text.plain_text(), "xay", "status: {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[1]], "the inserted a is drawn with the pick"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(glyph_ids(&app, &id), plain, "undo takes the character back out"); + // The cell's own glyph inserts the plain character, as a double-click does. + select(&mut app, 1, 1); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[0].center()); + assert_eq!(glyph_ids(&app, &id), [plain[0], a, plain[1]]); + // An alternate with no feature that draws it here (u1 is listed by aalt) still goes on. + select(&mut app, 2, 2); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(glyph_ids(&app, &id), [plain[0], a, u1, plain[1]], "status: {}", app.ui.status); + } + + /// With the Type tool's selection exactly the cell's character, a pick draws that character + /// with the glyph and keeps the text; picking the glyph it already has adds no undo step. + /// Without the Type tool, and with text in another font, the status says why and nothing + /// changes. + #[test] + fn a_pick_replaces_the_selected_character_and_says_why_when_it_cannot() { + use vectorcraft_text::test_fonts::{alternates_family, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xay"); + let plain = glyph_ids(&app, &id); + select(&mut app, 1, 2); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind else { panic!("text") }; + assert_eq!(text.plain_text(), "xay", "the selected a stays: status {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[2]]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + select(&mut app, 1, 2); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the glyph it already has changes nothing"); + assert_eq!(glyph_ids(&app, &id), [plain[0], u2, plain[2]]); + + // Text set in another font than the one the panel browses. + let family = alternates_family(true); + set_pstate(&ctx, "gl-font", Some((family.to_string(), "Regular".to_string()))); + app.run("text.setRangeStyle", json!({"id": id, "font": vectorcraft_text::FALLBACK_FAMILY})).unwrap(); + select(&mut app, 3, 3); + let undo = app.session.active().unwrap().history.undo.len(); + let before = glyph_ids(&app, &id); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(glyph_ids(&app, &id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert!(app.ui.status.contains("not of the font the selected text is set in"), "{}", app.ui.status); + + // No Type tool caret. + app.session.select_tool("select", Default::default()).unwrap(); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(glyph_ids(&app, &id), before); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + assert_eq!(app.ui.status, "Select text or click into text with the Type tool to insert glyphs"); + } + + /// A pick the inserted character cannot be drawn with (All Caps keeps a glyph choice from + /// being drawn) takes the character back out and keeps the status that says why: on its own, + /// and inside an undo group that is already open, which stays open with its earlier edit and + /// takes a pick that can be drawn in place of the selection. + #[test] + fn a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was() { + let [_, u2, ..] = vectorcraft_text::test_fonts::unencoded_glyphs().expect("unencoded glyphs"); + let (mut app, id, ctx) = basic_latin_of_the_alternates_font("xy"); + let text = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + app.run("text.setFormat", json!({"ids": [id], "allCaps": true})).unwrap(); + // A step to redo, which the failed pick keeps. + app.run("text.setFormat", json!({"ids": [id], "underline": true})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + select(&mut app, 1, 1); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "no undo step is left"); + assert_eq!(app.session.active().unwrap().history.redo.len(), 1, "the redo step stays"); + assert!(!app.ui.status.is_empty(), "the status says why"); + + // In an open group with no edit yet, the failed pick leaves the group with nothing to undo. + app.run("edit.undoGroup.begin", json!({})).unwrap(); + select(&mut app, 0, 1); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy"); + assert!(!app.ui.status.is_empty(), "the status says why"); + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "the empty group adds no step"); + + app.run("edit.undoGroup.begin", json!({})).unwrap(); + app.run("text.setFormat", json!({"ids": [id], "underline": true})).unwrap(); + select(&mut app, 0, 1); + app.ui.status.clear(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[1].center()); + assert_eq!(text(&app), "xy", "the replaced x is back: status {}", app.ui.status); + assert!(!app.ui.status.is_empty(), "the status says why"); + assert!(app.session.active().unwrap().undo_group.is_some(), "the group stays open"); + // A pick that can be drawn replaces the selection inside the group. + app.run("text.setFormat", json!({"ids": [id], "allCaps": false})).unwrap(); + select(&mut app, 0, 1); + let plain = glyph_ids(&app, &id); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + assert_eq!(text(&app), "ay", "status {}", app.ui.status); + assert_eq!(glyph_ids(&app, &id), [u2, plain[1]]); + assert!(app.session.active().unwrap().undo_group.is_some(), "the group stays open"); + app.run("edit.undoGroup.end", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the group is one step"); + } + + /// After Select All in a threaded story, a pick replaces the whole story's text, as typing + /// does: the character drawn with the glyph stays, in one undo step. + #[test] + fn a_pick_replaces_a_threaded_story_that_select_all_selected() { + use vectorcraft_text::test_fonts::{alternates_family, alternates_font, unencoded_glyphs}; + let [_, u2, ..] = unencoded_glyphs().expect("unencoded glyphs"); + FontDb::global().add_font(alternates_font(true).expect("the test font builds")); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 300})).unwrap(); + let story = "a bad cab ".repeat(30); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.run("text.create", area).unwrap()["id"].as_u64().unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [400, 10, 150, 200]})).unwrap()["id"].as_u64().unwrap(); + for id in [a, b, c] { + app.run("text.setRangeStyle", json!({"id": id, "font": alternates_family(true)})).unwrap(); + } + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + assert_eq!(super::super::character::text_story(&app).map(|s| s.len()), Some(3), "the whole story is selected"); + let ctx = egui::Context::default(); + set_pstate(&ctx, "gl-subset", 1usize); + let undo = app.session.active().unwrap().history.undo.len(); + let popup = open_corner_popup(&ctx, &mut app); + click(&ctx, &mut app, popup[3].center()); + let plain = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("text"), + }; + let texts: String = [a, b, c].iter().map(|id| plain(&app, *id)).collect(); + assert_eq!(texts, "a", "status: {}", app.ui.status); + let first = [a, b, c].into_iter().find(|id| !plain(&app, *id).is_empty()).expect("a frame with the character"); + assert_eq!(glyph_ids(&app, &json!(first)), [u2]); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + + /// In Entire Font, a glyph no character maps whose substitutions give other glyphs has the + /// corner triangle too: its pop-up lists it and those glyphs, and a pick goes on the selected + /// character as a double-click on that glyph's cell would put it. + #[test] + fn an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection() { + use vectorcraft_text::test_fonts::{JOINING_ALTERNATES_FAMILY, joining_alternates_font, source_sans_gid}; + FontDb::global().add_font(joining_alternates_font().expect("the test font builds")); + let g = |c| u32::from(source_sans_gid(c).expect("a glyph")); + let (mut app, id) = editing("\u{628}\u{62A}\u{646}"); + app.run("text.setRangeStyle", json!({"id": id, "font": JOINING_ALTERNATES_FAMILY})).unwrap(); + select(&mut app, 2, 4); + let ctx = egui::Context::default(); + choose(&ctx, &mut app, "Entire Font"); + let face = FontDb::global().face(JOINING_ALTERNATES_FAMILY, "Regular").expect("the test face"); + let medial = g('u'); + assert!(face.unencoded_glyphs().contains(&medial) && face.has_alternates(medial), "the medial teh is unencoded and has alternates"); + // A screen tall enough for every cell of the font. + let run = |ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec| { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(280.0, 200_000.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes.into_iter().map(|c| c.shape).collect::>() + }; + let click_at = |ctx: &egui::Context, app: &mut VectorcraftApp, at: Pos2| { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(ctx, app, vec![egui::Event::PointerMoved(at), button(true)]); + run(ctx, app, vec![button(false)]); + }; + let drawn = run(&ctx, &mut app, vec![]); + let (cells, corners) = (squares(&drawn), corner_triangles(&drawn)); + let chars = face.chars().into_iter().filter(|(c, _)| !c.is_control() && !c.is_whitespace()).count(); + let unencoded = face.unencoded_glyphs(); + assert_eq!(cells.len(), chars + unencoded.len(), "every glyph has a cell"); + let cell = cells[chars + unencoded.iter().position(|g| *g == medial).expect("an unencoded glyph")]; + let corner = corners.iter().find(|t| cell.contains(t.center())).expect("its corner triangle"); + let undo = app.session.active().unwrap().history.undo.len(); + click_at(&ctx, &mut app, corner.center() + vec2(1.0, 1.0)); + let after = squares(&run(&ctx, &mut app, vec![])); + let popup = &after[cells.len()..]; + assert_eq!(popup.len(), 4, "the medial teh and its three alternates"); + click_at(&ctx, &mut app, popup[2].center()); + assert_eq!(glyph_ids(&app, &id), [g('B'), g('x'), g('M')], "status: {}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// Show › Entire Font also lists the glyphs no character maps. #[test] fn entire_font_lists_the_unencoded_glyphs() { diff --git a/docs/type-parity.md b/docs/type-parity.md index 5b332efd5e..9924ce4e43 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -32,7 +32,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Copy or Cut selected characters, then paste as separate text art | done | A Type-range copy keeps the selected characters' font family, size and color when pasted on the canvas after leaving text editing, in the same document or another. On desktop the clipboard offers plain text to text consumers and rich art for canvas Paste; Paste Without Formatting while editing uses the destination text's style. `tests::clipboard::type_range_copy_stays_styled_when_pasted_as_art` (#5636) | | Character size and horizontal scale after object/group scaling | done | #1034: fields and setters compensate the stored affine; point size follows the transformed em-height axis, not the glyph ink bounds. Range edits, keyboard increments, leading and baseline shift use document points; rotation, reflection and shear remain editable. | | Preserve font sizes while scaling a group | missing | Separate enhancement; scaling still scales text with the other artwork. | -| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. The glyph-cell pop-up of alternates is not there yet | +| OpenType panel, Glyphs panel, alternates | done | Highlight Alternate Glyphs preference (#394, off by default) paints pink behind OpenType substitutions on screen when on (required shaping such as Arabic joining forms and the lam-alef ligature, including a lam-alef older fonts file under `liga`, is not highlighted; an optional feature that changes the ligature is); stylistic sets ss01–ss20, stylistic and titling alternates, proportional and lining figures, superscript and subscript are character-style features (`text.setStyle {features}`, #1607); the OpenType panel's Position menu sets superscript, subscript, numerator or denominator glyphs (`sups`, `subs`, `numr`, `dnom`). The OpenType panel's Stylistic Sets menu lists the selected font's `ss01`–`ss20` features, using a font-supplied name where available and `Set N` otherwise; several sets can be active, and selecting an active one removes it. For a mixed-font selection it uses the first selected character's font, a VectorCraft design choice ([public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html), [OpenType feature specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt)). The Glyphs panel highlights the character selected with the Type tool (a range's first character, else the one before the caret) and scrolls it into view as the selection moves (#4908; `panels::glyphs` tests); its Show menu lists Unicode ranges and Alternates for Current Selection, the selected character's alternate glyphs from the font's `GSUB` table. A double-click applies the OpenType feature that draws a variant to that character alone, or uses a glyph choice when no supported feature draws it; see the Glyphs panel row below for Entire Font and the joining limits. A grid cell whose glyph has alternates shows a triangle in its lower right corner; a click on it opens a pop-up of that glyph and its alternates in the font's order, and a pick inserts the character at the caret drawn with that glyph, or draws the selected character with it, in one undo step; in Entire Font a glyph no character maps has the triangle too, and a pick goes on the selected character as a double-click on that glyph's cell does ([CS6 reference, Glyphs panel overview](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=373)); the triangle's size and the pop-up's eight columns and six rows are VectorCraft's own (`panels::glyphs` tests `a_cells_corner_triangle_opens_its_alternates_and_a_pick_inserts_one`, `a_pick_replaces_the_selected_character_and_says_why_when_it_cannot`, `a_pick_that_cannot_be_drawn_leaves_the_text_as_it_was`, `an_unencoded_glyphs_corner_triangle_applies_its_alternates_to_the_selection`; `has_alternates_follows_the_listed_substitutions` in the text crate) | | Glyphs panel: alternates as OpenType feature values, unencoded glyphs | done | #5514, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes (Show › Alternates For Current Selection; replace the selected character by double-clicking the glyph). A character-style feature takes a value (`"salt=2"`, the font's alternate number; `ss01`–`ss20`, `swsh`, `titl` and `aalt` too) in `features` and `featureChanges`, in SVG `font-feature-settings` (`"salt" 2`) and in native files as the plain string. Show › Entire Font applies an unencoded glyph the same way when it is an alternate of the selected character in its word, applies one no feature reaches (`A.salt` in a font with no `salt`) to the selected character as a glyph choice (it may not join), and dims the others with the reason in the tooltip (e.g. `yehfarsi.fina.alt2 belongs to ی (U+06CC) at the end of a word; your selection is ي (U+064A)`); an Arabic presentation form picked there inserts its letter so the word joins. Runs that differ only in their features shape as one piece of text, each run's features over its own characters, so a variant on one letter of an Arabic word keeps its neighbours' initial, medial and final forms and the letters still touch. The panel lists the alternates of the glyph the shaper makes for the selected character in its word (a medial letter shows medial variants), and a double-click applies the OpenType feature that draws the variant (`salt=N` or `ssNN`) to that character alone, in one undo step (`text.setRangeStyle`); a variant no feature reaches falls back to a replacement glyph (`text.setGlyphAlternate`), which its tooltip says may not join. Show › Entire Font also lists the glyphs no character maps, with their name or `gid N` and the feature that gives them. The text crate reads each face's `GSUB` once (alternate sets, single substitutions, the feature that reaches a glyph). Not done: alternates reached through contextual or ligature lookups, and features of the font that the style has no tag for (`cv01`–`cv99`, `hist`). Evidence: `tests::glyph_alternates` in the text crate (a fixture font with a medial teh at `salt=1` to `3`, the neighbours' forms, no gap; Kufi Murabba PIIIX when it is installed), `features::tests::feature_values_are_parsed_validated_and_shaped`, `tests::textedit::feature_values_are_set_replaced_and_saved`, the `panels::glyphs` tests. | | OpenType panel menu: H or V Style, Roman Italics | done | With Show East Asian Options, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes: H or V Style is the character feature `hkna` (kana in the font's horizontal forms, shaped as `vkna` in vertical type) and Roman Italics is `ital` (the font's italic half-width alphanumerics), set with `text.setStyle` / `text.setRangeStyle {features, featureChanges}`, on or off only, and in Character Style Options › OpenType Features ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). | | Font menu: samples, live preview, filters, favourites, recent families; font matching by any name; Find Font | done | #3515: recently applied families appear first, once each; missing families are omitted and the existing Number of Recent Fonts setting applies; #339; script filter: Japanese, Latin, Thai; 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); Select Text by Font takes a scope: the document, chosen artboards or chosen layers; Find Font's Find In offers Document, Artboard (the active one) and Layers (the selected ones, else the current one) (#5529, a VectorCraft addition); Replace With Font lists family and style rows, one click setting both, with a search over them; its list scrolls on its own, apart from the document's font list (#4972); wherever the font menu opens, its filters keep the same four rows, and it opens at least wide enough for them and for a family name up to 220 points wide with its sample (up to 60% of the window), each sample filling its row's height (a VectorCraft layout); a filter chosen in the font menu of the Character panel, the Control bar or the Properties panel is on in the others, and the filters are cleared when the app quits ([Font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html)); the font menus of the Glyphs panel and of the dialogs that pick a font share the same filters (a VectorCraft choice). | From a8cb5d03ec36a7bd9e6bb7715ebe900c9623b071 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:51:15 -0800 Subject: [PATCH 40/77] i18n: drop Georgian and Russian script error rows that main already has main's Georgian and Russian catalogs now translate the thirteen script interpreter core errors themselves, so the rows this branch added for them were duplicates and bundled_catalogs_are_consistent rejected the catalogs. The rows main has stay as they are. --- crates/ui-egui/src/i18n/ka.tsv | 13 ------------- crates/ui-egui/src/i18n/ru.tsv | 13 ------------- 2 files changed, 26 deletions(-) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 316895997b..6ee7f0c0e4 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7754,19 +7754,6 @@ imageTrace Outline კონტური @msg $.evalFile requires a file path $.evalFile-ს სჭირდება ფაილის მისამართი @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: დროის ლიმიტი უნდა იყოს მილიწამების სასრული რიცხვი, 0 ან მეტი @msg $.evalFile: takes a file path and a timeout $.evalFile: იღებს ფაილის მისამართს და დროის ლიმიტს -@msg assignment to a constant binding მინიჭება მუდმივ ბმაზე -@msg invalid array length მასივის არასწორი სიგრძე -@msg array literal too long მასივის ლიტერალი ძალიან გრძელია -@msg the value is not a function მნიშვნელობა არ არის ფუნქცია -@msg apply was called on a value that is not a function apply გამოიძახეს მნიშვნელობაზე, რომელიც არ არის ფუნქცია -@msg the argument list is not an object არგუმენტების სია არ არის ობიექტი -@msg too many arguments ზედმეტად ბევრი არგუმენტი -@msg the value is not a constructor მნიშვნელობა არ არის კონსტრუქტორი -@msg cannot convert the object to a primitive value ობიექტი პრიმიტიულ მნიშვნელობად ვერ გარდაიქმნება -@msg cannot convert undefined or null to an object undefined ან null ობიექტად ვერ გარდაიქმნება -@msg the right side of 'in' is not an object 'in' ოპერატორის მარჯვენა მხარე არ არის ობიექტი -@msg the right side of 'instanceof' is not a function 'instanceof' ოპერატორის მარჯვენა მხარე არ არის ფუნქცია -@msg the function's prototype is not an object ფუნქციის პროტოტიპი არ არის ობიექტი @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 289acf54b6..72aa7eced9 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4478,19 +4478,6 @@ axis Both Оба @msg $.evalFile requires a file path $.evalFile требует путь к файлу @msg $.evalFile: the timeout must be a finite number of milliseconds, 0 or more $.evalFile: тайм-аут должен быть конечным числом миллисекунд, 0 или больше @msg $.evalFile: takes a file path and a timeout $.evalFile: принимает путь к файлу и тайм-аут -@msg assignment to a constant binding присваивание константной привязке -@msg invalid array length недопустимая длина массива -@msg array literal too long литерал массива слишком длинный -@msg the value is not a function значение не является функцией -@msg apply was called on a value that is not a function apply вызван для значения, которое не является функцией -@msg the argument list is not an object список аргументов не является объектом -@msg too many arguments слишком много аргументов -@msg the value is not a constructor значение не является конструктором -@msg cannot convert the object to a primitive value невозможно преобразовать объект в примитивное значение -@msg cannot convert undefined or null to an object невозможно преобразовать undefined или null в объект -@msg the right side of 'in' is not an object правая часть 'in' не является объектом -@msg the right side of 'instanceof' is not a function правая часть 'instanceof' не является функцией -@msg the function's prototype is not an object прототип функции не является объектом @msg Error: {e} Error: {e} @msg TypeError: {e} TypeError: {e} @msg ReferenceError: {e} ReferenceError: {e} From 831e539ecc2455171bb1558f1e5f0a12a231da96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:54:05 -0800 Subject: [PATCH 41/77] SVG export: a drawn repeat mark in scaled type keeps its character's width In horizontally scaled type, live SVG text stretched the character a repeat mark is drawn as (Kurikaeshi Moji Shori) to the mark's advance with textLength, so a reader narrowed or widened it whenever the two glyphs' widths differ. Its textLength now takes the width the canvas draws that character at; the text after it is still placed anew. --- crates/svg/src/export/text.rs | 36 +++++++++++++++++++++++++++--- crates/svg/tests/it/text_layout.rs | 30 +++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 907068c56d..b341a62c0c 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -439,7 +439,8 @@ impl Writer<'_> { // reader would draw elsewhere, the next segment is placed. place = seg.brk || (!fewer && !base.anchored && positioned); if (st.h_scale - st.v_scale).abs() > 1e-9 || seg.scale != 1.0 { - attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(seg.advance * seg.scale))); + let length = seg.advance * seg.scale + seg.repeat_widen; + attrs.push_str(&format!(" textLength=\"{}\" lengthAdjust=\"spacingAndGlyphs\"", self.num(length))); } if st.rotation != 0.0 { attrs.push_str(&format!(" rotate=\"{}\"", self.num(-st.rotation))); @@ -716,6 +717,9 @@ struct Segment { /// Glyph Scaling of the segment's one glyph (Justification…), which a reader stretches it to /// (`textLength`); 1 for other segments. scale: f64, + /// How much wider than the repeat mark the canvas draws the character the mark is drawn as + /// (Kurikaeshi Moji Shori), which a reader stretches it to (`textLength`); 0 for other segments. + repeat_widen: f64, /// A list marker's characters and tab, written in /// [`vectorcraft_doc::text::ParaList::marker_style`] of the run's style. marker: bool, @@ -736,6 +740,30 @@ fn shown_repeat(lay: &vectorcraft_text::TextLayout, i: usize, g: &vectorcraft_te lay.repeat_marks.get(at).map(|&(_, c)| c) } +/// Kurikaeshi Moji Shori: how much wider than repeat mark `cluster` the canvas draws glyph `g`, the +/// character the mark is drawn as in the mark's place (text space), or 0 when the face or the +/// mark's glyph is not found. +fn repeat_widen(g: &vectorcraft_text::PositionedGlyph, cluster: &str) -> f64 { + let Some(face) = FontDb::global().face_by_id(g.font_id) else { return 0.0 }; + // ゝ or ヽ with a combining voicing mark is drawn as one glyph, the voiced mark's. + let mark = match cluster { + "ゝ\u{3099}" => 'ゞ', + "ヽ\u{3099}" => 'ヾ', + _ => match cluster.chars().next() { + Some(c) => c, + None => return 0.0, + }, + }; + let mark_gid = face.glyph_for(mark); + if mark_gid == 0 { + return 0.0; + } + // Font units along the baseline → text space (size, Horizontal Scale and Glyph Scaling). + let [a, b, ..] = g.xf.as_coeffs(); + let widen = (face.advance(g.gid) - face.advance(mark_gid)) * a.hypot(b); + if widen.is_finite() { widen } else { 0.0 } +} + /// The laid-out lines of `t` as segments: a new segment at every style change, after tabs and, /// on justified lines, after each word space (unless `fewer`). The text comes from the clusters /// the layout placed: soft hyphens draw nothing, a line broken by hyphenation ends in `-`, all @@ -829,6 +857,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - Some(c) => c.to_string(), None => source(line.glyph_start + k, g).chars().filter(|c| *c != '\u{ad}').map(|c| run.style.digits.map(c)).collect(), }; + let widen = if repeat.is_some() { repeat_widen(g, source(line.glyph_start + k, g)) } else { 0.0 }; let piece = if run.style.all_caps { src.to_uppercase() } else { src }; // The character a repeat mark is drawn as takes the mark's width on the canvas, which a // reader does not know: the text after it is placed anew. @@ -846,7 +875,8 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - let marker = lay.marker_of(line.glyph_start + k).is_some(); let tab_apart = piece == "\t" && (run.style.h_scale - run.style.v_scale).abs() > 1e-9; match segs.last_mut() { - Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart => { + // The character a repeat mark is drawn as is a segment of its own, stretched to its width. + Some(last) if last.run == g.run && !last.brk && !fresh && !moved && last.marker == marker && !tab_apart && repeat.is_none() => { last.text.push_str(&piece); last.advance += advance; last.brk = brk; @@ -856,7 +886,7 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - last.brk |= moved || last.marker != marker; end_segment(last, tail, t, lay, &mut unkerned); } - segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, marker }); + segs.push(Segment { run: g.run, x, y: g.origin.y, text: piece, advance, brk, scale, repeat_widen: widen, marker }); } } tail = set.map(|_| (g.byte, advance)); diff --git a/crates/svg/tests/it/text_layout.rs b/crates/svg/tests/it/text_layout.rs index ff27c96955..95d2fd0b24 100644 --- a/crates/svg/tests/it/text_layout.rs +++ b/crates/svg/tests/it/text_layout.rs @@ -942,6 +942,36 @@ fn a_repeat_mark_at_a_line_start_is_written_as_the_character_it_draws() { } } +/// Kurikaeshi Moji Shori in horizontally scaled type: the character a repeat mark is drawn as is +/// stretched (`textLength`) to the width the canvas draws that character at, not to the mark's +/// advance, so a reader does not distort it when the two characters' widths differ. +#[test] +fn a_drawn_repeat_mark_in_scaled_type_keeps_the_width_of_its_character() { + use vectorcraft_text::test_fonts::{RARE_REPEAT_MARK_FAMILY, rare_repeat_mark_font}; + vectorcraft_text::FontDb::global().add_font(rare_repeat_mark_font().unwrap()); + // The test font draws 龘 and 々 with glyphs of different widths. + let st = CharStyle { font_family: RARE_REPEAT_MARK_FAMILY.into(), h_scale: 50.0, ..style(12.0) }; + let mut t = TextObject::point(Point::new(20.0, 40.0), "龘\u{2028}々", st); + t.para.kurikaeshi_moji_shori = true; + let mut d = Document::new(300.0, 200.0); + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let svg = export(&d, &ExportOptions::default()); + // The textLength of each `` that holds 龘 alone: the one on the first line and the one + // the mark is drawn as on the second. + let lengths: Vec<&str> = svg + .match_indices(">龘<") + .map(|(at, _)| { + let tag = &svg[svg[..at].rfind('<').unwrap_or(0)..at]; + let from = tag.find("textLength=\"").unwrap_or_else(|| panic!("{tag}: {svg}")) + "textLength=\"".len(); + &tag[from..from + tag[from..].find('"').unwrap_or(0)] + }) + .collect(); + assert_eq!(lengths.len(), 2, "{svg}"); + assert_eq!(lengths[0], lengths[1], "{svg}"); +} + /// Kurikaeshi Moji Shori: a `` cannot draw a character in another character's width, so /// type on a path whose threaded frame starts with a repeat mark drawn as the character it repeats /// is outlined, with a warning; with the setting off it stays live text. From d4bbacc3ebb4bfac4b83eff349f483768abccfd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:57:09 -0800 Subject: [PATCH 42/77] Export: live effects in symbol art apply in EMF, WMF and SVG EMF, WMF and SVG wrote a symbol instance from its symbol's art as stored, so live effects inside that art were missing: a square moved 100 pt by a Transform effect stayed in place in the file while the canvas drew it moved. Art whose own place is off the artboard was left out even when the effect moved it onto it. These exports now call bake_document_placing_symbols, as PDF, print, EPS and DXF do: each instance of a symbol whose art needs baking is written as that art placed by the instance and then baked, so an instance that scales or turns its art does not scale what its effects do. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances are written as groups; instances of symbols without such effects still share one . Preserve Editing still embeds the document with its live effects. WrittenLayers gains hidden_objects. SVG sets it with Hidden Layers on, since it then writes hidden objects too, so a hidden instance is written hidden with its effects applied. The other exporters leave it off. An SVG instance nested in another instance's art was shared through when the def allowed its own transform, while the writes that transform after the outer instances'. A stroked symbol nested in a scaled instance then drew its stroke at double weight. The check now uses the transform the writes. --- crates/cad/src/lib.rs | 4 +- crates/effects/src/bake.rs | 24 ++++---- crates/effects/src/bake/tests.rs | 14 ++++- crates/eps/src/lib.rs | 4 +- crates/metafile/src/lib.rs | 11 ++-- crates/metafile/src/tests/import.rs | 37 +++++++++++++ crates/pdf/src/export/entry.rs | 1 + crates/pdf/src/print.rs | 2 +- crates/svg/src/export.rs | 8 ++- crates/svg/src/export/nodes.rs | 7 ++- crates/svg/tests/it/symbols_layers.rs | 79 +++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 12 files changed, 167 insertions(+), 25 deletions(-) diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index bb752267aa..6ab16c61e3 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -429,8 +429,8 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result { return Err("the export region is not finite".into()); } // Symbols' art is placed without clipping, as the scene places it. - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); let doc = baked.as_ref().unwrap_or(doc); Ok(scene::Scene::new(doc, opts).run()) } diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index d8f3ae0fe4..ec63c28707 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -162,7 +162,7 @@ struct Placing { layers: WrittenLayers, } -/// The layers an exporter writes besides the shown, printing ones +/// The layers and objects an exporter writes besides the shown, printing ones /// ([`bake_document_placing_symbols`]). Template layers are never written. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct WrittenLayers { @@ -170,16 +170,19 @@ pub struct WrittenLayers { pub hidden: bool, /// Layers that do not print. pub non_printing: bool, + /// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden + /// layers). + pub hidden_objects: bool, } /// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`] -/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer +/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer /// that does not print when the export leaves those out ([`WrittenLayers`]). fn unwritten(n: &Node) -> bool { PLACING.with(|p| { p.borrow().as_ref().is_some_and(|p| match n.kind { NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden), - _ => !n.visible, + _ => !(n.visible || p.layers.hidden_objects), }) }) } @@ -1014,13 +1017,14 @@ pub fn bake_document(doc: &Document) -> Option { /// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or /// in the art of the symbols it places) replaced by that art as the instance places it, baked /// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For -/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than -/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped -/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the -/// exporter places other instances. `layers`: the hidden layers and layers that do not print -/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden -/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The -/// symbols' own art is left as it is. +/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and +/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`: +/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not +/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`: +/// the hidden layers, layers that do not print and hidden objects that the exporter writes. +/// Instances the export does not write (template layers, and the hidden objects and layers +/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as +/// it is. pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option { bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers))) } diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index fba4f75e5f..292d9461d6 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -1328,7 +1328,7 @@ fn placing_symbols_keeps_the_instances_stain() { } /// Every layer written, as DXF writes them (template layers are never written). -const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true }; +const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; fn is_instance(d: &Document, id: u64) -> bool { d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) @@ -1455,10 +1455,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() { } // An export that writes the layers that do not print, or the hidden layers, places that // layer's instance first; the template layer's instance is never placed. - for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] { + for (layers, first) in + [(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)] + { let out = bake(&d, Some((true, each, layers))).unwrap(); assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}"); } + // An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance + // first, and the instance in the hidden group would come next; the hidden layer's instance + // stays, since that layer is still left out. + let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap(); + assert!(!is_instance(&out, 901), "the hidden instance is placed"); + for id in [900, 903, 911, 921, 931] { + assert!(is_instance(&out, id), "{id} stays as it is"); + } } /// `leaf` in `levels` groups, with ids from `id` up. diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index e36422b759..39737dae3a 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -232,8 +232,8 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb } // Type in the document's composite fonts is drawn in them, whether or not an app has the document open. let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts); - let baked = - vectorcraft_effects::bake_document_placing_symbols(doc, true, vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); let page = scene::Scene::new(doc, opts).run(); let mut setting_notes = vec![]; diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 86d268cee1..61126ef228 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -74,15 +74,18 @@ pub struct Output { } /// Write the visible art of `doc` over `region` (document space: its top-left corner is the -/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first; -/// template layers, hidden objects and guides are left out. Raster effects should be turned into -/// images before (the engine does); the ones left are reported and left out. +/// picture's origin, its size the picture's) as `kind`. Live geometry effects are applied first, +/// in symbols' art too, where each instance places that art (EMF clips 9-slice cells, WMF does +/// not); template layers, hidden objects and guides are left out. Raster effects should be turned +/// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result { let r = region.abs(); if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { return Err("the export region is empty".into()); } - let baked = vectorcraft_effects::bake_document(doc); + // The scene writes layers that do not print and leaves hidden layers and objects out. + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); let bytes = match kind { diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index f5870c5f95..622a800414 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -85,6 +85,43 @@ fn wmf_output_round_trips() { assert!(near(ellipse.geometric_bounds().unwrap(), Rect::new(100.0, 20.0, 180.0, 80.0), 0.1)); } +/// A symbol's square that a Transform effect moves 100 pt right is written where the canvas draws +/// it, in EMF and in WMF, read back: art whose own place is off the artboard is written where the +/// effect moves it onto it, and an instance that doubles the art's width places it first, so the +/// effect still moves it 100 pt (to x = 120, not 220). A stained instance keeps its stain. +#[test] +fn symbol_art_effects_are_written_where_they_draw() { + let moved = |rect: Rect| { + let mut art = path(shapes::rectangle(rect), red(), Paint::None, 0.0); + art.appearance.effects.push(vectorcraft_doc::Effect { + id: "distort.transform".into(), + params: [("moveH", 100.0)].into_iter().collect(), + visible: true, + }); + art + }; + // The art's square, the instance's transform and fill, and the square and color it draws. + let cases = [ + (Rect::new(-90.0, 10.0, -80.0, 20.0), Affine::IDENTITY, None, Rect::new(10.0, 10.0, 20.0, 20.0), [255, 0, 0]), + (Rect::new(10.0, 30.0, 20.0, 40.0), Affine::scale_non_uniform(2.0, 1.0), Some(blue()), Rect::new(120.0, 30.0, 140.0, 40.0), [0, 0, 255]), + ]; + for (square, xf, stain, want, rgb) in cases { + let mut inst = Node::new(vectorcraft_doc::NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf }); + if let Some(p) = stain { + inst.appearance = vectorcraft_doc::Appearance::basic(p, Paint::None, 0.0).into(); + } + let mut d = doc_with(200.0, 100.0, vec![inst]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: std::sync::Arc::new(moved(square)) }); + for kind in [Kind::Emf, Kind::Wmf] { + let back = import(&export(&d, d.artboards[0].rect, kind).unwrap().bytes).unwrap(); + let drawn: Vec<(Option, Option<[u8; 3]>)> = paths(&back.document).iter().map(|n| (n.geometric_bounds(), fill_rgb(n))).collect(); + assert_eq!(drawn.len(), 1, "{kind:?} {xf:?}: {drawn:?}"); + assert!(drawn[0].0.is_some_and(|b| near(b, want, 0.1)), "{kind:?} {xf:?}: {drawn:?}"); + assert_eq!(drawn[0].1, Some(rgb), "{kind:?} {xf:?}"); + } + } +} + #[test] fn freeform_points_that_share_a_model_are_written_as_their_mix() { use vectorcraft_color::{Color, Freeform, FreeformPoint, GradientKind}; diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index 00ac16a3fe..fcdcd01f63 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -57,6 +57,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let layers = vectorcraft_effects::WrittenLayers { hidden: set.writes_layers() && !doc.page_knockout, non_printing: set.include_non_printing || set.create_layers, + hidden_objects: false, }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); // Baking stops early when cancelled, leaving a half-baked copy that must not be written. diff --git a/crates/pdf/src/print.rs b/crates/pdf/src/print.rs index 2a3cbf98af..54e85f44b4 100644 --- a/crates/pdf/src/print.rs +++ b/crates/pdf/src/print.rs @@ -187,7 +187,7 @@ pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, D // the art that prints; the layers kept are shown. let mut kept = doc.clone(); keep_layers(&mut kept.layers, set.print_layers); - let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true }; + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept); composite_overprints(&mut d, set); Cow::Owned(d) diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 05107bfb65..4c1f8f0ec2 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -38,7 +38,13 @@ const UNIQUE_PLACEHOLDER: &str = "u_vc_unique_-"; pub(crate) fn export(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>) -> Output { // Live geometry effects (Roughen, Warp, Offset Path, Effect → Pathfinder…) export as their result. - let baked = vectorcraft_effects::bake_document(doc); + // An instance of a symbol whose art has such effects is written as that art placed by the + // instance and then baked, as the canvas draws it; other symbols keep one `` def. + // Hidden layers and objects are written when the options keep them; layers that do not print + // always are. `native` (Preserve Editing) is the document as it is, with its live effects. + let hidden = opts.hidden_layers; + let layers = vectorcraft_effects::WrittenLayers { hidden, non_printing: true, hidden_objects: hidden }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers); let doc = baked.as_ref().unwrap_or(doc); if opts.object_ids != ObjectIds::Unique { return write(doc, opts, native, ""); diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index ea1d5ab95b..b9af2a6c06 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -1061,8 +1061,8 @@ impl Writer<'_> { (self.xf, self.instance_xf) = saved; return; } - if let Some(def) = self.symbol_use(sym, n, *xf) { - let m = self.xf * *xf; + let m = self.xf * *xf; + if let Some(def) = self.symbol_use(sym, n, m) { let tr = if m == Affine::IDENTITY { String::new() } else { format!(" transform=\"{}\"", self.matrix(m)) }; self.line(&format!("")); return; @@ -1103,7 +1103,8 @@ impl Writer<'_> { } } - /// The id of the `` def instance `inst` (transform `xf`) can ``, written on first + /// The id of the `` def instance `inst` can `` with transform `xf` (the ``'s + /// own: the instance's transform after those of the instances it sits in), written on first /// use. `None` when the instance needs its own copy of the art: stained by its fill, or moved /// by a transform under which the def would not look as the canvas paints it ([`Reuse`]). fn symbol_use(&mut self, sym: &vectorcraft_doc::Symbol, inst: &Node, xf: Affine) -> Option { diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index 005a03e0fa..63b9136424 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -299,6 +299,85 @@ fn a_stained_instance_with_a_geometry_effect_keeps_its_stain() { } } +/// Symbol "Moved": a red square whose Transform effect moves it `dx` pt right. +fn add_moved_symbol(d: &mut Document, square: Rect, dx: f64) { + let mut art = Node::path(d.alloc_id(), shapes::rectangle(square), Appearance::basic(Paint::solid(Color::rgb8(255, 0, 0)), Paint::None, 0.0)); + art.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": dx}), visible: true }); + d.symbols.push(Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) }); +} + +/// Instances of a symbol whose art has a geometry effect are written as their art placed by the +/// instance and then baked, where the canvas draws it: moved by the instance, doubled in width +/// (the effect still moves it 100 pt, not 200 pt) and turned. They use no ``, while the +/// instances of a symbol without effects still share one. +#[test] +fn symbol_art_effects_are_written_where_the_canvas_draws_them() { + let mut d = symbol_doc(0.0, &[Affine::translate((30.0, 100.0)), Affine::translate((60.0, 100.0))]); + add_moved_symbol(&mut d, Rect::new(10.0, 10.0, 20.0, 20.0), 100.0); + instance(&mut d, "Moved", Affine::IDENTITY); + instance(&mut d, "Moved", Affine::translate((0.0, 20.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Moved", Affine::translate((-60.0, 40.0)) * Affine::rotate(0.5)); + let svg = export(&d, &ExportOptions::default()); + assert_eq!((svg.matches("