diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 007fcfec09..c74a3e83ab 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -31,3 +31,8 @@ jobs: require-craft-fonts: true craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 run-package-check: true + # The test builds of this workspace's largest crates (engine, ui-egui) need more than the + # VM's 12 GB when two compile at once: the build was killed (exit 137) every night with + # four jobs and again with two. One rustc at a time; it still uses every core. + cargo-build-extra-args: "-j 1" + cargo-test-extra-args: "-j 1" diff --git a/ROADMAP.md b/ROADMAP.md index dabed3eb94..283d7d7dff 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -129,6 +129,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. - 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged. - 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged. - 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged. - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 31ca462799..9f9ba151e9 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -19,11 +19,11 @@ use std::f64::consts::PI; use std::sync::Arc; -use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; +use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint}; use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv}; use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; -use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile}; +use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile}; use crate::live::{BlendOrientation, BlendSpacing, BlendSpec}; use crate::node::{Node, NodeId, NodeKind}; use crate::text::TextObject; @@ -79,7 +79,11 @@ fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) -> /// of the two stops around `t` at the tint and plates between theirs (unlinked when they differ), /// as [`Gradient::sample_with`] walks. fn link_at(g: &Gradient, t: f32) -> (Option, f32, Option<[f32; 4]>) { - let stops = &g.stops; + link_in(&g.stops, t) +} + +/// [`link_at`] of a gradient's `stops`. +fn link_in(stops: &[GradientStop], t: f32) -> (Option, f32, Option<[f32; 4]>) { let link = |s: &GradientStop| (s.swatch.clone(), s.tint, s.plates); let Some(first) = stops.first() else { return (None, 1.0, None) }; if t <= first.offset { @@ -103,15 +107,32 @@ fn link_at(g: &Gradient, t: f32) -> (Option, f32, Option<[f32; 4]>) { stops.last().map_or((None, 1.0, None), link) } -/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). +/// How close two places a gradient changes are for [`common_stops`] to give them one stop (two +/// where either gradient steps there: two of its stops at the same offset). +const STEP: f32 = 1e-4; + +/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). An +/// offset given twice is a step: the second stop paints what `g` steps to there (the last of its +/// stops at one offset within [`STEP`] of it), or what it paints there when it does not step. fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient { let mut out = g.clone(); out.stops = offsets .iter() - .map(|&o| { - let (color, opacity) = g.sample_keep_model(o); - let (swatch, tint, plates) = link_at(g, o); - GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) } + .enumerate() + .map(|(i, &o)| { + let after = i.checked_sub(1).and_then(|j| offsets.get(j)) == Some(&o); + let stepped = + if after { g.stops.windows(2).rfind(|w| w[0].offset == w[1].offset && (w[0].offset - o).abs() < STEP).map(|w| &w[1]) } else { None }; + match stepped { + Some(s) => { + GradientStop { opacity: s.opacity, swatch: s.swatch.clone(), tint: s.tint, plates: s.plates, ..GradientStop::new(o, s.color) } + } + None => { + let (color, opacity) = g.sample_keep_model(o); + let (swatch, tint, plates) = link_at(g, o); + GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) } + } + } }) .collect(); out @@ -130,7 +151,7 @@ fn gradient_breaks(g: &Gradient, out: &mut Vec) { } /// Two gradients of one kind with the same number of stops: as they are when the counts match, -/// else both resampled at every place either changes. +/// else both resampled at every place either changes, with two stops where either steps. fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> { if a.kind != b.kind { return None; @@ -146,8 +167,22 @@ fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> { gradient_breaks(b, &mut offs); offs.retain(|o| o.is_finite()); offs.sort_by(f32::total_cmp); - offs.dedup_by(|x, y| (*x - *y).abs() < 1e-4); - Some((resample_stops(a, &offs), resample_stops(b, &offs))) + offs.dedup_by(|x, y| (*x - *y).abs() < STEP); + let mut steps: Vec = + [a, b].into_iter().flat_map(|g| g.stops.windows(2).filter(|w| w[1].offset == w[0].offset).map(|w| w[0].offset)).collect(); + steps.sort_by(f32::total_cmp); + let mut at = Vec::with_capacity(offs.len() + steps.len()); + let mut k = 0; + for o in offs { + at.push(o); + while steps.get(k).is_some_and(|&s| s <= o - STEP) { + k += 1; + } + if steps.get(k).is_some_and(|&s| (s - o).abs() < STEP) { + at.push(o); + } + } + Some((resample_stops(a, &at), resample_stops(b, &at))) } fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option { @@ -627,12 +662,128 @@ fn reoriented(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wr out } -/// A stroke read along its subpath turned as `o` says: its width profile (whose sides swap when -/// reversed), pen pressure, tilt, bearing and rotation. Its arrowheads stay as they are. -fn reorient_stroke(s: &mut StrokeLayer, o: Orient) { +/// Gradient `g` laid along a closed subpath that now starts at fraction `s` of its length: the +/// part from `s` on runs first, then the part before it, stepping where the old start now falls. +/// The stops follow its colors as [`Gradient::span`] reads them, mixed linearly, and run once. +/// One of `g`'s own stops keeps its swatch link (each stop of a step its own), and a stop between +/// two of them the link [`link_at`] reads there. +fn gradient_from(g: &Gradient, s: f32) -> Gradient { + // A hue gradient that reflects unrolls through its curve, whose stops have no links: the links + // come from its own stops unrolled as a Classic gradient's, which keep them. + let hue_reflect = g.is_spread() && g.spread == GradientSpread::Reflect && g.method.is_hue(); + let classic = hue_reflect.then(|| Gradient { method: GradientMethod::Classic, ..g.clone() }); + let g = g.unrolled(); + let mut own = classic.as_ref().map_or_else(|| g.stops.clone(), |c| c.unrolled().stops.clone()); + own.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + let mut stops = Vec::new(); + // The part from `s` to the end runs first, then the part up to `s`. + for (from, to, at) in [(s, 1.0, 0.0), (0.0, s, 1.0 - s)] { + // The first of `own` not yet matched: the parts' stops run in order, so the links are + // found in one pass. + let mut j = 0; + for (k, st) in g.span(from, to).stops.into_iter().enumerate() { + let p = from + (to - from) * st.offset; + while own.get(j).is_some_and(|o| o.offset <= p - STEP) { + j += 1; + } + let same = |i: usize| own.get(i).is_some_and(|o| o.color == st.color && o.opacity == st.opacity); + let near = (j..own.len()).take_while(|&i| own.get(i).is_some_and(|o| o.offset < p + STEP)); + let mut hit = near.clone().find(|&i| same(i)); + // A part starting on a step starts with the color after it, so its first stop takes + // the link of the step's last stop of that color. + if k == 0 + && let Some(at) = hit.and_then(|i| own.get(i)).map(|o| o.offset) + { + hit = near.filter(|&i| own.get(i).is_some_and(|o| o.offset == at) && same(i)).last().or(hit); + } + let (swatch, tint, plates) = match hit.and_then(|i| own.get(i).map(|o| (i, o))) { + Some((i, o)) => { + j = i + 1; + (o.swatch.clone(), o.tint, o.plates) + } + None => link_in(own.get(j.saturating_sub(1)..(j + 1).min(own.len())).unwrap_or_default(), p), + }; + stops.push(GradientStop { offset: at + (to - from) * st.offset, swatch, tint, plates, ..st }); + } + } + Gradient { stops, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1, ..g.into_owned() } +} + +/// Dash pattern `d` read along subpaths of lengths `lens` turned as `o` says. Reversed, the +/// pattern runs backwards: from the start of a dash, that is the dash and then the other entries +/// in reverse order. Exact dashes also start where the turned subpaths now start. The pattern +/// restarts on every subpath at the one offset, so the offset moves only when every subpath needs +/// the same one (as subpaths whose lengths differ by whole periods do); dashes fitted to corners +/// ignore the offset, which stays as it is. A dash pattern starts once per subpath, so on a closed +/// subpath started elsewhere the dashes match the key's as far as its own start, and past it run +/// on without restarting there. +fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) { + if !d.is_dashed() || !d.offset.is_finite() { + return; + } + let mut pat = d.pattern.clone(); + // An odd pattern repeats twice per period (dash, gap, dash / gap, dash, gap). + if pat.len() % 2 == 1 { + pat.extend_from_within(..); + } + let period: f64 = pat.iter().sum(); + // Where along the key's own subpath the turned one starts (a closed one wraps round). A + // closed one reversed from its own start runs back from its end. + let at = match (o.closed, o.seam()) { + (true, s) if s == 0.0 && o.reversed => 1.0, + (true, s) => s, + (false, _) => o.start, + }; + let first = pat.first().copied().unwrap_or(0.0); + let offset = |len: f64| if o.reversed { first - at * len - d.offset } else { d.offset + at * len }; + let offsets: Vec = lens.iter().map(|&len| offset(len)).collect(); + let agree = offsets.first().is_some_and(|&a| { + offsets.iter().all(|&b| { + let r = (b - a).rem_euclid(period); + r.is_finite() && r.min(period - r) <= 1e-6 + }) + }); + if o.reversed { + if let Some(rest) = pat.get_mut(1..) { + rest.reverse(); + } + d.pattern = pat; + } + if let Some(&off) = offsets.first().filter(|_| agree && !d.align_corners) { + d.offset = off; + } +} + +/// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width +/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes, +/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as +/// they are. +fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) { if o.is_identity() { return; } + if let Some(d) = &mut s.dash { + reorient_dash(d, o, lens); + } + let along = s.gradient_mode == StrokeGradientMode::Along; + if s.path_gradient().is_some() + && let Paint::Gradient(g) = &mut s.paint + { + let start = along && o.seam() > 0.0; + if start { + g.gradient = gradient_from(&g.gradient, o.seam() as f32); + } + // Stops that reflect an even number of times read the same either way. + let (spread, runs) = g.gradient.painted_spread(); + let reverse = o.reversed && !(spread == GradientSpread::Reflect && runs % 2 == 0); + if reverse { + g.gradient.reverse(); + } + if start || reverse { + // The turned gradient is no longer the swatch's. + g.swatch = None; + } + } let same = |v: f64| v; if let Some(p) = &mut s.profile { let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect(); @@ -676,9 +827,11 @@ fn reorient_strokes(n: &mut Node, o: Orient) { if o.is_identity() { return; } + let lens: Vec = + node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default(); for it in n.appearance.items.iter_mut() { if let AppearanceItem::Stroke(s) = it { - reorient_stroke(s, o); + reorient_stroke(s, o, &lens); if o.reversed && !o.closed { std::mem::swap(&mut s.start_arrow, &mut s.end_arrow); s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0); @@ -709,9 +862,11 @@ pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) { if o.is_identity() || !turns.all(|t| t.same_turn(&o)) { return; } + let lens: Vec = + node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default(); for it in n.appearance.items.iter_mut() { if let AppearanceItem::Stroke(s) = it { - reorient_stroke(s, o); + reorient_stroke(s, o, &lens); } } } @@ -2791,6 +2946,275 @@ mod tests { assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation); } + #[test] + fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() { + let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| { + let mut ap = Appearance::default(); + ap.set_stroke(Paint::solid(Color::BLACK)); + if let Some(s) = ap.stroke_mut() { + edit(s); + } + Node::path(NodeId(1), path, ap) + }; + let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke")); + // How light the stroke's gradient is at `u` (0 black, 3 white). + let light = |s: &StrokeLayer, u: f32| match &s.paint { + Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::(), + p => panic!("a gradient: {p:?}"), + }; + // Whether dash pattern `d` draws a dash `at` this far along its subpath. + let dash_at = |d: &Dash, at: f64| { + let p = if d.pattern.len() % 2 == 1 { d.pattern.repeat(2) } else { d.pattern.clone() }; + let mut x = (at + d.offset).rem_euclid(p.iter().sum()); + for (i, v) in p.iter().enumerate() { + if x < *v { + return i % 2 == 0; + } + x -= v; + } + false + }; + let graded = |mode: StrokeGradientMode| { + move |s: &mut StrokeLayer| { + s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + s.gradient_mode = mode; + s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false }); + } + }; + // An open key clicked at its last anchor runs the other way: a gradient along it or across + // it (whose sides swap) runs the other way too, and its dashes are read from its end. + let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false)); + let plain = keyed(line(0.0), &|_| {}); + for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] { + let key = keyed(line(100.0), &graded(mode)); + let s = stroke(&Lerp::new(&plain, &key, (None, Some(1))).at(1.0)); + assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{mode:?}: {:?}", s.paint); + let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default()); + for k in 1..130 { + let u = k as f64 / 10.0 + 0.03; + assert_eq!(dash_at(&d, u), dash_at(&own, 13.0 - u), "at {u}: {d:?}"); + } + } + // A closed key started half way round starts its gradient along it there too, stepping + // where its own start was, and its dashes start there. + let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)); + let key = keyed(square(100.0), &graded(StrokeGradientMode::Along)); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0)); + for (u, want) in [(0.0, 1.5), (0.25, 0.75), (0.499, 0.0), (0.501, 3.0), (0.75, 2.25), (1.0, 1.5)] { + assert!((light(&s, u) - want).abs() < 0.02, "at {u}: {} for {want}: {:?}", light(&s, u), s.paint); + } + let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default()); + for k in 1..200 { + let u = k as f64 / 10.0 + 0.03; + assert_eq!(dash_at(&d, u), dash_at(&own, u + 20.0), "at {u}: {d:?}"); + } + // A closed key that winds the other way runs the other way from the same anchor: its + // dashes are read back from the end of its own subpath, which is 40 long and not a whole + // number of periods. + let wound = |x: f64| { + let mut p = square(x); + for sp in &mut p.subpaths { + sp.reverse(); + } + p + }; + let back = keyed(wound(100.0), &graded(StrokeGradientMode::Along)); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &back, (Some(0), Some(0))).at(1.0)); + let (own, d) = (stroke(&back).dash.unwrap_or_default(), s.dash.unwrap_or_default()); + for k in 1..400 { + let u = k as f64 / 10.0 + 0.03; + assert_eq!(dash_at(&d, u), dash_at(&own, 40.0 - u), "at {u}: {d:?}"); + } + // Stops that reflect twice read the same either way; a link to a swatch stays. + let reflected = keyed(line(100.0), &|s| { + let mut g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::default() }; + g.stops[1].swatch = Some("Ink".into()); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + assert_eq!(stroke(&Lerp::new(&plain, &reflected, (None, Some(1))).b).paint, stroke(&reflected).paint); + let linked = keyed(square(100.0), &|s| { + let mut g = Gradient::default(); + g.stops[1].swatch = Some("Ink".into()); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &linked, (Some(0), Some(2))).b); + let links = match &s.paint { + Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some("Ink")).map(|st| st.offset).collect::>(), + p => panic!("a gradient: {p:?}"), + }; + assert!(links.contains(&0.5), "the stop the old start ended on keeps its link: {:?}", s.paint); + // Each stop of a step keeps its own link. + let step = keyed(square(100.0), &|s| { + let mut g = Gradient::default(); + let (mut before, mut after) = (GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.25, Color::WHITE)); + (before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into())); + g.stops.splice(1..1, [before, after]); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &step, (Some(0), Some(2))).b); + let links = match &s.paint { + Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.offset == 0.75).map(|st| st.swatch.clone()).collect::>(), + p => panic!("a gradient: {p:?}"), + }; + assert_eq!(links, vec![Some("Ink".into()), Some("Paper".into())], "{:?}", s.paint); + // A step of one color between two swatches, where the turned subpath now starts: the + // start takes the link after the step and the end the link before it. + let seam_step = keyed(square(100.0), &|s| { + let mut g = Gradient::default(); + let gray = Color::rgb8(128, 128, 128); + let (mut before, mut after) = (GradientStop::new(0.5, gray), GradientStop::new(0.5, gray)); + (before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into())); + g.stops.splice(1..1, [before, after]); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &seam_step, (Some(0), Some(2))).b); + let ends = match &s.paint { + Paint::Gradient(g) => (g.gradient.stops.first().map(|st| st.swatch.clone()), g.gradient.stops.last().map(|st| st.swatch.clone())), + p => panic!("a gradient: {p:?}"), + }; + assert_eq!(ends, (Some(Some("Paper".into())), Some(Some("Ink".into()))), "{:?}", s.paint); + // A hue gradient that reflects keeps its links on the repeated stops. + let hue = keyed(square(100.0), &|s| { + let (mut red, mut blue) = + (GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 })); + (red.swatch, blue.swatch) = (Some("Ink".into()), Some("Paper".into())); + let g = Gradient { + method: GradientMethod::HueClockwise, + spread: GradientSpread::Reflect, + repeats: 2, + ..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![red, blue]) + }; + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue, (Some(0), Some(2))).b); + let linked = |name: &str| match &s.paint { + Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some(name)).map(|st| st.offset).collect::>(), + p => panic!("a gradient: {p:?}"), + }; + assert!(linked("Paper").contains(&0.0) && linked("Paper").contains(&1.0), "{:?}", s.paint); + assert!(linked("Ink").contains(&0.5), "{:?}", s.paint); + // Two stops of one color at one place keep their own links, in reverse in a mirrored run. + let hue_step = keyed(square(100.0), &|s| { + let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 }; + let (mut before, mut after) = (GradientStop::new(0.5, green), GradientStop::new(0.5, green)); + (before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into())); + let stops = vec![ + GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), + before, + after, + GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }), + ]; + let g = Gradient { + method: GradientMethod::HueClockwise, + spread: GradientSpread::Reflect, + repeats: 2, + ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops) + }; + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_step, (Some(0), Some(2))).b); + // The links at `u` in order, a link repeated by the next stop listed once. + let links_at = |u: f32| match &s.paint { + Paint::Gradient(g) => { + let mut links = + g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::>(); + links.dedup(); + links + } + p => panic!("a gradient: {p:?}"), + }; + assert_eq!(links_at(0.25), vec!["Paper".to_string(), "Ink".to_string()], "{:?}", s.paint); + assert_eq!(links_at(0.75), vec!["Ink".to_string(), "Paper".to_string()], "{:?}", s.paint); + // Where two runs meet, each run's stops keep their own links. + let hue_end = keyed(square(100.0), &|s| { + let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 }; + let (mut a, mut b) = (GradientStop::new(1.0, green), GradientStop::new(1.0, green)); + (a.swatch, b.swatch) = (Some("Ink".into()), Some("Paper".into())); + let g = Gradient { + method: GradientMethod::HueClockwise, + spread: GradientSpread::Reflect, + repeats: 2, + ..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), a, b]) + }; + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_end, (Some(0), Some(1))).b); + let links_at = |u: f32| match &s.paint { + Paint::Gradient(g) => { + let mut links = + g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::>(); + links.dedup(); + links + } + p => panic!("a gradient: {p:?}"), + }; + assert_eq!(links_at(0.25), vec!["Ink".to_string(), "Paper".to_string(), "Ink".to_string()], "{:?}", s.paint); + // Blended with a gradient of other stops, the steps keep that step. + let three = keyed(square(0.0), &|s| { + let mut g = Gradient::default(); + g.stops.insert(1, GradientStop::new(0.5, Color::BLACK)); + s.paint = Paint::Gradient(Box::new(GradientPaint::new(g))); + s.gradient_mode = StrokeGradientMode::Along; + }); + let s = stroke(&Lerp::new(&three, &key, (Some(0), Some(2))).at(0.75)); + assert!(light(&s, 0.501) - light(&s, 0.499) > 1.5, "{:?}", s.paint); + // Subpaths whose lengths call for different dash offsets keep the offset. + let rings = |x: f64, turn: usize| { + let mut inner = shapes::rectangle(Rect::new(x, 20.0, x + 7.0, 27.0)).subpaths.remove(0); + inner.anchors.rotate_left(turn); + PathData::new(vec![square(x).subpaths.remove(0), inner]) + }; + let key = keyed(rings(100.0, 2), &graded(StrokeGradientMode::Along)); + let blend = Lerp::new(&keyed(rings(0.0, 0), &|_| {}), &key, (Some(0), Some(2))); + let turned = match &blend.shape { + Shape::Path { pair, .. } => pair.orient.1, + _ => panic!("a path blend"), + }; + assert!((turned.seam() - 0.5).abs() < 1e-9, "both rings turn half way round: {turned:?}"); + let s = stroke(&blend.at(1.0)); + assert_eq!(s.dash.map(|d| d.offset), Some(0.75)); + } + + #[test] + fn gradients_of_other_stop_counts_keep_their_steps() { + let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }; + let stepped = Gradient::new( + vectorcraft_color::GradientKind::Linear, + vec![ + GradientStop::new(0.0, Color::WHITE), + GradientStop::new(0.5, Color::BLACK), + GradientStop::new(0.5, Color::WHITE), + GradientStop::new(0.50015, red), + GradientStop::new(1.0, Color::BLACK), + ], + ); + let (a, b) = common_stops(&stepped, &Gradient::default()).unwrap_or_else(|| panic!("one kind")); + let at = |g: &Gradient| g.stops.iter().map(|s| (s.offset, s.color)).collect::>(); + assert_eq!(at(&a), vec![(0.0, Color::WHITE), (0.5, Color::BLACK), (0.5, Color::WHITE), (0.50015, red), (1.0, Color::BLACK)]); + assert_eq!(b.stops.len(), 5); + assert_eq!(b.stops.get(1).map(|s| s.color), b.stops.get(2).map(|s| s.color), "a gradient without the step paints one color there"); + // A gradient with two stops close to the other's step, but no step of its own, does not step there. + let close = Gradient::new( + vectorcraft_color::GradientKind::Linear, + vec![ + GradientStop::new(0.0, Color::WHITE), + GradientStop::new(0.5, Color::BLACK), + GradientStop::new(0.50005, red), + GradientStop::new(1.0, Color::BLACK), + ], + ); + let (_, b) = common_stops(&stepped, &close).unwrap_or_else(|| panic!("one kind")); + assert_eq!(b.stops.get(1).map(|s| s.color), Some(Color::BLACK)); + assert_eq!(b.stops.get(2).map(|s| s.color), Some(Color::BLACK), "{:?}", b.stops); + } + #[test] fn odd_dash_blends_to_solid_with_closed_gaps() { let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap(); diff --git a/crates/doc/src/graph.rs b/crates/doc/src/graph.rs index 2746390b86..e9507d25a8 100644 --- a/crates/doc/src/graph.rs +++ b/crates/doc/src/graph.rs @@ -379,6 +379,22 @@ pub struct SeriesPaint { /// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal. #[serde(skip_serializing_if = "Option::is_none")] pub blend: Option, + /// Object opacity (0..1) of the series group itself, taken from the transparency set on the group. Absent: fully opaque. + /// Graph labels keep none. + #[serde(skip_serializing_if = "Option::is_none")] + pub group_opacity: Option, + /// Object blend mode of the series group itself, as [`Self::group_opacity`]. Absent: Normal. + #[serde(skip_serializing_if = "Option::is_none")] + pub group_blend: Option, + /// Isolate Blending of the series group itself, as [`Self::group_opacity`]. Absent: off. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub group_isolate: bool, + /// Knockout Group state of the series group itself, as [`Self::group_opacity`]. Absent: neutral. + #[serde(skip_serializing_if = "Option::is_none")] + pub group_knockout: Option, + /// Knockout Shape of the series group itself, as [`Self::group_opacity`]. Absent: off. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub group_knockout_shape: bool, /// A gradient in [`Self::fill`] is placed relative to the unit box (0, 0)–(1, 1), and each mark takes it on its own /// geometric bounds. False: the gradient is in document coordinates, and every mark takes it unchanged. #[serde(skip_serializing_if = "std::ops::Not::not")] @@ -527,6 +543,10 @@ pub struct GraphSpec { /// Bounds of the art when it was last generated (detects moves/scales of the graph group). #[serde(skip_serializing_if = "Option::is_none")] pub placed: Option, + /// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph + /// group are measured on these when present; graphs saved without them are measured on [`Self::placed`]. + #[serde(skip_serializing_if = "Option::is_none")] + pub placed_art: Option, } fn at_most_one(n: &usize) -> bool { @@ -610,6 +630,32 @@ impl GraphSpec { } } +/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend +/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these. +pub fn art_bounds(children: &[std::sync::Arc]) -> Option { + children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b)) +} + +/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type +/// gives its own bounds, so a clipping group gives the bounds of its clip. +fn art_bounds_of(n: &crate::Node) -> (Option, bool) { + if matches!(n.kind, crate::NodeKind::Text(_)) { + return (None, true); + } + let Some(children) = n.children() else { return (n.geometric_bounds(), false) }; + let mut bounds: Option = None; + let mut had_type = false; + for c in children { + let (b, t) = art_bounds_of(c); + had_type |= t; + bounds = match (bounds, b) { + (Some(a), Some(b)) => Some(a.union(b)), + (a, b) => a.or(b), + }; + } + if had_type { (bounds, true) } else { (n.geometric_bounds(), false) } +} + impl Default for GraphSpec { fn default() -> Self { Self { @@ -659,6 +705,7 @@ impl Default for GraphSpec { connect_points: true, edge_to_edge: false, placed: None, + placed_art: None, } } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c286492236..8507b50754 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -55,6 +55,7 @@ mod pixels; pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick}; pub mod placed_document; pub mod plugin_data; +pub mod ppi; pub mod profiles; pub mod puppet; pub mod range; diff --git a/crates/doc/src/ppi.rs b/crates/doc/src/ppi.rs new file mode 100644 index 0000000000..5c3bd24b53 --- /dev/null +++ b/crates/doc/src/ppi.rs @@ -0,0 +1,287 @@ +//! Image resolution metadata (pixels per inch) in the formats the image decoder reads: PNG `pHYs`, +//! JPEG JFIF density or EXIF, TIFF and WebP EXIF resolution tags, and BMP pixels per metre. An image +//! converted to PNG keeps it as a `pHYs` chunk ([`with_png_resolution`]). + +const INCH_M: f64 = 0.0254; +const INCH_CM: f64 = 2.54; + +/// Is `bytes` a PNG, JPEG, TIFF, WebP or BMP file, the formats [`resolution`] reads? +pub fn reads(bytes: &[u8]) -> bool { + bytes.starts_with(b"\x89PNG\r\n\x1a\n") + || bytes.starts_with(&[0xff, 0xd8]) + || bytes.starts_with(b"II*\0") + || bytes.starts_with(b"MM\0*") + || (bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP") + || bytes.starts_with(b"BM") +} + +/// The resolution a PNG, JPEG, TIFF, WebP or BMP file declares as (horizontal, vertical) ppi, each +/// from 1 to 100,000; `None` when it declares none (or only an aspect ratio), and for other files. +pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { + let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + png(bytes) + } else if bytes.starts_with(&[0xff, 0xd8]) { + jpeg(bytes) + } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") { + tiff(bytes) + } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + webp(bytes) + } else if bytes.starts_with(b"BM") { + bmp(bytes) + } else { + None + }; + r.filter(|(x, y)| [*x, *y].iter().all(|v| v.is_finite() && (1.0..=100_000.0).contains(v))) +} + +/// `n` bytes at `at` (`None` past the end; offsets come from the file, so no overflow either). +fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { + b.get(at..at.checked_add(n)?) +} +fn bytes(b: &[u8], at: usize) -> Option<[u8; N]> { + slice(b, at, N)?.try_into().ok() +} +fn be16(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u16::from_be_bytes) +} +fn be32(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u32::from_be_bytes) +} +fn le32(b: &[u8], at: usize) -> Option { + bytes(b, at).map(u32::from_le_bytes) +} + +/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when +/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi). +fn per_metre(ppm: u32) -> f64 { + let v = ppm as f64 * INCH_M; + let whole = v.round(); + if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v } +} + +/// PNG chunks after the signature: (type, data). +pub fn png_chunks(b: &[u8]) -> impl Iterator { + let mut at = 8; + std::iter::from_fn(move || { + let len = be32(b, at)? as usize; + let ty = slice(b, at + 4, 4)?; + let data = slice(b, at + 8, len)?; + at = at.checked_add(12 + len)?; + Some((ty, data)) + }) +} + +fn png(b: &[u8]) -> Option<(f64, f64)> { + let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?; + // Unit 1 = metre; 0 only gives the pixel aspect ratio. + (d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0)))) +} + +fn jpeg(b: &[u8]) -> Option<(f64, f64)> { + let (mut jfif, mut exif) = (None, None); + let mut at = 2; + while at + 4 <= b.len() && b[at] == 0xff { + let marker = b[at + 1]; + // 0xff fill bytes pad between segments. + if marker == 0xff { + at += 1; + continue; + } + if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) { + at += 2; + continue; + } + // Start of scan or end of image: no more metadata. + if marker == 0xda || marker == 0xd9 { + break; + } + let len = be16(b, at + 2)? as usize; + let seg = slice(b, at + 4, len.checked_sub(2)?)?; + match marker { + 0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => { + let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64); + jfif = match seg[7] { + 1 => Some((x, y)), + 2 => Some((x * INCH_CM, y * INCH_CM)), + _ => None, + }; + } + 0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]), + _ => {} + } + at += 2 + len; + } + jfif.or(exif) +} + +/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit, as (horizontal, vertical) ppi +/// in the stored pixels' axes, unchecked; `None` without an absolute unit. +pub fn tiff(b: &[u8]) -> Option<(f64, f64)> { + let le = b.starts_with(b"II"); + let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes }); + let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes }); + let ifd = u32_at(4)? as usize; + let (mut x, mut y, mut unit) = (None, None, 2); + for i in 0..u16_at(ifd)? as usize { + let e = ifd.checked_add(2 + i * 12)?; + let rational = || -> Option { + let at = u32_at(e + 8)? as usize; + let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?); + (d != 0).then(|| n as f64 / d as f64) + }; + match u16_at(e)? { + 282 => x = rational(), + 283 => y = rational(), + 296 => unit = u16_at(e + 8)?, + _ => {} + } + } + let k = match unit { + 2 => 1.0, + 3 => INCH_CM, + _ => return None, + }; + let x = x?; + Some((x * k, y.unwrap_or(x) * k)) +} + +fn webp(b: &[u8]) -> Option<(f64, f64)> { + let mut at = 12; + while at + 8 <= b.len() { + let len = le32(b, at + 4)? as usize; + let data = slice(b, at + 8, len)?; + if &b[at..at + 4] == b"EXIF" { + return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data)); + } + at += 8 + len + (len & 1); + } + None +} + +fn bmp(b: &[u8]) -> Option<(f64, f64)> { + // BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28. + if le32(b, 14)? < 40 { + return None; + } + let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre); + Some((ppm(38)?, ppm(42)?)) +} + +/// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores). +pub fn pixels_per_metre(ppi: f64) -> u32 { + (ppi / INCH_M).round().clamp(1.0, u32::MAX as f64) as u32 +} + +/// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another. +fn crc32(parts: &[&[u8]]) -> u32 { + let mut crc = !0u32; + for &b in parts.iter().flat_map(|p| p.iter()) { + crc ^= u32::from(b); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xEDB8_8320 & u32::from(crc & 1 != 0).wrapping_neg()); + } + } + !crc +} + +/// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch. +pub fn phys_chunk(x: f64, y: f64) -> Vec { + let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes()); + // x, y, unit 1 = metre. + let data = [x.as_slice(), y.as_slice(), &[1]].concat(); + let mut out = Vec::with_capacity(21); + out.extend_from_slice(&9u32.to_be_bytes()); + out.extend_from_slice(b"pHYs"); + out.extend_from_slice(&data); + out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes()); + out +} + +/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced). +pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec { + let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() }; + let chunk = phys_chunk(x, y); + let mut out = Vec::with_capacity(png.len() + chunk.len()); + out.extend_from_slice(head); + out.extend_from_slice(&chunk); + let mut at = head.len(); + while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) { + if chunk.get(4..8) != Some(b"pHYs") { + out.extend_from_slice(chunk); + } + at += chunk.len(); + } + out.extend_from_slice(png.get(at..).unwrap_or_default()); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png_of(w: u32, h: u32) -> Vec { + let mut out = Vec::new(); + image::RgbaImage::new(w, h).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + /// The `pHYs` chunk carries the CRC a PNG reader checks, and replaces the one already there. + #[test] + fn a_png_takes_its_resolution_and_still_decodes() { + let png = png_of(4, 3); + assert_eq!(resolution(&png), None); + let tagged = with_png_resolution(&png, (300.0, 150.0)); + assert_eq!(resolution(&tagged), Some((300.0, 150.0))); + let again = with_png_resolution(&tagged, (72.0, 72.0)); + assert_eq!(resolution(&again), Some((72.0, 72.0)), "replaced, not duplicated"); + assert_eq!(again.len(), tagged.len()); + let img = image::load_from_memory(&again).unwrap(); + assert_eq!((img.width(), img.height()), (4, 3)); + // Every PNG ends with this IEND chunk CRC. + assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082); + } + + /// RIFF chunk `ty` holding `data`, padded to an even length. + fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec { + let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat(); + if data.len() % 2 == 1 { + out.push(0); + } + out + } + + fn webp_of(chunks: &[Vec]) -> Vec { + let body = chunks.concat(); + let size = u32::try_from(body.len() + 4).unwrap(); + [b"RIFF".as_slice(), &size.to_le_bytes(), b"WEBP", &body].concat() + } + + /// A WebP's EXIF chunk is found past an odd-length chunk and its padding byte, and a chunk whose + /// length runs past the end of the file (up to `u32::MAX`, more than a 32-bit `usize` can add to + /// an offset) gives no resolution. + #[test] + fn a_webp_reads_its_exif_and_rejects_a_chunk_past_the_end() { + // Little-endian TIFF: two IFD0 entries, XResolution 300/1 at offset 38 and ResolutionUnit inch. + let mut tiff = b"II*\0".to_vec(); + tiff.extend_from_slice(&8u32.to_le_bytes()); + tiff.extend_from_slice(&2u16.to_le_bytes()); + for (tag, ty, value) in [(282u16, 5u16, 38u32), (296, 3, 2)] { + tiff.extend_from_slice(&tag.to_le_bytes()); + tiff.extend_from_slice(&ty.to_le_bytes()); + tiff.extend_from_slice(&1u32.to_le_bytes()); + tiff.extend_from_slice(&value.to_le_bytes()); + } + tiff.extend_from_slice(&0u32.to_le_bytes()); + tiff.extend_from_slice(&300u32.to_le_bytes()); + tiff.extend_from_slice(&1u32.to_le_bytes()); + let exif = [b"Exif\0\0".as_slice(), &tiff].concat(); + let exif_len = u32::try_from(exif.len()).unwrap(); + let ok = webp_of(&[riff_chunk(b"VP8X", 3, &[0, 0, 0]), riff_chunk(b"EXIF", exif_len, &exif)]); + assert_eq!(resolution(&ok), Some((300.0, 300.0))); + + for len in [u32::MAX, u32::MAX - 7, 1_000] { + let bad = webp_of(&[riff_chunk(b"VP8X", len, &[0; 10])]); + assert_eq!(resolution(&bad), None, "chunk length {len}"); + } + } +} diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index e7e74972e6..9934ea026e 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -85,7 +85,7 @@ pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art, - outline_text, reshape, + outline_text, paint_type_piece, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 5e86dafe96..70e5994cb5 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -508,6 +508,20 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::Bez (runs, all, layout.bounds, colours) } +/// Paint `piece`, a piece of type's outline in text space (glyphs, ruby glyphs or an underline or +/// strikethrough bar), with `style`, the fills and strokes of its run, and place it in the document +/// by `xf`, the type's transform, as the renderer paints the run: its unplaced gradients are fixed +/// to `bounds`, the layout's bounds in text space, so every piece of the type shows the one +/// gradient fitted across the whole layout, and the transform also scales its stroke weights and +/// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and +/// move with the type. +pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) { + let mut ap = style.appearance(); + ap.pin_gradients(bounds); + piece.appearance = ap.into(); + piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }); +} + /// Type as glyph outlines in document space: one path per run with the run's fill and stroke, /// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole /// outline with the object's items below the characters under them and the others over them, as @@ -520,7 +534,6 @@ pub fn outline_text(n: &Node) -> Option { let NodeKind::Text(t) = &n.kind else { return None }; let (runs, all, bounds, colours) = laid_out(t); let path = |bp: &kurbo::BezPath| PathData::from_bezpath(bp).transformed(t.xf); - let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() }; let mut children: Vec> = vec![]; for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { // Colour glyphs paint themselves, under their run's fill, as the renderer paints them. @@ -528,10 +541,8 @@ pub fn outline_text(n: &Node) -> Option { if bp.elements().is_empty() { continue; } - let mut ap = run.style.appearance(); - ap.pin_gradients(bounds); - let mut piece = Node::path(n.id, PathData::from_bezpath(bp), ap); - piece.transform(t.xf, scaling); + let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default()); + paint_type_piece(&mut piece, &run.style, bounds, t.xf); children.push(Arc::new(piece)); } if !n.appearance.items.is_empty() && !all.elements().is_empty() { diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index e9a8f2a0a7..a9c9482d1d 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -6,7 +6,7 @@ use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; -use vectorcraft_three_d::{Edge, Revolve}; +use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; use crate::solids::wireframe::WireFace; use crate::solids::{ @@ -338,34 +338,80 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { /// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with /// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when /// the surface it is cast from is past the limits. -fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result, String> { +/// +/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the +/// surface is swept again for its shadow alone. +fn shadow_of( + id: NodeId, + fx: &Effect, + path: &PathData, + item: &AppearanceItem, + b: Rect, + options: Revolve, + kept: Option, +) -> Result, String> { let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) }; let (_, opacity, blend) = paint_of(item); if opacity <= 0.0 { return Ok(None); } let mut caster = vectorcraft_three_d::ShadowCaster::new(); - caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?; + cast_surface(&mut caster, path, b, options, kept)?; Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend })) } +/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces +/// its shadow is cast from ([`surface`])? +fn casts(fx: &Effect, opacity: f32) -> bool { + opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some() +} + +/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was +/// drawn, or without them, the surface swept for its shadow alone. +fn cast_surface( + caster: &mut vectorcraft_three_d::ShadowCaster, + path: &PathData, + b: Rect, + options: Revolve, + kept: Option, +) -> Result, String> { + match kept { + Some(kept) => caster.add_solid(kept), + None => { + #[cfg(test)] + crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options) + } + } +} + /// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one, /// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque, /// in its paint's blending mode, and its opacity mask and blending mode apply to that part /// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the -/// limits. -fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result>, String> { +/// limits. `kept` holds, member by member, the faces each surface drawn kept for its shadow +/// ([`surface`]); a member without them is swept again for its shadow alone. +fn group_shadow( + id: NodeId, + fx: &Effect, + shapes: &[Profile], + b: Rect, + options: Revolve, + kept: Vec>, +) -> Result>, String> { let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) }; let mut caster = vectorcraft_three_d::ShadowCaster::new(); let mut cast = vec![]; + let mut kept = kept.into_iter(); for s in shapes { + let kept = kept.next().flatten(); let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue }; // A member whose surface is fully transparent casts nothing. let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend }; if ink.opacity <= 0.0 { continue; } - let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?; + let faces = cast_surface(&mut caster, &s.path, b, options, kept)?; cast.push((s.scopes.as_slice(), ink, faces)); } Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes))) @@ -377,7 +423,8 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R /// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face /// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the /// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): -/// a face with a part of a graphic is a group of the face and that part. +/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep +/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). #[allow(clippy::too_many_arguments)] fn surface( doc: Option<&Document>, @@ -391,11 +438,18 @@ fn surface( blend: vectorcraft_doc::color::BlendMode, expand: bool, copies: &mut Copies, -) -> Option<(Vec, Node)> { + cast: bool, +) -> Option<(Vec, Node, Option)> { + #[cfg(test)] + crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); // A loaded file or a profile edited past the limits keeps drawing its source path instead // of crashing the frame. Commands validate the same evaluator and report its errors. if fx.id == CLASSIC_REVOLVE { - let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?; + let (facets, kept) = if cast { + vectorcraft_three_d::revolve_facets_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))? + } else { + (vectorcraft_three_d::revolve_facets(path, b, options).ok()?, None) + }; copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint)); if copies.surfaces > MAX_PAINT_COPIES { return None; @@ -405,10 +459,14 @@ fn surface( let drawn = facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect(); let p = merged_params(&fx.id, &fx.params); - return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p))); + return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept)); } let colored = options.light_color != [1.0; 3] || options.lights.is_some(); - let faces = vectorcraft_three_d::revolve(path, b, options).ok()?; + let (faces, kept) = if cast { + vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))? + } else { + (vectorcraft_three_d::revolve(path, b, options).ok()?, None) + }; copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint)); if copies.surfaces > MAX_PAINT_COPIES { return None; @@ -532,7 +590,7 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some((keys, group)) + Some((keys, group, kept)) } /// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the @@ -549,8 +607,9 @@ fn in_order(items: Vec, order: &[usize]) -> Vec { order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect() } -/// A surface of one object about the bounds of `path`, built with options derived from `fx`. -/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`. +/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and +/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count +/// [`surface`] adds to; its graphics take the symbols of `doc`. fn object_surface( doc: Option<&Document>, n: &Node, @@ -559,10 +618,11 @@ fn object_surface( item: &AppearanceItem, expand: bool, copies: &mut Copies, -) -> Option { +) -> Option<(Node, Option)> { let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); - surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art) + let cast = casts(fx, opacity); + surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept)) } /// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of @@ -692,7 +752,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result, n: &Node) -> Result, n: &Node, expand: bool) -> Option { let paints = solid_paints(n); let item = surface_item(&paints)?; let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; + let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?; if let Some(b) = path.bounds() - && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()? + && let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()? { children.push(Arc::new(shadow)); } @@ -790,10 +850,10 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let fx = item.effects().get(index)?; let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original)); let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); - let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; + let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?; art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect(); if let Some(b) = p.bounds() - && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()? + && let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()? { shadow.appearance.effects = art.appearance.effects.clone(); shadows.push(Arc::new(shadow)); @@ -942,21 +1002,28 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id)); let mut copies = Copies::default(); let mut surfaces = vec![]; + // The faces each member's surface kept for the shadow, member by member. + let mut kept = vec![]; let mut opaque = true; // The graphics go once, on the side of the member with the longest profile. Without graphics // no member is measured for them. let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty(); let longest = if mapped { graphics_member(&shapes, b, options) } else { None }; for (k, s) in shapes.iter().enumerate() { - let Some(item) = surface_item(&s.items) else { continue }; + let Some(item) = surface_item(&s.items) else { + kept.push(None); + continue; + }; // The opacity and blending of the member and the groups it is in apply through its scopes. let (paint, opacity, blend) = paint_of(item); opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); // A member with transparency of its own keeps every face, as a transparent object does. let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); - let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?; + let cast = casts(fx, opacity * s.opacity); + let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; surfaces.push((depths, art, s.scopes.as_slice())); + kept.push(faces); } if surfaces.is_empty() { return None; @@ -1057,7 +1124,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { }; // One shadow for every member's surface, behind them all. let mut children = children; - children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?); + children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options, kept).ok()?); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); art.kind = NodeKind::Group { children, clip: false }; @@ -1682,6 +1749,67 @@ mod tests { } assert_eq!(expand_revolve_art(&sample), revolve_art(&sample)); } + + /// The settings the shadows are compared with: the defaults, a partial sweep turned with + /// perspective, and an open surface away from its axis under a colored light. + fn shadow_settings() -> [Value; 3] { + [ + json!({"shadow": true}), + json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "angle": 220, "shadowDistance": 40}), + json!({"shadow": true, "shadowDistance": 30, "lightColor": "#ff8040", "offset": 20, "cap": false}), + ] + } + + /// The shadow of the faces Revolve and Revolve (Classic) kept when they swept their surfaces, + /// to the bit: the shadow of surfaces swept for the shadow alone, for one object, for an + /// object whose fill is half transparent, and for a group of two members, one at half opacity. + #[test] + fn the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it() { + for id in [REVOLVE, CLASSIC_REVOLVE] { + for params in shadow_settings() { + // Revolve (Classic) takes no shadow settings from commands, but a file can carry them. + let mut fx = crate::new_effect(id, &json!({})).unwrap(); + fx.params = params.clone(); + let n = profile_node(); + let (path, _) = profile(&n).unwrap(); + let b = path.bounds().unwrap(); + let mut half = n.clone(); + if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] { + f.opacity = 0.5; + } + for n in [n, half] { + let item = surface_item(&n.appearance.items).unwrap(); + let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap(); + let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(); + let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(); + assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}"); + assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); + } + let mut other = profile_node(); + other.id = NodeId(2); + other.transform(Affine::translate((120.0, 0.0)), false); + other.opacity = 0.5; + let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]); + g.appearance.effects.push(fx.clone()); + let shapes = members(&g, "").unwrap(); + let b = union_bounds(&shapes).unwrap(); + let options = shared_options(&shapes, fx_options(&fx)).unwrap(); + let kept: Vec> = shapes + .iter() + .map(|s| { + let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); + let cast = casts(&fx, opacity * s.opacity); + surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + }) + .collect(); + assert!(kept.iter().all(Option::is_some), "{id} {params}"); + let drawn = group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(); + let alone = group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap(); + assert!(!alone.is_empty() || id == CLASSIC_REVOLVE, "{id} {params}"); + assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); + } + } + } } #[cfg(test)] diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 9338d74393..c0d44947d7 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -7,7 +7,9 @@ use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask}; use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2}; use vectorcraft_pathops::BoolOp; -use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, View}; +use vectorcraft_three_d::{ + Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View, +}; #[cfg(test)] use vectorcraft_doc::color::Color; @@ -236,6 +238,30 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> } } +/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast +/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the +/// classic effects cast no shadow: they keep no faces. +fn facets_and_faces( + id: &str, + path: &PathData, + rule: FillRule, + bounds: Rect, + p: &Value, + cast: bool, +) -> Result<(Vec, Option), String> { + let view = view_options(p); + #[cfg(test)] + if cast && id == EXTRUDE { + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + } + let built = match id { + EXTRUDE if cast => vectorcraft_three_d::extrude_shadowed(path, rule, bounds, extrude_options(p), view), + ROTATE if cast => vectorcraft_three_d::plane_shadowed(path, rule, bounds, view), + _ => return facets(id, path, rule, bounds, p).map(|f| (f, None)), + }; + built.map(|(f, faces)| (f, Some(faces))) +} + /// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not /// need the object. fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { @@ -693,7 +719,9 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec>, Rect) { #[cfg(test)] thread_local! { /// How many solids [`built_solids`] and [`meshes_for`] have built on this thread, for the tests. - static SOLIDS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Rotate's planes drawn, the solids built to cast a shadow ([`cast_shadow`]) and Revolve's + /// surfaces count too. + pub(crate) static SOLIDS_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; /// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and /// [`built_solids`] have built on this thread, for the tests. static SOLID_GEOMETRY_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -712,10 +740,35 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { + built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f))) +} + +/// One solid's facets and, when its shadow is cast, the faces it is cast from. +type CastingSolid = (Vec, Option); + +/// The surfaces of an object's solids, and the faces each solid kept for its shadow +/// ([`surfaces_for`]). +type SurfacesAndFaces = (Vec>, Vec>); + +/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow +/// is cast from, from the same build ([`SolidFaces`]). +fn built_solids_cast<'a>( + id: &'a str, + p: &'a Value, + parts: &'a [Part<'a>], + bounds: Rect, + limit: usize, + cast: bool, +) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. - let mut inflated = (id == INFLATE).then(|| { + let mut inflated = (id == INFLATE).then(|| -> Box>> { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); - vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p)) + let (o, view) = (inflate_options(p), view_options(p)); + if cast { + Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces))))) + } else { + Box::new(vectorcraft_three_d::inflate_each(&shapes, bounds, o, view).map(|r| r.map(|f| (f, None)))) + } }); let mut kept = 0usize; let mut ended = false; @@ -729,13 +782,13 @@ fn built_solids<'a>( Some(each) => { #[cfg(test)] SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); - each.next().unwrap_or_else(|| Ok(vec![])) + each.next().unwrap_or_else(|| Ok((vec![], None))) } - None => facets(id, area, *rule, bounds, p), + None => facets_and_faces(id, area, *rule, bounds, p, cast), }; let result = match built { Ok(f) => { - kept = kept.saturating_add(f.len()); + kept = kept.saturating_add(f.0.len()); if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) } } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None), @@ -1364,12 +1417,19 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// otherwise each solid is a surface of its own, in that order. A member's opacity mask and /// blending mode, and those of a group it is in, apply to the surfaces of the members it holds /// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it -/// off), to be drawn behind every surface of the object, and the surfaces. +/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every +/// surface of the object, and the surfaces. fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option { - let art = surfaces_for(doc, n, fx, shapes)?; + let p = crate::merged_params(&fx.id, &fx.params); + let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some(); + let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?; // A shadow past the limits draws the source path, as a solid past them does; commands report // the error ([`validate_solid_in`]). - let shadow = shadow_for(n.id, fx, shapes).ok()?; + let shadow = if cast { cast_built(&fx.id, &p, shapes, built) } else { Ok(None) }; + let shadow = match shadow.ok()? { + Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)), + None => vec![], + }; Some((shadow, art)) } @@ -1408,6 +1468,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result 0.0) { let (area, rule) = region(&s.path, s.rule, item); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); let faces = caster.plane(&area, rule, b, view)?; cast.push((s.scopes.as_slice(), ink(item, s.opacity), faces)); } @@ -1419,10 +1481,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result, String>> = if id == INFLATE { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); let casts: Vec = inks.iter().map(|i| i.opacity > 0.0).collect(); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len())); caster.inflate(&shapes, &casts, bounds, inflate_options(p), view) } else { let mut added = vec![]; for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) { + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0))); added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) }); } added @@ -1444,6 +1510,76 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result(id: &str, p: &Value, shapes: &'a [Profile], built: Vec>) -> Result>, String> { + if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE { + return Ok(None); + } + let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) }; + let view = view_options(p); + let mut caster = vectorcraft_three_d::ShadowCaster::new(); + let mut cast: Vec = vec![]; + let ink = |item: &AppearanceItem, member: f32| { + let (_, opacity, blend) = paint_of(item, member); + shadow::Ink { opacity, blend } + }; + if id == ROTATE { + let items: Vec<(&Profile, &AppearanceItem)> = shapes.iter().flat_map(|s| s.items.iter().map(move |item| (s, item))).collect(); + if items.len() != built.len() { + return cast_shadow(id, p, shapes); + } + for ((s, item), kept) in items.into_iter().zip(built) { + let ink = ink(item, s.opacity); + if ink.opacity <= 0.0 { + continue; + } + let faces = match kept { + Some(kept) => caster.add_solid(kept)?, + None => { + let (area, rule) = region(&s.path, s.rule, item); + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + caster.plane(&area, rule, b, view)? + } + }; + cast.push((s.scopes.as_slice(), ink, faces)); + } + return Ok(Some((caster, settings, cast))); + } + let (parts, bounds) = solid_parts(shapes, b); + let inks: Vec = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect(); + if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) { + return cast_shadow(id, p, shapes); + } + for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) { + if ink.opacity <= 0.0 { + continue; + } + let faces = match kept { + Some(kept) => caster.add_solid(kept), + None => { + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + caster.extrude(area, *rule, bounds, extrude_options(p), view) + } + }; + // A stroke whose own solid is past the limits is left out; past the shadow's limit for all + // the solids together, the shadow is refused. + let faces = match faces { + Ok(faces) => faces, + Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue, + Err(e) => return Err(e), + }; + cast.push((*scopes, ink, faces)); + } + Ok(Some((caster, settings, cast))) +} + /// The faces a shadow is cast from, its settings, and the faces of each solid of visible art with /// its member's scopes and ink ([`cast_shadow`]). type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec>); @@ -1502,31 +1638,31 @@ fn masks_surface(paint: &Paint, colored: bool) -> bool { colored && crate::lighting::opaque_paint(paint).1.is_some() } +/// A graphic of [`placed_graphics`]: the index of the first surface of the solids that share it, +/// the index of the surface it is drawn right after, its face and its art. +type Placement = (usize, usize, PlanarFace, Arc); + /// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is /// drawn right after (the last of those solids holding its face) and its face. Solids in a run -/// with the same opacity and blending mode share their graphics. With `per_member` -/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get -/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes. -/// All the groups share one limit on the path elements drawn: once it is reached, later groups -/// draw no graphics. -fn placed_graphics( - doc: Option<&Document>, - id: NodeId, - effect: (&str, &Value), - bounds: Rect, - filled: &[Filled], - per_member: bool, -) -> Vec<(usize, PlanarFace, Arc)> { +/// with the same opacity and blending mode share their graphics, one on each face. With +/// `per_member` (a member's opacity mask or blending mode applies to its surfaces) each member's +/// solids get graphics of their own, clipped to that member's caps, so they stay in that member's +/// scopes. All the groups share one limit on the path elements drawn: once it is reached, later +/// groups draw no graphics. +fn placed_graphics(doc: Option<&Document>, id: NodeId, effect: (&str, &Value), bounds: Rect, filled: &[Filled], per_member: bool) -> Vec { let mut groups: Vec> = vec![]; for f in filled { // Solids whose fills or strokes differ in opacity or blending mode get graphics of their - // own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask - // gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the - // group of the solid before it, so a graphic is never drawn past a solid painted between. - let joins = |first: &Filled| { - (!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked + // own, each drawn as its fill or stroke is. One member's solids share their graphics + // whether or not their surfaces carry an opacity mask, and each graphic takes the mask of + // the surface it is drawn after ([`with_graphics`]). Solids of different members share + // them only when neither surface carries a mask. A solid joins only the group of the solid + // before it, so a graphic is never drawn past a solid painted between. + let joins = |g: &&Filled| { + let member = g.member == f.member; + (member || !per_member && !g.masked && !f.masked) && g.opacity == f.opacity && g.blend == f.blend }; - match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) { + match groups.last_mut().filter(|g| g.iter().all(joins)) { Some(g) => g.push(f), None => groups.push(vec![f]), } @@ -1535,12 +1671,13 @@ fn placed_graphics( let mut elements = 0usize; for group in groups { let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect(); + let first = group.first().map_or(0, |f| f.at); let opacity = group.first().map_or(1.0, |f| f.opacity); let blend = group.first().map_or(BlendMode::Normal, |f| f.blend); for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) { if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) { Arc::make_mut(&mut art).blend = blend; - out.push((f.at, face, art)); + out.push((first, f.at, face, art)); } } } @@ -1552,23 +1689,19 @@ fn placed_graphics( type BuiltSurface<'s> = (Vec, Node, &'s [Scope], Vec>); /// [`with_graphics`] of built surfaces, each drawn whole. -fn whole_surfaces<'s>(surfaces: Vec>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { +fn whole_surfaces<'s>(surfaces: Vec>, arts: &[Placement]) -> Vec<(&'s [Scope], Arc)> { with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts) } /// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts` /// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes /// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is. -fn with_graphics<'s>( - surfaces: Vec<(&'s [Scope], Arc)>, - first: usize, - arts: &[(usize, PlanarFace, Arc)], -) -> Vec<(&'s [Scope], Arc)> { +fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc)>, first: usize, arts: &[Placement]) -> Vec<(&'s [Scope], Arc)> { let mut out = Vec::with_capacity(surfaces.len() + arts.len()); for (k, (scopes, s)) in surfaces.into_iter().enumerate() { let mask = s.extras().mask.clone(); out.push((scopes, s)); - out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| { + out.extend(arts.iter().filter(|(_, at, ..)| *at == first + k).map(|(.., art)| { let mut art = art.clone(); if let Some(mask) = &mask { Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone()); @@ -1585,8 +1718,10 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { } /// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar -/// faces drawn right after the last of the solids' surfaces that holds that face. -fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option>> { +/// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each +/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the +/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. +fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -1601,11 +1736,15 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile // the centre of theirs), so they stay together. let mut out = vec![]; let mut filled = vec![]; + let mut built = vec![]; for (member, s) in shapes.iter().enumerate() { for item in &s.items { let (paint, opacity, blend) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - let f = facets(ROTATE, &area, rule, b, &p).ok()?; + #[cfg(test)] + SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); + let (f, faces) = facets_and_faces(ROTATE, &area, rule, b, &p, cast).ok()?; + built.push(faces); if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) { return None; } @@ -1622,19 +1761,23 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile } let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks); let out = with_graphics(out, 0, &arts); - return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); + return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built)); } let (parts, bounds) = solid_parts(shapes, b); let mut solids = vec![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES)) { + let mut built = vec![]; + for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) { let item: &AppearanceItem = item; match f { - Ok(Some(f)) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { + Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { return None; } - Ok(Some(f)) => solids.push((item, *opacity, *scopes, f, *member)), + Ok(Some((f, faces))) => { + solids.push((item, *opacity, *scopes, f, *member)); + built.push(faces); + } // A stroke's outline past the limits is left out; the fill's solid still draws. - Ok(None) => {} + Ok(None) => built.push(None), // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; // commands validate the same evaluator and report its errors. @@ -1763,14 +1906,14 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile out.extend(with_graphics(run.collect(), first, &arts)); } } - return Some(masked(n.id, out)); + return Some((masked(n.id, out), built)); } if !opaque || !surfaces.iter().all(plain) { let surfaces = surfaces.into_iter().enumerate().map(|(k, (d, s, scopes, e))| (d, underlaid_surface(n.id, s, seal(k..k + 1)), scopes, e)).collect(); - return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); + return Some((whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect(), built)); } - Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))]) + Some((vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))], built)) } /// A plain `surface` ([`surface`]: a group of its facets) over an underlay of its facets when @@ -1793,16 +1936,9 @@ fn underlaid_surface(id: NodeId, surface: Node, seal: bool) -> Node { /// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is. /// The faces of the surfaces that `seals` marks lie over underlays of themselves /// ([`underlaid_runs`], [`underlaid_surface`]). -fn in_one_order( - id: NodeId, - surfaces: Vec>, - first: usize, - arts: &[(usize, PlanarFace, Arc)], - sealed: bool, - seals: &[bool], -) -> Vec> { +fn in_one_order(id: NodeId, surfaces: Vec>, first: usize, arts: &[Placement], sealed: bool, seals: &[bool]) -> Vec> { let masks: Vec>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); - let arts: Vec<&(usize, PlanarFace, Arc)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect(); + let arts: Vec<&Placement> = arts.iter().filter(|(_, at, ..)| (first..first + surfaces.len()).contains(at)).collect(); let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { if let NodeKind::Group { children, .. } = s.kind { @@ -1813,24 +1949,18 @@ fn in_one_order( } let order = draw_order(&placed, sealed); // Each graphic goes right after the last of the faces it is drawn on, among the surfaces that - // share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a - // mask that ends at its surface. + // share it ([`placed_graphics`]): those from the first of them to its own. let last: Vec> = arts .iter() - .map(|(at, face, _)| { - let at = at - first; - let from = if masks.get(at).is_some_and(Option::is_some) { - at - } else { - masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1) - }; + .map(|(from, at, face, _)| { + let (from, at) = (from.saturating_sub(first), at - first); order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface))) }) .collect(); let mut drawn: Vec<(usize, Arc)> = Vec::with_capacity(order.len() + arts.len()); for (at, k) in order.into_iter().enumerate() { drawn.extend(faces.get_mut(k).and_then(Option::take)); - drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| { + drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (_, surface, _, art))| { let mut art = art.clone(); if let Some(mask) = masks.get(surface - first).cloned().flatten() { Arc::make_mut(&mut art).extras_mut().mask = Some(mask); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index e0935a43e7..f0da6b992b 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -617,10 +617,11 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() { }; // The graphic carries the cap's mask, so it is hidden where the gradient is transparent. assert_eq!(masks(&art), vec![true]); - // With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own - // and the stroke's outline gets an unmasked one. + // With an opaque stroke drawn after the fill, the fill and the stroke share one graphic, drawn + // after the stroke's cap as for a fill without a mask, and it takes the stroke's surface, + // which carries no mask. n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))); - assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]); + assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![false]); } /// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its @@ -649,23 +650,56 @@ fn face_paths(art: &Node) -> Vec { out } +/// The graphics in `art` (clip groups of solid-color paths), in drawing order: for each, how many +/// faces ([`face_paths`]) are drawn before it, whether it carries an opacity mask, its opacity and +/// its blending mode. +fn graphic_places(art: &Node) -> Vec<(usize, bool, f32, BlendMode)> { + fn walk(n: &Node, faces: &mut usize, out: &mut Vec<(usize, bool, f32, BlendMode)>) { + match &n.kind { + NodeKind::Group { children, clip: true } => { + let graphic = children.get(1).is_some_and(|inner| match &inner.kind { + NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| { + p.path_data().is_some() + && p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some())) + }), + _ => false, + }); + if graphic { + out.push((*faces, n.extras().mask.is_some(), n.opacity, n.blend)); + } else if children.first().and_then(|c| c.path_data()).is_some() { + *faces += 1; + } + } + NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, faces, out)), + _ => *faces += usize::from(n.path_data().is_some()), + } + } + let mut out = vec![]; + walk(art, &mut 0, &mut out); + out +} + /// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke /// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without -/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's. +/// the graphic, and draws the graphic once, where it goes in a gradient without transparent stops: +/// after the stroke's cap, without a mask. #[test] fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; let d = document(); - let mut stop = GradientStop::new(1.0, red()); - stop.opacity = 0.25; - let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); - let solid = |graphics: Value| { + // A red gradient whose last stop has opacity `last`. + let gradient = |last: f32| { + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = last; + GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])) + }; + let solid = |fill: &GradientPaint, graphics: Value| { let mut n = object( EXTRUDE, json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}), ); if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { - f.paint = Paint::Gradient(Box::new(gradient.clone())); + f.paint = Paint::Gradient(Box::new(fill.clone())); } // A gradient stroke: a solid color under the colored light would be one composite. let blues = Gradient::new( @@ -677,54 +711,76 @@ fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() { n.appearance.items.push(AppearanceItem::Stroke(stroke)); solid_art_in(Some(&d), &n).unwrap() }; - let with = solid(json!([{"symbol": "Mark"}])); - let without = solid(json!([])); + let masked = gradient(0.25); + let with = solid(&masked, json!([{"symbol": "Mark"}])); + let without = solid(&masked, json!([])); assert!(face_paths(&without).len() > 20, "the faces are found"); assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order"); - // The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the - // symbol's red square); the fill's, whose surface carries the mask, carries it too. - let mut masked = vec![]; - with.walk(&mut |c| { - if let NodeKind::Group { children, clip: true } = &c.kind - && let [_, inner] = children.as_slice() - && let NodeKind::Group { children: paths, clip: false } = &inner.kind - && paths.iter().any(|p| { - p.appearance.items.iter().any(|i| match i { - AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3), - AppearanceItem::Stroke(_) => false, - }) - }) - { - masked.push(c.extras().mask.is_some()); - } - }); - masked.sort_unstable(); - assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask"); - // The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn - // after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face, - // the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds. - let mut drawn: Vec<(&str, Rect)> = vec![]; - with.walk(&mut |c| { - if let NodeKind::Group { children, clip: true } = &c.kind - && c.extras().mask.is_some() - && let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds) - { - drawn.push(("graphic", bounds)); - } - let first_stop = c.appearance.items.iter().find_map(|i| match i { - AppearanceItem::Fill(f) => match &f.paint { - Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()), - _ => None, - }, - AppearanceItem::Stroke(_) => None, - }); - if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) { - drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds)); - } - }); - let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap(); - let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0; - assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic"); + let mut mask = false; + with.walk(&mut |c| mask |= c.extras().mask.is_some()); + assert!(mask, "the fill's faces carry the gradient's mask"); + let opaque = solid(&gradient(1.0), json!([{"symbol": "Mark"}])); + assert_eq!(face_paths(&opaque), face_paths(&with)); + let places = graphic_places(&with); + assert_eq!(places.iter().map(|(_, mask, opacity, blend)| (*mask, *opacity, *blend)).collect::>(), [(false, 1.0, BlendMode::Normal)]); + assert_eq!(places, graphic_places(&opaque), "drawn where a fill without a mask draws it"); +} + +/// A plane in a gradient with transparent stops under a colored light draws its graphic with the +/// fill's mask, and with a dashed stroke draws it once, after the stroke, without a mask. +#[test] +fn a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); + let mut n = object(ROTATE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient)); + } + let places = graphic_places(&solid_art_in(Some(&d), &n).unwrap()); + assert_eq!(places.iter().map(|(_, mask, ..)| *mask).collect::>(), [true]); + let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + n.appearance.items.push(AppearanceItem::Stroke(stroke)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let places = graphic_places(&art); + assert_eq!(places, [(face_paths(&art).len(), false, 1.0, BlendMode::Normal)], "one graphic, drawn after every face"); +} + +/// Members of a group share a graphic only when neither surface carries an opacity mask, while +/// one member's fill and stroke share theirs. +#[test] +fn members_in_transparent_gradients_keep_graphics_of_their_own() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])))); + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let (left, right) = (Rect::new(0.0, 0.0, 50.0, 100.0), Rect::new(50.0, 0.0, 100.0, 100.0)); + // Whether each graphic drawn on the group of `members` carries an opacity mask, in order. + let masks = |members: Vec| { + let mut group = Node::group(NodeId(3), members.into_iter().map(Arc::new).collect()); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 1000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let mut masks: Vec = graphic_places(&solid_art_in(Some(&d), &group).unwrap()).iter().map(|(_, mask, ..)| *mask).collect(); + masks.sort_unstable(); + masks + }; + assert_eq!(masks(vec![square(1, left, gradient.clone()), square(2, right, gradient.clone())]), [true, true]); + // With a dashed stroke, the first member's fill and stroke share one graphic, without a mask. + let mut stroked = square(1, left, gradient.clone()); + let mut stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 6.0); + stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false }); + stroked.appearance.items.push(AppearanceItem::Stroke(stroke)); + assert_eq!(masks(vec![stroked, square(2, right, gradient.clone())]), [false, true]); + // A member with a gray stroke listed before its fill in the gradient does not share its + // graphic with the gray member after it. + let mut layered = square(1, left, gradient); + layered.appearance.items.insert(0, AppearanceItem::Stroke(StrokeLayer::new(gray.clone(), 6.0))); + assert_eq!(masks(vec![layered, square(2, right, gray)]), [false, true]); } #[test] diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 7e7d2e1595..4d62961612 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -223,3 +223,92 @@ fn expand_appearance_keeps_the_shadow_as_a_path() { assert!((after.x0 - before.x0 - 40.0).abs() < 1e-6, "{id}: {before:?} {after:?}"); } } + +/// A square filled red and stroked blue, its stroke as opaque as `stroke`. +fn stroked_square(id: u64, dx: f64, stroke: f32) -> Node { + let mut n = square_node(id, dx); + n.appearance = Appearance::basic(Paint::solid(RED), Paint::solid(Color::rgb(0.1, 0.2, 0.9)), 6.0).into(); + for item in &mut n.appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.opacity = stroke; + } + } + n +} + +/// Objects with 3D effect `id` and its shadow on (`params`): a filled and stroked square, one whose +/// stroke is half transparent, one whose stroke is fully transparent, and a group of two members, +/// one of them at half opacity. +fn shadowed(id: &str, params: &Value) -> Vec { + let with = |mut n: Node| { + n.appearance.effects.push(crate::new_effect(id, params).unwrap()); + n + }; + let mut half = stroked_square(2, 200.0, 1.0); + half.opacity = 0.5; + let group = Node::group(NodeId(9), vec![Arc::new(stroked_square(1, 0.0, 1.0)), Arc::new(half)]); + vec![with(stroked_square(1, 0.0, 1.0)), with(stroked_square(1, 0.0, 0.5)), with(stroked_square(1, 0.0, 0.0)), with(group)] +} + +/// The settings the shadows of effect `id` are compared with: the defaults, turned with +/// perspective, and under a colored light, below the object for Extrude & Bevel, Inflate and +/// Rotate and behind it for Revolve. +fn shadow_settings(id: &str) -> [Value; 3] { + let position = if id == crate::REVOLVE { "behind" } else { "below" }; + [ + json!({"shadow": true}), + json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "shadowDistance": 40}), + json!({"shadow": true, "shadowPosition": position, "shadowDistance": 30, "lightColor": "#ff8040", "twist": 30}), + ] +} + +/// How many solids drawing the art of `n` with effect `id` builds. +fn solids_built(n: &Node, id: &str) -> usize { + let start = SOLIDS_BUILT.with(std::cell::Cell::get); + assert!(art(n, id).is_some(), "{id}"); + SOLIDS_BUILT.with(std::cell::Cell::get) - start +} + +/// Drawing a 3D object with its shadow on builds each of its solids once: the shadow is cast from +/// the faces the solids drawn kept, so it builds no more solids than the art without a shadow. +#[test] +fn a_shadowed_3d_object_builds_each_solid_once() { + for id in CASTING { + for params in shadow_settings(id) { + for (lit, mut plain) in shadowed(id, ¶ms).into_iter().zip(shadowed(id, ¶ms)) { + plain.appearance.effects.iter_mut().for_each(|e| e.params["shadow"] = json!(false)); + let mut cast = 0; + art(&lit, id).unwrap().walk(&mut |c| cast += usize::from(shadow_opacity(c).is_some())); + assert!(cast > 0, "{id} {params}"); + let built = solids_built(&plain, id); + assert!(built > 0, "{id}"); + assert_eq!(solids_built(&lit, id), built, "{id} {params}: the shadow builds no solid of its own"); + } + } + } +} + +/// The shadow of the faces Extrude & Bevel, Inflate and Rotate kept when they drew their solids, +/// to the bit: the shadow [`cast_shadow`] casts from solids built for the shadow alone. +#[test] +fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() { + for id in [EXTRUDE, INFLATE, ROTATE] { + for params in shadow_settings(id) { + for n in shadowed(id, ¶ms) { + let (_, fx) = solid(&n.appearance.effects).unwrap(); + let shapes = if is_container(&n) { + members(&n, "").unwrap() + } else { + let (path, rule) = profile(&n).unwrap(); + vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }] + }; + let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap(); + let p = crate::merged_params(&fx.id, &fx.params); + let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap(); + let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes)); + assert!(!alone.is_empty(), "{id} {params}"); + assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}"); + } + } + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index a2d0316913..99b8e1ecdd 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -827,7 +827,7 @@ pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; -pub use plugin_call::{Location, key_location, location_in, location_keys}; +pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub(crate) use vectorcraft_doc::range::parse_range; /// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index b6b0669f12..f81d7a599a 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -23,7 +23,7 @@ use vectorcraft_render::effects; use super::super::appearance::series_children_in_paint_order; use super::super::colorcmds::edit_if_changed; use super::super::edit::selected_roots; -use super::super::graph::capture_series_object_opacity; +use super::super::graph::{capture_series_object_opacity, series_groups_among}; use super::super::menucmds::whole_or; use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns}; use super::super::typecmd::refresh_bounds_of; @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Randomize Opacity", ["Object", "Plug-ins", "Arrange Tools"], None, - "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}", + "{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md) → {count}", has_selection, randomize_opacity ), @@ -102,7 +102,7 @@ pub fn specs() -> Vec { "Sort Objects", ["Object", "Plug-ins", "Arrange Tools"], None, - "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}", + "{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}", has_multi, sort ), @@ -418,9 +418,11 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result { /// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are /// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn -/// again; the frontmost of them in a series sets them. +/// again; the frontmost of them in a series sets them. A series group among `changed` has its own opacity stored for the +/// group. fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) { - let marks = series_children_in_paint_order(d, changed); + let mut marks = series_children_in_paint_order(d, changed); + marks.extend(series_groups_among(d, changed)); capture_series_object_opacity(d, &marks); } diff --git a/crates/engine/src/cmd/addons/cleanup/text.rs b/crates/engine/src/cmd/addons/cleanup/text.rs index a13110cf67..ea7e3314bb 100644 --- a/crates/engine/src/cmd/addons/cleanup/text.rs +++ b/crates/engine/src/cmd/addons/cleanup/text.rs @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Remove Breaks", ["Object", "Plug-ins", "Artwork Cleanup"], None, - "{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", + "{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story, locked and hidden frames included), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}", has_selection, remove_breaks ), @@ -821,9 +821,9 @@ fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize { } /// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or -/// start of a frame between words of the frames on either side becomes a space. Each editable frame -/// (each frame when `all`) comes with its own breaks, at its own bytes. -fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(NodeId, Vec<(usize, bool)>)> { +/// start of a frame between words of the frames on either side becomes a space. Each frame comes +/// with its own breaks, at its own bytes, its locked and hidden frames included. +fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> { let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect(); let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect(); // The breaks in story order, handed to the frames in one pass. @@ -836,9 +836,7 @@ fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(Node while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) { own.push((at - start, space)); } - if all || d.is_editable(id) { - out.push((id, own)); - } + out.push((id, own)); start = end; } out @@ -859,7 +857,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; // Each type object with the breaks that go from it. let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing { - Some(_) if !story.is_empty() => story_cuts(d, &story, brk, false), + Some(_) if !story.is_empty() => story_cuts(d, &story, brk), Some((id, a, b)) => vec![(id, a.min(b), a.max(b))] .into_iter() .filter(|(id, ..)| d.is_editable(*id)) @@ -886,8 +884,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result { }; if !story.is_empty() && story.iter().all(|f| named.contains(f)) { done.extend(story.iter().copied()); - // Every frame is among them, so each one keeps its breaks. - out.extend(story_cuts(d, &story, brk, true)); + out.extend(story_cuts(d, &story, brk)); } else if let Some(t) = text_of(d, id) { // `id` is type, so the story of its thread is the same for each of its frames. partial.extend(thread); diff --git a/crates/engine/src/cmd/addons/cutting.rs b/crates/engine/src/cmd/addons/cutting.rs index 37e9f2fa79..6ad2af043b 100644 --- a/crates/engine/src/cmd/addons/cutting.rs +++ b/crates/engine/src/cmd/addons/cutting.rs @@ -2,9 +2,11 @@ //! Bridges cuts bridges out of the selected art so that a stencil cut from it holds together //! ([`stencil`]), and Weed Box and Lines adds a weed box and weeding lines around the selected art //! for vinyl cutting ([`weed`]). Banner Hems and Grommets marks the hems and grommets of a banner -//! ([`banner`]). Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's. +//! ([`banner`]). Nest Shapes packs the selected art onto a sheet or a roll of material ([`nest`]). +//! Its submenu (Object › Plug-ins › Cutting Tools) and dialogs are the UI's. mod banner; +mod nest; mod stencil; mod weed; @@ -14,5 +16,6 @@ pub fn specs() -> Vec { let mut v = stencil::specs(); v.extend(weed::specs()); v.extend(banner::specs()); + v.extend(nest::specs()); v } diff --git a/crates/engine/src/cmd/addons/cutting/nest.rs b/crates/engine/src/cmd/addons/cutting/nest.rs new file mode 100644 index 0000000000..18d4dd70f2 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/nest.rs @@ -0,0 +1,403 @@ +//! Nest Shapes (`addon.cutting.nest`), a command of the built-in Cutting Tools add-on that packs +//! the selected objects onto a sheet or a roll of material by their bounding boxes +//! (). The sheet is an +//! artboard, or a set size from the artboard's top-left corner; a roll is as wide as the sheet +//! and has no end. The objects are moved, and with `rotate` turned a quarter turn when that places +//! them better; they are never scaled or changed otherwise. + +#[cfg(test)] +mod tests; + +use std::collections::VecDeque; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2}; +use vectorcraft_render::effects; + +use super::super::super::edit::selected_roots_to_transform; +use super::super::super::object::{keep_compound_aligned, transform_node, transform_patterns}; +use super::super::super::pathops::length_given; +use super::super::super::{CommandSpec, bad, check_switches, cmd, has_selection, switch_or}; +use crate::{Result, Session}; + +/// Nest Shapes' command. +pub const NEST: &str = "addon.cutting.nest"; +/// The largest sheet width or height, in points. +const MAX_SIZE: f64 = 1_000_000.0; +/// The largest margin or spacing, in points. +const MAX_GAP: f64 = 100_000.0; +/// The most objects one run nests. +const MAX_SHAPES: usize = 10_000; +/// How far a box may reach past the sheet's edge and still fit (rounding). +const EPS: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.cutting.nest", + "Nest Shapes…", + ["Object", "Plug-ins", "Cutting Tools"], + None, + "{roll?: bool (false: a sheet `width` × `height`; true: a roll `width` wide with no end), width?: pt 0..1000000 (0: the artboard's width), height?: pt 0..1000000 (0: the artboard's height; not used with roll), margin?: pt 0..100000 (18: kept clear inside each edge of the sheet; on a roll, the sides and the start), spacing?: pt 0..100000 (9: kept between two objects), rotate?: bool (false: objects keep their orientation; true: an object may turn 90° clockwise where that puts its bottom edge higher, or where only the turned object fits), usePreviewBounds?: bool (true: objects are measured with their strokes and effects, the reach of shadows, glows and blurs included; false: by their geometry), artboard?: index (0-based; the sheet's artboard; default: the artboard under the center of the selection, else the first), patterns?: bool (Transform Patterns: pattern fills and strokes move with the art; default: prefs transformPatternTiles)} move the selected objects onto the sheet or roll, which starts at the artboard's top-left corner, packed by their bounding boxes: the tallest first (with rotate, the longest side first), each where its bottom edge is highest and then furthest left, without resizing them. An object on the pixel grid moves by whole points and takes 1 pt more room across and down; a path of a pixel-aligned compound path is not turned. Objects that do not fit on the sheet go in a column to the right of it, `spacing` from its edge and from each other, from its top, in stacking order (back to front). Objects without bounds (an empty group) are not moved. One undo step; nothing changes when no object moves → {placed: count, unplaced: [ids of the objects put beside the sheet], rotated: [ids], skipped: [ids of the objects without bounds], length: pt (from the sheet's top edge to the bottom margin below the lowest object placed)}", + has_selection, + nest + )] +} + +/// The length `p` gives for `key`, from 0 to `max`, or `default`. +fn length(p: &Value, key: &str, default: f64, max: f64) -> Result { + match length_given(p, key, NEST)? { + None => Ok(default), + Some(v) if (0.0..=max).contains(&v) => Ok(v), + Some(_) => Err(bad(NEST, format!("`{key}` must be from 0 to {max} pt"))), + } +} + +/// One stretch of a skyline: from `x`, `w` wide, filled down to `y`. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Span { + x: f64, + w: f64, + y: f64, +} + +/// Bottom-left packing of boxes on a skyline: a strip `width` wide and `height` deep +/// (`f64::INFINITY` for a roll), whose filled part is the spans' outline along its top. +struct Skyline { + spans: Vec, + width: f64, + height: f64, +} + +impl Skyline { + fn new(width: f64, height: f64) -> Self { + Skyline { spans: vec![Span { x: 0.0, w: width, y: 0.0 }], width, height } + } + + /// Where a box `w` × `h` goes: at the left edge of a span, as high as the spans under it + /// allow, choosing the place where its bottom edge is highest and then furthest left. `None` + /// when it fits nowhere. The spans under the box at each span are a window whose two ends only + /// move right, and `window` holds the indices in it whose depth no later span in it reaches, so + /// its front is the deepest: one call takes time in proportion to the number of spans. + fn find(&self, w: f64, h: f64) -> Option<(f64, f64)> { + let mut best: Option<(f64, f64)> = None; + let mut window: VecDeque = VecDeque::new(); + let mut end = 0; + for (i, s) in self.spans.iter().enumerate() { + if s.x + w > self.width + EPS { + break; + } + while window.front().is_some_and(|&j| j < i) { + window.pop_front(); + } + end = end.max(i); + while let Some(t) = self.spans.get(end) + && (end == i || t.x < s.x + w - EPS) + { + while window.back().and_then(|&j| self.spans.get(j)).is_some_and(|b| b.y <= t.y) { + window.pop_back(); + } + window.push_back(end); + end += 1; + } + let y = window.front().and_then(|&j| self.spans.get(j)).map_or(0.0, |t| t.y.max(0.0)); + if y + h > self.height + EPS { + continue; + } + // The box is `h` tall at every place, so the place with the highest bottom edge is the + // place with the highest top edge. + if best.is_none_or(|(bx, by)| y < by - EPS || ((y - by).abs() <= EPS && s.x < bx)) { + best = Some((s.x, y)); + } + } + best + } + + /// Fills the skyline down to `y + h` from `x` across `w`. + fn place(&mut self, x: f64, y: f64, w: f64, h: f64) { + if w <= 0.0 { + return; + } + let end = x + w; + let mut out = Vec::with_capacity(self.spans.len() + 2); + let mut added = false; + for s in &self.spans { + let s_end = s.x + s.w; + if s_end <= x || s.x >= end { + out.push(*s); + continue; + } + if s.x < x { + out.push(Span { x: s.x, w: x - s.x, y: s.y }); + } + if !added { + out.push(Span { x, w, y: y + h }); + added = true; + } + if s_end > end { + out.push(Span { x: end, w: s_end - end, y: s.y }); + } + } + // Neighbors filled to the same depth are one span. + let mut merged: Vec = Vec::with_capacity(out.len()); + for s in out { + match merged.last_mut() { + Some(l) if l.y == s.y => l.w = s.x + s.w - l.x, + _ => merged.push(s), + } + } + self.spans = merged; + } +} + +/// One box to pack: its width and height as it stands, and when it may turn, as it is turned. +type Sizes = ((f64, f64), Option<(f64, f64)>); + +/// The side a box is ordered by: its height, or its longest side when it may turn. +fn lead(b: &Sizes) -> (f64, f64) { + let ((w, h), turned) = *b; + if turned.is_some() { (w.max(h), w.min(h)) } else { (h, w) } +} + +/// Packs `boxes` onto a strip `width` wide and `height` deep, the tallest first (a box that may +/// turn by its longest side; then the widest, then in their order), each where [`Skyline::find`] +/// puts it, turned when that puts its bottom edge higher (then further left), or when only the +/// turned box fits. Gives each box's top-left corner and whether it is turned, or `None` for a box +/// that does not fit. +fn pack(boxes: &[Sizes], width: f64, height: f64) -> Vec> { + let mut order: Vec = (0..boxes.len()).collect(); + order.sort_by(|&a, &b| { + let (la, lb) = (lead(&boxes[a]), lead(&boxes[b])); + lb.0.total_cmp(&la.0).then(lb.1.total_cmp(&la.1)) + }); + let mut sky = Skyline::new(width, height); + let mut at = vec![None; boxes.len()]; + for i in order { + let Some(&((w, h), turned)) = boxes.get(i) else { continue }; + let mut best = sky.find(w, h).map(|(x, y)| (x, y, false, w, h)); + if let Some((tw, th)) = turned + && let Some((x, y)) = sky.find(tw, th) + { + let better = best.is_none_or(|(bx, by, _, _, bh)| { + let (was, now) = (by + bh, y + th); + now < was - EPS || ((now - was).abs() <= EPS && x < bx - EPS) + }); + if better { + best = Some((x, y, true, tw, th)); + } + } + if let Some((x, y, t, bw, bh)) = best { + sky.place(x, y, bw, bh); + if let Some(slot) = at.get_mut(i) { + *slot = Some((x, y, t)); + } + } + } + at +} + +/// A quarter turn clockwise on the page about `c`. +fn quarter_turn(c: Point) -> Affine { + Affine::translate(c.to_vec2()) * vectorcraft_geom::rotate_deg(90.0) * Affine::translate(-c.to_vec2()) +} + +fn finite(r: &Rect) -> bool { + [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) +} + +/// The box `id` is packed by: with `preview`, its visual bounds with geometry effects +/// ([`effects::preview::bounds_of`]) and the reach of its raster effects, such as shadows, glows +/// and blurs ([`vectorcraft_render::drawn_bounds`]); else its geometric bounds. +fn measure(d: &vectorcraft_doc::Document, id: NodeId, preview: bool) -> Option { + let b = effects::preview::bounds_of(d, &[id], preview).filter(finite)?; + if !preview { + return Some(b); + } + match d.node(id).and_then(|n| vectorcraft_render::drawn_bounds(d, n)).filter(finite) { + Some(r) => Some(b.union(r)), + None => Some(b), + } +} + +/// Whether `id` is a path of a pixel-aligned compound path. +fn in_aligned_compound(d: &Document, id: NodeId) -> bool { + d.parent_of(id).and_then(|p| d.node(p)).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.extras().pixel_aligned) +} + +/// Whether moving `id` snaps it, or an object in it, to the pixel grid: it, an object it holds or +/// the art of a linked opacity mask in it is pixel-aligned, or it is a path of a pixel-aligned +/// compound path. +fn snaps(d: &Document, id: NodeId) -> bool { + if in_aligned_compound(d, id) { + return true; + } + let mut stack: Vec<&Node> = d.node(id).into_iter().collect(); + while let Some(n) = stack.pop() { + if n.extras().pixel_aligned { + return true; + } + stack.extend(n.children().map_or(&[][..], Vec::as_slice).iter().map(|c| &**c)); + if let Some(m) = n.extras().mask.as_ref() + && m.linked + { + stack.push(&*m.art); + } + } + false +} + +fn nest(s: &mut Session, p: &Value) -> Result { + check_switches(p, &["patterns"], NEST)?; + let roll = switch_or(p, "roll", false, NEST)?; + let width = length(p, "width", 0.0, MAX_SIZE)?; + let height = length(p, "height", 0.0, MAX_SIZE)?; + let margin = length(p, "margin", 18.0, MAX_GAP)?; + let spacing = length(p, "spacing", 9.0, MAX_GAP)?; + let turn = switch_or(p, "rotate", false, NEST)?; + let preview = switch_or(p, "usePreviewBounds", true, NEST)?; + let named = match p.get("artboard") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(NEST, "`artboard` must be an artboard's index"))?), + }; + // A path of a compound path selected on its own moves without the rest of the compound path. + let ids = selected_roots_to_transform(s)?; + if ids.len() > MAX_SHAPES { + return Err(bad(NEST, format!("select at most {MAX_SHAPES} objects to nest"))); + } + // Objects without a finite box (an empty group, empty type) are left where they are and + // listed as `skipped`. + let mut skipped = vec![]; + let (items, board): (Vec<(NodeId, Rect)>, Rect) = { + let d = &s.doc()?.doc; + let mut items: Vec<(NodeId, Rect)> = Vec::with_capacity(ids.len()); + for id in &ids { + match measure(d, *id, preview) { + Some(r) => items.push((*id, r)), + None => skipped.push(id.0), + } + } + let board = match named { + Some(i) => d.artboards.get(i).ok_or_else(|| bad(NEST, format!("there is no artboard {i}")))?.rect, + None => { + let all = items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b)); + let i = all.and_then(|r| d.artboard_at(r.center())).unwrap_or(0); + d.artboards.get(i).ok_or_else(|| bad(NEST, "there is no artboard for the sheet"))?.rect + } + }; + (items, board) + }; + if items.is_empty() { + return Err(bad(NEST, "the selection has nothing to nest")); + } + let sheet_w = if width > 0.0 { width } else { board.width() }; + let sheet_h = if roll { + f64::INFINITY + } else if height > 0.0 { + height + } else { + board.height() + }; + // Every box is `spacing` wider and taller, and the strip is `spacing` wider and deeper than + // the room inside the margins, so the spacing falls between boxes and not at the far edges. + let room_w = sheet_w - 2.0 * margin; + let room_h = if roll { f64::INFINITY } else { sheet_h - 2.0 * margin }; + if room_w <= 0.0 || room_h <= 0.0 { + return Err(bad(NEST, "the margin leaves no room on the sheet")); + } + let all: Vec = items.iter().map(|(id, _)| *id).collect(); + let grid: Vec = { + let d = &s.doc()?.doc; + all.iter().map(|id| snaps(d, *id)).collect() + }; + let sc = Scaling { patterns: transform_patterns(s, p, &all)?, ..Scaling::default() }; + // With `rotate`, each object is turned in a copy of the document and measured there, so the + // box packed for a turned object is the box its turned strokes and effects take. A path of a + // pixel-aligned compound path keeps its orientation: turning it snaps the whole compound path + // again, which would move the compound's other paths away from where they were measured. + let turned: Vec> = if turn { + let mut t = vectorcraft_doc::Document::clone(&s.doc()?.doc); + let xfs: Vec> = items.iter().map(|(id, r)| (!in_aligned_compound(&t, *id)).then(|| quarter_turn(r.center()))).collect(); + for ((id, _), xf) in items.iter().zip(&xfs) { + if let (Some(xf), Some(n)) = (xf, t.node_mut(*id)) { + transform_node(n, *xf, sc, true); + } + } + items.iter().zip(xfs).map(|((id, _), xf)| xf.and_then(|xf| measure(&t, *id, preview).map(|r| (xf, r)))).collect() + } else { + vec![None; items.len()] + }; + // An object that snaps to the pixel grid moves by whole points, so it stays on the grid and the + // snap after the move does not shift it; its box is 1 pt wider and taller to hold the rounding. + let slack = |g: bool| if g { 1.0 } else { 0.0 }; + let boxes: Vec = items + .iter() + .zip(&turned) + .zip(&grid) + .map(|(((_, r), t), g)| { + let pad = spacing + slack(*g); + ((r.width() + pad, r.height() + pad), t.map(|(_, q)| (q.width() + pad, q.height() + pad))) + }) + .collect(); + let at = pack(&boxes, room_w + spacing, room_h + spacing); + let origin = Vec2::new(board.x0 + margin, board.y0 + margin); + // The move that puts the top-left corner of box `b` at `to`: rounded up to whole points for an + // object on the pixel grid, so it moves at most 1 pt further right and down, into its slack. + let shift = |b: &Rect, to: Vec2, g: bool| { + let v = Vec2::new(to.x - b.x0, to.y - b.y0); + if g { Vec2::new(v.x.ceil(), v.y.ceil()) } else { v } + }; + // Each move: the quarter turn first, when the object turns, then the shift. + let mut moves: Vec<(NodeId, Option, Vec2)> = vec![]; + let mut aside: Vec<(NodeId, Option, Vec2)> = vec![]; + let mut unplaced = vec![]; + let mut rotated = vec![]; + let mut bottom = 0.0_f64; + // Objects that do not fit go in a column to the right of the sheet, `spacing` from its edge + // and from each other, so that no object placed on the sheet covers them. + let aside_x = board.x0 + sheet_w + spacing; + let mut aside_y = board.y0; + for ((((id, r), spot), t), g) in items.iter().zip(&at).zip(&turned).zip(&grid) { + match (spot, t) { + (Some((x, y, true)), Some((xf, q))) => { + let dv = shift(q, Vec2::new(origin.x + x, origin.y + y), *g); + moves.push((*id, Some(*xf), dv)); + rotated.push(id.0); + bottom = bottom.max(q.y1 + dv.y - origin.y); + } + (Some((x, y, _)), _) => { + let dv = shift(r, Vec2::new(origin.x + x, origin.y + y), *g); + moves.push((*id, None, dv)); + bottom = bottom.max(r.y1 + dv.y - origin.y); + } + (None, _) => { + aside.push((*id, None, shift(r, Vec2::new(aside_x, aside_y), *g))); + aside_y += r.height() + spacing + slack(*g); + unplaced.push(id.0); + } + } + } + if moves.is_empty() { + return Err(bad(NEST, "no selected object fits on the sheet")); + } + moves.extend(aside); + let length = 2.0 * margin + bottom; + let placed = moves.len() - unplaced.len(); + let result = json!({ "placed": placed, "unplaced": unplaced, "rotated": rotated, "skipped": skipped, "length": length }); + if moves.iter().all(|(_, xf, dv)| xf.is_none() && dv.x.abs() <= EPS && dv.y.abs() <= EPS) { + return Ok(result); + } + s.edit("Nest Shapes", |d, _| { + for (id, xf, dv) in &moves { + // The turn is the one the object was measured with in the copy, and the shift after it + // is whole points for an object on the pixel grid. + for step in xf.iter().copied().chain([Affine::translate(*dv)]) { + if let Some(n) = d.node_mut(*id) { + transform_node(n, step, sc, true); + } + keep_compound_aligned(d, *id, sc); + } + } + Ok(()) + })?; + Ok(result) +} diff --git a/crates/engine/src/cmd/addons/cutting/nest/tests.rs b/crates/engine/src/cmd/addons/cutting/nest/tests.rs new file mode 100644 index 0000000000..6ca6548a19 --- /dev/null +++ b/crates/engine/src/cmd/addons/cutting/nest/tests.rs @@ -0,0 +1,433 @@ +//! Tests for `addon.cutting.nest`: packing the selected objects onto a sheet or a roll. + +use serde_json::{Value, json}; +use vectorcraft_geom::Rect; + +use super::{Skyline, pack}; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn overlap(a: Rect, b: Rect) -> bool { + a.x0 < b.x1 - 1e-9 && b.x0 < a.x1 - 1e-9 && a.y0 < b.y1 - 1e-9 && b.y0 < a.y1 - 1e-9 +} + +#[test] +fn boxes_pack_tallest_first_from_the_top_left() { + // 100 wide: the 60 × 50 box goes first at the left and the 40 × 30 one beside it. The 50 × 20 + // one is too wide for the 40 pt beside the first box, so it goes below the first box. + let at = pack(&fixed(&[(40.0, 30.0), (60.0, 50.0), (50.0, 20.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((60.0, 0.0, false)), Some((0.0, 0.0, false)), Some((0.0, 50.0, false))]); +} + +#[test] +fn a_box_that_does_not_fit_is_left_out() { + let at = pack(&fixed(&[(80.0, 80.0), (80.0, 80.0), (120.0, 10.0)]), 100.0, 100.0); + assert_eq!(at, vec![Some((0.0, 0.0, false)), None, None]); +} + +/// Boxes that keep their orientation. +fn fixed(b: &[(f64, f64)]) -> Vec { + b.iter().map(|&s| (s, None)).collect() +} + +/// Boxes that may turn a quarter. +fn turning(b: &[(f64, f64)]) -> Vec { + b.iter().map(|&(w, h)| ((w, h), Some((h, w)))).collect() +} + +#[test] +fn a_box_turns_where_its_bottom_edge_ends_higher_or_only_turned_it_fits() { + // A 20 × 90 box lies down as 90 × 20 at the top; a 120 × 10 box only fits the 100 pt strip + // turned, as 10 × 120. + let at = pack(&turning(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((10.0, 0.0, true)), Some((0.0, 0.0, true))]); + // Without turning, the 120 pt wide box is left out and the other stands up. + let at = pack(&fixed(&[(20.0, 90.0), (120.0, 10.0)]), 100.0, f64::INFINITY); + assert_eq!(at, vec![Some((0.0, 0.0, false)), None]); + // A square box is never turned: turned, it is no better. + let at = pack(&turning(&[(30.0, 30.0)]), 100.0, 100.0); + assert_eq!(at, vec![Some((0.0, 0.0, false))]); +} + +#[test] +fn the_skyline_fills_and_merges_spans() { + let mut sky = Skyline::new(100.0, f64::INFINITY); + sky.place(0.0, 0.0, 30.0, 10.0); + sky.place(30.0, 0.0, 30.0, 10.0); + assert_eq!(sky.spans.len(), 2, "two spans at the same depth are one: {:?}", sky.spans); + assert_eq!(sky.find(50.0, 5.0), Some((0.0, 10.0)), "50 wide does not fit in the 40 left at the top"); + assert_eq!(sky.find(40.0, 5.0), Some((60.0, 0.0))); +} + +#[test] +fn selected_objects_are_nested_on_the_artboard_as_one_undo_step() { + let mut s = session(); + let ids: Vec = (0..6).map(|i| rect(&mut s, 900.0 + 300.0 * i as f64, 700.0, 150.0, 100.0 + 10.0 * i as f64)).collect(); + select(&mut s, &ids); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &json!({"margin": 10, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["placed"], json!(6)); + assert_eq!(r["unplaced"], json!([])); + let boxes: Vec = ids.iter().map(|id| bounds(&s, *id)).collect(); + for (i, a) in boxes.iter().enumerate() { + assert!(a.x0 >= 10.0 - 1e-9 && a.y0 >= 10.0 - 1e-9 && a.x1 <= 790.0 + 1e-9 && a.y1 <= 590.0 + 1e-9, "{a:?} inside the margins"); + assert!((a.width(), a.height()) == (150.0, 100.0 + 10.0 * i as f64), "moved, not resized"); + for b in &boxes[i + 1..] { + assert!(!overlap(a.inflate(2.5, 2.5), b.inflate(2.5, 2.5)), "{a:?} and {b:?} are 5 pt apart"); + } + } + // The tallest (150 pt) is at the top-left corner inside the margin, and five 150 pt wide + // boxes with 5 pt between them fill the 780 pt inside the margins. The shortest goes 5 pt below + // the 110 pt tall box at the right, where its bottom edge is highest. + assert_eq!((boxes[5].x0, boxes[5].y0), (10.0, 10.0)); + assert_eq!(boxes.iter().filter(|b| b.y0 == 10.0).count(), 5); + assert_eq!((boxes[0].x0, boxes[0].y0), (630.0, 125.0)); + assert_eq!(r["length"], json!(10.0 + 115.0 + 100.0 + 10.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, ids[0]), Rect::new(900.0, 700.0, 1050.0, 800.0)); +} + +#[test] +fn objects_that_do_not_fit_go_beside_the_sheet() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 500.0, 400.0); + let b = rect(&mut s, 1500.0, 0.0, 500.0, 400.0); + let big = rect(&mut s, 2100.0, 0.0, 900.0, 100.0); + select(&mut s, &[a, b, big]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(1)); + assert_eq!(r["unplaced"], json!([b.0, big.0])); + assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 500.0, 400.0)); + // A column 5 pt to the right of the 800 pt sheet, in stacking order, 5 pt apart. + assert_eq!(bounds(&s, b), Rect::new(805.0, 0.0, 1305.0, 400.0)); + assert_eq!(bounds(&s, big), Rect::new(805.0, 405.0, 1705.0, 505.0)); +} + +#[test] +fn the_column_beside_the_sheet_is_in_stacking_order() { + let mut s = session(); + let back = rect(&mut s, 900.0, 0.0, 900.0, 100.0); + let front = rect(&mut s, 900.0, 200.0, 900.0, 50.0); + let small = rect(&mut s, 900.0, 400.0, 50.0, 50.0); + // Selected front first: the column still starts with the object at the back. + select(&mut s, &[front, small, back]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 5, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["unplaced"], json!([back.0, front.0])); + assert_eq!(bounds(&s, back), Rect::new(805.0, 0.0, 1705.0, 100.0)); + assert_eq!(bounds(&s, front), Rect::new(805.0, 105.0, 1705.0, 155.0)); +} + +#[test] +fn objects_without_bounds_are_skipped_and_listed() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0); + let layer = s.doc().unwrap().doc.parent_of(a); + let empty = s + .edit("empty group", |d, _| { + let g = vectorcraft_doc::Node::new(d.alloc_id(), vectorcraft_doc::NodeKind::Group { children: vec![], clip: false }); + Ok(d.insert(layer, usize::MAX, g).unwrap()) + }) + .unwrap(); + select(&mut s, &[a, empty]); + let r = s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["skipped"].clone()), (json!(1), json!([]), json!([empty.0]))); + assert_eq!(bounds(&s, a), Rect::new(0.0, 0.0, 50.0, 50.0)); +} + +#[test] +fn the_sheet_is_the_artboard_under_the_center_of_the_selection() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap(); + let a = rect(&mut s, 1100.0, 100.0, 50.0, 50.0); + let b = rect(&mut s, 1200.0, 200.0, 40.0, 40.0); + select(&mut s, &[a, b]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0), "on the second artboard, not the first"); + assert_eq!(bounds(&s, b), Rect::new(1050.0, 0.0, 1090.0, 40.0)); +} + +#[test] +fn rotate_turns_clockwise() { + let mut s = session(); + // A 400 × 100 group with a 20 pt mark at its top-left corner. Turned clockwise on the page, the + // top-left corner goes to the top-right. + let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + let mark = rect(&mut s, 900.0, 0.0, 20.0, 20.0); + select(&mut s, &[long, mark]); + s.execute("object.group", &json!({})).unwrap(); + let r = s + .execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false})) + .unwrap(); + assert_eq!(r["rotated"].as_array().map(Vec::len), Some(1)); + assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0)); + assert_eq!(bounds(&s, mark), Rect::new(80.0, 0.0, 100.0, 20.0), "the mark is at the top-right"); +} + +#[test] +fn a_path_of_a_pixel_aligned_compound_path_is_not_turned() { + let mut s = session(); + let outer = rect(&mut s, 900.0, 100.0, 500.0, 200.0); + let hole = rect(&mut s, 950.0, 150.0, 400.0, 100.0); + select(&mut s, &[outer, hole]); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + select(&mut s, &[hole]); + // The 400 pt wide path fits the 300 pt sheet only turned, and it keeps its orientation. + let r = + s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true, "usePreviewBounds": false})); + let e = r.unwrap_err().to_string(); + assert!(e.contains("no selected object fits"), "{e}"); +} + +/// [`Skyline::find`] as a search of every span and every span under the box. +fn find_by_search(sky: &Skyline, w: f64, h: f64) -> Option<(f64, f64)> { + let mut best: Option<(f64, f64)> = None; + for (i, s) in sky.spans.iter().enumerate() { + if s.x + w > sky.width + 1e-9 { + break; + } + let y = sky.spans[i..].iter().take_while(|t| t.x == s.x || t.x < s.x + w - 1e-9).fold(0.0_f64, |m, t| m.max(t.y)); + if y + h > sky.height + 1e-9 { + continue; + } + if best.is_none_or(|(bx, by)| y < by - 1e-9 || ((y - by).abs() <= 1e-9 && s.x < bx)) { + best = Some((s.x, y)); + } + } + best +} + +#[test] +fn find_matches_a_search_of_every_span() { + // A fixed pseudo-random sequence of boxes, each placed where `find` puts it. + let mut seed: u64 = 0x2545_f491_4f6c_dd1d; + let mut next = |n: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n) as f64 + 1.0 + }; + let mut sky = Skyline::new(200.0, 400.0); + for _ in 0..400 { + let (w, h) = (next(60), next(30)); + let got = sky.find(w, h); + assert_eq!(got, find_by_search(&sky, w, h), "{w} × {h} on {:?}", sky.spans); + if let Some((x, y)) = got { + sky.place(x, y, w, h); + } + } +} + +#[test] +fn an_object_that_does_not_fit_is_not_covered_by_the_others() { + let mut s = session(); + // The wide object sits on the sheet and does not fit; the small one must not land on it. + let wide = rect(&mut s, 0.0, 0.0, 900.0, 100.0); + let small = rect(&mut s, 300.0, 300.0, 50.0, 50.0); + select(&mut s, &[wide, small]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert!(!overlap(bounds(&s, wide), bounds(&s, small)), "{:?} {:?}", bounds(&s, wide), bounds(&s, small)); +} + +#[test] +fn objects_on_the_pixel_grid_keep_the_margin_and_spacing() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 90.0); + select(&mut s, &[a, b]); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + let on_grid = |r: Rect| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| (v * 2.0).fract() == 0.0); + assert!(on_grid(bounds(&s, a)) && on_grid(bounds(&s, b))); + s.execute("addon.cutting.nest", &json!({"margin": 0.6, "spacing": 0.6, "usePreviewBounds": false})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + assert!(on_grid(ba) && on_grid(bb), "still on the grid: {ba:?} {bb:?}"); + assert!(ba.x0 >= 0.6 && ba.y0 >= 0.6 && bb.y0 >= 0.6, "inside the margin: {ba:?} {bb:?}"); + assert!(bb.x0 >= ba.x1 + 0.6, "0.6 pt apart: {ba:?} {bb:?}"); + assert!(ba.x1.max(bb.x1) <= 800.0 - 0.6, "inside the margin: {ba:?} {bb:?}"); +} + +#[test] +fn preview_bounds_take_in_a_drop_shadow() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [a.0], "params": {"x": 20, "y": 0, "blur": 0}})).unwrap(); + select(&mut s, &[a, b]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + let shadow = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(a).unwrap()).unwrap(); + assert!(shadow.x1 >= ba.x1 + 20.0 - 1e-9, "the shadow reaches 20 pt right: {shadow:?}"); + let shadow_b = vectorcraft_render::drawn_bounds(&s.doc().unwrap().doc, s.doc().unwrap().doc.node(b).unwrap()).unwrap_or(bb); + assert!(!overlap(shadow, shadow_b.union(bb)), "the shadow {shadow:?} does not reach {bb:?}"); +} + +#[test] +fn a_roll_has_no_end() { + let mut s = session(); + let ids: Vec = (0..5).map(|i| rect(&mut s, 900.0, 300.0 * i as f64, 500.0, 400.0)).collect(); + select(&mut s, &ids); + let r = s.execute("addon.cutting.nest", &json!({"roll": true, "margin": 0, "spacing": 10, "usePreviewBounds": false})).unwrap(); + assert_eq!((r["placed"].clone(), r["unplaced"].clone()), (json!(5), json!([]))); + let mut tops: Vec = ids.iter().map(|id| bounds(&s, *id).y0).collect(); + tops.sort_by(f64::total_cmp); + assert_eq!(tops, vec![0.0, 410.0, 820.0, 1230.0, 1640.0], "one 500 pt wide shape per row on the 800 pt roll"); + assert_eq!(r["length"], json!(2040.0)); +} + +#[test] +fn width_and_height_set_the_sheet_from_the_artboard_corner() { + let mut s = session(); + let ids: Vec = (0..3).map(|i| rect(&mut s, 50.0 * i as f64, 300.0, 40.0, 40.0)).collect(); + select(&mut s, &ids); + let r = s.execute("addon.cutting.nest", &json!({"width": "1 in", "height": 200, "margin": 0, "spacing": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(3)); + for id in &ids { + let b = bounds(&s, *id); + assert!(b.x0 == 0.0 && b.x1 <= 72.0, "one 40 pt shape per row on a 72 pt sheet: {b:?}"); + } +} + +#[test] +fn preview_bounds_keep_strokes_apart() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 1100.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + s.execute("stroke.set", &json!({"weight": 10})).unwrap(); + s.execute("addon.cutting.nest", &json!({"margin": 0, "spacing": 0})).unwrap(); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + assert_eq!((ba.x0, ba.y0), (5.0, 5.0), "the stroke's outer half is inside the sheet"); + assert_eq!((bb.x0 - ba.x1), 10.0, "the strokes touch and do not overlap"); +} + +#[test] +fn a_selection_already_nested_adds_no_undo_step() { + let mut s = session(); + let a = rect(&mut s, 18.0, 18.0, 100.0, 100.0); + select(&mut s, &[a]); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &json!({"usePreviewBounds": false})).unwrap(); + assert_eq!(r["placed"], json!(1)); + assert_eq!(steps(&s), n, "nothing moved"); +} + +#[test] +fn bad_params_are_refused_and_change_nothing() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 100.0, 100.0); + select(&mut s, &[a]); + let n = steps(&s); + let bad: [(Value, &str); 10] = [ + (json!({"rotate": 1}), "`rotate` must be true or false"), + (json!({"width": -1}), "`width` must be from 0"), + (json!({"height": 2e6}), "`height` must be from 0"), + (json!({"margin": "x"}), "`margin` must be a number"), + (json!({"spacing": 1e6}), "`spacing` must be from 0"), + (json!({"roll": "yes"}), "`roll` must be true or false"), + (json!({"usePreviewBounds": 1}), "`usePreviewBounds` must be true or false"), + (json!({"artboard": 3}), "there is no artboard 3"), + (json!({"artboard": -1}), "`artboard` must be"), + (json!({"margin": 400}), "the margin leaves no room"), + ]; + for (p, want) in bad { + let e = s.execute("addon.cutting.nest", &p).expect_err(&p.to_string()).to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + let e = s.execute("addon.cutting.nest", &json!({"width": 50, "margin": 0})).unwrap_err().to_string(); + assert!(e.contains("no selected object fits"), "{e}"); + let e = s.execute("addon.cutting.nest", &json!({"patterns": "no"})).unwrap_err().to_string(); + assert!(e.contains("`patterns` must be true or false"), "{e}"); + assert_eq!(steps(&s), n, "a refused run changes nothing"); + assert_eq!(bounds(&s, a), Rect::new(900.0, 0.0, 1000.0, 100.0)); +} + +#[test] +fn the_named_artboard_is_the_sheet() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 300, "height": 300})).unwrap(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + select(&mut s, &[a]); + s.execute("addon.cutting.nest", &json!({"artboard": 1, "margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, a), Rect::new(1000.0, 0.0, 1050.0, 50.0)); +} + +#[test] +fn rotate_turns_objects_a_quarter_to_fit_the_sheet() { + let mut s = session(); + // On a 300 × 500 sheet with no margin, a 400 × 100 object only fits standing up. + let long = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + let small = rect(&mut s, 900.0, 300.0, 50.0, 40.0); + select(&mut s, &[long, small]); + let p = json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "usePreviewBounds": false}); + let r = s.execute("addon.cutting.nest", &p).unwrap(); + assert_eq!((r["unplaced"].clone(), r["rotated"].clone()), (json!([long.0]), json!([])), "without rotate it does not fit"); + s.execute("edit.undo", &json!({})).unwrap(); + let mut p = p; + p["rotate"] = json!(true); + let n = steps(&s); + let r = s.execute("addon.cutting.nest", &p).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!((r["placed"].clone(), r["unplaced"].clone(), r["rotated"].clone()), (json!(2), json!([]), json!([long.0]))); + assert_eq!(bounds(&s, long), Rect::new(0.0, 0.0, 100.0, 400.0), "turned and at the corner"); + // The 50 × 40 object stays as it is: turned, its bottom edge would be lower. + assert_eq!(bounds(&s, small), Rect::new(100.0, 0.0, 150.0, 40.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(bounds(&s, long), Rect::new(900.0, 0.0, 1300.0, 100.0), "undo turns it back"); +} + +#[test] +fn rotate_measures_the_turned_preview_bounds() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 400.0, 100.0); + select(&mut s, &[a]); + s.execute("stroke.set", &json!({"weight": 10})).unwrap(); + let r = s.execute("addon.cutting.nest", &json!({"width": 300, "height": 500, "margin": 0, "spacing": 0, "rotate": true})).unwrap(); + assert_eq!(r["rotated"], json!([a.0])); + assert_eq!(bounds(&s, a), Rect::new(5.0, 5.0, 105.0, 405.0), "the turned stroke's outer half is inside the sheet"); +} + +#[test] +fn a_compound_paths_path_selected_alone_moves_alone() { + let mut s = session(); + let outer = rect(&mut s, 900.0, 100.0, 40.0, 40.0); + let hole = rect(&mut s, 910.0, 110.0, 10.0, 10.0); + select(&mut s, &[outer, hole]); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + select(&mut s, &[hole]); + s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!(bounds(&s, hole), Rect::new(0.0, 0.0, 10.0, 10.0), "the path moved"); + assert_eq!(bounds(&s, outer), Rect::new(900.0, 100.0, 940.0, 140.0), "the rest of the compound path stayed"); +} + +#[test] +fn a_group_is_nested_as_one_object() { + let mut s = session(); + let a = rect(&mut s, 900.0, 0.0, 50.0, 50.0); + let b = rect(&mut s, 1000.0, 100.0, 50.0, 50.0); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + s.execute("addon.cutting.nest", &json!({"margin": 0, "usePreviewBounds": false})).unwrap(); + assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(0.0, 0.0, 50.0, 50.0), Rect::new(100.0, 100.0, 150.0, 150.0))); +} diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 97230cec0e..b9b517ae85 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -498,8 +498,9 @@ pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec { } /// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own -/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. -pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) { +/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. The graph stops keeping the +/// groups' opacity, blend mode, isolation and knockout. Returns whether what a graph keeps changed. +pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) -> bool { for id in groups { if let Some(n) = d.node_mut(*id) { clear(n); @@ -507,6 +508,7 @@ pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) { n.extras_mut().graphic_style = None; } } + super::graph::capture_series_object_opacity(d, groups) } /// [`whole_targets`] of `cmd`, which needs at least one. @@ -943,7 +945,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape); super::object::snap_if_aligned(to); } - clear_stood_for(d, &group); + let forgot = clear_stood_for(d, &group); for id in &cleared { if let Some(n) = d.node_mut(*id) { clear(n); @@ -961,7 +963,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { // 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); let all: Vec = from.iter().chain(&targets).chain(&group).copied().collect(); - Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels)) + Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot)) })?; s.active_appearance_item = None; Ok(json!({ "source": source.0, "target": target.0 })) diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index e30e6efcdc..cb990e4857 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -89,7 +89,7 @@ pub fn specs() -> Vec { "Asset Export Settings", [], None, - "{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?, antiAlias?} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step", + "{exportPreset?: (a preset of document.exportPresets.list: its formats or preset, its format settings over the saved ones, its prefix (none when it has none), its folders (or subfolders: rows or none) with subfolders on for rows, and antiAlias; the other keys go over it), formats?, preset?: mobile|density|\"\" (none), settings?, prefix?, subfolders?: true|false (Create Sub-folders: true sorts the files into a folder per row; false puts assets.export's files in the folder itself and, given without exportPreset, sets a remembered folder per format or item to none as well), antiAlias?, openLocation?: true|false (Open Location after Export: remembered in document.exportSettings, not in presets or the reply; given alone to a document without settings, Create Sub-folders stays on)} change the export settings the Asset Export panel and Export for Screens share (document.exportSettings; the values of document.exportForScreens; null removes one): formats replace a preset, a preset replaces the formats → {settings}. Not an undo step", has_doc, settings_set ), @@ -435,19 +435,35 @@ fn export(s: &mut Session, p: &Value) -> Result { fn settings_set(s: &mut Session, p: &Value) -> Result { const C: &str = "assets.settings.set"; let o = p.as_object().ok_or_else(|| bad(C, "give the settings to change, e.g. {\"formats\": [{\"format\": \"png\", \"scale\": \"2x\"}]}"))?; - if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && k.as_str() != "exportPreset") { - return Err(bad(C, format!("`{k}` isn't an export setting: {}", SCREEN_SETTINGS_KEYS.join(", ")))); + if let Some(k) = o.keys().find(|k| !SCREEN_SETTINGS_KEYS.contains(&k.as_str()) && !matches!(k.as_str(), "exportPreset" | "openLocation")) { + return Err(bad(C, format!("`{k}` isn't an export setting: {}, openLocation", SCREEN_SETTINGS_KEYS.join(", ")))); + } + for k in ["subfolders", "openLocation"] { + if o.get(k).is_some_and(|v| !v.is_boolean() && !v.is_null()) { + return Err(bad(C, format!("`{k}` is true or false"))); + } } let mut settings = s.doc()?.doc.export_settings.clone(); let mut given = o.clone(); + // Create Sub-folders is on for a document without settings (Export for Screens opens so), and + // Open Location after Export set on its own leaves it on. + if settings.is_empty() && o.len() == 1 && o.get("openLocation").is_some_and(Value::is_boolean) { + given.insert("subfolders".into(), json!(true)); + } if let Some(name) = given.remove("exportPreset") { let name = name.as_str().ok_or_else(|| bad(C, "`exportPreset` is the name of a preset of document.exportPresets.list"))?; with_screen_export_preset(s, C, &mut settings, name)?; } // Create Sub-folders is Export for Screens' folder per row: the dialog opens on the choice. + // Turned off on its own (the panel menu), it also ends a remembered folder per format or item; + // with an export preset, that preset's folder per format or item stays. + let folders = settings.get("folders").and_then(Value::as_str).map(str::to_string); + let sorted = folders.as_deref().is_some_and(|f| f != "none"); match given.get("subfolders").and_then(Value::as_bool) { Some(true) => _ = settings.insert("folders".into(), json!("rows")), - Some(false) if settings.get("folders").and_then(Value::as_str) == Some("rows") => _ = settings.insert("folders".into(), json!("none")), + Some(false) if folders.as_deref() == Some("rows") || (sorted && !o.contains_key("exportPreset")) => { + _ = settings.insert("folders".into(), json!("none")) + } _ => {} } overlay(&mut settings, &given); diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 038a4202a6..6a1f0d6496 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Shape Builder", [], None, - "{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one", + "{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it, where filled means any fill row is shown, painted and above 0% opacity, whichever row is on top; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one", has_selection_or_ids, sb_merge ), diff --git a/crates/engine/src/cmd/buildcmds/shape_builder.rs b/crates/engine/src/cmd/buildcmds/shape_builder.rs index fea79a0e6a..472ba2208b 100644 --- a/crates/engine/src/cmd/buildcmds/shape_builder.rs +++ b/crates/engine/src/cmd/buildcmds/shape_builder.rs @@ -63,7 +63,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result { && let Some(&q) = pts.first() && let Some((i, run)) = map.stroke_at(&outlines, q, tol) && let (Some(leaf), Some(drawn)) = (leaves.get(i), outlines.get(i)) - && let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && !leaf.appearance.fill_paint().is_none(), b::outline_snap(drawn)) + && let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && leaf.appearance.has_drawn_fill(), b::outline_snap(drawn)) && rest.length() > b::outline_snap(drawn) { // The path keeps the rest of it, and a copy of it with the run under the click goes diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 89091248df..647f4a4342 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -70,13 +70,26 @@ pub(super) fn grid_show(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(_) => Some(switch_or(p, "visible", false, C)?), }; - let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?; + // A hidden grid holds no plane for Automatic Plane Positioning. + let g = silent(s, |g| { + g.visible = want.unwrap_or(!g.visible); + if !g.visible { + g.inferred = None; + } + })?; Ok(json!({ "visible": g.visible })) } pub(super) fn plane_set(s: &mut Session, p: &Value) -> Result { let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?; - silent(s, |g| g.plane = plane)?; + // The new active plane passes through the point Automatic Plane Positioning holds, unless no + // plane is active or that would put the plane behind the viewer. + silent(s, |g| { + g.plane = plane; + if g.inferred.is_some() && (plane == Plane::None || g.validate().is_err()) { + g.inferred = None; + } + })?; Ok(json!({ "plane": plane.id() })) } @@ -138,6 +151,9 @@ pub(super) fn attach(s: &mut Session, p: &Value) -> Result { store_grid(d, &g); Ok(()) })?; + if !ids.is_empty() { + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; + } Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "plane": plane.id() })) } @@ -205,8 +221,13 @@ fn persp_edit( return Err(EngineError::Other("select the objects to transform in perspective".into())); } let mut g = grid_of(&s.doc()?.doc); + // An object not in perspective yet attaches to `fallback` where that plane is now. + let attaches = { + let d = &s.doc()?.doc; + fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none())) + }; let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None }; - s.edit(label, |d, sel| { + let edited = s.edit(label, |d, sel| { g.adopt_stored_attachments(d); let targets = match &kept { // The document becomes the snapshot with the kept copies, not yet mapped, and the loop @@ -236,7 +257,11 @@ fn persp_edit( } store_grid(d, &g); Ok((targets, first)) - }) + })?; + if let Some(plane) = attaches { + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; + } + Ok(edited) } /// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one @@ -430,6 +455,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["offset", "by"], C)?; let old = grid_of(&s.doc()?.doc); let plane = plane_param(&old, p, C)?; + // A plane that Automatic Plane Positioning holds moves from where it is held, and the move + // places it there for good: the moved grid holds no plane (undoing the move holds it again). + let held = old.inferred; let from = old.offset(plane); let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) { (Some(o), _) => o, @@ -440,7 +468,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { if !matches!(objects, "none" | "move" | "copy") { return Err(bad(C, "objects must be none, move or copy")); } - let mut g = old.clone(); + let mut g = PerspectiveGrid { inferred: None, ..old.clone() }; g.set_offset(plane, to); g.validate().map_err(|e| bad(C, e))?; let label = match objects { @@ -458,8 +486,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { .collect() }; // A plane moved to where it is, with its objects or without them, moves nothing: when the - // document holds the grid already, the document and its undo history stay as they are. - if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) { + // document holds the grid already, the document and its undo history stay as they are (a + // plane held where it was placed stays held). + if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) { let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] }; return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::>() })); } @@ -507,12 +536,19 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result { named_id(p)?.or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select an object in perspective".into()))?; let mut g = grid_of(&st.doc); let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?; + // The moved grid holds no plane for Automatic Plane Positioning (undoing the move holds it + // again). + let held = g.inferred.take(); g.set_offset(plane, depth); g.plane = plane; g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?; // When the plane is at the object and active already, and the document holds that grid, the - // document and its undo history stay as they are. - if grid_kept(&st.doc, &g) { + // document and its undo history stay as they are; a plane held elsewhere goes back to that + // place as view state. + if grid_kept(&st.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) { + if held.is_some() { + silent(s, |g| g.inferred = None)?; + } return Ok(json!({ "plane": plane.id(), "offset": depth })); } s.edit("Move Plane to Match Object", |d, _| { @@ -573,6 +609,7 @@ pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result { st.history.recost_last(&st.doc); } res?; + crate::cmd::perspgrid::plane_positioning_used(s, plane)?; Ok(json!({ "id": id.0, "plane": plane.id() })) } diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 02dbad5d23..43975fe4e4 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -265,25 +265,27 @@ fn gradient_expands(d: &Document, l: &Node) -> bool { /// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the /// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough -/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline -/// graphics and color glyphs become other art. Leaves the document as it is and stops at the -/// first such path. +/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one +/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves +/// the document as it is and stops at the first such path. fn text_gradient_expands(d: &Document, t: &TextObject) -> bool { if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) { return false; } let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let first = t.first_style(); let expands = |run: usize, outline: &BezPath| { - let style = t.runs.get(run).map(|r| &r.style); - if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) { + let style = t.runs.get(run).map_or(&first, |r| &r.style); + if !matches!(style.fill, Paint::Gradient(_)) { return false; } - let path = PathData::from_bezpath(outline).transformed(t.xf); + let path = PathData::from_bezpath(outline); if path.is_empty() { return false; } - let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance()); - gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance)) + let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default()); + vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf); + gradient_expands(d, &piece) }; let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some())); lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline)) diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 24a71cc883..a46f46492a 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds), in a row, and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 1a3c4c6e2c..ee33f64c41 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -678,15 +678,28 @@ impl ReadFile { /// ([`super::importer`]). pub fn read_for_open(name: &str, bytes: &[u8], path: Option, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result { let opts = LoadOptions::from_params("document.open", p)?; - let mut loaded = match super::importer::pick(name, bytes, p)? { - Some(plugin) => super::importer::load(name, bytes, &plugin, p)?, - None => load_with(name, bytes, &opts)?, + let mut loaded = if opts.link_pages { + linked_pages(name, bytes, path.as_deref(), &opts)? + } else { + match super::importer::pick(name, bytes, p)? { + Some(plugin) => super::importer::load(name, bytes, &plugin, p)?, + None => load_with(name, bytes, &opts)?, + } }; let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps); Session::refresh_text_bounds(&mut loaded.doc); Ok(ReadFile { loaded, opts, path, links }) } +/// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents +/// linked to them ([`super::pdfimport::linked_pages`]), named after the file. +fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions) -> Result { + let (mut doc, warnings) = super::pdfimport::linked_pages(name, bytes, path, opts)?; + doc.title = file_name(name); + let format = detect(name, bytes).ok_or_else(|| err(format!("can't open `{}`: not a PDF", file_name(name))))?; + Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None }) +} + /// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active /// document → `document.open`'s result. pub fn open_read(s: &mut Session, file: ReadFile) -> Result { diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 2a0dede17f..b0f08ca4c5 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -2,11 +2,15 @@ //! and `file.place` read ([`LoadOptions`]), the pages they import and `document.pdfInfo` (pages, //! boxes, a thumbnail; one page for a PostScript file) for the Import PDF dialog. +use std::sync::Arc; + use serde_json::{Value, json}; -use vectorcraft_doc::{ColorMode, Document}; +use vectorcraft_doc::{Artboard, ColorMode, Document, LayerColor, LinkInfo, Node, NodeKind}; +use vectorcraft_geom::{Affine, Rect}; use vectorcraft_pdf::{Choice, CropTo, ImportOptions, PdfError, TextAs}; use super::super::colormgmt::Grays; +use super::super::place::document; use super::super::{Result, Session, bad, check_numbers, number_or, parse_range, text_param}; use super::{err, source}; @@ -47,6 +51,9 @@ pub struct LoadOptions { /// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries; /// off, it opens as another app would open it, from the editing copy of its art or its pages. pub native: bool, + /// Each page of a PDF opens as a placed document linked to that page of its file, on an + /// artboard of its own, instead of as editable art (`linkPages`; see [`linked_pages`]). + pub link_pages: bool, } impl Default for LoadOptions { @@ -65,6 +72,7 @@ impl Default for LoadOptions { trust_editing_data: false, legacy_names: vectorcraft_eps::NameEncoding::default(), native: true, + link_pages: false, } } } @@ -74,8 +82,8 @@ impl LoadOptions { /// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`, /// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false), /// `editingData` (true | false | `always`), - /// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF - /// import options). + /// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true | + /// false) and `dxf` (the DXF import options). pub fn from_params(cmd: &str, p: &Value) -> Result { let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) { None => None, @@ -115,6 +123,10 @@ impl LoadOptions { .and_then(vectorcraft_eps::NameEncoding::from_label) .ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?, }; + let link_pages = match p.get("linkPages").filter(|v| !v.is_null()) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?, + }; let dxf = super::dxfimport::options(cmd, p.get("dxf"))?; Ok(Self { pages, @@ -130,14 +142,15 @@ impl LoadOptions { trust_editing_data, legacy_names, native: true, + link_pages, }) } /// Does the document read only part of the file, or read it differently (a page range, another - /// box, a password, without its hidden layers, without the VectorCraft document it carries)? - /// Writing it back would lose the rest, so Save doesn't (it asks for a name). + /// box, a password, without its hidden layers, without the VectorCraft document it carries, its + /// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name). pub fn is_partial(&self) -> bool { - self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native + self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages } /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible @@ -201,6 +214,82 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } +/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or +/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to +/// that page of the file as File › Place with Link places one ([`document::source`]). Each page +/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`), in a row from the left +/// with the gap a PDF's artboards open with, and a layer named after the page. The document opens +/// in CMYK when most of the pages read in CMYK, unless `o.color_mode` names a mode. Refused without a +/// path, for any other file, with a password (a linked page is read again without one), with +/// `textAs: outlines` (a linked page shows the file's own type) and for a file over +/// [`document::MAX_FILE`] → the document and the notes of reading its pages. +pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &LoadOptions) -> Result<(Document, Vec)> { + const C: &str = "document.open"; + let file = super::file_name(name); + if !document::is_pdf(name, bytes) { + return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file"))); + } + let path = path.ok_or_else(|| bad(C, "linkPages needs the file's path: linked pages are read from it"))?; + if o.password.is_some() { + return Err(bad(C, "linkPages can't open a file with a password: linked pages are read again without it")); + } + if o.text_as != TextAs::Text { + return Err(bad(C, "linkPages can't be used with textAs: outlines: linked pages show the file's own type")); + } + if bytes.len() > document::MAX_FILE { + return Err(bad(C, format!("linkPages: `{file}` is over {} MB", document::MAX_FILE >> 20))); + } + let count = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?.page_count(); + let picked = match &o.pages { + None => (0..count).collect(), + Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?, + }; + let bounding = o.crop == CropTo::Bounding; + let mut doc = Document::new(1.0, 1.0); + let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?; + doc.artboards.clear(); + doc.layers.clear(); + let link = crate::cmd::links::link_info(path, bytes); + let gap = ImportOptions::default().artboard_gap; + // Every page's object keeps the same one copy of the file. + let shared = Arc::new(bytes.to_vec()); + let (mut x, mut warnings, mut cmyk_pages) = (0.0, Vec::::new(), 0); + for (i, &index) in picked.iter().enumerate() { + let page = index as u32 + 1; + let s = document::shared_source(name, &shared, Some(path), page, bounding, document::page_box(o.crop), C)?; + cmyk_pages += usize::from(s.color_mode == ColorMode::Cmyk); + let mut node = document::node(&mut doc, &s, LinkInfo { page: Some(page), ..link.clone() }, bounding); + if let NodeKind::PlacedDocument(p) = &mut node.kind { + p.xf = Affine::translate((x, 0.0)); + } + node.name = Some(file.clone()); + let mut layer = Node::layer(doc.alloc_id(), &format!("Page {page}"), LayerColor::Preset((i % 27) as u8)); + if let NodeKind::Layer { children, .. } = &mut layer.kind { + children.push(Arc::new(node)); + } + doc.layers.push(Arc::new(layer)); + let rect = Rect::new(x, 0.0, x + s.frame.width(), s.frame.height()); + doc.artboards.push(Artboard { id: i as u32 + 1, name: format!("Artboard {}", i + 1), rect, ..board.clone() }); + x = rect.x1 + gap; + for w in s.warnings { + if !warnings.contains(&w) { + warnings.push(w); + } + } + } + // Pages painted mostly in CMYK read as CMYK documents, as opening them as art does: the + // document opens in CMYK (with the CMYK default swatches) when most of its pages do. + if cmyk_pages * 2 > picked.len() { + doc.color_mode = ColorMode::Cmyk; + let (swatches, groups) = vectorcraft_color::default_swatches(ColorMode::Cmyk.model()); + (doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into()); + } + if let Some(mode) = o.color_mode.filter(|m| *m != doc.color_mode) { + super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, o.grays); + } + Ok((doc, warnings)) +} + const INFO: &str = "document.pdfInfo"; /// `document.pdfInfo`. diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 6998d86b28..119201bb87 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -3,26 +3,22 @@ //! header's HDpi and VDpi, JP2 capture and display resolution boxes, or a HEIF image's EXIF //! resolution tags. Place //! sizes an image by it (72 ppi when the file has none); images converted to PNG on import keep it -//! as a `pHYs` chunk. +//! as a `pHYs` chunk. The formats the image decoder reads are read by [`vectorcraft_doc::ppi`]. + +pub(super) use vectorcraft_doc::ppi::png_chunks; +use vectorcraft_doc::ppi::tiff; +pub use vectorcraft_doc::ppi::with_png_resolution; const INCH_M: f64 = 0.0254; -const INCH_CM: f64 = 2.54; /// The resolution a file declares as (horizontal, vertical) ppi; `None` when it declares none (or /// only an aspect ratio). pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> { - let r = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { - png(bytes) - } else if bytes.starts_with(&[0xff, 0xd8]) { - jpeg(bytes) - } else if bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*") { - tiff(bytes) - } else if super::jxlread::is_jxl(bytes) { + if vectorcraft_doc::ppi::reads(bytes) { + return vectorcraft_doc::ppi::resolution(bytes); + } + let r = if super::jxlread::is_jxl(bytes) { jxl(bytes) - } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { - webp(bytes) - } else if bytes.starts_with(b"BM") { - bmp(bytes) } else if super::psdread::is_psd(bytes) { super::psdread::resolution(bytes) } else if super::pcxread::is_pcx(bytes) { @@ -82,121 +78,9 @@ fn slice(b: &[u8], at: usize, n: usize) -> Option<&[u8]> { fn bytes(b: &[u8], at: usize) -> Option<[u8; N]> { slice(b, at, N)?.try_into().ok() } -fn be16(b: &[u8], at: usize) -> Option { - bytes(b, at).map(u16::from_be_bytes) -} fn be32(b: &[u8], at: usize) -> Option { bytes(b, at).map(u32::from_be_bytes) } -fn le32(b: &[u8], at: usize) -> Option { - bytes(b, at).map(u32::from_le_bytes) -} - -/// Pixels per inch from the whole pixels per metre PNG and BMP store: a whole number of ppi when -/// the metre value is that rounded (300 ppi is stored as 11811 per metre, 299.9994 ppi). -fn per_metre(ppm: u32) -> f64 { - let v = ppm as f64 * INCH_M; - let whole = v.round(); - if (v - whole).abs() <= INCH_M / 2.0 + 1e-9 { whole } else { v } -} - -/// PNG chunks after the signature: (type, data). -pub(super) fn png_chunks(b: &[u8]) -> impl Iterator { - let mut at = 8; - std::iter::from_fn(move || { - let len = be32(b, at)? as usize; - let ty = slice(b, at + 4, 4)?; - let data = slice(b, at + 8, len)?; - at = at.checked_add(12 + len)?; - Some((ty, data)) - }) -} - -fn png(b: &[u8]) -> Option<(f64, f64)> { - let (_, d) = png_chunks(b).take_while(|(ty, _)| *ty != b"IDAT").find(|(ty, _)| *ty == b"pHYs")?; - // Unit 1 = metre; 0 only gives the pixel aspect ratio. - (d.get(8) == Some(&1)).then(|| (per_metre(be32(d, 0).unwrap_or(0)), per_metre(be32(d, 4).unwrap_or(0)))) -} - -fn jpeg(b: &[u8]) -> Option<(f64, f64)> { - let (mut jfif, mut exif) = (None, None); - let mut at = 2; - while at + 4 <= b.len() && b[at] == 0xff { - let marker = b[at + 1]; - // 0xff fill bytes pad between segments. - if marker == 0xff { - at += 1; - continue; - } - if marker == 0xd8 || marker == 0x01 || (0xd0..=0xd7).contains(&marker) { - at += 2; - continue; - } - // Start of scan or end of image: no more metadata. - if marker == 0xda || marker == 0xd9 { - break; - } - let len = be16(b, at + 2)? as usize; - let seg = slice(b, at + 4, len.checked_sub(2)?)?; - match marker { - 0xe0 if seg.starts_with(b"JFIF\0") && seg.len() >= 12 => { - let (x, y) = (be16(seg, 8)? as f64, be16(seg, 10)? as f64); - jfif = match seg[7] { - 1 => Some((x, y)), - 2 => Some((x * INCH_CM, y * INCH_CM)), - _ => None, - }; - } - 0xe1 if seg.starts_with(b"Exif\0\0") => exif = tiff(&seg[6..]), - _ => {} - } - at += 2 + len; - } - jfif.or(exif) -} - -/// TIFF (or EXIF) IFD0 XResolution / YResolution / ResolutionUnit. -fn tiff(b: &[u8]) -> Option<(f64, f64)> { - let le = b.starts_with(b"II"); - let u16_at = |at: usize| bytes(b, at).map(if le { u16::from_le_bytes } else { u16::from_be_bytes }); - let u32_at = |at: usize| bytes(b, at).map(if le { u32::from_le_bytes } else { u32::from_be_bytes }); - let ifd = u32_at(4)? as usize; - let (mut x, mut y, mut unit) = (None, None, 2); - for i in 0..u16_at(ifd)? as usize { - let e = ifd.checked_add(2 + i * 12)?; - let rational = || -> Option { - let at = u32_at(e + 8)? as usize; - let (n, d) = (u32_at(at)?, u32_at(at.checked_add(4)?)?); - (d != 0).then(|| n as f64 / d as f64) - }; - match u16_at(e)? { - 282 => x = rational(), - 283 => y = rational(), - 296 => unit = u16_at(e + 8)?, - _ => {} - } - } - let k = match unit { - 2 => 1.0, - 3 => INCH_CM, - _ => return None, - }; - let x = x?; - Some((x * k, y.unwrap_or(x) * k)) -} - -fn webp(b: &[u8]) -> Option<(f64, f64)> { - let mut at = 12; - while at + 8 <= b.len() { - let len = le32(b, at + 4)? as usize; - let data = b.get(at + 8..at + 8 + len)?; - if &b[at..at + 4] == b"EXIF" { - return tiff(data.strip_prefix(b"Exif\0\0").unwrap_or(data)); - } - at += 8 + len + (len & 1); - } - None -} fn jxl(b: &[u8]) -> Option<(f64, f64)> { if !b.starts_with(&[0, 0, 0, 12, b'J', b'X', b'L', b' ', 13, 10, 135, 10]) { @@ -224,33 +108,6 @@ fn jxl(b: &[u8]) -> Option<(f64, f64)> { None } -fn bmp(b: &[u8]) -> Option<(f64, f64)> { - // BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28. - if le32(b, 14)? < 40 { - return None; - } - let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre); - Some((ppm(38)?, ppm(42)?)) -} - -/// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced). -pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec { - let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() }; - let chunk = vectorcraft_render::encode::png::phys_chunk(x, y); - let mut out = Vec::with_capacity(png.len() + chunk.len()); - out.extend_from_slice(head); - out.extend_from_slice(&chunk); - let mut at = head.len(); - while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) { - if chunk.get(4..8) != Some(b"pHYs") { - out.extend_from_slice(chunk); - } - at += chunk.len(); - } - out.extend_from_slice(png.get(at..).unwrap_or_default()); - out -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 5cbdd8f291..879767d8be 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -865,7 +865,8 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se } /// Store on their graphs what the members `edited`, and the objects in them, took on the paths directly in a graph -/// series, for the graph's next redraw. The edited member is left to the edit's own command. +/// series, and the transparency a series group among them took, for the graph's next redraw. The edited member is left to +/// the edit's own command. fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) { let mut taken = vec![]; for id in edited { @@ -874,6 +875,8 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) { } } super::appearance::capture_series_changes(before, d, &taken); + let groups = super::graph::series_groups_among(d, &taken); + super::graph::capture_series_object_opacity(d, &groups); } /// The outlines of the members of the active document's Global Edit that are not selected, hold diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index da23bd4f04..3a6ee2fdf5 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -40,6 +40,7 @@ pub use commands::specs; pub(crate) use data::apply_csv; #[cfg(test)] use data::{fmt_value, parse_csv, to_csv}; +pub(crate) use edit::{graphs_holding, keep_placed}; #[cfg(test)] use generate::generate; #[cfg(test)] @@ -47,7 +48,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_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, + label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in, series_object_opacity_differs, shown_paint, }; diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index c7f6d52ea8..e1c5c336b3 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -1,3 +1,5 @@ +use vectorcraft_doc::graph::art_bounds; + use super::axis::{MAX_TICK_MARKS, count_given, one_line}; use super::data::apply_data; use super::generate::{children_bounds, generate}; @@ -17,11 +19,62 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result>> { } } +/// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now: +/// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such +/// bounds with a width and a height, or has no art without type now. +fn measured(n: &Node) -> Option<(Rect, Rect)> { + let kept = n.extras().graph.as_deref()?; + let c = n.children()?; + let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c)); + art.or_else(|| kept.placed.zip(children_bounds(c))) +} + +/// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them. +/// `None` when `from` has no width or no height. +fn carried(r: Rect, from: Rect, to: Rect) -> Option { + if from.width() <= 1e-9 || from.height() <= 1e-9 { + return None; + } + let (sx, sy) = (to.width() / from.width(), to.height() / from.height()); + Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy)) +} + +/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to +/// [`keep_placed`] after an edit that changes a graph's art without moving the graph. +pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option, Option)> { + let mut out: Vec<(NodeId, Option, Option)> = vec![]; + for id in ids { + let Some(chain) = d.ancestry(*id) else { continue }; + let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some())); + let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue }; + let children = d.node(gid).and_then(Node::children); + out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c)))); + } + out +} + +/// After an edit that changed the art of `graphs` (from [`graphs_holding`]) without moving them, set the bounds each +/// keeps so that its next redraw measures the same move or scale as it would have before the edit. +pub(crate) fn keep_placed(d: &mut Document, graphs: &[(NodeId, Option, Option)]) { + for &(gid, art_was, whole_was) in graphs { + let Some(n) = d.node(gid) else { continue }; + let children = n.children(); + let (art_now, whole_now) = (children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c))); + let Some(spec) = d.node_mut(gid).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; + if let (Some(placed), Some(was), Some(now)) = (spec.placed_art, art_was, art_now) { + spec.placed_art = carried(now, was, placed).or(spec.placed_art); + } + if let (Some(placed), Some(was), Some(now)) = (spec.placed, whole_was, whole_now) { + spec.placed = carried(now, was, placed).or(spec.placed); + } + } +} + /// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last -/// generation, which is recorded in the spec's `placed` bounds). +/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them). pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> { let n = d.node(id).ok_or(EngineError::NoNode(id))?; - if let (Some(placed), Some(now)) = (n.extras().graph.as_ref().and_then(|g| g.placed), n.children().and_then(|c| children_bounds(c))) + if let Some((placed, now)) = measured(n) && placed.width() > 1e-9 && placed.height() > 1e-9 && (placed.x0 - now.x0).abs() + (placed.y0 - now.y0).abs() + (placed.x1 - now.x1).abs() + (placed.y1 - now.y1).abs() > 1e-6 @@ -33,6 +86,7 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R } let children = generate(d, &spec); spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; if let Some(ch) = n.children_mut() { *ch = children; diff --git a/crates/engine/src/cmd/graph/generate.rs b/crates/engine/src/cmd/graph/generate.rs index fe8ffb98f8..5fadcb8768 100644 --- a/crates/engine/src/cmd/graph/generate.rs +++ b/crates/engine/src/cmd/graph/generate.rs @@ -6,7 +6,7 @@ use super::labels::{ recolour_text, runs, shadow_of, }; use super::markers::{MARKER_BUDGET, marker_cost, marker_designs}; -use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_opacity}; +use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_group_opacity, with_series_opacity}; use super::{ Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes, }; @@ -1005,7 +1005,7 @@ impl<'a> Plot<'a> { } } let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1)); - let grp = self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items))); + let grp = with_series_group_opacity(g, s, self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items)))); self.b.out.push(grp); } self.b.out.append(&mut self.on_top); diff --git a/crates/engine/src/cmd/graph/series.rs b/crates/engine/src/cmd/graph/series.rs index 5f6d602ad5..681c1a6a4a 100644 --- a/crates/engine/src/cmd/graph/series.rs +++ b/crates/engine/src/cmd/graph/series.rs @@ -475,15 +475,16 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool settle_series_paints(doc, before) } -/// Copy the object opacity and blend mode of generated series art just edited (`edited`) into that series' object opacity -/// and blend mode. Called inside the same document edit, so both undo together. Returns whether a series' kept object -/// opacity or blend mode changed. +/// Copy the object transparency of generated series art just edited (`edited`) into what that series keeps: a path +/// directly in a series group sets the paths' object opacity and blend mode, and the series group itself sets the +/// group's opacity, blend mode, isolation, knockout and knockout shape. Called inside the same document edit, so both undo +/// together. Returns whether what a series keeps changed. pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId]) -> bool { let mut before = SeriesPaintsBefore::new(); - for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) { + for (graph, index, group, look) in object_opacity_captures(doc, edited) { let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue }; // A fully opaque Normal object on a series the graph keeps nothing for leaves the graph as it is. - if opacity.is_none() && blend.is_none() && spec.series_paints.len() <= index { + if look == ObjectOpacity::default() && spec.series_paints.len() <= index { continue; } before.entry(graph).or_insert_with(|| spec.series_paints.clone()); @@ -492,7 +493,12 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default()); } let Some(slot) = spec.series_paints.get_mut(index) else { continue }; - (slot.opacity, slot.blend) = (opacity, blend); + if group { + (slot.group_opacity, slot.group_blend) = (look.opacity, look.blend); + (slot.group_isolate, slot.group_knockout, slot.group_knockout_shape) = (look.isolate, look.knockout, look.knockout_shape); + } else { + (slot.opacity, slot.blend) = (look.opacity, look.blend); + } } settle_series_paints(doc, before) } @@ -500,20 +506,50 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId /// Would [`capture_series_object_opacity`] change what the graph stores for `edited`? Reads the document without copying /// it. pub(crate) fn series_object_opacity_differs(doc: &Document, edited: &[NodeId]) -> bool { - let mut after: HashMap<(NodeId, usize), (Option, Option)> = HashMap::new(); - let stored = |graph: NodeId, index: usize| { + let mut after: HashMap<(NodeId, usize, bool), ObjectOpacity> = HashMap::new(); + let stored = |graph: NodeId, index: usize, group: bool| { let spec = doc.node(graph).and_then(|n| n.extras().graph.as_deref()); - spec.and_then(|g| g.series_paints.get(index)).map_or((None, None), |slot| (slot.opacity, slot.blend)) + let slot = spec.and_then(|g| g.series_paints.get(index)); + slot.map_or_else(ObjectOpacity::default, |slot| { + if group { + ObjectOpacity { + opacity: slot.group_opacity, + blend: slot.group_blend, + isolate: slot.group_isolate, + knockout: slot.group_knockout, + knockout_shape: slot.group_knockout_shape, + } + } else { + ObjectOpacity { opacity: slot.opacity, blend: slot.blend, ..ObjectOpacity::default() } + } + }) }; - for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) { - after.insert((graph, index), (opacity, blend)); + for (graph, index, group, look) in object_opacity_captures(doc, edited) { + after.insert((graph, index, group), look); } - after.into_iter().any(|((graph, index), pair)| stored(graph, index) != pair) + after.into_iter().any(|((graph, index, group), look)| stored(graph, index, group) != look) } -/// The series and object opacity and blend mode (None for 100% and Normal) of each of `edited` that is a path directly in a -/// series group, in order. -fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, Option, Option)> { +/// The series groups among `ids`, for an edit that changes only what a group's transparency has beyond its opacity and +/// blend mode (isolation, knockout and knockout shape), which the graph keeps for series groups alone. +pub(crate) fn series_groups_among(doc: &Document, ids: &[NodeId]) -> Vec { + ids.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| n.extras().series_index.is_some())).collect() +} + +/// An object's transparency as a graph keeps it: the object opacity and blend mode (None for 100% and Normal), and for a +/// series group its isolation, knockout (None for neutral) and knockout shape. Paths keep the first two only. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct ObjectOpacity { + opacity: Option, + blend: Option, + isolate: bool, + knockout: Option, + knockout_shape: bool, +} + +/// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object +/// transparency of each of `edited` that is one of those, in order. +fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> { if edited.is_empty() { return Vec::new(); } @@ -524,14 +560,48 @@ fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, us edited .iter() .filter_map(|id| { - // Only the paths the graph draws again, not the copy of a graph design. - let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?; - let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?; - Some((r.graph, r.index, (node.opacity < 1.0).then_some(node.opacity), (node.blend != BlendMode::Normal).then_some(node.blend))) + let r = members.get(id)?; + let group = r.group == *id; + // Only the series group and the paths the graph draws again, not the copy of a graph design. + let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?; + let mut look = ObjectOpacity { + opacity: (node.opacity < 1.0).then_some(node.opacity), + blend: (node.blend != BlendMode::Normal).then_some(node.blend), + ..ObjectOpacity::default() + }; + if group { + look.isolate = node.isolate; + look.knockout = (node.knockout != vectorcraft_doc::Knockout::Neutral).then_some(node.knockout); + look.knockout_shape = node.knockout_shape; + } + Some((r.graph, r.index, group, look)) }) .collect() } +/// Series `i`'s group (`group`) with the object opacity, blend mode, isolation, knockout and knockout shape the graph +/// keeps for it. An opacity read from a file is held to 0..1, and one that is not a number is left out. +pub(super) fn with_series_group_opacity(g: &GraphSpec, i: usize, mut group: Arc) -> Arc { + let Some(slot) = g.series_paints.get(i) else { return group }; + let opacity = slot.group_opacity.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0)); + if opacity.is_none() && slot.group_blend.is_none() && !slot.group_isolate && slot.group_knockout.is_none() && !slot.group_knockout_shape { + return group; + } + let n = Arc::make_mut(&mut group); + if let Some(o) = opacity { + n.opacity = o; + } + if let Some(b) = slot.group_blend { + n.blend = b; + } + if let Some(k) = slot.group_knockout { + n.knockout = k; + } + n.isolate |= slot.group_isolate; + n.knockout_shape |= slot.group_knockout_shape; + group +} + /// Graph Data › Transpose row/column: categories become series and series categories. pub(super) fn transpose(g: &mut GraphSpec) { let cells = g.cells(); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 04eff93a6c..a66bb34c27 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -923,6 +923,32 @@ fn what_global_edit_gives_the_marks_of_another_series_group_survives_regeneratio assert!(series(&n, 1).children().unwrap().iter().all(|m| m.appearance.fill_paint() == given)); } +/// With a whole series group picked and Global Edit on, the opacity and blend mode set on that group reach the other +/// series groups of the same form, and the graph stores them for those groups too. +#[test] +fn the_transparency_global_edit_gives_another_series_group_survives_regeneration() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + // Series without names draw no legend, so each series group holds only its columns, laid out like the other's. + let csv = ",,\nQ1,3,3\nQ2,5,5"; + let made = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(made["id"].as_u64().unwrap()); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let (first, other) = (series(&n, 0).id, series(&n, 1).id); + s.execute("object.isolate", &json!({"id": id.0})).unwrap(); + s.execute("select.set", &json!({"ids": [first.0]})).unwrap(); + let r = s.execute("select.globalEdit", &json!({})).unwrap(); + assert!(r["ids"].as_array().unwrap().contains(&json!(other.0)), "{r}"); + s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 40, "blend": "multiply"})).unwrap(); + let g = s.doc().unwrap().doc.node(other).unwrap().clone(); + assert_eq!((g.opacity, g.blend), (0.4, BlendMode::Multiply), "Global Edit reaches the other group"); + let kept = spec(&s, id).series_paints[1].clone(); + assert_eq!((kept.group_opacity, kept.group_blend), (Some(0.4), Some(BlendMode::Multiply))); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 1).0, (0.4, BlendMode::Multiply)); +} + /// A blend mode set on the top fill or stroke row of one series mark is kept by the graph and drawn on every mark of /// the series again; Normal forgets it. #[test] @@ -2210,8 +2236,8 @@ fn appearance_commands_given_a_series_group_edit_its_marks() { s.execute("edit.undo", &json!({})).unwrap(); let (rect, blue) = blue_style(&mut s, "Blue", false); - let was = spec(&s, id).series_paints; s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap(); + let was = spec(&s, id).series_paints; s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap(); assert!(series_0_group(&s, id).1); assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity"); @@ -2433,10 +2459,10 @@ fn a_graphic_style_applied_to_a_series_group_styles_its_marks() { let (mut s, id, marks) = stored_red_stroke(); let (group, _) = series_0_group(&s, id); let (_, blue) = blue_style(&mut s, "Blue", false); - let was = spec(&s, id).series_paints; let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null}); s.execute("transparency.set", &own).unwrap(); s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap(); + let was = spec(&s, id).series_paints; let g = s.doc().unwrap().doc.node(group).unwrap().clone(); assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal); s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap(); @@ -2513,6 +2539,161 @@ fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() { assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id))); } +/// Series `index`'s group: its object opacity and blend mode, and those of each path directly inside it. +fn group_transparency(s: &Session, id: NodeId, index: u32) -> ((f32, BlendMode), Vec<(f32, BlendMode)>) { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let g = series(&n, index); + ((g.opacity, g.blend), g.children().unwrap().iter().map(|m| (m.opacity, m.blend)).collect()) +} + +/// An object opacity and blend mode set on a selected series group are kept by the graph for the group: the series group +/// has them after the graph is drawn again, the graph's data reads them back unchanged after it is written to JSON, its +/// paths and the other series stay opaque and Normal, setting them again records no step, 100% and Normal forget them, +/// and undo takes them back. +#[test] +fn an_opacity_and_blend_mode_on_a_series_group_survive_regeneration() { + let (mut s, id, _, _) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 40, "blend": "multiply"})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.group_opacity, kept.group_blend), (Some(0.4), Some(BlendMode::Multiply))); + assert_eq!((kept.opacity, kept.blend), (None, None), "the paths keep their own"); + let restored: GraphSpec = serde_json::from_value(serde_json::to_value(spec(&s, id)).unwrap()).unwrap(); + assert_eq!(restored, spec(&s, id)); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + let normal = (1.0, BlendMode::Normal); + let (own, paths) = group_transparency(&s, id, 0); + assert_eq!(own, (0.4, BlendMode::Multiply)); + assert!(!paths.is_empty() && paths.iter().all(|t| *t == normal), "{paths:?}"); + let (own, paths) = group_transparency(&s, id, 1); + assert_eq!(own, normal); + assert!(paths.iter().all(|t| *t == normal), "{paths:?}"); + + let (group, _) = series_0_group(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("object.setProps", &json!({"id": group.0, "opacity": 40, "blend": "multiply"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already"); + s.execute("object.setProps", &json!({"id": group.0, "opacity": 100, "blend": "normal"})).unwrap(); + let kept = spec(&s, id).series_paints[0].clone(); + assert_eq!((kept.group_opacity, kept.group_blend), (None, None)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setData", &json!({"rows": [[2, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 0).0, normal); + for _ in 0..4 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(spec(&s, id).series_paints.is_empty(), "undo takes back the edit and what the graph stored"); +} + +/// Commands that clear a series group's own opacity and blend mode also remove what the graph keeps for it: Clear +/// Appearance on the group, a graphic style applied to it and Move Appearance onto it. +#[test] +fn clearing_a_series_groups_opacity_forgets_what_the_graph_keeps() { + let kept = |s: &Session, id: NodeId| { + let slot = spec(s, id).series_paints[0].clone(); + (slot.group_opacity, slot.group_blend) + }; + let faded = (Some(0.5), Some(BlendMode::Screen)); + let (mut s, id, _, _) = column_marks(); + let (rect, _) = blue_style(&mut s, "Blue", false); + let (group, _) = series_0_group(&s, id); + s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap(); + assert_eq!(kept(&s, id), faded); + let commands = [ + ("appearance.clear", json!({"ids": [group.0]})), + ("graphicStyle.apply", json!({"name": "Blue", "ids": [group.0]})), + ("appearance.transfer", json!({"source": rect.0, "target": group.0, "copy": true})), + ]; + for (cmd, params) in commands { + s.execute(cmd, ¶ms).unwrap(); + assert_eq!(kept(&s, id), (None, None), "{cmd}"); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal), "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(kept(&s, id), faded, "{cmd}"); + } +} + +/// Redefining a graphic style a series group is linked to clears the group's own opacity and blend mode, and removes +/// what the graph keeps for them. +#[test] +fn redefining_a_style_linked_to_a_series_group_forgets_its_kept_opacity() { + let (mut s, id, _, _) = column_marks(); + let (group, _) = series_0_group(&s, 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 i = d.graphic_style_index("Blue").unwrap(); + (d.graphic_styles[i].opacity, d.graphic_styles[i].blend) = (0.5, BlendMode::Screen); + let g = d.node_mut(group).unwrap(); + g.appearance = style.appearance.clone().into(); + (g.opacity, g.blend) = (0.5, BlendMode::Screen); + g.extras_mut().graphic_style = Some(style.id); + Ok(()) + }) + .unwrap(); + s.execute("object.setProps", &json!({"id": group.0, "opacity": 50, "blend": "screen"})).unwrap(); + let slot = spec(&s, id).series_paints[0].clone(); + assert_eq!((slot.group_opacity, slot.group_blend), (Some(0.5), Some(BlendMode::Screen))); + assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, Some(style.id), "still linked"); + s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap(); + let slot = spec(&s, id).series_paints.first().cloned().unwrap_or_default(); + assert_eq!((slot.group_opacity, slot.group_blend), (None, None)); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 0).0, (1.0, BlendMode::Normal)); +} + +/// Isolate Blending, a knockout state and Knockout Shape set on a selected series group are kept by the graph for the +/// group, through the graph being drawn again; the other series' group stays as the graph draws it, and turning them off +/// forgets them. +#[test] +fn isolation_and_knockout_on_a_series_group_survive_regeneration() { + let (mut s, id, _, _) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("transparency.set", &json!({"isolate": true, "knockout": "off", "knockoutShape": true})).unwrap(); + let slot = spec(&s, id).series_paints[0].clone(); + assert_eq!((slot.group_isolate, slot.group_knockout, slot.group_knockout_shape), (true, Some(vectorcraft_doc::Knockout::Off), true)); + assert_eq!((slot.group_opacity, slot.group_blend, slot.opacity, slot.blend), (None, None, None, None)); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("object.setProps", &json!({"id": group.0, "isolate": true})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the values the group and the graph have already"); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let (g, other) = (series(&n, 0), series(&n, 1)); + assert_eq!((g.isolate, g.knockout, g.knockout_shape), (true, vectorcraft_doc::Knockout::Off, true)); + assert_eq!((other.isolate, other.knockout, other.knockout_shape), (false, vectorcraft_doc::Knockout::Neutral, false)); + let (group, _) = series_0_group(&s, id); + s.execute("object.setProps", &json!({"id": group.0, "isolate": false, "knockout": "neutral", "knockoutShape": false})).unwrap(); + assert!(spec(&s, id).series_paints.iter().all(|p| *p == vectorcraft_doc::SeriesPaint::default()), "nothing is kept"); +} + +/// Randomize Opacity and Sort Objects given a series group keep the opacity they give it for the group. +#[test] +fn randomize_and_sort_opacity_on_a_series_group_are_kept() { + let (mut s, id, _, _) = column_marks(); + let (group, _) = series_0_group(&s, id); + s.execute("addon.arrange.randomizeOpacity", &json!({"ids": [group.0], "min": 30, "max": 60, "seed": 7})).unwrap(); + let given = s.doc().unwrap().doc.node(group).unwrap().opacity; + assert!(given < 1.0); + assert_eq!(spec(&s, id).series_paints[0].group_opacity, Some(given)); + s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, 2], [3, 4]]})).unwrap(); + assert_eq!(group_transparency(&s, id, 0).0, (given, BlendMode::Normal)); + + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + let (first, second) = (series(&n, 0).id, series(&n, 1).id); + s.execute("object.setProps", &json!({"id": second.0, "opacity": 80})).unwrap(); + s.execute("addon.arrange.sort", &json!({"ids": [first.0, second.0], "by": "x", "apply": "opacity", "order": "descending"})).unwrap(); + let d = &s.doc().unwrap().doc; + let (a, b) = (d.node(first).unwrap().opacity, d.node(second).unwrap().opacity); + assert_eq!((a, b), (0.8, given), "the opacities trade places"); + let kept = &spec(&s, id).series_paints; + assert_eq!((kept[0].group_opacity, kept.get(1).and_then(|k| k.group_opacity)), ((a < 1.0).then_some(a), (b < 1.0).then_some(b))); +} + /// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph. #[test] fn default_fill_and_stroke_on_a_series_mark_is_kept() { @@ -5691,6 +5872,151 @@ fn formatting_one_label_keeps_that_kind_of_label() { assert!(serde_json::to_value(GraphSpec::default()).unwrap().get("labelStyles").is_none()); } +/// Character and paragraph edits that resize a graph's labels leave the plot where it is when the graph is drawn +/// again, and a move or scale of the graph made after them is still followed. +#[test] +fn restyling_a_graphs_labels_leaves_the_plot_in_place() { + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let redraw = |s: &mut Session, id: NodeId| s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": 14})).unwrap(); + redraw(&mut s, id); + assert_eq!(spec(&s, id).rect, rect, "after a size change to every label"); + let c = text_id(&s, id, "Axes", "Q2"); + s.execute("text.setFormat", &json!({"ids": [c.0], "leftIndent": 20})).unwrap(); + redraw(&mut s, id); + assert_eq!(spec(&s, id).rect, rect, "after an indent on the category labels"); + let l = text_id(&s, id, "Legend", "2025"); + s.execute("text.setStyle", &json!({"ids": [l.0], "size": 4})).unwrap(); + redraw(&mut s, id); + assert_eq!(spec(&s, id).rect, rect, "after a smaller size on the legend labels"); + // A move and a scale of the whole graph still carry the plot with them. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap(); + redraw(&mut s, id); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); + s.execute("object.scale", &json!({"sx": 200, "sy": 100, "origin": [moved.x0, moved.y0]})).unwrap(); + redraw(&mut s, id); + let scaled = spec(&s, id).rect; + assert!((scaled.width() - 2.0 * rect.width()).abs() < 1e-6 && (scaled.height() - rect.height()).abs() < 1e-6, "{scaled:?}"); + assert!((scaled.x0 - moved.x0).abs() < 1e-6 && (scaled.y0 - moved.y0).abs() < 1e-6, "{scaled:?}"); +} + +/// Moving one label of a graph on its own leaves the plot where it is when the graph is drawn again. +#[test] +fn moving_one_label_leaves_the_plot_in_place() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + for (grp, text) in [("Legend", "2025"), ("Axes", "Q2")] { + let l = text_id(&s, id, grp, text); + s.execute("select.set", &json!({"ids": [l.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 120, "dy": 60})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "after moving {text}"); + } +} + +/// Label edits leave the plot in place in graphs whose legend swatches follow the size of the labels at the next +/// drawing: a legend across the top, a legend after a right value axis, and legend labels of several lines. A move of +/// the graph made after them is still followed. +#[test] +fn restyling_the_labels_of_a_graph_whose_legend_follows_them_leaves_the_plot_in_place() { + let csv = ",North|East|Coast,South|West,Inland|Hills|Lakes|Plains\nQ1,3,2,4\nQ2,5,4,1\nQ3,-1,6,2"; + for options in [json!({"legendAcrossTop": true}), json!({"valueAxis": "right"}), json!({"valueAxis": "both"}), json!({})] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.setType", &options).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let rect = spec(&s, id).rect; + for size in [16, 5] { + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("text.setStyle", &json!({"size": size})).unwrap(); + for _ in 0..2 { + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "{options}: labels at {size} pt"); + } + } + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 30, "dy": 20})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 20.0)).abs() < 1e-6, "{options}: {moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{options}: {moved:?}"); + } +} + +/// Outlining a graph's labels leaves the plot where it is when the graph is drawn again, and a move of the graph made +/// before them is still followed. +#[test] +fn outlining_a_graphs_labels_leaves_the_plot_in_place() { + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q2").0, text_id(&s, id, "Legend", "2025").0]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + assert_eq!(spec(&s, id).rect, rect, "after outlining labels"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 30, "dy": 15})).unwrap(); + s.execute("select.set", &json!({"ids": [text_id(&s, id, "Axes", "Q1").0, text_id(&s, id, "Legend", "2024").0]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": csv})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 30.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 15.0)).abs() < 1e-6, "{moved:?}"); + assert!((moved.width() - rect.width()).abs() < 1e-6 && (moved.height() - rect.height()).abs() < 1e-6, "{moved:?}"); +} + +/// A graph whose kept bounds of its art without type have no width follows a move with the bounds of all of its art. +#[test] +fn a_graph_whose_art_without_type_kept_no_width_still_follows_a_move() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let mut flat = spec(&s, id); + let art = flat.placed_art.unwrap(); + flat.placed_art = Some(vectorcraft_geom::Rect::new(art.x0, art.y0, art.x0, art.y1)); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(flat)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}"); +} + +/// A graph saved before it kept the bounds of its art without type follows a move made since with its old bounds. +#[test] +fn a_graph_saved_with_only_its_whole_bounds_still_follows_a_move() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let rect = spec(&s, id).rect; + let mut old = serde_json::to_value(spec(&s, id)).unwrap(); + old.as_object_mut().unwrap().remove("placedArt"); + let old: GraphSpec = serde_json::from_value(old).unwrap(); + assert_eq!(old.placed_art, None); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().extras_mut().graph = Some(Box::new(old)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 25, "dy": 5})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap(); + let moved = spec(&s, id).rect; + assert!((moved.x0 - (rect.x0 + 25.0)).abs() < 1e-6 && (moved.y0 - (rect.y0 + 5.0)).abs() < 1e-6, "{moved:?}"); + assert!(spec(&s, id).placed_art.is_some(), "the next drawing keeps the bounds of the art without type"); +} + /// Each Axes and Legend text after the graph is drawn again, with its object rows (fill or stroke, color, opacity, and /// for a stroke its weight) and its object opacity. type RowLooks = Vec<(bool, String, f32, f64)>; @@ -6935,3 +7261,42 @@ fn a_graph_opened_from_ai_keeps_its_data_for_editing() { assert!(notes.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("graphs are written as their art"))), "{name}: {r}"); } } + +/// A graph opened from a `.ai` keeps the bounds of its art without type, so moving one of its labels on its own +/// leaves the plot where it is at the first redraw. +#[test] +fn a_graph_opened_from_ai_measures_moves_without_its_labels() { + let graph = "%_Gs\n%_100 200 300 100 Gb\n%_5 0 0 14 0 1 0 0 6 44 Gy\n%_10 2 0 0 90 80 0 Gd\n\ + %_1 () Ga\n%_0 13 0 0 0 0 0 () GA\n%_2 () Ga\n%_0 14 0 0 0 0 0 () GA\n%_4 () Ga\n%_0 14 0 0 0 0 0 () GA\n\ + %_2 2 1 1 Gz\n%_() Gc (East) Gc (Q1) Gc 5 Gc GC\n\ + u\nu\n0.6 0 1 0 k\n110 100 m\n110 150 L\n130 150 L\n130 100 L\nf\nU\n%_2 1 0 0 Go\n\ + u\n0 0 0 1 K\n100 200 m\n100 100 L\n300 100 L\nS\nU\n\ + 0 To\n1 0 0 1 100 220 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 12 Tf\n(Sales) Tx\nTO\nU\n%_GS\n"; + let text = format!( + "%!PS-Adobe-3.0\n%%Creator: a script\n%%BoundingBox: 0 0 400 400\n%AI5_FileFormat 3\n%AI3_Cropmarks: 0 0 400 400\n%%EndComments\n\ + %%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Graph) Ln\n0 A\n{graph}LB\n\ + %AI5_EndLayer--\n%%PageTrailer\n%%Trailer\n%%EOF\n" + ); + let dir = vectorcraft_testkit::temp_dir("graph-ai-label"); + let path = dir.join("graph.ai"); + std::fs::write(&path, text).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": path})).unwrap(); + let (mut graphs, mut labels) = (vec![], vec![]); + s.doc().unwrap().doc.walk(|n| { + if n.extras().graph.is_some() { + graphs.push(n.id); + } + if matches!(&n.kind, NodeKind::Text(t) if t.plain_text() == "Sales") { + labels.push(n.id); + } + }); + assert_eq!((graphs.len(), labels.len()), (1, 1)); + let (id, label) = (graphs[0], labels[0]); + let before = spec(&s, id); + assert!(before.placed_art.is_some()); + s.execute("select.set", &json!({"ids": [label.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 80, "dy": -40})).unwrap(); + s.execute("graph.setData", &json!({"id": id.0, "csv": ",East\nQ1,8\nQ2,2"})).unwrap(); + assert_eq!(spec(&s, id).rect, before.rect); +} diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9a026598e8..ecc4a12bff 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Links", [], None, - "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", + "{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded)|size (the linked file's size in bytes as Link Info shows it, smallest first; rows without one, embedded images and missing files whose size is not kept, last; equal sizes by name); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots", has_doc, list ), @@ -2211,6 +2211,16 @@ fn document_row(p: &PlacedDocument) -> Value { json!({ "format": pdf.map_or("VectorCraft", |f| f.label), "document": true, "pageWidth": p.width, "pageHeight": p.height }) } +/// The size in bytes of the file that link `l` (of `st`) names, as Link Info shows it: the file's +/// size now, else the size the document keeps of it when the caller may see its path. +fn link_file_size(st: &crate::DocState, l: &LinkInfo) -> Option { + let doc_path = LinkBase::of(st).doc; + let kept = l.size.filter(|_| path_shown(&l.path, doc_path)); + let roots = crate::file_access::current().or_else(|| st.opened_by.clone()); + let now = crate::file_access::confine(roots.as_ref(), || fileio::document_path(&l.path, doc_path).ok().as_deref().and_then(file_stamp)); + now.map(|s| s.0).or(kept) +} + /// Sort rank of a `links.list` status: missing, modified, ok, embedded. fn status_rank(status: &str) -> usize { ["missing", "modified", "ok", "embedded"].iter().position(|s| *s == status).unwrap_or(4) @@ -2277,8 +2287,14 @@ fn list(s: &mut Session, p: &Value) -> Result { if !matches!(show, "all" | "missing" | "modified" | "embedded") { return Err(bad(C, format!("show `{show}`: all, missing, modified or embedded"))); } + let sort = str_param(p, "sort"); + if let Some(x) = sort.filter(|x| !matches!(*x, "name" | "kind" | "status" | "size")) { + return Err(bad(C, format!("sort `{x}`: name, kind, status or size"))); + } let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() }; let statuses = statuses(st); + // The file size of each listed row's link, read only to sort by size. + let mut sizes: BTreeMap = BTreeMap::new(); // The layer tree's objects, top first as the Layers panel lists them, then the others in the // order they are stored (opacity-mask art, symbols, graph designs, patterns, the art of the // stored brushes), each once. @@ -2326,6 +2342,11 @@ fn list(s: &mut Session, p: &Value) -> Result { } let doc_path = LinkBase::of(st).doc; if let Some(l) = link { + if sort == Some("size") + && let Some(size) = link_file_size(st, l) + { + sizes.insert(n.id.0, size); + } note_path(&mut row, "path", &l.path, doc_path); if let Some(page) = l.page { row["page"] = json!(page); @@ -2346,12 +2367,17 @@ fn list(s: &mut Session, p: &Value) -> Result { rows.push(row); } let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_lowercase(); - match str_param(p, "sort") { - None => {} + match sort { Some("name") => rows.sort_by_cached_key(|r| text(r, "name")), Some("kind") => rows.sort_by_cached_key(|r| (text(r, "format"), text(r, "name"))), Some("status") => rows.sort_by_cached_key(|r| (status_rank(r["status"].as_str().unwrap_or_default()), text(r, "name"))), - Some(x) => return Err(bad(C, format!("sort `{x}`: name, kind or status"))), + // Smallest file first; rows without a file size (embedded images, a missing file whose + // size the document does not keep) come last; equal sizes by name. + Some("size") => rows.sort_by_cached_key(|r| { + let size = r["id"].as_u64().and_then(|id| sizes.get(&id).copied()); + (size.is_none(), size.unwrap_or(0), text(r, "name")) + }), + _ => {} } let count = |k: &str| counts.get(k).copied().unwrap_or(0); Ok(json!({ "links": rows, "missing": count("missing"), "modified": count("modified"), "embedded": count("embedded") })) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 6ffdb04a5c..b86f260cd8 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, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind", has_doc, set_props ), diff --git a/crates/engine/src/cmd/object/props.rs b/crates/engine/src/cmd/object/props.rs index bd00b6b323..54ad23eb2f 100644 --- a/crates/engine/src/cmd/object/props.rs +++ b/crates/engine/src/cmd/object/props.rs @@ -68,8 +68,14 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result { // A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label // for its kind of label, so a value a mark or label already has still replaces the one another left on the graph. let transparency = opacity.is_some() || blend.is_some(); - let stores = - || transparency && (crate::cmd::graph::series_object_opacity_differs(d, &ids) || crate::cmd::graph::label_object_opacity_differs(d, &ids)); + // A series group's isolation, knockout and knockout shape are kept for the group alone. + let group_only = !transparency && ["isolate", "knockout", "knockoutShape"].iter().any(|k| p.get(*k).is_some()); + let kept = if group_only { crate::cmd::graph::series_groups_among(d, &ids) } else { ids.clone() }; + let stores = || { + (transparency || group_only) + && (crate::cmd::graph::series_object_opacity_differs(d, &kept) + || transparency && crate::cmd::graph::label_object_opacity_differs(d, &ids)) + }; if ids.iter().all(|id| d.node(*id).is_some_and(has_values)) && !stores() { // Hidden or locked objects can't stay selected. if hides { @@ -123,8 +129,10 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result { }); } } + if transparency || group_only { + crate::cmd::graph::capture_series_object_opacity(d, &kept); + } if transparency { - crate::cmd::graph::capture_series_object_opacity(d, &ids); crate::cmd::graph::capture_label_object_opacity(d, &ids); } // Hidden or locked objects can't stay selected. diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 4f822da5db..ccdb86197b 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; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). 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; when every target is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso, those points take the opacity themselves). 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, and on a series group without an item, the group's own opacity, blend mode, isolate, knockout and knockoutShape (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", has_doc, transparency ), diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index f475aae760..c6cb4d987d 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Convert to Text", [], None, - "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of the story's frames that are neither locked nor hidden; while the story is selected, its locked and hidden frames are not converted even when named, nor a paragraph whose text starts in one) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", + "{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches; after Select All in a frame of threaded text, without `ids`, `id` or a range, every paragraph of every frame of the story, locked and hidden frames included) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them (a whole story that Select All selected stays selected when the call converts all of it); in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}", has_doc, convert_list_to_text ), @@ -1335,19 +1335,11 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { use vectorcraft_doc::text::ParaList; let range = super::typecmd::TextRange::parse(p, C)?; // After Select All in a frame of threaded text, a call that names no type and no range takes - // every paragraph of the story's editable frames; its locked and hidden frames stay as they are - // whichever way they are named. - let full = super::textedit::editing_story(s); - let story: Vec = full.iter().copied().filter(|f| s.doc().is_ok_and(|st| st.doc.is_editable(*f))).collect(); + // every paragraph of every frame of the story, its locked and hidden frames included: the story + // is one text. + let story = super::textedit::editing_story(s); let named = ["ids", "id"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); - let ids = if !story.is_empty() && !named && range.is_none() { - story.clone() - } else { - super::typecmd::text_targets(s, p, C)?.into_iter().filter(|id| !full.contains(id) || story.contains(id)).collect() - }; - // The selected story's locked and hidden frames: no paragraph whose text starts in one is - // converted, and none of their paragraphs is restyled. - let held: Vec = full.iter().copied().filter(|f| !story.contains(f)).collect(); + let ids = if !story.is_empty() && !named && range.is_none() { story.clone() } else { super::typecmd::text_targets(s, p, C)? }; // Converting the whole story leaves it selected. let whole_story = !story.is_empty() && range.is_none() && story.iter().all(|f| ids.contains(f)); let editing = match super::textedit::editing_range(s)? { @@ -1381,7 +1373,6 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { let mut converted = 0; for story in &stories { let frames: Vec<&vectorcraft_doc::TextObject> = story.iter().filter_map(|id| text(*id)).collect(); - let is_held = |f: usize| story.get(f).is_some_and(|id| held.contains(id)); let mut paras: Vec = vec![]; let mut named_parts = vec![]; let plains: Vec = frames.iter().map(|t| t.plain_text()).collect(); @@ -1407,7 +1398,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { } for (i, named) in named_parts { if let Some(para) = paras.get_mut(i) { - let listed = para.main_part().is_some_and(|p| p.list.is_some() && !is_held(p.frame)); + let listed = para.main_part().is_some_and(|p| p.list.is_some()); para.converts |= named && listed; } } @@ -1497,7 +1488,7 @@ fn convert_list_to_text(s: &mut Session, p: &Value) -> Result { let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' }; style.tabs.insert(i, tab); } - for part in story_para.parts.iter().filter(|q| (std::ptr::eq(*q, para) || q.bytes.is_empty()) && !is_held(q.frame)) { + for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) { if let Some((stops, _)) = frame_edits.get_mut(part.frame) { stops.push((part.index, style.clone())); } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index fe8431a6c6..4bb6bcba1d 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -183,7 +183,7 @@ pub(crate) fn accepted_keys(doc: &'static str) -> Option> { /// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands /// its `…` entries name)? -pub(crate) fn takes_key(doc: &'static str, key: &str) -> bool { +pub fn takes_key(doc: &'static str, key: &str) -> bool { doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key)) } diff --git a/crates/engine/src/cmd/perspgrid.rs b/crates/engine/src/cmd/perspgrid.rs index aaeee36d80..150d716421 100644 --- a/crates/engine/src/cmd/perspgrid.rs +++ b/crates/engine/src/cmd/perspgrid.rs @@ -7,7 +7,8 @@ //! fields; `perspective.grid.preset` applies one, `perspective.presets.*` manage them. //! //! View options (Lock Grid, Lock Station Point, Snap to Grid, Show Rulers) are view state on -//! the grid: they toggle without an undo step, as Show Grid does. +//! the grid: they toggle without an undo step, as Show Grid does. So is the point Automatic Plane +//! Positioning holds the active plane through (`perspective.plane.infer`). use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -15,12 +16,15 @@ use vectorcraft_doc::{Document, NodeId}; use vectorcraft_geom::{Point, Rect, Vec2}; use vectorcraft_tools::distort::perspective::Plane; use vectorcraft_tools::distort::perspective::define::{BUILTINS, LETTER, first_artboard, is_builtin}; +use vectorcraft_tools::distort::perspective::infer::{HIT_PX, InferSource}; use vectorcraft_tools::distort::perspective::widget::{WidgetCorner, WidgetPlace}; -use vectorcraft_tools::distort::perspective::{GridDefinition, PerspectiveGrid}; +use vectorcraft_tools::distort::perspective::{GridDefinition, MAX_DEPTH, PerspectiveGrid}; use vectorcraft_tools::{PointerEvent, PointerKind, ToolKey}; use super::distortcmds::{grid_kept, grid_of, silent, store_grid}; -use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, str_param, switch_or, unique_name}; +use super::{ + CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, number_or, str_param, switch_or, unique_name, +}; pub fn specs() -> Vec { vec![ @@ -92,10 +96,19 @@ pub fn specs() -> Vec { "Perspective Grid Options", [], None, - "{show?: bool, position?: topLeft|topRight|bottomLeft|bottomRight} the Plane Switching Widget: shown or not, and the corner of the document window it stays in (kept with the preferences; no params reads them) → {show, position}", + "{show?: bool, position?: topLeft|topRight|bottomLeft|bottomRight, anchorPoint?: bool, gridlineIntersection?: bool} the Plane Switching Widget: shown or not, and the corner of the document window it stays in; Automatic Plane Positioning: whether it takes a point from an anchor point of art in perspective and from a gridline intersection (both on by default; see perspective.plane.infer). Kept with the preferences; no params reads them → {show, position, anchorPoint, gridlineIntersection}", always, widget_options ), + cmd!( + "perspective.plane.infer", + "Automatic Plane Positioning", + [], + None, + "{at?: [x, y], tolerance?: pt around `at` (default 6), clear?: bool} with `at` on an anchor point of shown art in perspective, or on a gridline intersection of a plane that shows, the active plane moves through that point for now and the other planes hide (the Perspective Selection tool: Shift held over one with no button down). An anchor point within reach wins over an intersection, and perspective.widget.options turns either off. Making another plane active (perspective.plane.set) brings that plane through the same point. The plane goes back to its place when an object is drawn on it or attached to it (perspective.draw, perspective.attach, an object brought into perspective by perspective.move or perspective.transform), when a plane is moved (perspective.plane.move, perspective.plane.matchObject), when the grid hides or no plane is active, when the file is opened again, and with `clear` (Escape with the Perspective Selection tool). View state: not an undo step; no params reads it → {active, plane, offset: where the active plane is, point?: [x, y, z] in the grid's frame, source?: anchor|gridline (what `at` found; absent when nothing was within reach)}", + has_doc, + plane_infer + ), cmd!( "perspective.grid.lock", "Lock Grid", @@ -259,21 +272,32 @@ pub(crate) fn grid_preset(s: &mut Session, p: &Value) -> Result { let old = grid_of(&s.doc()?.doc); let ab = s.doc()?.doc.artboards.first().map(|a| a.rect).ok_or_else(|| EngineError::Other("no artboard".into()))?; let g = s.perspective_preset_grid(&name, ab).ok_or_else(|| bad(C, format!("no perspective grid preset named `{name}`")))?; - // The objects stay attached and the view options stay as they were. - let g = PerspectiveGrid { attached: old.attached, locked: old.locked, lock_station: old.lock_station, snap: old.snap, rulers: old.rulers, ..g }; + // The objects stay attached and the view options stay as they were, and so does a plane held + // by Automatic Plane Positioning while the new grid can hold it. + let mut g = PerspectiveGrid { + attached: old.attached, + locked: old.locked, + lock_station: old.lock_station, + snap: old.snap, + rulers: old.rulers, + inferred: old.inferred, + ..g + }; + g.keep_positioning_valid(); // When the document holds this grid already, apart from whether it shows and its active plane, // the preset only sets those two, without an undo step (as perspective.grid.show and // perspective.plane.set do). - let view = PerspectiveGrid { visible: old.visible, plane: old.plane, ..g.clone() }; + let view = PerspectiveGrid { visible: old.visible, plane: old.plane, inferred: old.inferred, ..g.clone() }; if !grid_kept(&s.doc()?.doc, &view) { s.edit("Perspective Grid Preset", |d, _| { store_grid(d, &g); Ok(()) })?; - } else if (old.visible, old.plane) != (g.visible, g.plane) { + } else if (old.visible, old.plane, old.inferred) != (g.visible, g.plane, g.inferred) { silent(s, |cur| { cur.visible = g.visible; cur.plane = g.plane; + cur.inferred = g.inferred; })?; } Ok(g.definition_json()) @@ -460,10 +484,100 @@ fn widget_options(s: &mut Session, p: &Value) -> Result { o.position = v.as_str().and_then(WidgetCorner::parse).ok_or_else(|| bad(C, "position must be topLeft, topRight, bottomLeft or bottomRight"))?; } + if let Some(v) = p.get("anchorPoint") { + o.anchor_point = v.as_bool().ok_or_else(|| bad(C, "anchorPoint must be true or false"))?; + } + if let Some(v) = p.get("gridlineIntersection") { + o.gridline_intersection = v.as_bool().ok_or_else(|| bad(C, "gridlineIntersection must be true or false"))?; + } s.prefs.perspective_widget = o; Ok(json!(o)) } +/// What `perspective.plane.infer` reports for `g`. +fn infer_info(g: &PerspectiveGrid, source: Option) -> Value { + let active = g.inferred.is_some() && g.plane != Plane::None; + let mut v = json!({ "active": active, "plane": g.plane.id(), "offset": g.offset(g.plane) }); + if let Some(at) = g.inferred.filter(|_| active) { + v["point"] = json!(at); + } + if let Some(source) = source { + v["source"] = json!(source.id()); + } + v +} + +fn plane_infer(s: &mut Session, p: &Value) -> Result { + const C: &str = "perspective.plane.infer"; + let clear = switch_or(p, "clear", false, C)?; + let at = match p.get("at") { + None | Some(Value::Null) => None, + Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be [x, y]"))?), + }; + let tol = number_or(p, "tolerance", HIT_PX, C)?; + if !(tol.is_finite() && (0.0..=MAX_DEPTH).contains(&tol)) { + return Err(bad(C, "tolerance must be 0 or more")); + } + if clear && at.is_some() { + return Err(bad(C, "give `at` or `clear`, not both")); + } + let doc = &s.doc()?.doc; + let g = PerspectiveGrid::current(doc); + let mut source = None; + let next = match at { + _ if clear => None, + None => g.inferred, + Some(at) => { + if !g.visible { + return Err(EngineError::Other("the perspective grid is hidden".into())); + } + if g.plane == Plane::None { + return Err(EngineError::Other("no active perspective plane".into())); + } + let targets = s.prefs.perspective_widget.targets(); + if !targets.any() { + return Err(EngineError::Other( + "Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options)".into(), + )); + } + match g.infer_at(doc, at, tol, targets) { + Some((found, point)) => { + source = Some(found); + Some(point) + } + None => g.inferred, + } + } + }; + if next == g.inferred { + return Ok(infer_info(&g, source)); + } + // A plane through the point stays in front of the viewer. + if next.is_some() { + PerspectiveGrid { inferred: next, ..g }.validate().map_err(|e| bad(C, e))?; + } + let g = silent(s, |g| g.inferred = next)?; + Ok(infer_info(&g, source)) +} + +/// An object was drawn on, or attached to, `plane`: when Automatic Plane Positioning holds that +/// plane, it goes back to its place as view state, not an undo step (a plane it doesn't hold +/// leaves it as it is). In a drag that happens once the drag is committed +/// ([`Session::commit_interaction`]), so the plane stays put while the object is drawn. +pub(crate) fn plane_positioning_used(s: &mut Session, plane: Plane) -> Result<()> { + let st = s.doc_mut()?; + let g = grid_of(&st.doc); + if g.inferred.is_none() || g.plane != plane { + return Ok(()); + } + if let Some(it) = &mut st.interaction { + it.plane_placed = true; + return Ok(()); + } + silent(s, |g| g.inferred = None)?; + Ok(()) +} + impl Session { /// The Plane Switching Widget's part of a pointer event: a press on it picks the plane (its /// drag and release go nowhere); None when the event isn't the widget's. diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index 8b00e95152..5809990e0f 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use vectorcraft_doc::links::hash_bytes; use vectorcraft_doc::placed_document::{PREVIEW_MAX, PREVIEW_PX_PER_PT, key_for}; -use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, NodeKind, PageBox, PlacedDocument, PlacementOptions}; +use vectorcraft_doc::{ColorMode, Document, ImageBlob, LinkInfo, Node, NodeKind, PageBox, PlacedDocument, PlacementOptions}; use vectorcraft_geom::{Affine, Rect}; use vectorcraft_pdf::CropTo; @@ -221,22 +221,57 @@ pub(crate) struct Source { /// What is shown, in the file's coordinates: the artboard, the page's box or the art's bounds. pub frame: Rect, pub warnings: Vec, + /// The colour mode the file's art was read in (a PDF page painted mostly in CMYK reads in CMYK). + pub color_mode: ColorMode, } /// The VectorCraft document `name` (`bytes`, from `path` when there is one) read for showing /// artboard `page`, or the PDF or `.ai` file for showing page `page` clipped to its box /// `page_box` (its art's bounds when `bounding`). pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bounding: bool, page_box: PageBox, cmd: &str) -> Result { + read_source(name, bytes, None, path, (page, bounding, page_box), cmd) +} + +/// [`source`] of the file whose bytes `bytes` holds, kept by the blob without a copy of its own: +/// several pages of one file read this way share one copy of it. +pub(crate) fn shared_source( + name: &str, + bytes: &Arc>, + path: Option<&str>, + page: u32, + bounding: bool, + page_box: PageBox, + cmd: &str, +) -> Result { + read_source(name, bytes, Some(bytes), path, (page, bounding, page_box), cmd) +} + +/// [`source`], the blob keeping `shared` when given (else a copy of `bytes`); `shown` is the page +/// (or artboard), whether the art's bounds are shown, and the page's box. +fn read_source( + name: &str, + bytes: &[u8], + shared: Option<&Arc>>, + path: Option<&str>, + shown: (u32, bool, PageBox), + cmd: &str, +) -> Result { + let (page, bounding, page_box) = shown; // The same document placed the same way is read once (placing it again is free). let key = key_for(&hash_bytes(bytes), page, bounding, page_box); // Resolving its links depends on where the file is and on what the caller may read, so a hit // needs the same path, and nothing is shared with or from a confined (automation) caller. let confined = crate::file_access::current().is_some(); - if !confined && let Some((_, s)) = lock_memo().iter().find(|(at, s)| s.key == key && at.as_deref() == path).cloned() { + if !confined && let Some((_, mut s)) = lock_memo().iter().find(|(at, s)| s.key == key && at.as_deref() == path).cloned() { + // The same bytes: the copy given is kept instead, so the pages that share it go on sharing. + if let Some(b) = shared { + s.blob.bytes = b.clone(); + } return Ok(s); } let a = document_art(name, bytes, path, page, bounding, page_box, cmd)?; - let mut blob = ImageBlob::new(mime(name, bytes), bytes.to_vec()); + let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec())); + let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None }; let shown = PlacedDocument { link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) }, key: key.clone(), @@ -249,9 +284,10 @@ pub(crate) fn source(name: &str, bytes: &[u8], path: Option<&str>, page: u32, bo }; let art = group(a.nodes, a.clip); blob.proxy = preview(&a.doc, &art, a.frame).map(Arc::new); + let color_mode = a.doc.color_mode; // Drawing it needn't read it again. vectorcraft_doc::placed_document::prime(&shown, blob.bytes.clone(), (a.doc, art, a.frame)); - let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings }; + let s = Source { blob, key, page_box, frame: a.frame, warnings: a.warnings, color_mode }; if !confined { let mut m = lock_memo(); if m.len() >= MEMO_SIZE { diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index d42cc5b82c..6d1ddbee43 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -101,12 +101,30 @@ const FILE_WORDS: &[&str] = &[ "clipboard", ]; -/// Param keys that name a file or a folder. -const FILE_KEYS: &[&str] = - &["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url", "diffPath"]; +/// Param keys that name a file or a folder, each by its whole name, the folder preferences +/// `prefs.set {values}` takes included: a command that adds a key naming one adds it here. A key +/// that only ends like one (`alignToPath`, `linksFolder`, `sortPaths`) names none, nor do `folders` +/// (how an export groups its files) and `url` (a web link). +const FILE_KEYS: &[&str] = &[ + "path", + "paths", + "file", + "files", + "folder", + "dir", + "directory", + "destinationFolder", + "sourceFolder", + "diffPath", + "fontsFolder", + "pluginsFolder", + "recoveryFolder", + "templatesFolder", +]; /// The keys in [`FILE_KEYS`] that name a folder. -const FOLDER_KEYS: &[&str] = &["folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder"]; +const FOLDER_KEYS: &[&str] = + &["folder", "dir", "directory", "destinationFolder", "sourceFolder", "fontsFolder", "pluginsFolder", "recoveryFolder", "templatesFolder"]; /// What a param key that names a place on disk names there. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -132,7 +150,83 @@ pub fn key_location(key: &str) -> Option { /// What `key` names on disk in command `spec`: [`key_location`], or `None` when [`NOT_FILES`] /// names it for `spec` (it names part of the document there). pub fn location_in(spec: &CommandSpec, key: &str) -> Option { - if NOT_FILES.contains(&(spec.id, key)) { None } else { key_location(key) } + ParamsPlace::top(Some(spec)).member(key, None).1 +} + +/// A place in the params of a command. What a key names on disk depends on the command and on the +/// keys above it: [`key_location`], less a key [`NOT_FILES`] names for the command at the top of its +/// params and one at the end of a [`NESTED_NOT_FILES`] key list. A walk of params starts at +/// [`ParamsPlace::top`] and goes down with [`ParamsPlace::member`] and [`ParamsPlace::item`]. +#[derive(Clone, Copy, Debug)] +pub struct ParamsPlace { + /// The command whose params these are; `None` for a command that isn't known. + command: Option<&'static str>, + /// Whether this is the top of the params. + top: bool, + /// The keys of a [`NESTED_NOT_FILES`] list still to follow below this place. + trail: Option<&'static [&'static str]>, +} + +impl ParamsPlace { + /// The top of the params of `spec`, or of a command that isn't known (`None`), where every key in + /// [`FILE_KEYS`] names a file or a folder. + pub fn top(spec: Option<&CommandSpec>) -> ParamsPlace { + ParamsPlace { command: spec.map(|s| s.id), top: true, trail: None } + } + + /// The top of the params of the command with id `id` ([`ParamsPlace::top`]). + pub fn of(id: &str) -> ParamsPlace { + ParamsPlace::top(super::find_command(id)) + } + + /// The top of the params of the command that object `fields` calls, when it is a call + /// (`{command | id: , params}`, as a `command.batch` step or a control request is): + /// the place of its `params` member ([`ParamsPlace::member`]). + pub fn carried(fields: &serde_json::Map) -> Option { + if !fields.contains_key("params") { + return None; + } + let id = fields.get("command").or_else(|| fields.get("id")).and_then(Value::as_str)?; + super::find_command(id).map(|spec| ParamsPlace::top(Some(spec))) + } + + /// The top of the params of the command that array `items` records, when it is a recorded step + /// (`[command id, params]`): the place of its item 1 ([`ParamsPlace::item`]). + pub fn step(items: &[Value]) -> Option { + match items { + [Value::String(id), Value::Object(_)] => super::find_command(id).map(|spec| ParamsPlace::top(Some(spec))), + _ => None, + } + } + + /// The place of member `key` of an object here, with what `key` names on disk there. `carried` is + /// [`ParamsPlace::carried`] of that object: its `params` member is then the top of that command's + /// params, and names no file. + pub fn member(self, key: &str, carried: Option) -> (ParamsPlace, Option) { + if key == "params" + && let Some(inner) = carried + { + return (inner, None); + } + let rest = if self.top { + let id = self.command; + NESTED_NOT_FILES.iter().find(|(c, keys)| Some(*c) == id && keys.first() == Some(&key)).map(|(_, keys)| keys.get(1..).unwrap_or_default()) + } else { + self.trail.filter(|keys| keys.first() == Some(&key)).map(|keys| keys.get(1..).unwrap_or_default()) + }; + let document = (self.top && self.command.is_some_and(|id| NOT_FILES.contains(&(id, key)))) || rest.is_some_and(<[&str]>::is_empty); + let place = ParamsPlace { command: self.command, top: false, trail: rest.filter(|keys| !keys.is_empty()) }; + (place, if document { None } else { key_location(key) }) + } + + /// The place of item `index` of an array here. `step` is [`ParamsPlace::step`] of that array: its + /// item 1 is then the top of that command's params. + pub fn item(self, index: usize, step: Option) -> ParamsPlace { + match step { + Some(inner) if index == 1 => inner, + _ => ParamsPlace { command: self.command, top: false, trail: None }, + } + } } /// The param keys of `spec` that name a file or a folder, with what they name: the keys in @@ -158,9 +252,6 @@ pub(crate) const NOT_FILES: &[(&str, &str)] = &[ ("symbol.instance.setAppearance", "path"), ("symbol.instance.selectPart", "path"), ("object.objectsOnPath.attach", "path"), - ("attributes.set", "url"), - ("object.slice.options", "url"), - ("document.exportForScreens", "folders"), ]; /// Commands and the keys from the top of their params down to a key in [`FILE_KEYS`] that, there, @@ -251,34 +342,24 @@ pub(crate) fn names_key(text: &str, key: &str) -> bool { }) } -/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth -/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`] -/// names for `id`, at the top level, and one at the end of a [`NESTED_NOT_FILES`] key list for -/// `id`, aren't counted. The walk keeps its own stack, so deep arguments can't overflow the -/// thread's. +/// Does `args`, the arguments of a call of command `id`, carry a key that names a file or a folder at +/// any depth (in objects and in arrays, [`ParamsPlace`]), such as an effect's `textureImage.path`? +/// Only a key [`NOT_FILES`] names for `id`, at the top level, and one at the end of a +/// [`NESTED_NOT_FILES`] key list for `id`, aren't counted. A call or a recorded step inside `args` +/// is read as part of `id`'s arguments, not as the command it names. The walk keeps its own stack, +/// so deep arguments can't overflow the thread's. fn names_file(id: &str, args: &Value) -> bool { - // Each value, whether it is the params themselves, and the keys of a NESTED_NOT_FILES list - // still to follow below it. - let mut stack: Vec<(&Value, bool, Option<&[&str]>)> = vec![(args, true, None)]; - while let Some((v, top, trail)) = stack.pop() { + let mut stack: Vec<(&Value, ParamsPlace)> = vec![(args, ParamsPlace::of(id))]; + while let Some((v, place)) = stack.pop() { match v { - Value::Array(a) => stack.extend(a.iter().map(|x| (x, false, None))), + Value::Array(a) => stack.extend(a.iter().enumerate().map(|(i, x)| (x, place.item(i, None)))), Value::Object(o) => { for (k, x) in o { - let k = k.as_str(); - let rest = if top { - NESTED_NOT_FILES - .iter() - .find(|(c, keys)| *c == id && keys.first() == Some(&k)) - .map(|(_, keys)| keys.get(1..).unwrap_or_default()) - } else { - trail.filter(|keys| keys.first() == Some(&k)).map(|keys| keys.get(1..).unwrap_or_default()) - }; - let document = (top && NOT_FILES.contains(&(id, k))) || rest.is_some_and(<[&str]>::is_empty); - if FILE_KEYS.contains(&k) && !document { + let (below, location) = place.member(k, None); + if location.is_some() { return true; } - stack.push((x, false, rest.filter(|keys| !keys.is_empty()))); + stack.push((x, below)); } } _ => {} @@ -638,7 +719,13 @@ mod tests { assert!(names_file("effect.apply", &texture)); assert!(names_file("effect.setParams", &texture)); assert!(names_file("effect.apply", &json!({"params": {"layers": [{"name": "a"}, {"folder": "/tmp"}]}}))); - assert!(names_file("select.all", &json!([[[{"url": "file:///etc/hosts"}]]]))); + assert!(names_file("select.all", &json!([[[{"file": "file:///etc/hosts"}]]]))); + // A web link and an export's grouping name no file. + assert!(!names_file("attributes.set", &json!({"url": "https://example.com/a"}))); + assert!(!names_file("object.move", &json!({"opts": {"folders": "rows", "alignToPath": "baseline"}}))); + // A call nested in the arguments doesn't vouch for its own keys. + assert!(names_file("object.move", &json!({"opts": {"command": "object.setLiveShape", "params": {"path": "/tmp/x"}}}))); + assert!(names_file("object.move", &json!({"opts": ["object.setLiveShape", {"path": "/tmp/x"}]}))); assert!(!names_file("effect.apply", &json!({"effect": "distort.glass", "params": {"distortion": 5, "textureImage": "frosted"}}))); assert!(!names_file("object.move", &json!({"dx": 5, "dy": 0, "ids": [1, 2], "opts": {"copy": false}}))); // `path` is the path text is set on in text.createInPath, but only as its own param. @@ -647,7 +734,13 @@ mod tests { assert!(names_file("object.move", &json!({"path": [[0, 0]]}))); // object.setLiveShape takes no `path`; its description says "on any path:" in its prose. assert!(names_file("object.setLiveShape", &json!({"path": "/tmp/x"}))); - // Image Trace's path fidelity setting, only inside its tracing settings. + } + + /// Image Trace's path fidelity setting `paths` names no file, but only inside its tracing + /// settings. + #[test] + fn image_trace_paths_name_no_file_only_in_its_settings() { + use serde_json::json; for id in ["imageTrace.make", "imageTrace.makeAndExpand"] { assert!(!names_file(id, &json!({"preset": "Default", "params": {"mode": "color", "paths": 50}}))); assert!(!names_file(id, &json!({"savedPreset": {"paths": 50, "corners": 75}}))); @@ -658,7 +751,12 @@ mod tests { assert!(names_file(id, &json!({"options": {"paths": 50}}))); } assert!(names_file("object.move", &json!({"params": {"paths": 50}}))); - // A custom arrowhead's outline in stroke.set, only where stroke.set takes one. + } + + /// A custom arrowhead's outline `path` names no file, but only where stroke.set takes one. + #[test] + fn a_custom_arrowhead_outline_names_no_file_only_in_stroke_set() { + use serde_json::json; let outline = json!({"subpaths": []}); assert!(!names_file("stroke.set", &json!({"endArrow": {"Custom": {"name": "A", "path": outline}}}))); assert!(!names_file("stroke.set", &json!({"startArrow": {"Custom": {"name": "A", "path": outline}}, "endArrow": "Triangle"}))); @@ -668,7 +766,12 @@ mod tests { assert!(names_file("stroke.set", &json!({"options": {"endArrow": {"Custom": {"path": "/tmp/x"}}}}))); assert!(names_file("stroke.set", &json!({"endArrow": [{"Custom": {"path": "/tmp/x"}}]}))); assert!(names_file("object.move", &json!({"endArrow": {"Custom": {"path": "/tmp/x"}}}))); - // Deep nesting is walked without recursion. + } + + /// A file key under deep nesting is found, and the walk doesn't recurse. + #[test] + fn a_file_key_is_found_under_deep_nesting() { + use serde_json::json; let mut deep = json!({"file": "/tmp/x"}); for _ in 0..10_000 { deep = Value::Array(vec![deep]); @@ -726,11 +829,48 @@ mod tests { assert!(found.iter().all(|(k, l)| (*l == Location::Folder) == FOLDER_KEYS.contains(k)), "{}: {found:?}", spec.id); assert!(denied(spec).is_some() || found.is_empty(), "{} names {found:?} but a plug-in may call it", spec.id); } - assert_eq!(key_location("url"), Some(Location::File)); + assert_eq!(key_location("url"), None); + assert_eq!(key_location("folders"), None); + assert_eq!(key_location("linksFolder"), None); assert_eq!(key_location("sourceFolder"), Some(Location::Folder)); assert_eq!(key_location("pathData"), None); } + /// A key keeps the meaning its command gives it at every depth: a call (`{command, params}`) and a + /// recorded step (`[command id, params]`) carry their command's exceptions down, and a custom + /// arrowhead's outline is part of the document only at its own place in `stroke.set`. + #[test] + fn a_params_place_follows_its_command() { + use serde_json::json; + let at = |place: ParamsPlace, keys: &[&str]| { + let mut place = place; + let mut location = None; + for k in keys { + (place, location) = place.member(k, None); + } + location + }; + assert_eq!(at(ParamsPlace::of("text.createInPath"), &["path"]), None); + assert_eq!(at(ParamsPlace::of("text.createInPath"), &["options", "path"]), Some(Location::File)); + assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "path"]), None); + assert_eq!(at(ParamsPlace::of("stroke.set"), &["endArrow", "Custom", "file"]), Some(Location::File)); + assert_eq!(at(ParamsPlace::of("no.such.command"), &["path"]), Some(Location::File)); + assert_eq!(at(ParamsPlace::top(None), &["destinationFolder"]), Some(Location::Folder)); + let call = json!({"command": "text.createInPath", "params": {"path": [[0, 0]]}}); + let carried = call.as_object().and_then(ParamsPlace::carried); + let (inner, location) = ParamsPlace::of("command.batch").member("params", carried); + assert_eq!(location, None); + assert_eq!(inner.member("path", None).1, None); + assert_eq!(ParamsPlace::carried(&serde_json::Map::new()).map(|_| ()), None); + let unknown = json!({"command": "no.such.command", "params": {}}); + assert!(unknown.as_object().and_then(ParamsPlace::carried).is_none()); + let step = [json!("text.createInPath"), json!({"path": [[0, 0]]})]; + let place = ParamsPlace::top(None).item(1, ParamsPlace::step(&step)); + assert_eq!(place.member("path", None).1, None); + assert_eq!(ParamsPlace::top(None).item(0, ParamsPlace::step(&step)).member("path", None).1, Some(Location::File)); + assert!(ParamsPlace::step(&[json!("text.createInPath")]).is_none()); + } + /// A file key counts as a command's param only where its description takes it: not a word in /// the prose after the params, in a nested object or in the result. A description that doesn't /// say which keys it takes counts any `key:` in its text. diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5329f23331..03a931ba5d 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -34,6 +34,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.contour.set", "addon.cutting.banner", "addon.cutting.bridges", + "addon.cutting.nest", "addon.cutting.weed", "addon.image.applyColorMask", "addon.image.colorMask", @@ -473,6 +474,7 @@ pub(super) const ALLOWED: &[&str] = &[ "perspective.grid.snap", "perspective.move", "perspective.nudge", + "perspective.plane.infer", "perspective.plane.matchObject", "perspective.plane.move", "perspective.plane.set", diff --git a/crates/engine/src/cmd/textwrap.rs b/crates/engine/src/cmd/textwrap.rs index d5eefe9d4d..9ff48848af 100644 --- a/crates/engine/src/cmd/textwrap.rs +++ b/crates/engine/src/cmd/textwrap.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, NodeId, NodeKind, TextWrap}; use super::typecmd::refresh_bounds; -use super::{CommandSpec, EngineError, Result, Session, bool_or, checked_ids_or_selection, cmd, f64_or, has_selection}; +use super::{CommandSpec, EngineError, Result, Session, bad, checked_ids_or_selection, cmd, has_selection, number_or, switch_or}; pub fn specs() -> Vec { vec![ @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Text Wrap"], None, - "{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; a negative offset (to -1000) lets the text that far into them → {ids}", + "{offset?: pt (6), invert?: bool, ids?} area type below the selected objects (same layer) wraps around them; offset -1000 to 1000 (a negative one lets the text that far into them); an offset outside that range or not a number, or an invert that is not true or false, is an error → {ids}", has_selection, make ), @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Text Wrap Options…", ["Object", "Text Wrap"], None, - "{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); no options → the current {offset, invert}", + "{offset?: pt, invert?: bool, ids?} set the options of the selected wrap objects (offset -1000 to 1000; a negative one lets text into the objects); an offset outside that range or not a number, or an invert that is not true or false, is an error; no options (or null ones) → the current {offset, invert}", has_selection, options ), @@ -37,14 +37,23 @@ pub fn specs() -> Vec { /// The Offset a wrap object takes, in points. pub const TEXT_WRAP_OFFSET_RANGE: std::ops::RangeInclusive = -1000.0..=1000.0; -fn wrap_param(p: &Value, base: TextWrap) -> TextWrap { - let (lo, hi) = (*TEXT_WRAP_OFFSET_RANGE.start(), *TEXT_WRAP_OFFSET_RANGE.end()); - TextWrap { offset: f64_or(p, "offset", base.offset).clamp(lo, hi), invert: bool_or(p, "invert", base.invert) } +/// The options `p` gives, with `base` for an omitted or null `offset` or `invert`. An `offset` that is +/// not a number or lies outside [`TEXT_WRAP_OFFSET_RANGE`], or an `invert` that is not true or false, +/// is an error. `base`'s offset is kept as it is. +fn wrap_param(p: &Value, base: TextWrap, cmd: &str) -> Result { + let key = "offset"; + let given = p.get(key).is_some_and(|v| !v.is_null()); + let offset = number_or(p, key, base.offset, cmd)?; + if given && !TEXT_WRAP_OFFSET_RANGE.contains(&offset) { + let (lo, hi) = (TEXT_WRAP_OFFSET_RANGE.start(), TEXT_WRAP_OFFSET_RANGE.end()); + return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi}"))); + } + Ok(TextWrap { offset, invert: switch_or(p, "invert", base.invert, cmd)? }) } fn make(s: &mut Session, p: &Value) -> Result { let ids = checked_ids_or_selection(s, p, "object.textWrap.make")?; - let w = wrap_param(p, TextWrap::default()); + let w = wrap_param(p, TextWrap::default(), "object.textWrap.make")?; s.edit("Make Text Wrap", |d, _| { for id in &ids { let n = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?; @@ -86,10 +95,10 @@ fn options(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; ids.iter().find_map(|i| d.node(*i).and_then(|n| n.extras().wrap)).unwrap_or_default() }; - if p.get("offset").is_none() && p.get("invert").is_none() { + if ["offset", "invert"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) { return Ok(json!({ "offset": current.offset, "invert": current.invert })); } - let w = wrap_param(p, current); + let w = wrap_param(p, current, "object.textWrap.options")?; s.edit("Text Wrap Options", |d, _| { for id in &ids { if let Some(n) = d.node_mut(*id) @@ -212,11 +221,72 @@ mod tests { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.execute("object.textWrap.options", &json!({})).unwrap()["offset"], json!(6.0)); assert!(beside(&s).iter().all(|x| (x - 206.0).abs() < 1e-6), "{:?}", beside(&s)); - // An offset past -1000 is kept at -1000: the whole object lets text through. - assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -5000})).unwrap()["offset"], json!(-1000.0)); + // An offset of -1000 lets the text through the whole object. + assert_eq!(s.execute("object.textWrap.options", &json!({"offset": -1000})).unwrap()["offset"], json!(-1000.0)); assert!(lines(&s, t).iter().all(|l| l.0 < 1.0 && l.1 > 300.0)); } + /// An offset that is not a number or lies outside -1000 to 1000 pt, or an invert that is not + /// true or false, is an error for Make and Options, and leaves the options and the history as + /// they were. Omitted and null values take the default, and the range's ends are accepted. + #[test] + fn text_wrap_commands_refuse_bad_offsets_and_inverts_without_editing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let wrap = |s: &Session| s.doc().unwrap().doc.node(NodeId(id)).unwrap().extras().wrap; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let refused = [ + (json!({"offset": "12"}), "`offset` must be a number"), + (json!({"offset": true}), "`offset` must be a number"), + (json!({"offset": [12]}), "`offset` must be a number"), + (json!({"offset": {"pt": 12}}), "`offset` must be a number"), + (json!({"offset": 1000.5}), "`offset` must be from -1000 to 1000"), + (json!({"offset": -1000.5}), "`offset` must be from -1000 to 1000"), + (json!({"offset": 5000}), "`offset` must be from -1000 to 1000"), + (json!({"offset": 12, "invert": "true"}), "`invert` must be true or false"), + (json!({"offset": 12, "invert": 1}), "`invert` must be true or false"), + (json!({"invert": "false"}), "`invert` must be true or false"), + ]; + let start = undo(&s); + for (p, msg) in &refused { + let e = s.execute("object.textWrap.make", p).unwrap_err().to_string(); + assert!(e.contains(msg), "make {p}: {e}"); + assert!(wrap(&s).is_none(), "make {p} made a wrap"); + assert_eq!(undo(&s), start, "make {p} added history"); + } + // Omitted and null values: Make's 6 pt default. + s.execute("object.textWrap.make", &json!({"offset": null, "invert": null})).unwrap(); + assert_eq!(wrap(&s), Some(vectorcraft_doc::TextWrap { offset: 6.0, invert: false })); + s.execute("object.textWrap.options", &json!({"offset": 40, "invert": true})).unwrap(); + let before = undo(&s); + for (p, msg) in &refused { + let e = s.execute("object.textWrap.options", p).unwrap_err().to_string(); + assert!(e.contains(msg), "options {p}: {e}"); + assert_eq!(wrap(&s), Some(vectorcraft_doc::TextWrap { offset: 40.0, invert: true }), "options {p}"); + assert_eq!(undo(&s), before, "options {p} added history"); + } + // Null options read the current ones without an undo step; a null one keeps its value. + assert_eq!(s.execute("object.textWrap.options", &json!({"offset": null, "invert": null})).unwrap(), json!({"offset": 40.0, "invert": true})); + assert_eq!(undo(&s), before); + assert_eq!( + s.execute("object.textWrap.options", &json!({"offset": null, "invert": false})).unwrap(), + json!({"offset": 40.0, "invert": false}) + ); + // The range's ends are accepted by both commands. + for (command, offset) in + [("object.textWrap.options", 1000), ("object.textWrap.options", -1000), ("object.textWrap.make", 1000), ("object.textWrap.make", -1000)] + { + s.execute(command, &json!({ "offset": offset })).unwrap(); + assert_eq!(wrap(&s).unwrap().offset, f64::from(offset), "{command} {offset}"); + } + // A stored offset outside the range (from a file) is kept when only Invert Wrap changes. + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(NodeId(id)).unwrap().extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset: 5000.0, invert: false }); + assert_eq!(s.execute("object.textWrap.options", &json!({"invert": true})).unwrap(), json!({"offset": 5000.0, "invert": true})); + } + #[test] fn text_flows_on_both_sides_of_a_centred_object() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 05b45cc051..31bcad4671 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -616,6 +616,21 @@ fn scale_text_attributes(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "changed": changed })) } +/// A path (or compound path) of `outline`, a piece of type `t`'s outline in text space, painted as +/// run `run` and placed in the document as the canvas paints it ([`paint_type_piece`]: unplaced +/// gradients fitted to `bounds`, the layout's bounds, stroke weights scaled by the type's +/// transform); `None` when the piece has no path. +fn type_piece(d: &mut Document, t: &TextObject, bounds: kurbo::Rect, run: usize, outline: &kurbo::BezPath) -> Option { + let path = PathData::from_bezpath(outline); + if path.is_empty() { + return None; + } + let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); + let mut node = shape_node(d, path, None); + vectorcraft_render::effects::paint_type_piece(&mut node, &st, bounds, t.xf); + Some(node) +} + fn create_outlines(s: &mut Session, _: &Value) -> Result { let roots = selected_roots(s)?; let ids = s.edit("Create Outlines", |d, sel| { @@ -623,6 +638,8 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { if texts.is_empty() { return Err(EngineError::Other("Create Outlines: select text objects".into())); } + // Outlining a graph's labels does not move or scale its plot at the next redraw. + let graphs = super::graph::graphs_holding(d, &texts); let before = (!super::dimension::reached(d, &roots).is_empty()).then(|| d.clone()); let ended = super::dimension::end_links(d, &roots); let mut new_sel: Vec = roots.iter().copied().filter(|r| !texts.contains(r)).collect(); @@ -658,14 +675,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { children.push(Arc::new(d.reid(&art))); break 'glyph; } - let path = PathData::from_bezpath(&g.outline).transformed(t.xf); - if path.is_empty() { - break 'glyph; + if let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) { + children.push(Arc::new(node)); } - let st = t.runs.get(g.run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); - let mut node = shape_node(d, path, None); - node.appearance = st.appearance().into(); - children.push(Arc::new(node)); } run_end.insert(g.run, children.len()); } @@ -674,13 +686,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { // nothing there either). let mut ruby: Vec<(usize, Arc)> = vec![]; for g in &lay.ruby { - let path = PathData::from_bezpath(&g.outline).transformed(t.xf); - if path.is_empty() { - continue; - } - let st = t.runs.get(g.run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); - let mut node = shape_node(d, path, None); - node.appearance = st.appearance().into(); + let Some(node) = type_piece(d, t, lay.bounds, g.run, &g.outline) else { continue }; // After the glyphs of its run and of the runs before it. let at = run_end.range(..=g.run).map(|(_, end)| *end).max().unwrap_or(0); ruby.push((at, Arc::new(node))); @@ -705,10 +711,9 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { // Underline and strikethrough bars become paths of their run's paint too (#847). for (run, bar) in vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t) { all.extend(bar.iter()); - let st = t.runs.get(run).map(|r| r.style.clone()).unwrap_or_else(|| t.first_style()); - let mut node = shape_node(d, PathData::from_bezpath(&bar).transformed(t.xf), None); - node.appearance = st.appearance().into(); - children.push(Arc::new(node)); + if let Some(node) = type_piece(d, t, lay.bounds, run, &bar) { + children.push(Arc::new(node)); + } } // The object's own fills and strokes (not its characters') paint the whole outline: // those below the Characters row under the characters, the others over them, with @@ -750,6 +755,7 @@ fn create_outlines(s: &mut Session, _: &Value) -> Result { } // Outlined frames of threaded text leave their threads with the text they show. super::threads::leave_threads(d, &threaded); + super::graph::keep_placed(d, &graphs); sel.set(new_sel); Ok(out) })?; diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index c140ba6572..d793fc12a3 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Smart Punctuation…", ["Type"], None, - "{quotes?: true (straight quotes become the Document Setup quotes), dashes?: true (-- → en dash, --- → em dash), ellipsis?: true (... → …), scope?: \"selection\"|\"document\"} → {changed}", + "{fiLigatures?: false (ff, fi, ffi → the ligatures U+FB00, U+FB01, U+FB03), flLigatures?: false (ff, fl, ffl → U+FB00, U+FB02, U+FB04), quotes?: true (straight quotes become the Document Setup quotes), spaces?: false (two or more spaces after a period → one), dashes?: true (-- → en dash, --- → em dash), ellipsis?: true (... → …), fractions?: false (1/2, 1/4, 3/4 and the other fractions Unicode encodes as one character, with no digit, slash or decimal point next to them, → ½, ¼, ¾ …), scope?: \"selection\"|\"document\"} the selected type, or every text object with scope document or nothing selected; a ligature or a fraction is written only where the run's font has a glyph for it. Nothing to replace records no undo step → {changed: text objects changed, replaced: {fiLigatures, flLigatures, quotes, spaces, dashes, ellipses, fractions}: how many of each were replaced}", has_doc, smart_punctuation ), @@ -268,24 +268,227 @@ fn change_case(s: &mut Session, p: &Value) -> Result { // ---------- Smart Punctuation ---------- -#[derive(Default)] -struct PunctState { - prev: Option, +/// What Smart Punctuation replaces: each option of its dialog. +struct Punct { + /// ff, fi and ffi become the ligatures U+FB00, U+FB01 and U+FB03. + fi_ligatures: bool, + /// ff, fl and ffl become the ligatures U+FB00, U+FB02 and U+FB04. + fl_ligatures: bool, + /// Straight quotes become these quotes (the Document Setup quotes). + quotes: Option, + /// Two or more spaces after a period become one. + spaces: bool, + /// `--` becomes an en dash and `---` an em dash. + dashes: bool, + /// `...` becomes an ellipsis. + ellipses: bool, + /// `1/2` and the other fractions [`FRACTIONS`] lists become their one-character forms. + fractions: bool, } -/// Dashes (`--` en, `---` em), ellipses and, with `quotes`, typographer's quotes. -pub(crate) fn smarten(text: &str, prev: &mut Option, quotes: Option<&Quotes>, dashes: bool, ellipsis: bool) -> String { - let mut s = text.to_string(); - if dashes { - s = s.replace("---", "—").replace("--", "–"); +/// How many of each replacement Smart Punctuation made. +#[derive(Default)] +struct PunctCounts { + fi_ligatures: usize, + fl_ligatures: usize, + quotes: usize, + spaces: usize, + dashes: usize, + ellipses: usize, + fractions: usize, +} + +/// The text before the run being rewritten, across the runs of one text object. +#[derive(Default)] +struct PunctState { + /// The character before the run. + prev: Option, + /// The number of spaces since the last period, while only spaces follow it. + after_period: Option, + /// An inline graphic comes right before the run. + after_graphic: bool, +} + +/// The fractions Expert Fractions writes as one character: every fraction Unicode encodes as a +/// vulgar fraction with a numerator of 1 to 7 and a denominator of 2 to 10. +const FRACTIONS: [(&str, char); 18] = [ + ("1/2", '½'), + ("1/3", '⅓'), + ("2/3", '⅔'), + ("1/4", '¼'), + ("3/4", '¾'), + ("1/5", '⅕'), + ("2/5", '⅖'), + ("3/5", '⅗'), + ("4/5", '⅘'), + ("1/6", '⅙'), + ("5/6", '⅚'), + ("1/7", '⅐'), + ("1/8", '⅛'), + ("3/8", '⅜'), + ("5/8", '⅝'), + ("7/8", '⅞'), + ("1/9", '⅑'), + ("1/10", '⅒'), +]; + +/// `s` with every `from` replaced by `to`, adding the number replaced to `n`. +fn replace_counted(s: String, from: &str, to: &str, n: &mut usize) -> String { + let found = s.matches(from).count(); + if found == 0 { + return s; } - if ellipsis { - s = s.replace("...", "…"); + *n += found; + s.replace(from, to) +} + +/// Smart Spaces: `text` without the second and later spaces after a period, adding the number of +/// periods whose spaces it shortened to `n`. `after` carries the spaces after a period from one run +/// to the next. +fn smart_spaces(text: &str, after: &mut Option, n: &mut usize) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match (c, *after) { + (' ', Some(k)) => { + *after = Some(k + 1); + if k >= 1 { + if k == 1 { + *n += 1; + } + continue; + } + } + ('.', _) => *after = Some(0), + _ => *after = None, + } + out.push(c); } - match quotes { - Some(q) => q.apply(&s, prev), + out +} + +/// The fraction `cs` starts with, and its length in characters: one of [`FRACTIONS`] that no digit, +/// slash or decimal part follows, so `1/25`, `1/2/2026` and `1/2.5` are left as they are. A digit +/// counts in any script. +fn fraction_at(cs: &[char]) -> Option<(usize, char)> { + FRACTIONS.iter().find_map(|(text, f)| { + let len = text.chars().count(); + if cs.len() < len || !cs[..len].iter().copied().eq(text.chars()) { + return None; + } + let ends = match &cs[len..] { + [c, ..] if c.is_numeric() || *c == '/' => false, + ['.' | ',', d, ..] if d.is_numeric() => false, + _ => true, + }; + ends.then_some((len, *f)) + }) +} + +/// Expert Fractions: `text` with each fraction [`fraction_at`] finds, and no digit, slash or +/// decimal point before, written as one character when `covers` it. `prev` is the character before +/// `text`, and `next` the two characters after it (in the next runs), so a fraction at the end of +/// a run is checked against what follows it. +fn expert_fractions(text: &str, prev: Option, next: [Option; 2], covers: &mut impl FnMut(char) -> bool, n: &mut usize) -> String { + let mut cs: Vec = text.chars().collect(); + let len_text = cs.len(); + cs.extend(next.into_iter().flatten()); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while i < len_text { + let before = if i == 0 { prev } else { Some(cs[i - 1]) }; + let free = !before.is_some_and(|c| c.is_numeric() || matches!(c, '/' | '.' | ',')); + let found = fraction_at(&cs[i..]).filter(|(len, f)| i + len <= len_text && covers(*f)); + if free && let Some((len, f)) = found { + out.push(f); + *n += 1; + i += len; + continue; + } + out.push(cs[i]); + i += 1; + } + out +} + +/// The ligatures and their letters, longest first, with whether each comes with the ff, fi, ffi +/// option (else with the ff, fl, ffl option). ff comes with both. +const LIGATURES: [(&str, char, bool); 5] = + [("ffi", '\u{FB03}', true), ("ffl", '\u{FB04}', false), ("ff", '\u{FB00}', true), ("fi", '\u{FB01}', true), ("fl", '\u{FB02}', false)]; + +/// The ligature options: `text` with the letters of each ligature an option `o` asks for written +/// as the ligature, the longest first, when `covers` it. +fn ligatures(text: &str, o: &Punct, covers: &mut impl FnMut(char) -> bool, n: &mut PunctCounts) -> String { + let cs: Vec = text.chars().collect(); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while i < cs.len() { + let found = (cs[i] == 'f').then(|| { + LIGATURES.iter().find(|(letters, lig, fi)| { + let on = if *letters == "ff" { + o.fi_ligatures || o.fl_ligatures + } else if *fi { + o.fi_ligatures + } else { + o.fl_ligatures + }; + let len = letters.chars().count(); + on && cs.len() - i >= len && cs[i..i + len].iter().copied().eq(letters.chars()) && covers(*lig) + }) + }); + if let Some(&(letters, lig, fi)) = found.flatten() { + out.push(lig); + // ff counts with the ff, fi, ffi option when that option is on. + if fi && (letters != "ff" || o.fi_ligatures) { + n.fi_ligatures += 1; + } else { + n.fl_ligatures += 1; + } + i += letters.chars().count(); + continue; + } + out.push(cs[i]); + i += 1; + } + out +} + +/// One run's text with the replacements `o` asks for, counted in `n`. Ligatures and fractions are +/// written only where the run's font has a glyph for them. `next` holds the two characters after +/// the run. +fn smarten(text: &str, style: &CharStyle, next: [Option; 2], o: &Punct, st: &mut PunctState, n: &mut PunctCounts) -> String { + let mut s = if o.spaces { smart_spaces(text, &mut st.after_period, &mut n.spaces) } else { text.to_string() }; + if o.dashes { + s = replace_counted(s, "---", "—", &mut n.dashes); + s = replace_counted(s, "--", "–", &mut n.dashes); + } + if o.ellipses { + s = replace_counted(s, "...", "…", &mut n.ellipses); + } + // The run's font, looked up once and only for a ligature or a fraction. + let mut face = None; + let mut covers = |c: char| { + face.get_or_insert_with(|| { + vectorcraft_text::FontDb::global().face_version(&style.font_family, &style.font_style, style.font_version.as_deref()) + }) + .as_ref() + .is_some_and(|f| f.covers(c)) + }; + if o.fractions && s.contains('/') { + let before = if st.after_graphic { None } else { st.prev }; + s = expert_fractions(&s, before, next, &mut covers, &mut n.fractions); + } + st.after_graphic = false; + if (o.fi_ligatures || o.fl_ligatures) && s.contains('f') { + s = ligatures(&s, o, &mut covers, n); + } + match &o.quotes { + Some(q) => { + let out = q.apply(&s, &mut st.prev); + n.quotes += s.chars().zip(out.chars()).filter(|(a, b)| a != b).count(); + out + } None => { - *prev = s.chars().last().or(*prev); + st.prev = s.chars().last().or(st.prev); s } } @@ -293,12 +496,20 @@ pub(crate) fn smarten(text: &str, prev: &mut Option, quotes: Option<&Quote fn smart_punctuation(s: &mut Session, p: &Value) -> Result { const C: &str = "type.smartPunctuation"; - let (d, e) = (switch_or(p, "dashes", true, C)?, switch_or(p, "ellipsis", true, C)?); let quotes = switch_or(p, "quotes", true, C)?; + let mut o = Punct { + fi_ligatures: switch_or(p, "fiLigatures", false, C)?, + fl_ligatures: switch_or(p, "flLigatures", false, C)?, + quotes: None, + spaces: switch_or(p, "spaces", false, C)?, + dashes: switch_or(p, "dashes", true, C)?, + ellipses: switch_or(p, "ellipsis", true, C)?, + fractions: switch_or(p, "fractions", false, C)?, + }; let document = choice(p, C, "scope", &["selection", "document"])? == Some("document"); let st = s.doc()?; // Quotes in the document's style (Document Setup → Type). - let q = quotes.then_some(st.doc.setup.quotes); + o.quotes = quotes.then_some(st.doc.setup.quotes); let ids = if document || st.selection.is_empty() { let mut v = vec![]; st.doc.walk(|n| { @@ -310,8 +521,93 @@ fn smart_punctuation(s: &mut Session, p: &Value) -> Result { } else { text_ids(&st.doc, &st.selection.objects) }; - let n = edit_runs::(s, "Smart Punctuation", &ids, |text, st| smarten(text, &mut st.prev, q.as_ref(), d, e))?; - Ok(json!({ "changed": n })) + let mut n = PunctCounts::default(); + let changed = super::overprint::edit_counted(s, "Smart Punctuation", |d| { + let mut changed = 0; + for id in &ids { + let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; + let mut st = PunctState::default(); + let mut any = false; + // The ruby spans' ends, in the plain text as it was. Each run is rewritten in pieces + // between them, so no replacement crosses one, and `moved` records where each end and + // each run's start lands in the new text. + let mut edges: Vec = t.ruby.iter().flat_map(|r| [r.start, r.end]).collect(); + edges.sort_unstable(); + edges.dedup(); + let mut moved = vec![]; + let (mut old_at, mut new_at) = (0, 0); + // Inline graphics are art, not characters to rewrite. Each run sees the first two + // characters of the runs after it, up to the next inline graphic, as they were. + for i in 0..t.runs.len() { + let len = t.runs[i].text.len(); + moved.push((old_at, new_at)); + if t.runs[i].inline.is_some() { + // A graphic separates the characters on either side of it for Smart Spaces and + // Expert Fractions; quotes still read the character before it. + st.after_period = None; + st.after_graphic = true; + (old_at, new_at) = (old_at + len, new_at + len); + continue; + } + let mut after = t.runs[i + 1..].iter().take_while(|r| r.inline.is_none()).flat_map(|r| r.text.chars()); + let following = [after.next(), after.next()]; + // Smart Spaces counts no space across a ruby span's end, so it removes no space on + // the other side of one. + if edges.binary_search(&old_at).is_ok() { + st.after_period = None; + } + let r = &mut t.runs[i]; + let mut cuts: Vec = + edges.iter().filter(|&&e| e > old_at && e < old_at + len && r.text.is_char_boundary(e - old_at)).map(|e| e - old_at).collect(); + cuts.push(len); + let mut new = String::with_capacity(len); + let mut from = 0; + for cut in cuts { + if from > 0 { + moved.push((old_at + from, new_at + new.len())); + st.after_period = None; + } + let mut after = r.text[cut..].chars().chain(following.into_iter().flatten()); + let next = [after.next(), after.next()]; + new.push_str(&smarten(&r.text[from..cut], &r.style, next, &o, &mut st, &mut n)); + from = cut; + } + (old_at, new_at) = (old_at + len, new_at + new.len()); + if new != r.text { + r.text = new; + any = true; + } + } + moved.push((old_at, new_at)); + if any { + changed += 1; + // Each ruby end moves with the text before it; an end inside a character keeps its + // distance from the last place recorded before it. + let to_new = |v: usize| { + let k = moved.partition_point(|&(old, _)| old <= v).saturating_sub(1); + moved.get(k).map_or(v, |&(old, new)| new + (v - old.min(v))) + }; + for span in &mut t.ruby { + (span.start, span.end) = (to_new(span.start), to_new(span.end)); + } + t.normalize_ruby(); + refresh_bounds(t); + } + } + Ok(changed) + })?; + Ok(json!({ + "changed": changed, + "replaced": { + "fiLigatures": n.fi_ligatures, + "flLigatures": n.fl_ligatures, + "quotes": n.quotes, + "spaces": n.spaces, + "dashes": n.dashes, + "ellipses": n.ellipses, + "fractions": n.fractions, + }, + })) } // ---------- Area / Point conversion ---------- diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 6ca724d810..9f676e737c 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -222,11 +222,11 @@ pub fn written_elsewhere(path: &str) -> bool { !cfg!(windows) && foreign && current().is_some() } -/// Does a command param named `key` hold a file or folder path: `path`, `paths`, `file`, `files`, -/// `folder`, or a name ending in `Path`, `Paths`, `File`, `Files` or `Folder` (`diffPath`, -/// `destinationFolder`)? +/// Does a command param named `key` hold a file or folder path in a command that gives it no other +/// meaning ([`crate::cmd::key_location`]: `path`, `file`, `diffPath`, `destinationFolder` and the +/// like)? [`crate::cmd::ParamsPlace`] tells what it holds in a given command. pub fn is_path_key(key: &str) -> bool { - matches!(key, "path" | "paths" | "file" | "files" | "folder") || ["Path", "Paths", "File", "Files", "Folder"].iter().any(|end| key.ends_with(end)) + crate::cmd::key_location(key).is_some() } /// May `path` be written here? Always, without roots in force. diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index e3cd563d55..99a2569005 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -24,6 +24,9 @@ pub struct Interaction { /// The perspective transform the previews make (`perspective.transform` params): Transform /// Again repeats it once the drag is committed. pub perspective_again: Option, + /// A preview drew an object on, or attached one to, a plane held by Automatic Plane + /// Positioning: the plane goes back to its place once the drag is committed. + pub(crate) plane_placed: bool, /// A transform or a perspective edit with `copy` keeps the copies it made of the snapshot here /// ([`PreviewCopies`]). pub(crate) copies: Option>, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 83e6368f8b..e25cde77cc 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -329,6 +329,8 @@ impl Session { // Ruler guides a reader left in the saved list become nodes on their layers. doc.guides_into_nodes(); cmd::dimension::conform(&mut doc); + // A plane held by Automatic Plane Positioning when the file was saved is back in its place. + vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(&mut doc); self.reset_tool_for_doc_switch(); let mut st = DocState::new(doc, path); st.history.limit = self.prefs.history_states as usize; @@ -357,6 +359,7 @@ impl Session { doc.resolve_inline_art(); doc.guides_into_nodes(); cmd::dimension::conform(&mut doc); + vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(&mut doc); // In the back, type set in a font named like a composite font is measured again below, in // the document's own composite fonts, not in the front document's. let back = self.active != Some(index); diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 73977f7d64..4f47b325b9 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -289,6 +289,7 @@ impl Session { variables_highlight: st.variables_highlight.clone(), isolation: st.isolation, perspective_again: None, + plane_placed: false, copies: None, move_box: std::sync::OnceLock::new(), }); @@ -319,6 +320,7 @@ impl Session { it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; + it.plane_placed = false; if selection_changed { st.selection.clone_from(&it.selection); } @@ -378,6 +380,7 @@ impl Session { after.clone_from(&paint); } let perspective_again = it.perspective_again.take(); + let plane_placed = it.plane_placed; let copy = preview.0 == "object.transform" && preview.1.get("copy").and_then(Value::as_bool).unwrap_or(false); // Alt pressed or released during a move drag turns it into a copy or back: name it for // what it did in the end. @@ -395,6 +398,12 @@ impl Session { preview.1.get("dy").and_then(Value::as_f64).unwrap_or(0.0), ); st.keep_interaction(it); + // The drag drew an object on, or attached one to, the plane Automatic Plane Positioning + // held: the plane is back in its place now, as view state (undoing the drag holds it again). + if plane_placed && changed && vectorcraft_tools::distort::perspective::PerspectiveGrid::positioning(&st.doc) { + vectorcraft_tools::distort::perspective::PerspectiveGrid::end_positioning(Arc::make_mut(&mut st.doc)); + st.revision += 1; + } if preview.0 == "object.transform" && changed { let m = cmd::matrix_param(&preview.1, "matrix"); if let Some(m) = m { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 57445a36be..3b54a532ef 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -128,6 +128,7 @@ mod pdffidelity; mod pdfmarks; mod pdfpresets; mod pdfraster; +mod persp_infer; mod persp_planes; pub(super) mod persp_select; mod persp_text; diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 8719873a94..64ef55d7ab 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -301,6 +301,42 @@ fn an_export_preset_sets_the_shared_settings() { assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["prefix"], "p_"); } +/// `openLocation` (Open Location after Export) is remembered in the document's export settings, +/// outside presets; null removes it, and only true or false is taken. +#[test] +fn open_location_is_remembered_in_the_export_settings() { + let mut s = session(); + let open = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["openLocation"].clone(); + let r = run(&mut s, "assets.settings.set", json!({"openLocation": false})); + assert_eq!(open(&mut s), false); + assert!(r["settings"].get("openLocation").is_none(), "{r}"); + // Create Sub-folders, on for a document without settings, stays on. + assert_eq!(r["settings"]["subfolders"], true, "{r}"); + run(&mut s, "document.exportPresets.save", json!({"name": "Kept", "settings": {"formats": [{"format": "svg"}]}})); + run(&mut s, "assets.settings.set", json!({"exportPreset": "Kept"})); + assert_eq!(open(&mut s), false, "a preset leaves it as it is"); + run(&mut s, "assets.settings.set", json!({"openLocation": null})); + assert_eq!(open(&mut s), Value::Null); + for bad in [json!({"openLocation": "yes"}), json!({"openLocation": 1}), json!({"subfolders": "no"})] { + assert!(s.execute("assets.settings.set", &bad).is_err(), "{bad}"); + } +} + +/// Create Sub-folders turned off on its own ends a remembered folder per format or item, so Export +/// for Screens opens with it off too; given with an export preset, the preset's folders stay. +#[test] +fn create_sub_folders_off_alone_ends_a_folder_per_format_or_item() { + let mut s = session(); + let folders = |s: &mut Session| run(s, "document.exportSettings", json!({}))["settings"]["folders"].clone(); + run(&mut s, "document.exportPresets.save", json!({"name": "Items", "settings": {"formats": [{"format": "svg"}], "folders": "item"}})); + for preset in ["Logo Package", "Items"] { + run(&mut s, "assets.settings.set", json!({"exportPreset": preset, "subfolders": false})); + assert_ne!(folders(&mut s), "none", "{preset}"); + run(&mut s, "assets.settings.set", json!({"subfolders": false})); + assert_eq!(folders(&mut s), "none", "{preset}"); + } +} + /// An export preset applied to the shared settings keeps its folders, with Create Sub-folders on /// for a folder per row; with Create Sub-folders off every file goes into the folder itself, /// mobile and density rows too. diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index dedcf2d8af..8fd5a3aa45 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1490,6 +1490,93 @@ fn shape_builder_open_filled_paths_cut_without_open_filled_as_closed() { assert!((area(&s, NodeId(r["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6); } +/// The fill rows of an open path's appearance (bottom first) for the open-path tests below, with +/// a 1 pt black stroke on top: a painted fill under an unpainted top fill, a painted fill that is +/// hidden, one with an opacity of 0, and a painted fill under a hidden painted top fill. +fn open_path_fill_stacks() -> [(&'static str, Vec, bool); 4] { + use vectorcraft_doc::{FillLayer, StrokeLayer}; + let fill = |p: Paint, visible: bool, opacity: f32| { + let mut f = FillLayer::new(p); + f.visible = visible; + f.opacity = opacity; + AppearanceItem::Fill(f) + }; + let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let blue = || Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let stroke = || AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 1.0)); + [ + ("a painted fill under an unpainted top fill", vec![fill(red(), true, 1.0), fill(Paint::None, true, 1.0), stroke()], true), + ("a hidden painted fill", vec![fill(red(), false, 1.0), stroke()], false), + ("a painted fill with an opacity of 0", vec![fill(red(), true, 0.0), stroke()], false), + ("a painted fill under a hidden painted top fill", vec![fill(red(), true, 1.0), fill(blue(), false, 1.0), stroke()], true), + ] +} + +/// Consider Open Filled Paths as Closed: an open path counts as filled when any of its fill rows +/// draws (shown, painted and above 0% opacity), whichever row is on top. The map, a merge inside +/// the area and what a merge keeps of the path follow the rows that draw; with the option off, none +/// of the paths closes. +#[test] +fn shape_builder_closes_open_paths_by_the_fill_rows_that_draw() { + for (what, items, closes) in open_path_fill_stacks() { + let mut s = session(); + let r = s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(p).unwrap().appearance.items = items; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [p.0]})).unwrap(); + let r = s.execute("shapeBuilder.regions", &json!({})).unwrap(); + assert_eq!( + (r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()), + if closes { (1, 0) } else { (0, 1) }, + "{what}: {r}" + ); + let r = s.execute("shapeBuilder.regions", &json!({"openFilledAsClosed": false})).unwrap(); + assert_eq!((r["regions"].as_array().unwrap().len(), r["lines"].as_array().unwrap().len()), (0, 1), "{what}, option off: {r}"); + let n = node(&s, p); + for on in [true, false] { + let inputs = vectorcraft_tools::builder::merge_inputs(&[&n], on); + assert_eq!(inputs.iter().map(|i| i.fill_closes).collect::>(), vec![closes && on], "{what}, option {on}"); + } + let merged = s.execute("shapeBuilder.merge", &json!({"points": [[75, 25]]})); + if closes { + assert!((area(&s, NodeId(merged.unwrap()["merged"].as_u64().unwrap())) - 5000.0).abs() < 1e-6, "{what}"); + } else { + assert!(merged.is_err(), "{what}: the open path encloses no region"); + } + } +} + +/// Clicking Stroke Splits the Path on the middle side of an open U cuts it along the outline its +/// drawn fill closes: with a fill row that draws, what is left runs on from the cut round the +/// implied closing edge (the top side, then the bottom side); without one, what is left is the +/// open path's two ends in path order (the bottom side, then the top side). +#[test] +fn shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw() { + for (what, items, closes) in open_path_fill_stacks() { + let mut s = session(); + let r = + s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}, {"x": 100, "y": 100}, {"x": 0, "y": 100}]})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(p).unwrap().appearance.items = items; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [p.0]})).unwrap(); + let r = s.execute("shapeBuilder.merge", &json!({"points": [[101, 50]], "splitStroke": true})).unwrap(); + let out = ids(&r); + assert_eq!(shapes_of(&s, &out), vec![(false, 4, 200.0), (false, 2, 100.0)], "{what}"); + let (rest, _) = outline(&node(&s, out[0])); + let starts: Vec<(f64, f64)> = rest.subpaths.iter().map(|sp| (sp.anchors[0].p.x.round(), sp.anchors[0].p.y.round())).collect(); + let order = if closes { vec![(100.0, 100.0), (0.0, 0.0)] } else { vec![(0.0, 0.0), (100.0, 100.0)] }; + assert_eq!(starts, order, "{what}"); + } +} + /// Pick Color From Color Swatches: the merged shape takes the current fill, not the fill of the /// object under the first point; setting the current fill without `ids` leaves the selection's. #[test] @@ -4105,6 +4192,58 @@ fn shape_builder_uses_the_filled_faces_of_a_live_paint_group() { assert!((stroked_length(&s, &out) - 600.0).abs() < 1.0, "{}", stroked_length(&s, &out)); } +/// The Shape Builder takes a Live Paint face or edge when any of its fill or stroke rows draws, +/// whichever row is on top: a painted lower row under an unpainted top row counts, and a part +/// whose only painted row is hidden, transparent or (for an edge) 0 pt wide, or whose own opacity +/// is 0, does not. +#[test] +fn shape_builder_takes_the_live_paint_faces_and_edges_that_draw() { + use vectorcraft_doc::{FillLayer, StrokeLayer}; + let fill = |p: Paint| AppearanceItem::Fill(FillLayer::new(p)); + let stroke = |p: Paint, w: f64| AppearanceItem::Stroke(StrokeLayer::new(p, w)); + let red = || Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let hidden = |mut i: AppearanceItem| { + match &mut i { + AppearanceItem::Fill(f) => f.visible = false, + AppearanceItem::Stroke(st) => st.visible = false, + } + i + }; + let clear = |mut i: AppearanceItem| { + match &mut i { + AppearanceItem::Fill(f) => f.opacity = 0.0, + AppearanceItem::Stroke(st) => st.opacity = 0.0, + } + i + }; + let mut s = session(); + let g = live(&mut s); + let lower_fill = set_live_part(&mut s, g, Some((25.0, 50.0)), None, vec![fill(red()), fill(Paint::None)], 1.0); + let hidden_fill = set_live_part(&mut s, g, Some((125.0, 50.0)), None, vec![hidden(fill(red()))], 1.0); + let clear_fill = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![clear(fill(red()))], 1.0); + let lower_stroke = set_live_part(&mut s, g, None, Some((0.0, 50.0)), vec![stroke(red(), 2.0), stroke(Paint::None, 1.0)], 1.0); + let hidden_stroke = set_live_part(&mut s, g, None, Some((150.0, 50.0)), vec![hidden(stroke(red(), 2.0))], 1.0); + let thin_stroke = set_live_part(&mut s, g, None, Some((100.0, 50.0)), vec![stroke(red(), 0.0)], 1.0); + let clear_stroke = set_live_part(&mut s, g, None, Some((50.0, 50.0)), vec![clear(stroke(red(), 2.0))], 1.0); + let clear_edge = set_live_part(&mut s, g, None, Some((75.0, 0.0)), vec![stroke(red(), 2.0)], 0.0); + let parts = [lower_fill, hidden_fill, clear_fill, lower_stroke, hidden_stroke, thin_stroke, clear_stroke, clear_edge]; + assert_eq!(parts.iter().collect::>().len(), parts.len()); + let d = s.doc().unwrap(); + let (_, leaves) = vectorcraft_tools::builder::shape_builder_shapes(&d.doc, &[g], true); + let taken: Vec = leaves.iter().map(|l| l.id).collect(); + assert!(taken.contains(&lower_fill) && taken.contains(&lower_stroke), "a painted lower row draws: {taken:?}"); + for id in [hidden_fill, clear_fill, hidden_stroke, thin_stroke, clear_stroke, clear_edge] { + assert!(!taken.contains(&id), "{id:?} draws nothing: {taken:?}"); + } + // A face with a painted fill whose own opacity is 0 is left out too. + let mut s = session(); + let g = live(&mut s); + let clear_face = set_live_part(&mut s, g, Some((75.0, 50.0)), None, vec![fill(red())], 0.0); + let d = s.doc().unwrap(); + let (_, leaves) = vectorcraft_tools::builder::shape_builder_shapes(&d.doc, &[g], true); + assert!(!leaves.iter().any(|l| l.id == clear_face), "a face with an opacity of 0 draws nothing"); +} + /// An edge that closes on itself is a line around its face, not a second shape over it. #[test] fn shape_builder_takes_a_closed_live_paint_edge_as_a_line() { diff --git a/crates/engine/src/tests/linkspanel.rs b/crates/engine/src/tests/linkspanel.rs index a9a3a17ec7..a1402cc43f 100644 --- a/crates/engine/src/tests/linkspanel.rs +++ b/crates/engine/src/tests/linkspanel.rs @@ -248,7 +248,42 @@ fn the_list_shows_each_image_with_its_status() { assert_eq!(run(&mut s, "links.list", json!({"show": "missing"}))["links"][0]["id"], linked.0); assert_eq!(run(&mut s, "links.list", json!({"sort": "name"}))["links"][0]["name"], "a.png"); assert!(s.execute("links.list", &json!({"show": "broken"})).is_err()); - assert!(s.execute("links.list", &json!({"sort": "size"})).is_err()); + assert!(s.execute("links.list", &json!({"sort": "date"})).is_err()); +} + +#[test] +fn sort_by_size_lists_the_smallest_file_first() { + let dir = Folder::new("list-size"); + let files = [("a.png", png(600, 300, RED)), ("b.png", png(10, 10, BLUE)), ("c.png", png(100, 100, RED)), ("d.png", png(10, 10, BLUE))]; + let mut s = session(); + for (name, bytes) in &files { + let path = dir.file(name); + write(&path, bytes); + place(&mut s, &path); + } + let e = dir.file("e.png"); + write(&e, &png(1, 1, RED)); + place_embedded(&mut s, &e); + let names = |s: &mut Session| -> Vec { + let l = run(s, "links.list", json!({"sort": "size"})); + l["links"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap_or_default().to_string()).collect() + }; + // Smallest first, equal sizes by name, the embedded image (no file) last. + let mut want: Vec<(usize, &str)> = files.iter().map(|(n, b)| (b.len(), *n)).collect(); + want.sort(); + assert!(want[0].0 < want[2].0 && want[2].0 < want[3].0, "{want:?}"); + let mut want: Vec = want.iter().map(|(_, n)| n.to_string()).collect(); + want.push("e.png".into()); + assert_eq!(names(&mut s), want); + // A missing file sorts by the size the document keeps of it. + std::fs::remove_file(dir.file("a.png")).unwrap(); + assert_eq!(names(&mut s), want); + // A modified file sorts by its size now. + let bigger = png(900, 900, BLUE); + assert!(bigger.len() > files[0].1.len()); + write(&dir.file("c.png"), &bigger); + let got = names(&mut s); + assert_eq!(got[got.len() - 2..], ["c.png".to_string(), "e.png".to_string()]); } #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index e8c4e46af3..1151f83910 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2234,6 +2234,10 @@ fn type_menu_and_find_commands_refuse_a_param_of_the_wrong_type() { ("type.smartPunctuation", json!({"dashes": "false"}), switch("dashes")), ("type.smartPunctuation", json!({"ellipsis": 0}), switch("ellipsis")), ("type.smartPunctuation", json!({"quotes": "no"}), switch("quotes")), + ("type.smartPunctuation", json!({"fiLigatures": 1}), switch("fiLigatures")), + ("type.smartPunctuation", json!({"flLigatures": "true"}), switch("flLigatures")), + ("type.smartPunctuation", json!({"spaces": "on"}), switch("spaces")), + ("type.smartPunctuation", json!({"fractions": [true]}), switch("fractions")), ("type.smartPunctuation", json!({"scope": 5}), scope.clone()), ("type.smartPunctuation", json!({"scope": "page"}), scope), ("type.changeCase", json!({"case": 5}), string("case")), @@ -3563,12 +3567,154 @@ fn smart_punctuation_with_nothing_to_change_records_no_undo_step() { for id in [t, r] { select_with_a_step_to_redo(&mut s, &[id]); let before = history(&s); - assert_eq!(s.execute("type.smartPunctuation", &json!({})).unwrap(), json!({"changed": 0}), "{id:?}"); + let r = s.execute("type.smartPunctuation", &json!({})).unwrap(); + assert_eq!(r["changed"], 0, "{id:?}"); + assert!(r["replaced"].as_object().unwrap().values().all(|n| n == 0), "{id:?}: {r}"); assert_eq!(history(&s), before, "{id:?}"); } assert_eq!(plain(&s, t), "“Hi” it’s 1–2 and 3—4…"); } +/// Does the face text `font` draws with have a glyph for every character of `chars`? +fn font_covers(font: &str, chars: &str) -> bool { + let face = vectorcraft_text::FontDb::global().face(font, "Regular"); + face.is_some_and(|f| chars.chars().all(|c| f.covers(c))) +} + +/// Every option on: the ligatures, Smart Spaces and Expert Fractions, each counted on its own, in +/// one undo step. Fractions next to a digit, a slash or a decimal part are left as they are. +#[test] +fn smart_punctuation_ligatures_spaces_and_fractions_are_counted() { + let mut s = session(); + assert!(font_covers("Source Sans 3", "\u{FB00}\u{FB01}\u{FB02}\u{FB03}\u{FB04}½¾"), "Source Sans 3 draws the ligatures and fractions"); + let words = "An office's fluffy flow. Then 1/2 and 3/4, not 1/25, 1/2/26 or 1/2.5."; + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap()); + sel(&mut s, &[t]); + let undo = history(&s).0; + let all = json!({"fiLigatures": true, "flLigatures": true, "quotes": true, "spaces": true, "dashes": true, "ellipsis": true, "fractions": true}); + let r = s.execute("type.smartPunctuation", &all).unwrap(); + assert_eq!(plain(&s, t), "An o\u{FB03}ce’s \u{FB02}u\u{FB00}y \u{FB02}ow. Then ½ and ¾, not 1/25, 1/2/26 or 1/2.5."); + let replaced = json!({"fiLigatures": 2, "flLigatures": 2, "quotes": 1, "spaces": 1, "dashes": 0, "ellipses": 0, "fractions": 2}); + assert_eq!(r, json!({"changed": 1, "replaced": replaced})); + assert_eq!(history(&s).0, undo + 1); +} + +/// The ff, fl, ffl option alone leaves fi and ffi as letters (ffi keeps its ff ligature, counted +/// with this option), and the other options are off unless asked for. +#[test] +fn smart_punctuation_fl_ligatures_alone() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "office fit baffle. 1/2", "font": "Source Sans 3"})).unwrap()); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"flLigatures": true})).unwrap(); + assert_eq!(plain(&s, t), "o\u{FB00}ice fit ba\u{FB04}e. 1/2"); + assert_eq!(r["replaced"], json!({"fiLigatures": 0, "flLigatures": 2, "quotes": 0, "spaces": 0, "dashes": 0, "ellipses": 0, "fractions": 0})); +} + +/// A ligature or a fraction the run's font has no glyph for stays as its letters, while the run's +/// other replacements still happen. +#[test] +fn smart_punctuation_skips_ligatures_and_fractions_the_font_lacks() { + let mut s = session(); + let mono = "JetBrains Mono"; + assert!(!font_covers(mono, "\u{FB01}") && !font_covers(mono, "⅐"), "{mono} has no fi ligature or one-seventh"); + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "fit 1/7 a--b", "font": mono})).unwrap()); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"fiLigatures": true, "fractions": true})).unwrap(); + assert_eq!(plain(&s, t), "fit 1/7 a–b"); + let counts = (&r["replaced"]["fiLigatures"], &r["replaced"]["fractions"], &r["replaced"]["dashes"]); + assert_eq!(counts, (&json!(0), &json!(0), &json!(1))); +} + +/// A fraction at the end of a run is checked against the start of the next run: 1/25 and 1/2.5 +/// split after their 1/2 stay as they are, and a 1/2 the next run's space ends is replaced. +#[test] +fn expert_fractions_look_past_the_end_of_a_run() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "1/25 1/2.5 1/2 x", "font": "Source Sans 3"})).unwrap()); + for (start, end) in [(0, 3), (5, 8), (11, 14)] { + s.execute("text.setRangeStyle", &json!({"id": t.0, "start": start, "end": end, "size": 30})).unwrap(); + } + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap(); + assert_eq!(plain(&s, t), "1/25 1/2.5 ½ x"); + assert_eq!(r["replaced"]["fractions"], 1); +} + +/// An inline graphic separates the text on either side of it: the space after it is not a second +/// space after the period before it, and the digit before it does not stop a fraction after it. +#[test] +fn an_inline_graphic_separates_smart_spaces_and_fractions() { + let mut s = session(); + let r = rect(&mut s, 600.0, 500.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "A. B 71/2", "font": "Source Sans 3"})).unwrap()); + s.execute("text.insertInline", &json!({"id": t.0, "at": 7, "symbol": "Mark"})).unwrap(); + s.execute("text.insertInline", &json!({"id": t.0, "at": 3, "symbol": "Mark"})).unwrap(); + let texts = |s: &Session| match node(s, t).kind { + NodeKind::Text(o) => o.runs.iter().map(|r| if r.inline.is_some() { "[g]".to_string() } else { r.text.clone() }).collect::(), + _ => String::new(), + }; + assert_eq!(texts(&s), "A. [g] B 7[g]1/2"); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fractions": true})).unwrap(); + assert_eq!(texts(&s), "A. [g] B 7[g]½"); + assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fractions"]), (&json!(0), &json!(1))); +} + +/// Smart Spaces keeps one space after each period, also when the spaces start in the next run, +/// and leaves single spaces and spaces after other characters alone. +#[test] +fn smart_spaces_keeps_one_space_after_a_period() { + let mut s = session(); + let t = text(&mut s, "A. B. C. D E"); + // "C." is in a run of its own, and the spaces after it start the next one. + s.execute("text.setRangeStyle", &json!({"id": t.0, "start": 8, "end": 10, "size": 30})).unwrap(); + assert!(matches!(node(&s, t).kind, NodeKind::Text(ref o) if o.runs.len() > 1)); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "quotes": false, "dashes": false, "ellipsis": false})).unwrap(); + assert_eq!(plain(&s, t), "A. B. C. D E"); + assert_eq!(r["replaced"]["spaces"], 2); +} + +/// Ruby stays on the characters it was set on when Smart Punctuation makes the text before them +/// longer (curly quotes) or shorter (Smart Spaces), and no replacement takes in characters on both +/// sides of a ruby span's end: the fi with ruby on its i stays as letters, and a second space after +/// a period with ruby of its own stays. +#[test] +fn smart_punctuation_keeps_ruby_on_its_characters() { + let mut s = session(); + let spans = |s: &Session, t| match node(s, t).kind { + NodeKind::Text(o) => o.ruby.iter().map(|r| (r.start, r.end)).collect::>(), + _ => vec![], + }; + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": "'A'. base fit X. Y", "font": "Source Sans 3"})).unwrap()); + sel(&mut s, &[t]); + for (start, end) in [(1, 2), (6, 10), (12, 13), (18, 19)] { + s.execute("type.ruby", &json!({"text": "r", "start": start, "end": end})).unwrap(); + } + let r = s.execute("type.smartPunctuation", &json!({"spaces": true, "fiLigatures": true})).unwrap(); + assert_eq!(plain(&s, t), "‘A’. base fit X. Y"); + assert_eq!((&r["replaced"]["spaces"], &r["replaced"]["fiLigatures"]), (&json!(1), &json!(0))); + let text = plain(&s, t); + let on: Vec<&str> = spans(&s, t).into_iter().map(|(a, b)| &text[a..b]).collect(); + assert_eq!(on, ["A", "base", "i", " "]); +} + +/// Expert Fractions leaves a fraction next to a digit of another script as it is. +#[test] +fn expert_fractions_skip_fractions_next_to_digits_of_any_script() { + let mut s = session(); + let words = "\u{662}1/2 1/2\u{662} 1/2.\u{662} 1/2"; + let t = id_of(&s.execute("text.create", &json!({"x": 50, "y": 50, "text": words, "font": "Source Sans 3"})).unwrap()); + sel(&mut s, &[t]); + let r = s.execute("type.smartPunctuation", &json!({"fractions": true})).unwrap(); + assert_eq!(plain(&s, t), "\u{662}1/2 1/2\u{662} 1/2.\u{662} ½"); + assert_eq!(r["replaced"]["fractions"], 1); +} + #[test] fn convert_point_area_roundtrip() { let mut s = session(); diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index a97d414500..3788185ae6 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -775,6 +775,78 @@ fn create_outlines_draws_the_type_objects_own_paint() { assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something"); } +/// Selected type "HIH" at 40 pt with ruby, underlined and struck through, its characters filled +/// with `fill` (a `paint.setFill` param) and stroked 2 pt wide, then scaled to 150% and rotated 20 +/// degrees (the stroke keeps its 2 pt, which is 4/3 pt in text space). +fn transformed_gradient_type(s: &mut Session, fill: Value) -> NodeId { + let t = run(s, "text.create", json!({"x": 30, "y": 110, "text": "HIH", "size": 40}))["id"].as_u64().unwrap(); + run(s, "select.set", json!({"ids": [t]})); + run(s, "type.ruby", json!({"text": "ab"})); + run(s, "text.setFormat", json!({"ids": [t], "underline": true, "strikethrough": true})); + run(s, "paint.setFill", fill); + run(s, "paint.setStroke", json!({"color": "#008000"})); + run(s, "stroke.set", json!({"weight": 2})); + run(s, "object.scale", json!({"ids": [t], "sx": 150, "sy": 150})); + run(s, "object.rotate", json!({"ids": [t], "angle": 20})); + NodeId(t) +} + +/// Create Outlines draws what the type drew: a gradient on the characters that has no vector of +/// its own keeps one gradient across every glyph, ruby glyph and bar, fitted to the layout's box, +/// and one with a vector keeps it where it was, both with the type's scale and rotation. The +/// characters' stroke keeps the weight it was drawn at. +#[test] +fn create_outlines_keeps_a_character_gradient_across_the_type() { + let placed = json!({"gradient": {"kind": "linear", "start": [40, 100], "end": [110, 100], + "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}); + for fill in [red_blue(), placed] { + let mut s = session(); + let t = transformed_gradient_type(&mut s, fill.clone()); + let NodeKind::Text(text) = &node(&s, t).kind else { panic!("not type") }; + assert!(!text.ruby.is_empty() && text.runs.iter().all(|r| r.style.underline && r.style.strikethrough), "{fill}"); + // The characters' stroke is kept in text space and drawn scaled by the type's transform. + let weight = text.runs[0].style.stroke_layer().width; + let drawn = weight * vectorcraft_doc::Scaling::factor(text.xf).unwrap_or(1.0); + assert!((drawn - weight).abs() > 0.1, "the type's transform scales: {weight} {drawn}"); + let before = render(&s); + let g = run(&mut s, "type.createOutlines", json!({}))["ids"][0].as_u64().unwrap(); + let after = render(&s); + let n = differing(&before, &after, 24); + assert!(n < 60, "{fill}: {n} pixels differ"); + assert!(differing(&before, &render(&session()), 24) > 1000, "the type paints something"); + // Every glyph, ruby glyph and bar takes the same gradient, placed, and the stroke at the + // weight it was drawn at. + let mut gradients = vec![]; + let mut widths = vec![]; + node(&s, NodeId(g)).walk(&mut |c: &Node| { + if let Paint::Gradient(gr) = c.appearance.fill_paint() { + gradients.push(gr.clone()); + } + widths.extend(c.appearance.stroke().map(|st| st.width)); + }); + assert!(gradients.len() >= 6, "{fill}: three glyphs, ruby and two bars: {}", gradients.len()); + assert!(gradients.iter().all(|gr| gr.is_placed() && *gr == gradients[0]), "{fill}: {gradients:?}"); + assert!(widths.len() == gradients.len() && widths.iter().all(|w| (w - drawn).abs() < 1e-9), "{fill}: {drawn} {widths:?}"); + } +} + +/// Expand outlines the type before its fills expand, so a gradient on its characters that has no +/// vector of its own expands across the whole type, as the canvas draws it, and the query reports +/// it. +#[test] +fn expand_keeps_a_character_gradient_across_the_type() { + let mut s = session(); + transformed_gradient_type(&mut s, red_blue()); + let info = run(&mut s, "object.expand.info", json!({})); + assert_eq!((info["gradient"].clone(), info["fill"].clone(), info["object"].clone()), (json!(true), json!(true), json!(true)), "{info}"); + let before = render(&s); + run(&mut s, "object.expand", json!({})); + let after = render(&s); + assert_eq!(gradients_and_type(&s), (0, 0), "outlined and expanded"); + let d = mean_diff(&before, &after); + assert!(d < 0.5, "{d}"); +} + /// `object.expand.info` reports the type object's own stroke, pattern fill and gradient fill, which /// Object turns into paths of its whole outline: a gradient only when that outline's box needs no /// more runs than are written. diff --git a/crates/engine/src/tests/persp_infer.rs b/crates/engine/src/tests/persp_infer.rs new file mode 100644 index 0000000000..79569a2437 --- /dev/null +++ b/crates/engine/src/tests/persp_infer.rs @@ -0,0 +1,273 @@ +//! Automatic Plane Positioning: Shift held over an anchor point of art in perspective or over a +//! gridline intersection moves the active plane through it for now (`perspective.plane.infer`), +//! the two Perspective Grid Options that turn the targets on and off, and what ends it. + +use serde_json::json; +use vectorcraft_geom::{Point, Vec2}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::tests_persp_select::{attached, bounds_of, drag, grid, persp_session, plane_pts, undo_len}; +use crate::*; + +fn shift() -> Mods { + Mods { shift: true, ..Default::default() } +} + +/// The top anchor of path `id` (on the right wall at depth 0): its page point and its height. +fn top_anchor(s: &Session, id: NodeId) -> (Point, f64) { + let page: Vec = s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect(); + let plane = plane_pts(s, id, Plane::Right, 0.0); + page.into_iter().zip(plane).map(|(p, q)| (p, q.y)).max_by(|a, b| a.1.total_cmp(&b.1)).unwrap() +} + +fn hover(s: &mut Session, p: Point, mods: Mods) { + s.pointer(&PointerEvent::new(PointerKind::Move, p.x, p.y).with_mods(mods), ViewInfo::default()).unwrap(); +} + +fn revision(s: &Session) -> u64 { + s.doc().unwrap().revision +} + +#[test] +fn shift_over_an_anchor_holds_the_active_plane_at_its_height_until_an_object_is_drawn() { + let (mut s, id) = persp_session(); + let v = ViewInfo::default(); + let (anchor, height) = top_anchor(&s, id); + assert!(height > 10.0, "{height}"); + s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap(); + s.select_tool("perspectiveSelection", v).unwrap(); + let steps = undo_len(&s); + // Without Shift the pointer only hovers. + hover(&mut s, anchor, Mods::default()); + assert_eq!(grid(&s).inferred, None); + hover(&mut s, anchor, shift()); + let g = grid(&s); + assert!(g.inferred.is_some()); + assert!((g.offset(Plane::Ground) - height).abs() < 1e-6, "{} {height}", g.offset(Plane::Ground)); + assert_eq!((g.ground_offset, g.shown_planes(), undo_len(&s)), (0.0, vec![Plane::Ground], steps)); + // Held there already, another hover over the anchor changes nothing. + let rev = revision(&s); + hover(&mut s, anchor, shift()); + assert_eq!(revision(&s), rev); + // The Rectangle tool draws on the plane where it is held, and the plane stays put for the drag. + s.select_tool("rectangle", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 420.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 470.0, 430.0), v).unwrap(); + assert!(grid(&s).inferred.is_some(), "held while the object is drawn"); + s.pointer(&PointerEvent::new(PointerKind::Up, 470.0, 430.0), v).unwrap(); + let drawn = s.doc().unwrap().selection.objects[0]; + assert_ne!(drawn, id); + let (plane, depth) = attached(&s, drawn).unwrap(); + assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}"); + // Drawn, the plane is back in its place and the other planes show: one undo step for the drag. + let g = grid(&s); + assert_eq!((g.inferred, g.offset(Plane::Ground), g.shown_planes().len(), undo_len(&s)), (None, 0.0, 3, steps + 1)); + // Undoing the drag holds the plane again; Escape with the Perspective Selection tool ends that. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(grid(&s).inferred.is_some()); + s.select_tool("perspectiveSelection", v).unwrap(); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + assert_eq!(grid(&s).inferred, None); +} + +#[test] +fn shift_during_a_drag_still_constrains_the_move() { + let (mut s, id) = persp_session(); + let v = ViewInfo::default(); + s.select_tool("perspectiveSelection", v).unwrap(); + let before = plane_pts(&s, id, Plane::Right, 0.0); + let h = grid(&s).homography(Plane::Right).unwrap(); + // From the middle of the object, along the wall and a little up. + let start = bounds_of(&before).center(); + let (from, to) = (h.apply(start).unwrap(), h.apply(start + Vec2::new(80.0, 20.0)).unwrap()); + drag(&mut s, &[from, to, to], shift()); + assert_eq!(grid(&s).inferred, None, "with a button down Shift constrains the move"); + for (a, b) in before.iter().zip(plane_pts(&s, id, Plane::Right, 0.0)) { + assert!((b - *a - Vec2::new(80.0, 0.0)).hypot() < 1e-6, "{a:?} → {b:?}"); + } +} + +#[test] +fn a_gridline_intersection_brings_each_plane_made_active_through_it() { + let (mut s, _) = persp_session(); + let (g, steps) = (grid(&s), undo_len(&s)); + s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap(); + let at = g.to_page(Plane::Left, Point::new(3.0 * g.cell, 2.0 * g.cell)).unwrap(); + let r = s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y], "tolerance": 1})).unwrap(); + assert_eq!((r["active"].as_bool(), r["source"].as_str(), r["plane"].as_str()), (Some(true), Some("gridline"), Some("left"))); + for (got, want) in r["point"].as_array().unwrap().iter().zip([0.0, 2.0 * g.cell, 3.0 * g.cell]) { + assert!((got.as_f64().unwrap() - want).abs() < 1e-6, "{r}"); + } + for (plane, want) in [("ground", 2.0 * g.cell), ("right", 3.0 * g.cell), ("left", 0.0)] { + s.execute("perspective.plane.set", &json!({"plane": plane})).unwrap(); + let r = s.execute("perspective.plane.infer", &json!({})).unwrap(); + assert!((r["offset"].as_f64().unwrap() - want).abs() < 1e-6 && r["active"] == json!(true) && r.get("source").is_none(), "{plane}: {r}"); + } + let held = grid(&s); + assert_eq!((held.left_offset, held.right_offset, held.ground_offset, undo_len(&s)), (0.0, 0.0, 0.0, steps)); + // Nothing within reach leaves the plane where it is held. + let rev = revision(&s); + let mid = held.to_page(Plane::Left, Point::new(3.5 * g.cell, 2.5 * g.cell)).unwrap(); + let r = s.execute("perspective.plane.infer", &json!({"at": [mid.x, mid.y], "tolerance": 0.5})).unwrap(); + assert!(r["active"] == json!(true) && r.get("source").is_none() && revision(&s) == rev, "{r}"); + // With no active plane nothing is held. + s.execute("perspective.plane.set", &json!({"plane": "none"})).unwrap(); + assert_eq!(grid(&s).inferred, None); + assert!(s.execute("perspective.plane.infer", &json!({"at": [at.x, at.y]})).is_err(), "no active plane"); + assert_eq!(s.execute("perspective.plane.infer", &json!({})).unwrap()["active"], json!(false)); +} + +#[test] +fn the_two_options_turn_the_targets_on_and_off_and_are_kept() { + let (mut s, id) = persp_session(); + assert!(s.prefs.perspective_widget.anchor_point && s.prefs.perspective_widget.gridline_intersection, "both on by default"); + let (anchor, _) = top_anchor(&s, id); + let infer = |s: &mut Session| s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01})); + assert_eq!(infer(&mut s).unwrap()["source"], json!("anchor")); + s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap(); + let r = s.execute("perspective.widget.options", &json!({"anchorPoint": false})).unwrap(); + assert_eq!((r["anchorPoint"].as_bool(), r["gridlineIntersection"].as_bool(), r["show"].as_bool()), (Some(false), Some(true), Some(true))); + assert!(infer(&mut s).unwrap().get("source").is_none(), "the anchor is no target now"); + assert_eq!(grid(&s).inferred, None); + let back: Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap(); + assert!(!back.perspective_widget.anchor_point && back.perspective_widget.gridline_intersection); + s.execute("perspective.widget.options", &json!({"gridlineIntersection": false})).unwrap(); + assert!(infer(&mut s).is_err(), "both off"); + for bad in [json!({"anchorPoint": "yes"}), json!({"gridlineIntersection": 1})] { + assert!(s.execute("perspective.widget.options", &bad).is_err(), "{bad}"); + } + assert!(!s.prefs.perspective_widget.anchor_point, "a refused value changes nothing"); + s.execute("prefs.set", &json!({"key": "perspectiveWidget", "value": {"anchorPoint": true}})).unwrap(); + assert!(s.prefs.perspective_widget.anchor_point && !s.prefs.perspective_widget.gridline_intersection); + // Preferences saved before the options existed read as both on. + let old: vectorcraft_tools::distort::perspective::widget::WidgetOptions = serde_json::from_value(json!({"show": false})).unwrap(); + assert!(old.anchor_point && old.gridline_intersection && !old.show); +} + +#[test] +fn bad_params_are_refused_and_leave_the_grid_as_it_is() { + let (mut s, id) = persp_session(); + let (anchor, _) = top_anchor(&s, id); + let rev = revision(&s); + for bad in [ + json!({"at": "here"}), + json!({"at": [1]}), + json!({"at": [anchor.x, anchor.y], "tolerance": -1}), + json!({"at": [anchor.x, anchor.y], "tolerance": "wide"}), + json!({"at": [anchor.x, anchor.y], "clear": true}), + json!({"clear": "yes"}), + ] { + assert!(s.execute("perspective.plane.infer", &bad).is_err(), "{bad}"); + } + assert_eq!((grid(&s).inferred, revision(&s)), (None, rev)); + // Clearing when nothing is held changes nothing. + assert_eq!(s.execute("perspective.plane.infer", &json!({"clear": true})).unwrap()["active"], json!(false)); + assert_eq!(revision(&s), rev); + s.execute("perspective.grid.show", &json!({"visible": false})).unwrap(); + assert!(s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y]})).is_err(), "hidden grid"); +} + +/// A session whose ground plane is held at the height of the attached rectangle's top anchor. +fn held_session() -> (Session, NodeId, f64) { + let (mut s, id) = persp_session(); + let (anchor, height) = top_anchor(&s, id); + s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap(); + let r = s.execute("perspective.plane.infer", &json!({"at": [anchor.x, anchor.y], "tolerance": 0.01})).unwrap(); + assert_eq!(r["source"], json!("anchor")); + (s, id, height) +} + +#[test] +fn attaching_an_object_ends_it_and_the_object_sits_where_the_plane_was_held() { + let (mut s, _, height) = held_session(); + let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap(); + let flat = NodeId(r["id"].as_u64().unwrap()); + s.execute("perspective.attach", &json!({"ids": [flat.0]})).unwrap(); + let (plane, depth) = attached(&s, flat).unwrap(); + assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}"); + assert_eq!((grid(&s).inferred, grid(&s).ground_offset), (None, 0.0)); + // An attach of nothing, or to a plane it doesn't hold, leaves it held. + let (mut s, ..) = held_session(); + s.execute("perspective.attach", &json!({"ids": []})).unwrap(); + assert!(grid(&s).inferred.is_some()); + let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap(); + let other = NodeId(r["id"].as_u64().unwrap()); + s.execute("perspective.attach", &json!({"ids": [other.0], "plane": "right"})).unwrap(); + assert_eq!(attached(&s, other).map(|a| a.0), Some(Plane::Right)); + assert!(grid(&s).inferred.is_some()); + // A move of an object already in perspective leaves it held; one brought into perspective ends it. + let (mut s, id, height) = held_session(); + s.execute("perspective.move", &json!({"ids": [id.0], "from": [460, 400], "to": [470, 400]})).unwrap(); + assert!(grid(&s).inferred.is_some()); + let r = s.execute("shape.rectangle", &json!({"x": 420, "y": 400, "width": 40, "height": 30})).unwrap(); + let flat = NodeId(r["id"].as_u64().unwrap()); + s.execute("perspective.move", &json!({"ids": [flat.0], "from": [430, 410], "to": [440, 410]})).unwrap(); + let (plane, depth) = attached(&s, flat).unwrap(); + assert!(plane == Plane::Ground && (depth - height).abs() < 1e-6, "{plane:?} {depth}"); + assert_eq!(grid(&s).inferred, None); +} + +#[test] +fn moving_a_plane_hiding_the_grid_and_reopening_the_file_end_it() { + // A moved plane moves from where it is held and is placed there for good, in one undo step; + // undoing the move holds it again. + let (mut s, _, height) = held_session(); + let steps = undo_len(&s); + s.execute("perspective.plane.move", &json!({"plane": "ground", "by": 10})).unwrap(); + let g = grid(&s); + assert_eq!((g.inferred, undo_len(&s)), (None, steps + 1)); + assert!((g.ground_offset - (height + 10.0)).abs() < 1e-6, "{}", g.ground_offset); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).inferred.is_some(), grid(&s).ground_offset), (true, 0.0)); + // A refused move leaves it held. + let (mut s, ..) = held_session(); + assert!(s.execute("perspective.plane.move", &json!({"plane": "ground", "offset": 1, "objects": "all"})).is_err()); + assert!(grid(&s).inferred.is_some()); + // A plane dragged while it is held, then the drag canceled, is held again. + let (mut s, ..) = held_session(); + s.begin_interaction("Move Plane").unwrap(); + s.preview("perspective.plane.move", &json!({"plane": "ground", "by": 20})).unwrap(); + assert_eq!(grid(&s).inferred, None); + s.cancel_interaction().unwrap(); + assert!(grid(&s).inferred.is_some()); + // Move Plane to Match Object. + let (mut s, id, _) = held_session(); + s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap(); + assert_eq!((grid(&s).inferred, grid(&s).plane), (None, Plane::Right)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).inferred.is_some(), grid(&s).plane), (true, Plane::Ground), "undo holds it again"); + // With the plane placed at the object already, matching only puts the held plane back there. + s.execute("perspective.plane.set", &json!({"plane": "right"})).unwrap(); + assert!(grid(&s).inferred.is_some()); + let steps = undo_len(&s); + s.execute("perspective.plane.matchObject", &json!({"id": id.0})).unwrap(); + assert_eq!((grid(&s).inferred, grid(&s).offset(Plane::Right), undo_len(&s)), (None, 0.0, steps)); + // Hide Grid. + let (mut s, ..) = held_session(); + s.execute("perspective.grid.show", &json!({"visible": false})).unwrap(); + assert_eq!(grid(&s).inferred, None); + // The grid's definition changing leaves it held, and it is not `perspective.grid.set`'s to set. + let (mut s, ..) = held_session(); + let held = grid(&s).inferred; + s.execute("perspective.grid.set", &json!({"cell": 31, "inferred": [1, 2, 3]})).unwrap(); + assert_eq!(grid(&s).inferred, held); + // `perspective.grid.set` hiding the grid or choosing no plane ends it. + for patch in [json!({"visible": false}), json!({"plane": "none"})] { + let (mut s, ..) = held_session(); + s.execute("perspective.grid.set", &patch).unwrap(); + assert_eq!(grid(&s).inferred, None, "{patch}"); + } + // Another preset leaves it held, as other changes to the grid's definition do. + let (mut preset, ..) = held_session(); + let before = grid(&preset).inferred; + preset.execute("perspective.grid.preset", &json!({"kind": 3})).unwrap(); + assert_eq!((grid(&preset).kind, grid(&preset).inferred), (3, before)); + // A file saved while a plane is held opens with the plane in its place. + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + let back = vectorcraft_format::load(&saved).unwrap(); + assert!(PerspectiveGrid::positioning(&back), "the saved file still holds the point"); + s.add_document(back, None); + assert_eq!(grid(&s).inferred, None); + assert_eq!(grid(&s).cell, 31.0); +} diff --git a/crates/engine/src/tests/perspgrid.rs b/crates/engine/src/tests/perspgrid.rs index dce149e98c..4b7c1c2ae4 100644 --- a/crates/engine/src/tests/perspgrid.rs +++ b/crates/engine/src/tests/perspgrid.rs @@ -520,7 +520,10 @@ fn the_plane_widget_stays_on_screen_and_takes_clicks_with_any_tool() { click(&mut s, q, view); assert_eq!(grid(&s).plane, Plane::Ground); // Perspective Grid Options move it to another corner or hide it. - assert_eq!(run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})), json!({"show": true, "position": "bottomRight"})); + assert_eq!( + run(&mut s, "perspective.widget.options", json!({"position": "bottomRight"})), + json!({"show": true, "position": "bottomRight", "anchorPoint": true, "gridlineIntersection": true}) + ); let r = face(&s, view, WidgetCorner::BottomRight, Plane::Left); assert!(r.x > 100.0 + 450.0 && r.y > 50.0 + 300.0, "{r:?}"); click(&mut s, r, view); diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index c639fc9232..65808d2360 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -599,6 +599,100 @@ fn with_link_a_pdf_page_places_linked() { assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); } +/// The colour at the centre of `r` in `doc`. +fn colour_at(doc: &Document, r: Rect) -> [u8; 3] { + let img = vectorcraft_render::Renderer::new().render_region(doc, r, 1.0, true); + let [red, g, b, _] = img.pixel((r.width() / 2.0) as u32, (r.height() / 2.0) as u32); + [red, g, b] +} + +#[test] +fn link_pages_opens_each_picked_pdf_page_as_a_linked_placed_document() { + let dir = Folder::new("open-pdf-link-pages"); + let src = dir.file("flyer.pdf"); + pdf_source(&src, "pdf", &[RED, BLUE, RED], 0); + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"path": src, "linkPages": true, "pages": "2-3"})).unwrap(); + assert_eq!((r["format"].as_str(), r["restored"].as_bool()), (Some("pdf"), Some(false)), "{r}"); + let st = s.doc().unwrap(); + assert_eq!(st.path, None, "Save asks for a name instead of writing over the PDF"); + let d = &st.doc; + let boards: Vec = d.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [Rect::new(0.0, 0.0, 100.0, 50.0), Rect::new(136.0, 0.0, 236.0, 50.0)]); + let layers: Vec<_> = d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(layers, ["Page 2", "Page 3"]); + let mut ids = vec![]; + for (layer, (page, board)) in d.layers.iter().zip([(2, boards[0]), (3, boards[1])]) { + let kids = layer.children().unwrap(); + assert_eq!(kids.len(), 1); + let p = placed(&s, kids[0].id); + assert_eq!((p.link.path.as_str(), p.link.page, p.bounding), (src.as_str(), Some(page), false), "{p:?}"); + assert_eq!(bounds(&s, kids[0].id), board); + ids.push(kids[0].id); + } + assert!(near(colour_at(d, boards[0]), BLUE)); + assert!(near(colour_at(d, boards[1]), RED)); + let links = s.execute("links.list", &json!({})).unwrap()["links"].clone(); + assert_eq!(links.as_array().map(Vec::len), Some(2), "{links}"); + assert!(links.as_array().unwrap().iter().all(|row| row["document"] == true && row["status"] == "ok"), "{links}"); + // Embed makes a page editable art. + s.execute("links.embed", &json!({"ids": [ids[0].0]})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(ids[0]).unwrap().kind_label(), "Clip Group"); + assert_eq!(bounds(&s, ids[0]), boards[0]); + assert!(near(colour_at(d, boards[0]), BLUE)); + // Every page, with the art's bounds as the artboard. + s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.artboards.len(), 3); + assert!(d.layers.iter().flat_map(|l| l.children().unwrap()).all(|n| matches!(&n.kind, NodeKind::PlacedDocument(p) if p.bounding))); +} + +#[test] +fn linked_pages_share_one_copy_of_the_file_and_open_in_the_pages_color_mode() { + use vectorcraft_testkit::pdf::{PdfPage, pdf}; + let dir = Folder::new("open-pdf-link-pages-cmyk"); + let src = dir.file("cmyk.pdf"); + let page = || PdfPage::new(100.0, 50.0, "0 0.5 1 0 k 0 0 100 50 re f"); + write(&src, &pdf(&[page(), page(), page()], None)); + let mut s = Session::new(); + s.execute("document.open", &json!({"path": src, "linkPages": true})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.color_mode, vectorcraft_doc::ColorMode::Cmyk, "pages painted in CMYK open as a CMYK document"); + let blobs: Vec<_> = d.images.values().map(|b| b.bytes.clone()).collect(); + assert_eq!(blobs.len(), 3); + assert!(blobs.iter().all(|b| std::sync::Arc::ptr_eq(b, &blobs[0])), "one copy of the file for every page"); + s.execute("document.open", &json!({"path": src, "linkPages": true, "colorMode": "rgb"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.color_mode, vectorcraft_doc::ColorMode::Rgb, "colorMode wins"); +} + +#[test] +fn link_pages_is_refused_without_a_path_for_other_files_and_with_a_password_or_outlines() { + let dir = Folder::new("open-pdf-link-pages-refused"); + let src = dir.file("flyer.pdf"); + pdf_source(&src, "pdf", &[RED, BLUE], 0); + let bytes = std::fs::read(&src).unwrap(); + let logo = dir.file("logo.vectorcraft"); + source(&logo, 100.0, 50.0, RED, 0); + let mut s = Session::new(); + let cases = [ + (json!({"name": "flyer.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes), "linkPages": true}), "needs the file's path"), + (json!({"path": logo, "linkPages": true}), "isn't a PDF"), + (json!({"path": src, "linkPages": true, "password": "secret"}), "password"), + (json!({"path": src, "linkPages": true, "textAs": "outlines"}), "textAs: outlines"), + (json!({"path": src, "linkPages": "yes"}), "linkPages must be true or false"), + (json!({"path": src, "linkPages": true, "pages": "3"}), "pages:"), + ]; + for (p, says) in cases { + let e = s.execute("document.open", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{p}: {e}"); + } + assert!(s.documents().is_empty(), "nothing opened"); + // Off, the pages open as editable art. + s.execute("document.open", &json!({"path": src, "linkPages": false})).unwrap(); + assert!(!s.doc().unwrap().doc.has_placed()); +} + #[test] fn a_changed_pdf_is_modified_and_update_links_reads_it_again() { let dir = Folder::new("placed-pdf-update"); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index adcc35d352..9dc35ff99b 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2265,6 +2265,36 @@ fn remove_breaks_takes_the_whole_story_that_select_all_selected() { assert!(obj(&s, a).plain_text().contains('\n') && obj(&s, b).plain_text().contains('\n')); } +#[test] +fn remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames() { + for command in ["object.lock", "object.hide"] { + for held_first in [false, true] { + let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); + let (held, other) = if held_first { (a, b) } else { (b, a) }; + let unrelated = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let unrelated = NodeId(unrelated); + s.execute(command, &json!({"ids": [held.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0})); + assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + let case = format!("{command}, held first: {held_first}"); + let steps = undo_labels(&s).len(); + let r = s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step"); + assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed"); + let joined = format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()); + assert_eq!(joined, story.trim_end_matches('\n').replace('\n', " "), "{case}: every frame's returns go"); + assert_eq!(obj(&s, unrelated).plain_text(), "One\nTwo", "{case}: other type is as it was"); + // No return is left: another call fails and adds no undo step. + assert!(s.execute("addon.cleanup.removeBreaks", &json!({"kind": "paragraph"})).is_err()); + assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text"); + } + } +} + #[test] fn remove_breaks_on_a_selected_threaded_story_puts_a_space_between_its_frames() { let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); @@ -2306,41 +2336,72 @@ fn convert_to_text_takes_the_whole_story_that_select_all_selected() { } } +/// Whether no paragraph of type `id` is a list. +fn no_list(s: &Session, id: NodeId) -> bool { + let t = obj(s, id); + (0..t.paragraph_count()).all(|k| t.para_at(k).list.is_none()) +} + +/// The bullets held as characters in the frames `ids`. +fn bullet_chars(s: &Session, ids: &[NodeId]) -> usize { + ids.iter().map(|id| obj(s, *id).plain_text().matches("\u{2022}\t").count()).sum() +} + #[test] -fn convert_to_text_of_the_whole_story_leaves_a_locked_frame() { - // Over MCP without ids, and as the Paragraph panel sends it, with every frame of the story. - for named in [false, true] { - let (mut s, a, b, _) = threaded_list_edited_in_its_second_frame(); - s.execute("object.lock", &json!({"ids": [b.0]})).unwrap(); - s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); - s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": 0, "caret": 0})); - assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); - // The first frame ends with a paragraph return, so the paragraph that starts the locked - // frame takes in the first frame's empty last part and starts its text there. - let in_a = obj(&s, a).plain_text(); - assert!(in_a.ends_with('\n')); - let own = in_a.split('\n').filter(|piece| !piece.is_empty()).count(); - let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) }; - let r = s.execute("text.convertListToText", &p).unwrap(); - assert_eq!(r["ids"], json!([a.0]), "only the editable frame is changed (ids named: {named})"); - assert_eq!(r["converted"], json!(own), "only the paragraphs whose text starts in the editable frame convert"); - assert!(r["inserted"].as_array().unwrap().iter().all(|i| i["id"] == json!(a.0))); - let (ta, tb) = (obj(&s, a), obj(&s, b)); - assert!(ta.plain_text().contains("\u{2022}\t"), "the editable frame is converted"); - let markers = ta.plain_text().matches("\u{2022}\t").count() + tb.plain_text().matches("\u{2022}\t").count(); - assert_eq!(markers, own, "the locked frame's first paragraph keeps its list"); - // The converted text is longer, so the story flows on into the locked frame; its own - // paragraphs stay a list. - let last = tb.paragraph_count() - 2; - assert!(tb.para_at(last).list.is_some(), "the locked frame's paragraphs stay a list (ids named: {named})"); - assert!(!tb.plain_text().ends_with("\u{2022}\tAlpha beta.\n")); - assert!(s.tool_options().get("story").is_some(), "the whole story stays selected"); +fn convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames() { + // Over MCP without ids, as the Paragraph panel sends it with every frame of the story, and with + // ids naming only the held frame. + for command in ["object.lock", "object.hide"] { + for held_first in [false, true] { + for call in ["none", "story", "held"] { + let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); + let (held, other) = if held_first { (a, b) } else { (b, a) }; + let unrelated = + s.execute("text.create", &json!({"x": 10, "y": 500, "text": "One\nTwo", "size": 12})).unwrap()["id"].as_u64().unwrap(); + let unrelated = NodeId(unrelated); + s.execute("text.setFormat", &json!({"ids": [unrelated.0], "list": "bullet"})).unwrap(); + let unrelated_before = obj(&s, unrelated); + s.execute(command, &json!({"ids": [held.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0})); + assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + let case = format!("{command}, held first: {held_first}, ids: {call}"); + let p = match call { + "none" => json!({}), + "story" => json!({"ids": [a.0, b.0]}), + _ => json!({"ids": [held.0]}), + }; + let steps = undo_labels(&s).len(); + let r = s.execute("text.convertListToText", &p).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: one undo step"); + assert!(r["ids"].as_array().unwrap().contains(&json!(held.0)), "{case}: the held frame is changed"); + assert!(no_list(&s, held), "{case}: the held frame leaves its list"); + assert_eq!(obj(&s, unrelated), unrelated_before, "{case}: other type is as it was"); + if call == "held" { + // The other frame's paragraphs whose text starts there keep their list. + assert!(!no_list(&s, other), "{case}: the frame not named keeps its list"); + continue; + } + assert!(no_list(&s, other), "{case}: the other frame leaves its list"); + assert_eq!(bullet_chars(&s, &[a, b]), 12, "{case}: each paragraph's bullet is held once as characters"); + assert!(s.tool_options().get("story").is_some(), "{case}: the whole story stays selected"); + // Nothing is a list any more: another call changes nothing and adds no undo step. + s.execute("text.convertListToText", &p).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "{case}: no undo step when nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story, "{case}: undo restores the text"); + assert!(!no_list(&s, a) && !no_list(&s, b), "{case}: undo restores the lists"); + } + } } } #[test] -fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked_frame() { - for named in [false, true] { +fn convert_to_text_of_the_whole_story_converts_a_paragraph_that_runs_across_a_locked_frame() { + // The paragraph that runs from the first frame into the second starts in the locked frame, or + // ends in it. + for (named, lock_first) in [(false, true), (true, true), (false, false), (true, false)] { let mut s = session(); let story = format!("Alpha beta.\nAlpha beta.\n{}end.\nAlpha beta.\nAlpha beta.\n", "Gamma delta ".repeat(40)); let a = NodeId( @@ -2354,22 +2415,23 @@ fn convert_to_text_of_the_whole_story_leaves_a_paragraph_that_starts_in_a_locked s.execute("text.setFormat", &json!({"ids": [a.0, b.0], "list": "bullet"})).unwrap(); let in_a = obj(&s, a).plain_text(); assert!(!in_a.ends_with('\n') && !obj(&s, b).plain_text().starts_with('\n'), "a paragraph runs on from the first frame into the second"); - s.execute("object.lock", &json!({"ids": [a.0]})).unwrap(); - s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let (locked, other) = if lock_first { (a, b) } else { (b, a) }; + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); s.select_tool("type", ViewInfo::default()).unwrap(); - s.set_tool_option("textSelection", &json!({"editing": b.0, "anchor": 0, "caret": 0})); + s.set_tool_option("textSelection", &json!({"editing": other.0, "anchor": 0, "caret": 0})); assert_eq!(s.execute("select.all", &json!({})).unwrap()["story"], json!([a.0, b.0])); + let case = format!("ids named: {named}, first frame locked: {lock_first}"); let p = if named { json!({"ids": [a.0, b.0]}) } else { json!({}) }; let r = s.execute("text.convertListToText", &p).unwrap(); - assert_eq!(r["ids"], json!([b.0]), "only the editable frame is changed (ids named: {named})"); - // The two paragraphs that start in the editable frame, and the empty one that ends the story. - assert_eq!(r["converted"], json!(3), "only the paragraphs that start in the editable frame convert"); + assert_eq!(r["ids"], json!([a.0, b.0]), "{case}: both frames are changed"); + // The five paragraphs with text, and the empty one that ends the story. + assert_eq!(r["converted"], json!(6), "{case}: every paragraph of the story converts"); let (ta, tb) = (obj(&s, a), obj(&s, b)); - assert_eq!(ta.plain_text(), in_a, "the locked frame's text is as it was"); - assert!((0..ta.paragraph_count()).all(|k| ta.para_at(k).list.is_some()), "the locked frame stays a list"); - assert!(tb.para_at(0).list.is_some(), "the paragraph the locked frame starts stays a list"); - assert!(!tb.plain_text().starts_with('\u{2022}')); - assert_eq!(tb.plain_text().matches("\u{2022}\t").count(), 2); + assert!(no_list(&s, a) && no_list(&s, b), "{case}: the story leaves its list"); + assert_eq!(bullet_chars(&s, &[a, b]), 5, "{case}: each paragraph's bullet is held once as characters"); + assert!(ta.plain_text().contains("\u{2022}\tGamma"), "{case}: the paragraph across the frames takes its bullet where its text starts"); + assert!(!tb.plain_text().starts_with('\u{2022}'), "{case}"); } } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index bb29b06e75..d33ad587fe 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -429,6 +429,7 @@ impl Session { }, screen: view.screen, plane_widget: self.prefs.perspective_widget.show.then_some(self.prefs.perspective_widget.position), + plane_targets: self.prefs.perspective_widget.targets(), precise_cursors: self.precise_cursors(), global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()), }; @@ -1543,7 +1544,7 @@ impl Session { if !std::sync::Arc::ptr_eq(&it.doc, &st.doc) { return None; } - let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone()); + let interaction_fields = (it.preview.clone(), it.copies.clone(), it.perspective_again.clone(), it.plane_placed); (st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields) }; let (overlays, transform_box) = if self.preview(cmd, p).is_ok() { @@ -1565,6 +1566,7 @@ impl Session { it.preview = interaction_fields.0; it.copies = interaction_fields.1; it.perspective_again = interaction_fields.2; + it.plane_placed = interaction_fields.3; } } self.pending_paint = paint; diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 797ca39f52..6fd17049d4 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -5,6 +5,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; +use vectorcraft_engine::cmd::{Location, ParamsPlace}; use vectorcraft_engine::{Session, command_specs}; use vectorcraft_testkit::catch_quiet; use vectorcraft_testkit::fixtures::Fixture; @@ -272,44 +273,46 @@ fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec) { +/// The strings in `v`, the value at `at` (found at `place`) in a case of command `id`, that name a +/// place on disk outside `dir`, as `id at: value`: `v` itself and the members of arrays in it when +/// `named` (it is under a key that names a file or folder), and in objects at any depth, the values +/// under such keys as the command reads them (`vectorcraft_engine::cmd::ParamsPlace`). +fn outside_locations( + id: &str, + at: &str, + v: &Value, + place: ParamsPlace, + named: bool, + dir: &std::path::Path, + out: &mut std::collections::BTreeSet, +) { match v { Value::String(s) if named && !std::path::Path::new(s).starts_with(dir) => { out.insert(format!("{id} {at}: {v}")); } Value::Array(a) => { + let step = ParamsPlace::step(a); for (i, x) in a.iter().enumerate() { - outside_locations(id, &format!("{at}[{i}]"), x, named, dir, out); + outside_locations(id, &format!("{at}[{i}]"), x, place.item(i, step), named, dir, out); } } Value::Object(o) => { + let carried = ParamsPlace::carried(o); for (k, x) in o { - outside_locations(id, &format!("{at}.{k}"), x, names_location(None, k), dir, out); + let (below, location) = place.member(k, carried); + outside_locations(id, &format!("{at}.{k}"), x, below, location.is_some(), dir, out); } } _ => {} } } -/// Does `key` name a file or folder, in command `spec` when given: a key in -/// `vectorcraft_engine::cmd::key_location`'s list that `vectorcraft_engine::cmd::location_in` keeps -/// for `spec`. -fn names_location(spec: Option<&vectorcraft_engine::CommandSpec>, key: &str) -> bool { - match spec { - Some(spec) => vectorcraft_engine::cmd::location_in(spec, key).is_some(), - None => vectorcraft_engine::cmd::key_location(key).is_some(), - } -} - /// Every string the sweeps send under a key that names a file or folder, in the command catalog /// (`vectorcraft_engine::cmd::location_keys`, so a command added later is checked too) or inside /// an object or an array at any depth, is inside the sweep's temp folder, so no run reads or /// writes in the working directory. `every_command_with_junk_params` sends every such key of every -/// command alone in at least one case ([`junk_cases`]). +/// command alone in at least one case ([`junk_cases`]). Which catalog keys name a file or folder is +/// checked on its own by [`catalog_path_keys_match_location_policy`]. #[test] fn sweep_cases_name_files_only_inside_the_temp_folder() { let dir = vectorcraft_testkit::TempDir::new("sweep"); @@ -330,7 +333,8 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { for p in &cases { let Some(o) = p.as_object() else { continue }; for (k, v) in o { - outside_locations(c.id, k, v, names_location(Some(c), k), &dir, &mut outside); + let (below, location) = ParamsPlace::top(Some(c)).member(k, None); + outside_locations(c.id, k, v, below, location.is_some(), &dir, &mut outside); } } } @@ -339,6 +343,104 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { assert!(outside.is_empty(), "{} cases name a location outside {}:\n{}", outside.len(), dir.display(), outside.join("\n")); } +/// The param keys that name a file or a folder, and which. +const LOCATION_KEYS: &[(&str, Location)] = &[ + ("path", Location::File), + ("paths", Location::File), + ("file", Location::File), + ("files", Location::File), + ("diffPath", Location::File), + ("folder", Location::Folder), + ("dir", Location::Folder), + ("directory", Location::Folder), + ("destinationFolder", Location::Folder), + ("sourceFolder", Location::Folder), + ("fontsFolder", Location::Folder), + ("pluginsFolder", Location::Folder), + ("recoveryFolder", Location::Folder), + ("templatesFolder", Location::Folder), +]; + +/// Param keys that read like a file or folder key ([`reads_like_a_location`]) and name neither: +/// web links, an export's grouping of its files, and choices and switches. +const NOT_LOCATIONS: &[&str] = &[ + "url", + "copyrightUrl", + "folders", + "alignToPath", + "wholePaths", + "emptyTextPaths", + "sortPaths", + "alterPaths", + "includeLinkedFiles", + "linksFolder", +]; + +/// Commands and the key in [`LOCATION_KEYS`] that, at the top of their params, names part of the +/// document (a path of its art, a result field), not a file. +const DOCUMENT_PARTS: &[(&str, &str)] = &[ + ("object.setLiveShape", "path"), + ("path.reverse", "paths"), + ("object.pathfinder.options", "paths"), + ("object.maskImage", "path"), + ("text.createInPath", "path"), + ("symbol.instance.setAppearance", "path"), + ("symbol.instance.selectPart", "path"), + ("object.objectsOnPath.attach", "path"), + ("svgInteractivity.info", "files"), + ("addon.cleanup.rejoin", "paths"), +]; + +/// Does param key `k` read like one that names a file, a folder or a link: a bare name for one, or a +/// name that ends like one? +fn reads_like_a_location(k: &str) -> bool { + const ENDS: &[&str] = &["Path", "Paths", "File", "Files", "Folder", "Folders", "Dir", "Directory", "Url", "URL"]; + matches!(k, "path" | "paths" | "file" | "files" | "folder" | "folders" | "dir" | "directory" | "url") || ENDS.iter().any(|end| k.ends_with(end)) +} + +/// Every key of every command that reads like a file or folder key (in its params description, the +/// commands its `…` entries name and its schema) is in [`LOCATION_KEYS`] or [`NOT_LOCATIONS`], so a +/// command that adds one fails here until it is sorted. The generic classifications +/// (`vectorcraft_engine::cmd::key_location`, `vectorcraft_engine::file_access::is_path_key`) agree +/// with those lists, and each command reads such a key as they say (`location_in`), less +/// [`DOCUMENT_PARTS`]. +#[test] +fn catalog_path_keys_match_location_policy() { + use vectorcraft_engine::cmd::{key_location, location_in, params::takes_key}; + let catalog: Vec<(&vectorcraft_engine::CommandSpec, Vec)> = command_specs().iter().map(|c| (c, command_param_keys(c))).collect(); + let mut keys: std::collections::BTreeSet = + catalog.iter().flat_map(|(_, keys)| keys.iter().filter(|k| reads_like_a_location(k)).cloned()).collect(); + keys.extend(LOCATION_KEYS.iter().map(|(k, _)| k.to_string()).chain(NOT_LOCATIONS.iter().map(|k| k.to_string()))); + let mut wrong = vec![]; + for k in &keys { + let want = LOCATION_KEYS.iter().find(|(l, _)| l == k).map(|(_, l)| *l); + if want.is_none() && !NOT_LOCATIONS.contains(&k.as_str()) { + wrong.push(format!("`{k}` is in neither LOCATION_KEYS nor NOT_LOCATIONS")); + continue; + } + if key_location(k) != want { + wrong.push(format!("key_location(`{k}`) is {:?}, not {want:?}", key_location(k))); + } + if vectorcraft_engine::file_access::is_path_key(k) != want.is_some() { + wrong.push(format!("is_path_key(`{k}`) is {}", want.is_none())); + } + for (c, named) in &catalog { + if !named.contains(k) && !(c.params.contains('…') && takes_key(c.params, k)) { + continue; + } + let here = if DOCUMENT_PARTS.contains(&(c.id, k.as_str())) { None } else { want }; + if location_in(c, k) != here { + wrong.push(format!("{}: location_in(`{k}`) is {:?}, not {here:?}", c.id, location_in(c, k))); + } + } + } + for (id, key) in DOCUMENT_PARTS { + let named = catalog.iter().any(|(c, _)| c.id == *id && c.params.contains(key)); + assert!(named, "{id} doesn't name `{key}`"); + } + assert!(wrong.is_empty(), "{} keys are classified unlike the reviewed lists:\n{}", wrong.len(), wrong.join("\n")); +} + /// The cases sweep keys the command catalog names as files and folders: `document.open`'s /// `{path | name …}`, `addon.document.saveTimestampedCopy`'s `{folder? (…)}`, `document.compare`'s /// `diffPath`, `file.saveAs`'s `path` after `{…as document.save}` and `links.relink`'s @@ -914,6 +1016,12 @@ fn structured_junk() { ("addon.cutting.banner", json!({"hem": 0, "grommetInset": 0, "spacing": 0.01, "allArtboards": true})), ("addon.cutting.banner", json!({"spacing": "1 mm", "grommets": false, "swatch": 5, "left": null})), ("addon.cutting.banner", json!({"top": false, "right": false, "bottom": false, "left": false, "allArtboards": false})), + ("addon.cutting.nest", json!({"width": 1e6, "height": 1e6, "margin": 1e5, "spacing": 1e5, "roll": true})), + ("addon.cutting.nest", json!({"width": 1e-300, "height": f64::MAX, "margin": -1, "spacing": "1 mm", "artboard": u64::MAX})), + ("addon.cutting.nest", json!({"width": 0, "height": 0, "margin": 0, "spacing": 0, "usePreviewBounds": "no", "patterns": 1})), + ("addon.cutting.nest", json!({"roll": null, "artboard": -1, "width": "1 in", "height": [1]})), + ("addon.cutting.nest", json!({"rotate": true, "roll": true, "width": 1e-6, "margin": 0, "spacing": 0, "usePreviewBounds": true})), + ("addon.cutting.nest", json!({"rotate": "yes", "width": f64::NAN, "spacing": -0.0})), // Type Tools add-on. ("addon.type.textTweaker", json!({"attribute": "size", "from": 1296, "to": 0.1, "shape": "random", "seed": u64::MAX})), ("addon.type.textTweaker", json!({"attribute": "tracking", "from": f64::MAX, "to": -1e308, "shape": "spike"})), diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 6e963e70e4..a67102f5d0 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -1187,6 +1187,32 @@ fn a_symbol_definition_is_written_only_with_room_for_its_instance() { } } +/// A live instance inside a stained instance's art, whose definition has no room left, is left out +/// without upsetting the art around it: with room for any number of objects the export finishes, +/// within that room. +#[test] +fn a_definition_without_room_inside_drawn_art_is_left_out() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let leaf = 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(leaf) }); + let inner = instance(&mut doc, "Leaf", Affine::translate((5.0, 5.0))); + let side = square(&mut doc, Rect::new(20.0, 0.0, 30.0, 10.0), Color::gray(0.5)); + let art = group(&mut doc, vec![inner, side], false); + doc.symbols.push(Symbol { dynamic: false, name: "Branch".into(), art: Arc::new(art) }); + let mut stained = instance(&mut doc, "Branch", Affine::translate((50.0, 10.0))); + stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into(); + doc.insert(Some(layer), usize::MAX, stained).unwrap(); + add_rect(&mut doc, Rect::new(150.0, 10.0, 160.0, 20.0)); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + for max in 0..read { + let out = export_within(&doc, &opts(), max).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "art is left out with room for {max} of {read} objects"); + let objects = crate::import::objects_read(&out.program).unwrap(); + assert!(objects <= max, "{objects} objects read with room for {max}"); + } +} + /// A symbol definition without room for its group, asked for by an instance in art drawn for an /// object (a stained instance's art), is left out and leaves the writing of that art as it was. #[test] @@ -10168,6 +10194,119 @@ fn envelopes_past_the_readers_checks_are_written_as_their_art() { assert!(!notes.iter().any(|n| n == crate::import::ENVELOPE_DRAWN), "{notes:?}"); } +/// A document of `envelopes` envelopes and `images` embedded images with one Warp, the images first +/// when `images_first`, saved and opened again: the live envelopes, the images with their Warp live +/// and all the objects it opens with, the save's warnings and the open's notes. +fn envelopes_and_warped_images(envelopes: usize, images: usize, images_first: bool) -> (usize, usize, usize, Vec, Vec) { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let add_images = |doc: &mut Document| { + for _ in 0..images { + let photo = warped_photo(doc, vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))]); + doc.insert(Some(layer), usize::MAX, photo).unwrap(); + } + }; + if images_first { + add_images(&mut doc); + } + for _ in 0..envelopes { + let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + } + if !images_first { + add_images(&mut doc); + } + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let a = back.layers[0].children().unwrap(); + let live = a.iter().filter(|n| matches!(n.kind, NodeKind::Envelope { .. })).count(); + let warped = a.iter().filter(|n| matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.iter().any(|e| e.id == "warp.arc")).count(); + (live, warped, a.len(), warnings, notes) +} + +/// Images with a Warp take the reader's checks as envelopes do: past them, an image is written as +/// its drawn look, with a warning, and the file opens with every object written live still live. +#[test] +fn warped_images_past_the_readers_checks_are_written_as_their_drawn_look() { + // GUARDS: images with a Warp were written live past the checks the envelopes left, and the + // file opened with the last one as its drawn look and no warning on saving. + let limit = crate::import::ENVELOPE_CHECKS; + let (live, warped, all, warnings, notes) = envelopes_and_warped_images(limit - 1, 2, false); + assert_eq!((live, warped, all), (limit - 1, 1, limit + 1), "{warnings:?} {notes:?}"); + assert!(warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + assert!(!notes.iter().any(|n| n.contains("drawn look") || n == crate::import::ENVELOPE_DRAWN), "{notes:?}"); +} + +/// An image with a Warp whose pixels can't be read is written as its gray outline, which the reader +/// doesn't check: it leaves its check to the objects after it. +#[test] +fn a_warped_image_written_as_its_outline_takes_no_check() { + // GUARDS: an image written as its gray outline took a check, and the image after it lost its Warp. + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let limit = crate::import::ENVELOPE_CHECKS; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for _ in 0..limit - 1 { + let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + } + let arc = || fx("warp.arc", serde_json::json!({"bend": 40.0})); + let mut broken = image_node(&mut doc, ImageBlob::png(b"not a png".to_vec()), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None); + broken.appearance = Appearance { effects: vec![arc()], ..Appearance::default() }.into(); + doc.insert(Some(layer), usize::MAX, broken).unwrap(); + let photo = warped_photo(&mut doc, vec![arc()]); + doc.insert(Some(layer), usize::MAX, photo).unwrap(); + let (p, warnings) = private_data(&doc, &opts()).unwrap(); + assert!(warnings.iter().any(|w| w == writer::IMAGES), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}"); + let (back, notes) = crate::ai_alone(&p.data).unwrap(); + let a = back.layers[0].children().unwrap(); + let warped = a.iter().filter(|n| matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.iter().any(|e| e.id == "warp.arc")).count(); + assert_eq!(warped, 1, "{notes:?}"); +} + +/// Past the reader's checks, an image with a Warp whose pixels can't be read is still written as its +/// gray outline, with the warning for its pixels and not the one for the checks. +#[test] +fn an_unreadable_warped_image_past_the_checks_is_warned_about_its_pixels() { + // GUARDS: an image whose pixels can't be read was warned about as past the checks. + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions}; + let limit = crate::import::ENVELOPE_CHECKS; + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for _ in 0..limit { + let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec(); + let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] }; + let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW); + doc.insert(Some(layer), usize::MAX, envelope).unwrap(); + } + let mut broken = image_node(&mut doc, ImageBlob::png(b"not a png".to_vec()), (8, 8), Affine::new([10.0, 0.0, 0.0, 10.0, 20.0, 10.0]), None); + broken.appearance = Appearance { effects: vec![fx("warp.arc", serde_json::json!({"bend": 40.0}))], ..Appearance::default() }.into(); + doc.insert(Some(layer), usize::MAX, broken).unwrap(); + let (_, warnings) = private_data(&doc, &opts()).unwrap(); + assert!(warnings.iter().any(|w| w == writer::IMAGES), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}"); +} + +/// Envelopes after images with a Warp get the checks the images left: past them, an envelope is +/// written as its art, with a warning. +#[test] +fn envelopes_get_the_checks_warped_images_left() { + // GUARDS: envelopes were written live past the checks the images with a Warp before them left. + let limit = crate::import::ENVELOPE_CHECKS; + let (live, warped, all, warnings, notes) = envelopes_and_warped_images(limit - 1, 2, true); + assert_eq!((live, warped, all), (limit - 2, 2, limit + 1), "{warnings:?} {notes:?}"); + assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w == writer::WARPED_IMAGES), "{warnings:?}"); + assert!(!notes.iter().any(|n| n.contains("drawn look") || n == crate::import::ENVELOPE_DRAWN), "{notes:?}"); +} + /// Every Envelope Options switch and the ends of Fidelity come back as saved. #[test] fn envelope_options_and_fidelity_are_read_back() { @@ -10695,4 +10834,25 @@ fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() { assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{text}"); same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]); } + + // The outer clipping object ends at x = 100 and the clipping path's fill starts at x = 101: the + // fill is cut away and writes nothing, and its 4 pt stroke, which reaches x = 99, keeps the + // options, whether or not the fill's lock state is written before it. + for locked in [false, true] { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(101.0, 20.0, 150.0, 80.0))); + cutter.appearance = Appearance::basic(solid(Color::gray(0.5)), solid(Color::BLACK), 4.0).into(); + cutter.locked = locked; + let cutter = wrapped(cutter, 5.0, true); + let member = square(&mut doc, Rect::new(110.0, 30.0, 140.0, 60.0), Color::rgb(1.0, 0.0, 0.0)); + let inner = group(&mut doc, vec![cutter, member], true); + 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); + let outer = group(&mut doc, vec![frame, inner], true); + doc.insert(Some(layer), usize::MAX, outer).unwrap(); + let text = program(&doc); + assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "locked {locked}: {text}"); + same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]); + } } diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index b9d7229186..98b027f79d 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -30,7 +30,7 @@ pub(super) use brushes::BRUSHES; pub(super) use envelopes::ENVELOPES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects}; #[cfg(test)] -pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, same_appearance}; +pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; pub(super) use images::PAYLOAD; #[cfg(test)] @@ -281,9 +281,9 @@ pub(super) struct Writer<'a> { /// The object just written is an envelope's distorted art, which the plugin's `XP` follows /// ([`Self::envelope`]). deform: bool, - /// How many more envelopes may be written live: as many as the reader checks in one file - /// ([`crate::import::ENVELOPE_CHECKS`]). - envelopes_left: usize, + /// How many more envelopes and images with a Warp may be written live: as many as the reader + /// checks in one file ([`crate::import::ENVELOPE_CHECKS`]), which it spends on both. + checks_left: usize, /// The image read last and its pixels ([`images::Samples::of`], `None` when they can't be /// read): the pieces of a warped image, which follow one another, read them once. last_samples: Option<(vectorcraft_doc::ImageBlob, Option)>, @@ -357,7 +357,7 @@ impl<'a> Writer<'a> { brush_set: brushes::Brushes::default(), brushes_live: true, deform: false, - envelopes_left: crate::import::ENVELOPE_CHECKS, + checks_left: crate::import::ENVELOPE_CHECKS, objects: 0, left_out: 0, definition_objects: 0, @@ -662,6 +662,7 @@ impl<'a> Writer<'a> { && self.clip.is_none() && !self.in_symbol && let Some(orig) = self.styled.get(&n.id).cloned() + && self.check_left(&orig) && let Some(name) = self.object_style(n, &orig) { return self.styled_object(n, &orig, &name); diff --git a/crates/eps/src/ai_editing/writer/envelopes.rs b/crates/eps/src/ai_editing/writer/envelopes.rs index dcd7274291..5e5e9068c0 100644 --- a/crates/eps/src/ai_editing/writer/envelopes.rs +++ b/crates/eps/src/ai_editing/writer/envelopes.rs @@ -26,7 +26,7 @@ use super::{MAX_NEST, Writer, Xy, hide}; use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number}; use crate::ps; -pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; +pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256 envelopes and images with a Warp, and envelopes nested more than 8 deep are written as their art in the editing data for other apps"; /// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the /// reader's). @@ -287,7 +287,7 @@ impl Writer<'_> { /// another shape, or some of it is left out for the object limit ([`Self::take_objects`]). pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool { let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false }; - if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.envelopes_left == 0 { + if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.checks_left == 0 { return false; } let Some(record) = record(n, content, kind, *fidelity, *editing, options, **frame) else { return false }; @@ -339,7 +339,7 @@ impl Writer<'_> { return false; } self.deform = true; - self.envelopes_left -= 1; + self.checks_left -= 1; true } diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs index 1d5b9a8c4c..3813deccf9 100644 --- a/crates/eps/src/ai_editing/writer/images.rs +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -121,29 +121,37 @@ impl Samples { } impl Writer<'_> { + /// Whether [`Self::image`] can read `im`'s pixels, rather than write its gray outline. + pub(super) fn image_readable(&mut self, im: &ImageObject) -> bool { + let doc = self.doc; + doc.image_blob(im).and_then(|b| self.samples(b)).is_some() + } + /// Image object `im` of transparency `xy`: embedded, a raster ([`Self::raster`]); linked, a /// placed file with a preview ([`Self::placed_file`]), except in a part of the data written on /// `%_` lines (other than a styled object's copy on the layers, [`Self::styled_object`]) and in /// a symbol's art. One whose pixels can't be read is its outline filled mid gray. Where the art is /// cut to a clipping path, the image is in a clipping group of that path; a raster of pixels /// written whole already is then the part of them that the path shows ([`ai_ops::image_window`]). - pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) { + /// True when the image is written as an image. + pub(super) fn image(&mut self, im: &ImageObject, xy: Xy) -> bool { let doc = self.doc; let blob = doc.image_blob(im); let read = blob.and_then(|b| self.samples(b)); let Some((samples, deep)) = read.as_deref() else { let bounds = PathData::from_bezpath(&(im.xf * Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1))); self.warn(IMAGES); - return self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy); + self.fill_object(&bounds, FillRule::NonZero, &FillLayer::new(Paint::solid(Color::gray(0.5))), xy); + return false; }; // A region that has nothing left hides the image. if self.clip.as_ref().is_some_and(|c| c.subpaths.iter().all(|sp| sp.anchors.is_empty())) { - return; + return false; } // The image, and where it is cut, the clipping group and its clipping path. let clipping = self.clip.as_ref().map_or(0, |c| 1 + super::object_count(c.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count())); if !self.take_objects(1 + clipping) { - return; + return false; } if *deep { self.warn(IMAGE_DEPTH); @@ -217,6 +225,7 @@ impl Writer<'_> { self.end_group("Q", Xy::PLAIN); } self.clip = cut; + true } /// An embedded image whose pixels `xf` places in the document: `%AI5_File:`, diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index ab9ed6a482..a8a2da677c 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -23,6 +23,7 @@ pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, pub(in crate::ai_editing) const PANEL_STYLES: &str = "graphic styles with gradient or pattern fills, with fills, strokes or effects the editing data can't hold as a graphic style, with a name another style has, with names over 1,024 bytes, or past 4,096 styles, are left out of the editing data for other apps"; pub(in crate::ai_editing) const PANEL_EMPTY: &str = "a Graphic Styles panel with no style written opens from the editing data with a new document's styles"; +pub(in crate::ai_editing) const WARPED_IMAGES: &str = "images with a Warp after the first 256 envelopes and images with a Warp are written as their drawn look, without their Warp, in the editing data for other apps"; pub(in crate::ai_editing) const STYLE_LINKS: &str = "links to graphic styles are left out of the editing data for other apps on type, images, symbol instances, knockout shapes and other objects that aren't written with their graphic style"; /// How many objects of `doc`'s layers, opacity masks and symbols are linked to a graphic style. @@ -719,6 +720,24 @@ impl Writer<'_> { items_keep && m.children().is_none_or(|c| c.iter().all(|c| self.member_keeps_outline(c))) } + /// Whether `orig` may be written with its art style as far as the reader's checks go: an image + /// with a Warp takes one of them, as an envelope does ([`Self::envelope`]); with none left, it is + /// written as its drawn look, with a warning. One whose pixels can't be read takes none: it is + /// written as its gray outline ([`Self::image`]). + pub(super) fn check_left(&mut self, orig: &Node) -> bool { + if !warped_image(orig) || self.checks_left > 0 { + return true; + } + let doc = self.doc; + if let NodeKind::Image(im) = &orig.kind + && !self.image_readable(&doc.shown_image(orig, im)) + { + return true; + } + self.warn(WARPED_IMAGES); + false + } + /// Object `n` (as baking left it; `orig` before baking) with the style `name`: its lock and /// hidden state; its drawn look (a group of its vector art as baking left it, without shadows, /// glows or feathers, the object's transparency @@ -729,7 +748,8 @@ impl Writer<'_> { /// `1 (name) XW`. /// The look's group and the object itself are counted first ([`Self::take_objects`]): without /// room for them, nothing is written, and the object counts neither as written with its graphic - /// style nor as written with a brush on its stroke. + /// style nor as written with a brush on its stroke. An image written as an image takes one of + /// the reader's checks ([`Self::check_left`]). pub(super) fn styled_object(&mut self, n: &Node, orig: &Node, name: &str) { let own = match &orig.kind { NodeKind::Path { path, .. } => super::object_count(path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()).count()), @@ -787,9 +807,12 @@ impl Writer<'_> { match &orig.kind { NodeKind::Path { path, rule, .. } => self.styled_outline(orig, path, *rule, fit, xy), NodeKind::Compound { rule, .. } => self.styled_outline(orig, &compound_path(orig), *rule, fit, xy), + // The reader checks the object only when it is an image, not its gray outline. NodeKind::Image(im) => { let was = std::mem::replace(&mut self.styled_copy, on_layers); - self.image(&self.doc.shown_image(orig, im), xy); + if self.image(&self.doc.shown_image(orig, im), xy) { + self.checks_left = self.checks_left.saturating_sub(1); + } self.styled_copy = was; } NodeKind::Group { children, .. } => { diff --git a/crates/eps/src/import/ai/read/graph.rs b/crates/eps/src/import/ai/read/graph.rs index 759eb4e1cd..9fb60408c7 100644 --- a/crates/eps/src/import/ai/read/graph.rs +++ b/crates/eps/src/import/ai/read/graph.rs @@ -631,6 +631,7 @@ impl<'a> Reader<'a> { let Some(paints) = series_paints(art, &tags, spec.kind == GraphKind::Line) else { return false }; spec.series_paints = paints; spec.placed = Some(placed); + spec.placed_art = art.children().and_then(|c| vectorcraft_doc::graph::art_bounds(c)); tag_series(art, &tags); art.extras_mut().graph = Some(Box::new(spec)); true diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 0ea7017c11..43346988ff 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -98,7 +98,7 @@ pub(crate) struct Interp<'a> { /// The font a `kshow` procedure sees as current while type in a CIDFont only named is set in /// a font of its own (see `text`). pub kshow_font: Option, - /// The `cshow` procedure running over type in a CIDFont only named, with the font it sees as + /// The `cshow` procedure running over a composite font's type, with the font it sees as /// current (see `text`). pub cshow: Option, pub g: GState, diff --git a/crates/eps/src/import/tests_cid.rs b/crates/eps/src/import/tests_cid.rs index d7ef0623d9..b44a5410ee 100644 --- a/crates/eps/src/import/tests_cid.rs +++ b/crates/eps/src/import/tests_cid.rs @@ -136,6 +136,31 @@ fn codes_map_by_their_codespace_with_notdef_fallbacks() { width("<01>", 30.0); } +/// `cshow` over a CMap runs its procedure once for each code, whatever its length, with the +/// code's last byte and its width (PLRM 3rd ed., `cshow`). +#[test] +fn cshow_runs_once_for_each_cmap_code() { + let fonts = String::from_utf8(cid_font(true)).unwrap() + CMAP; + let check = |cond: &str| check(&format!("{fonts} /TestFont 50 selectfont {cond}")); + check("[ {pop pop} <418001> cshow ] dup length 2 eq exch aload pop 1 eq exch 65 eq and and"); + check("0 {pop exch pop add} <418001> cshow 55 sub abs 0.01 lt"); + check( + "{pop pop pop currentfont /CIDFontName get /seen exch def rootfont /FontName get /root exch def} <41> cshow seen /TestCID eq root /TestFont eq and", + ); + // With the CIDFont current, the byte the procedure was given shows the glyph of its code's + // CID: <8001>'s last byte draws CID 2, not code 01's CID 1. Another string is an error. + let shown = "{pop pop ( ) dup 0 4 -1 roll put show} <418001> cshow"; + check(&format!("gsave nulldevice 10 20 moveto {shown} currentpoint grestore pop 65 sub abs 0.01 lt")); + check("gsave nulldevice 10 20 moveto {{pop pop pop (B) show} <41> cshow} stopped grestore"); + let r = import(&program(true, &format!("/TestFont 50 selectfont 10 20 moveto {shown}"))).unwrap(); + let want = import(&program(true, "/TestFont 50 selectfont 10 20 moveto <418001> show")).unwrap(); + let (p, q) = (paths(&r), paths(&want)); + assert_eq!(p.len(), 2, "{p:?}"); + for (a, b) in p.iter().zip(&q) { + assert!((a.x0 - b.x0).abs() < 0.01 && (a.width() - b.width()).abs() < 0.01 && (a.height() - b.height()).abs() < 0.01, "{p:?} {q:?}"); + } +} + /// `kshow` over a CMap runs its procedure between each two codes with their values, whatever /// their length, and the next character follows where it moves the point (PLRM 3rd ed., `kshow`). #[test] @@ -188,6 +213,22 @@ fn type2_cidfonts_draw_their_truetype_glyphs_through_cidmap() { } } +/// A `cshow` procedure over a Type 2 CIDFont without a `FontMatrix` sees the CIDFont current at +/// the scale its glyphs are drawn at: an em of the composite font's size, as with the identity. +#[test] +fn cshow_over_a_type2_cidfont_without_a_matrix_sees_it_at_its_drawn_scale() { + let (h, i) = (glyph('H').0, glyph('I').0); + let with = cid2_font(&format!("<0000{h:04x}{i:04x}>")); + let without = with.replace("/FontMatrix [1 0 0 1 0 0] def", ""); + assert_ne!(with, without); + for fonts in [with, without] { + check(&format!( + "{fonts}/T2 /Identity-H [/TestCID2] composefont 50 scalefont setfont \ + {{pop pop pop currentfont /FontMatrix get 0 get /m exch def}} <0001> cshow m 50 sub abs 0.01 lt" + )); + } +} + /// `Identity-V`: each glyph an em below the one before (writing mode 1). #[test] fn identity_v_sets_glyphs_downwards() { @@ -385,6 +426,30 @@ fn cmaps_map_codes_to_base_fonts_codes_and_glyph_names() { }) .collect(); assert_eq!(text, "ABC"); + // A `cshow` procedure that shows the byte it was given, in the base font current while it + // runs, shows the character the code maps to, as `show` does. + let body = format!( + "{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 20 scalefont setfont 10 20 moveto \ + {{pop pop ( ) dup 0 4 -1 roll put show}} <001000110012> cshow" + ); + let r = super::tests::read(&body); + let text: String = all(&r.document) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Text(t) => Some(t.plain_text()), + _ => None, + }) + .collect(); + assert_eq!(text, "ABC"); + let body = format!( + "{plain}{BF_CMAP}/BF /TestBF-H [/Plain42 /Helvetica] composefont 50 scalefont setfont 10 20 moveto \ + {{pop pop ( ) dup 0 4 -1 roll put show}} <000100020003> cshow" + ); + let q = paths(&super::tests::read(&body)); + assert_eq!(q.len(), 3, "{q:?}"); + for (a, b) in p.iter().zip(&q) { + assert!((a.x0 - b.x0).abs() < 0.01 && (a.width() - b.width()).abs() < 0.01, "{p:?} {q:?}"); + } } /// A CID-keyed font over a predefined Unicode CMap the file doesn't define, its CIDFont only diff --git a/crates/eps/src/import/tests_composite.rs b/crates/eps/src/import/tests_composite.rs index 2f4074af97..ff3b3382d3 100644 --- a/crates/eps/src/import/tests_composite.rs +++ b/crates/eps/src/import/tests_composite.rs @@ -119,6 +119,45 @@ fn widthshow_matches_a_composite_character_by_font_number_and_code() { check(format!("{} {} sub abs 0.01 lt", end(2), 10.0 + 100.0 * wh)); } +/// `cshow` runs its procedure once for each character of a composite font, not for each byte, +/// with the last byte of its code and its width, and with the descendant that draws it as the +/// current font while `rootfont` gives the composite font (PLRM 3rd ed., `cshow` and `rootfont`). +#[test] +fn cshow_runs_once_for_each_composite_character_in_its_descendant() { + let (_, wh) = glyph('H'); + let (_, wi) = glyph('I'); + let check = |cond: String| super::tests::check(&format!("{} /Comp findfont 50 scalefont setfont {cond}", fonts())); + check("[ {pop pop} (\\000\\001\\000\\002) cshow ] dup length 2 eq exch aload pop 2 eq exch 1 eq and and".into()); + check(format!("0 {{pop exch pop add}} (\\000\\001\\000\\002) cshow {} sub abs 0.01 lt", 50.0 * (wh + wi))); + check("{pop pop pop currentfont /FontName get /seen exch def rootfont /FontName get /root exch def} (\\000\\001) cshow seen /T42 eq root /Comp eq and".into()); + check("{pop pop pop} (\\000\\001) cshow currentfont /FontName get /Comp eq".into()); + // A character the procedure shows in the descendant is as wide as the composite font sets it. + check(format!( + "gsave nulldevice 10 20 moveto {{pop pop ( ) dup 0 4 -1 roll put show}} (\\000\\001\\000\\002) cshow currentpoint grestore pop {} sub abs 0.01 lt", + 10.0 + 50.0 * (wh + wi) + )); + // A character in font number 1 still gives only the last byte of its code, not 258. + let two = fonts().replace("/Encoding [0] def", "/Encoding [0 0] def"); + super::tests::check(&format!("{two} /Comp findfont 50 scalefont setfont [ {{pop pop}} (\\001\\002) cshow ] dup length 1 eq exch 0 get 2 eq and")); +} + +/// A `cshow` procedure over a Type 42 descendant without a `FontMatrix` sees it current at the +/// scale its characters are drawn at: another character it measures there is as wide as the +/// composite font sets it, as with the identity. +#[test] +fn cshow_over_a_type42_descendant_without_a_matrix_sees_it_at_its_drawn_scale() { + let (_, wi) = glyph('I'); + let with = fonts(); + let without = with.replacen("/FontType 42 def /FontMatrix [1 0 0 1 0 0] def", "/FontType 42 def", 1); + assert_ne!(with, without); + for fonts in [with, without] { + super::tests::check(&format!( + "{fonts} /Comp findfont 50 scalefont setfont {{pop pop pop (\\002) stringwidth pop /w exch def}} (\\000\\001) cshow w {} sub abs 0.01 lt", + 50.0 * wi + )); + } +} + /// `kshow` runs its procedure between each two characters of a composite font, with the values of /// their codes (font number times 256 plus code), and the next character follows where it moves /// the current point (PLRM 3rd ed., `kshow`). diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 257fdc2247..3de16d7bbf 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -251,6 +251,15 @@ impl Interp<'_> { self.g.font = root; return r; } + // In a composite font the file carries, once for each character it maps. + if let Some(glyphs) = self.composite_glyphs(&s)? { + let root = self.g.font.clone(); + let before = self.cshow.take(); + let r = self.composite_cshow(&glyphs, &proc, root.clone()); + self.cshow = before; + self.g.font = root; + return r; + } for b in s { let v = self.width_of(&[b])?; self.push(Obj::Int(i64::from(b)))?; @@ -992,6 +1001,7 @@ impl Spacing { /// A character of a composite font: the descendant font that draws it, its code there (its last /// byte for a CID), its CID and the notdef mapping's (`FMapType` 9), the composite font's matrix /// (over the descendant's own) and whether it is set vertically (`WMode` 1). +#[derive(Clone)] struct Mapped { font: DictRef, /// The byte that picked the descendant (the font number). @@ -1006,6 +1016,13 @@ struct Mapped { value: u32, } +impl Mapped { + /// The last byte of the character's code in the shown string (what `cshow` gives its procedure). + fn last(&self) -> u8 { + (self.value & 0xff) as u8 + } +} + /// Type in a CIDFont only named, over a predefined CMap ([`Interp::named_cid_type`]): its codes /// with their characters, the font it is set in, whether it runs down a column, and whether each /// code moves the point one em (down a column, or in a CMap VectorCraft can't read). @@ -1016,13 +1033,15 @@ struct NamedCid { ems: bool, } -/// A `cshow` procedure running over type in a CIDFont only named ([`Interp::named_cshow`]): the -/// CIDFont it sees as current, the composite font `rootfont` gives while that CIDFont is current, -/// and the type of the code it was given. +/// A `cshow` procedure running over a composite font's type ([`Interp::named_cshow`], +/// [`Interp::composite_cshow`]): the descendant it sees as current, the composite font `rootfont` +/// gives while that descendant is current, and the code it was given: over a CIDFont only named, +/// its type; over a composite font the file carries, the character it maps to. pub(super) struct CShowFont { selected: DictRef, root: DictRef, - code: NamedCid, + code: Option, + mapped: Option, } /// What drawing a glyph does with it. @@ -1069,6 +1088,22 @@ impl Interp<'_> { /// codes mapped to a descendant and a CID, §5.11.5); `None` for other fonts and mappings, /// which are set as type in the font of the composite font's name. fn composite_glyphs(&mut self, s: &[u8]) -> Res>> { + // Inside a `cshow` procedure over a composite font the file carries, with the descendant + // it selected current, the one byte the procedure was given stands for the character its + // code maps to: a CMap's CID, base-font code or glyph name. In a CIDFont any other string + // is a `rangecheck` error (PLRM 3rd ed., `cshow`: the glyph of the selected CID); in a + // base font it is shown as it is. + if let Some(c) = self.cshow.as_ref() + && let Some(mapped) = c.mapped.as_ref() + && self.g.font.as_ref().is_some_and(|f| f.same(&c.selected)) + { + if s == [mapped.last()] { + return Ok(Some(vec![mapped.clone()])); + } + if mapped.cid.is_some() { + return ps_err("rangecheck", "a string shown in cshow"); + } + } let Some(font) = self.g.font.clone() else { return Ok(None) }; let map = { let f = font.borrow(); @@ -1220,17 +1255,18 @@ impl Interp<'_> { /// that code when `code` and with none otherwise, while the CIDFont it selected is current. fn cshow_code(&self, code: bool) -> Option { let c = self.cshow.as_ref()?; + let given = c.code.as_ref()?; if !self.g.font.as_ref().is_some_and(|f| f.same(&c.selected)) { return None; } let mut codes = Decoded::default(); if code { - let mut chars = c.code.codes.text.chars(); - for &(value, n) in &c.code.codes.codes { + let mut chars = given.codes.text.chars(); + for &(value, n) in &given.codes.codes { codes.push(value, chars.by_ref().take(n)); } } - Some(NamedCid { codes, font: c.code.font.clone(), vertical: c.code.vertical, ems: c.code.ems }) + Some(NamedCid { codes, font: given.font.clone(), vertical: given.vertical, ems: given.ems }) } /// The CMap's name, the composite font, the CIDFont's name and the writing mode of @@ -1318,7 +1354,7 @@ impl Interp<'_> { self.push(Obj::Int(i64::from(code & 0xff)))?; self.push_num(v.x)?; self.push_num(v.y)?; - self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: one }); + self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: Some(one), mapped: None }); self.g.font = Some(selected.clone()); let go = self.body(proc); self.g.font = root.clone(); @@ -1329,6 +1365,41 @@ impl Interp<'_> { Ok(()) } + /// `cshow`'s procedure `proc` run for each character `glyphs` of composite font `root` maps, + /// with the last byte of its code and its width (PLRM 3rd ed., `cshow`). While it runs the + /// descendant that draws the character, at the size the composite font sets it, is the current + /// font and `rootfont` gives `root`. The current font is restored when the procedure completes. + fn composite_cshow(&mut self, glyphs: &[Mapped], proc: &Obj, root: Option) -> Res { + let Some(composite) = root.clone() else { return Ok(()) }; + for g in glyphs { + let v = self.composite_glyph(g, Point::ZERO, Draw::No)?; + self.push(Obj::Int(i64::from(g.last())))?; + self.push_num(v.x)?; + self.push_num(v.y)?; + // Scaling the descendant copies its dictionary for every character: charged by its + // size, so a huge font dictionary in a loop runs out of the budget. + let entries = g.font.borrow().len(); + self.spend(entries as u64)?; + // Without a matrix, a Type 42 font or a Type 2 CIDFont is in ems, as `composite_glyph` + // and `cid_glyph_at` draw it. + let selected = { + let f = g.font.borrow(); + let default = if units(&f) == 1.0 { 1.0 } else { 0.001 }; + let mut d = f.clone(); + d.insert(Key::name("FontMatrix"), matrix_obj(g.outer * font_matrix(&f, default))); + DictRef::new(d) + }; + self.cshow = Some(CShowFont { selected: selected.clone(), root: composite.clone(), code: None, mapped: Some(g.clone()) }); + self.g.font = Some(selected); + let go = self.body(proc); + self.g.font = root.clone(); + if !go? { + break; + } + } + Ok(()) + } + /// How far codes `codes` of type `named` move the current point (user space) when /// [`Self::show_named_cid`] shows them with no extra spacing. fn named_cid_width(&mut self, named: &NamedCid, codes: &Decoded) -> Res { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index beda6d8ade..1502f11662 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1634,6 +1634,27 @@ fn text_effect_pathfinder_transform_graph_and_wrap_tools() { let ds = d.to_string(); // The wrap object carries the options and the area type resolved its shape. assert!(ds.contains("\"wrap\":{\"invert\":false,\"offset\":8.0}") && ds.contains("\"wrap\":[{\"invert\":false,\"offset\":8.0"), "{area}"); + // An offset outside -1000 to 1000 pt, an invert or a release that is not true or false is an + // error, with release too, and the wrap and the selection stay as they were. + let r = call(&mut s, 20, "run_command", json!({"command": "select.set", "params": {"ids": [g]}})); + assert_eq!(r["isError"], false, "{r}"); + for (id, args) in [ + (21, json!({"ids": [c], "offset": 5000})), + (22, json!({"ids": [c], "offset": "8"})), + (23, json!({"ids": [c], "invert": "true"})), + (24, json!({"ids": [c], "release": "true"})), + (25, json!({"ids": [c], "release": true, "offset": -5000})), + ] { + let r = call(&mut s, id, "text_wrap", args.clone()); + assert_eq!(r["isError"], true, "{args}: {r}"); + assert!(doc_json(&mut s).to_string().contains("\"wrap\":{\"invert\":false,\"offset\":8.0}"), "{args}"); + } + // The graph is still the selection: a wrap made without ids goes on it, not on the circle. + let r = call(&mut s, 26, "text_wrap", json!({"offset": 9})); + assert_eq!(r["isError"], false, "{r}"); + let made: Value = serde_json::from_str(&text_of(&r)).unwrap(); + assert_eq!(made["ids"], json!([g]), "{r}"); + call(&mut s, 27, "text_wrap", json!({"release": true})); call(&mut s, 15, "text_wrap", json!({"ids": [c], "release": true})); assert!(!doc_json(&mut s).to_string().contains("\"offset\":8.0")); } diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index e583753e4d..e7ba79df7c 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -507,7 +507,7 @@ pub fn tool_definitions() -> Vec { tool( "text_wrap", "Text wrap", - "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap.", + "Make the selected (or `ids`) objects wrap objects: area type below them in the same layer flows around them (offset in pt, invert = flow inside). `release: true` removes the wrap. An offset outside -1000 to 1000 or not a number, or an invert or release that is not true or false, is an error and changes nothing.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 8e514ac48d..8d410af183 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -20,6 +20,29 @@ pub(super) const MAX_SIDE_WINDOW: &str = /// The `traceViews` argument of the artboard renders. pub(super) const TRACE_VIEWS: &str = "Draw Image Trace objects in the view set with imageTrace.setView (outlines, the source image…), as the app's window does; by default they draw their tracing result, as exports do"; +/// The `text_wrap` tool's `release` and its `offset` and `invert` for `object.textWrap.make`, checked +/// before the tool changes the selection: an omitted or null value is left out, an `offset` that is +/// not a number or lies outside [`vectorcraft_engine::TEXT_WRAP_OFFSET_RANGE`] is an error, and so is +/// an `invert` or `release` that is not true or false. +fn text_wrap_args(a: &Args) -> Result<(bool, Value), String> { + let mut p = json!({}); + for k in ["offset", "invert", "release"] { + let Some(v) = a.get(k).filter(|v| !v.is_null()) else { continue }; + if k == "offset" { + let range = vectorcraft_engine::TEXT_WRAP_OFFSET_RANGE; + let n = v.as_f64().ok_or_else(|| format!("`{k}` must be a number, not {v}"))?; + if !range.contains(&n) { + return Err(format!("`{k}` must be from {} to {}", range.start(), range.end())); + } + } else if !v.is_boolean() { + return Err(format!("`{k}` must be true or false")); + } + p[k] = v.clone(); + } + let release = p.as_object_mut().and_then(|m| m.remove("release")).is_some_and(|v| v == true); + Ok((release, p)) +} + /// `traceViews`: false when absent. pub(super) fn trace_views(a: &Args) -> Result { match a.get("traceViews") { @@ -261,16 +284,11 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result { + let (release, p) = text_wrap_args(a)?; select_ids(b, a)?; - if a.get("release").and_then(Value::as_bool) == Some(true) { + if release { return j(exec(b, "object.textWrap.release", json!({}))?); } - let mut p = json!({}); - for k in ["offset", "invert"] { - if let Some(v) = a.get(k) { - p[k] = v.clone(); - } - } j(exec(b, "object.textWrap.make", p)?) } "undo" => j(exec(b, "edit.undo", json!({}))?), diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 8110ce2db5..af686e1857 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -138,6 +138,7 @@ impl Exporter<'_> { } let doc = self.doc; let out = self.out.clone(); + let profiles = !out.standard.cmyk_only(); 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 { @@ -147,12 +148,12 @@ impl Exporter<'_> { let icc = out.cmyk_image_icc(blob); crate::images::recode_cmyk(blob, size, c, interpolate, out.cmyk_pixels(), None, icc.as_deref()) } else { - crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels()) + crate::images::recode(&blob.bytes, size, c, interpolate, out.pixels(), profiles) }; if let Some(w) = r.warning { self.warn(w); } - r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit)) + r.image.or_else(|| embed(blob, interpolate, self.sixteen_bit, profiles)) }); if img.is_none() { self.warn(UNDECODED); @@ -316,9 +317,13 @@ pub(super) fn png_8_bit(bytes: &[u8]) -> Option> { } /// Image `blob` as it is: PNG, JPEG, GIF and WebP through the PDF writer (JPEG data unchanged), -/// other formats decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG of 16 bits a -/// sample is written at 8 bits ([`png_8_bit`]). -pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool) -> Option { +/// other formats (a TIFF) decoded with their 16-bit samples and, when `profiles` allows it (not in +/// PDF/X-1a), the ICC profile they carry ([`crate::images::decoded_image`]). Without `profiles`, an +/// image that carries a gray or RGB profile is written without it, and so is one whose gray or RGB +/// profile is malformed ([`crate::images::valid_icc`]): a JPEG with its data unchanged, an image of +/// another format decoded. Without `sixteen_bit` (a file before PDF 1.5), a PNG or another image of +/// 16 bits a sample is written at 8 bits ([`png_8_bit`]). +pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option { // The header's size first: the writer's decoders allocate what it declares, and the encoded // bytes of an image that is far larger than any the app reads may be a few kilobytes. let size = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions(); @@ -326,7 +331,17 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee return None; } let bytes = blob.bytes.as_ref().clone(); + // The PDF writer keeps a gray or RGB image's ICC profile: without `profiles`, or when the + // profile is malformed, such a JPEG is written without its profile, and an image of another + // format is decoded and written without it. The color space is read from the header's bytes + // 16..20 even in a profile cut short, as the PDF writer reads it. + let strip = crate::images::source_icc(&bytes).is_some_and(|icc| match icc.get(16..20) { + Some(space @ (b"GRAY" | b"RGB ")) => !profiles || <[u8; 4]>::try_from(space).is_ok_and(|s| !crate::images::valid_icc(&icc, s)), + _ => false, + }); let direct = match blob.mime.as_str() { + "image/jpeg" | "image/jpg" if strip => Image::from_jpeg_with_icc(bytes.clone().into(), None, interpolate).ok(), + _ if strip => None, "image/png" if !sixteen_bit && png_16_bit(&bytes) => png_8_bit(&bytes).and_then(|png| Image::from_png(png.into(), interpolate).ok()), "image/png" => Image::from_png(bytes.clone().into(), interpolate).ok(), "image/jpeg" | "image/jpg" => Image::from_jpeg(bytes.clone().into(), interpolate).ok(), @@ -334,11 +349,7 @@ pub(super) fn embed(blob: &vectorcraft_doc::ImageBlob, interpolate: bool, sixtee "image/webp" => Image::from_webp(bytes.clone().into(), interpolate).ok(), _ => None, }; - direct.or_else(|| { - let rgba = image::load_from_memory(&bytes).ok()?.to_rgba8(); - let (w, h) = rgba.dimensions(); - Some(Image::from_rgba8(rgba.into_raw(), w, h)) - }) + direct.or_else(|| crate::images::decoded_image(&bytes, interpolate, sixteen_bit, profiles)) } #[cfg(test)] @@ -357,7 +368,7 @@ mod tests { let crc = !png[12..29].iter().fold(!0u32, |c, b| (0..8).fold(c ^ u32::from(*b), |c, _| if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 })); png[29..33].copy_from_slice(&crc.to_be_bytes()); - assert!(super::embed(&ImageBlob::png(png), false, true).is_none()); + assert!(super::embed(&ImageBlob::png(png), false, true, true).is_none()); } #[test] diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index 4b0b3a047a..c9ef8203c7 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -325,7 +325,7 @@ impl Exporter<'_> { let img = match self.images.get(&cache) { Some(img) => img.clone(), None => { - let img = embed(&image.blob, self.interpolate, self.sixteen_bit); + let img = embed(&image.blob, self.interpolate, self.sixteen_bit, !self.out.standard.cmyk_only()); self.images.insert(cache, img.clone()); img } diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index d8b873364c..5204e4f396 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -29,8 +29,8 @@ use vectorcraft_doc::resample::{Resample, premultiply, resized, unpremultiply}; use crate::output::{CmykPixels, Pixels}; use crate::{CompressionSettings, Downsample, ImageCodec, JpegQuality, MonoCodec}; -/// Raw 8-bit pixels: colour samples (RGB, grey or CMYK) and an optional alpha channel, with the -/// ICC profile the colour samples are in, if any. +/// Raw pixels: colour samples (RGB, grey or CMYK) and an optional alpha channel, of 8 bits a +/// sample or of 16 (big-endian), with the ICC profile the colour samples are in, if any. #[derive(Clone, Hash)] struct Raw { color: Arc>, @@ -38,6 +38,7 @@ struct Raw { width: u32, height: u32, space: ImageColorspace, + bits: BitsPerComponent, icc: Option>>, } @@ -51,7 +52,7 @@ impl CustomImage for Raw { } fn bits_per_component(&self) -> BitsPerComponent { - BitsPerComponent::Eight + self.bits } fn size(&self) -> (u32, u32) { @@ -67,24 +68,86 @@ impl CustomImage for Raw { } } +/// `icc` when it is a well-formed profile ([`valid_icc`]) of the colour space `space` names: `GRAY` +/// for grey samples, `RGB ` for RGB ones. `None` for other profiles and spaces. +fn icc_for(icc: Option>, space: ImageColorspace) -> Option>> { + let want = match space { + ImageColorspace::Luma => *b"GRAY", + ImageColorspace::Rgb => *b"RGB ", + ImageColorspace::Cmyk | ImageColorspace::DeviceN => return None, + }; + icc.filter(|icc| valid_icc(icc, want)).map(Arc::new) +} + +/// The ICC profile image `bytes` carries: a TIFF's tag 34675 (read by the TIFF decoder itself, +/// which reads tags of any size), another format's as its decoder reads it. `None` without one. +pub(crate) fn source_icc(bytes: &[u8]) -> Option> { + let reader = ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + if reader.format() == Some(ImageFormat::Tiff) { + return vectorcraft_doc::cmyk::tiff_icc_profile(bytes); + } + let mut decoder = reader.into_decoder().ok()?; + decoder.icc_profile().ok().flatten().filter(|icc| !icc.is_empty()) +} + /// A `width` × `height` image of straight (not premultiplied) RGBA pixels, written as RGB (as /// CMYK when `pixels` converts to CMYK), or as grey when every pixel is grey, with an alpha -/// channel only when some pixel isn't opaque. `interpolate` asks viewers to smooth it when -/// enlarged (PDF/A forbids it). `None` when `rgba` doesn't hold that many pixels. -fn from_rgba(rgba: &[u8], width: u32, height: u32, interpolate: bool, pixels: Option<&Pixels>) -> Option { +/// channel only when some pixel isn't opaque. With an RGB `icc` profile, pixels that `pixels` +/// doesn't convert stay RGB and carry it; a grey one tags grey pixels. `interpolate` asks viewers +/// to smooth it when enlarged (PDF/A forbids it). `None` when `rgba` doesn't hold that many pixels. +fn from_rgba(rgba: &[u8], width: u32, height: u32, interpolate: bool, pixels: Option<&Pixels>, icc: Option>) -> Option { let px = rgba.as_chunks::<4>().0; if px.len() as u64 != width as u64 * height as u64 || px.is_empty() { return None; } - let (color, space) = if neutral(rgba) { + let rgb_icc = pixels.is_none() && icc.as_deref().is_some_and(|icc| valid_icc(icc, *b"RGB ")); + let (color, space) = if neutral(rgba) && !rgb_icc { (px.iter().map(|p| p[0]).collect(), ImageColorspace::Luma) } else if let Some(cmyk) = pixels.and_then(|p| p.cmyk(rgba)) { (cmyk, ImageColorspace::Cmyk) } else { (px.iter().flat_map(|p| [p[0], p[1], p[2]]).collect(), ImageColorspace::Rgb) }; + let icc = icc_for(icc.filter(|_| pixels.is_none()), space); let alpha = px.iter().any(|p| p[3] < 255).then(|| Arc::new(px.iter().map(|p| p[3]).collect())); - Image::from_custom(Raw { color: Arc::new(color), alpha, width, height, space, icc: None }, interpolate).ok() + Image::from_custom(Raw { color: Arc::new(color), alpha, width, height, space, bits: BitsPerComponent::Eight, icc }, interpolate).ok() +} + +/// Decoded image `img` written losslessly as it is: grey or RGB samples (other kinds as RGB), with +/// an alpha channel only when some pixel isn't opaque, at 16 bits a sample when it has more than 8 +/// and `sixteen_bit` allows it (PDF 1.5 and later), else at 8; tagged with ICC profile `icc` when +/// that is a profile of the samples' colour space (`GRAY` or `RGB `). `None` when it has no pixels. +pub(crate) fn from_decoded(img: DynamicImage, icc: Option>, interpolate: bool, sixteen_bit: bool) -> Option { + let (width, height) = (img.width(), img.height()); + if width == 0 || height == 0 { + return None; + } + let kind = img.color(); + let space = if kind.has_color() { ImageColorspace::Rgb } else { ImageColorspace::Luma }; + let n = if kind.has_color() { 3 } else { 1 }; + let deep = sixteen_bit && kind.bits_per_pixel() > 8 * u16::from(kind.channel_count()); + let (color, alpha, bits) = if deep { + let s = if kind.has_color() { img.into_rgba16().into_raw() } else { img.into_luma_alpha16().into_raw() }; + let px = s.chunks_exact(n + 1); + let color = px.clone().flat_map(|p| p[..n].iter().flat_map(|v| v.to_be_bytes())).collect(); + let alpha = (kind.has_alpha() && px.clone().any(|p| p[n] < u16::MAX)).then(|| px.flat_map(|p| p[n].to_be_bytes()).collect()); + (color, alpha, BitsPerComponent::Sixteen) + } else { + let s = if kind.has_color() { img.into_rgba8().into_raw() } else { img.into_luma_alpha8().into_raw() }; + let px = s.chunks_exact(n + 1); + let color = px.clone().flat_map(|p| p[..n].iter().copied()).collect(); + let alpha = (kind.has_alpha() && px.clone().any(|p| p[n] < u8::MAX)).then(|| px.map(|p| p[n]).collect()); + (color, alpha, BitsPerComponent::Eight) + }; + let raw = Raw { color: Arc::new(color), alpha: alpha.map(Arc::new), width, height, space, bits, icc: icc_for(icc, space) }; + Image::from_custom(raw, interpolate).ok() +} + +/// Image `bytes` decoded within [`limits`], with the ICC profile it carries ([`source_icc`]) when +/// `profiles` allows it (not in PDF/X-1a, which allows no ICC-based color spaces), as +/// [`from_decoded`] writes it. `None` when it can't be decoded. +pub(crate) fn decoded_image(bytes: &[u8], interpolate: bool, sixteen_bit: bool, profiles: bool) -> Option { + from_decoded(decoded(bytes)?, profiles.then(|| source_icc(bytes)).flatten(), interpolate, sixteen_bit) } /// Are all of the RGBA pixels `rgba` grey? @@ -104,26 +167,28 @@ fn lossless( icc: Option<&[u8]>, ) -> Option { let icc = icc.map(|icc| Arc::new(icc.to_vec())); - Image::from_custom(Raw { color: Arc::new(samples), alpha: alpha.map(Arc::new), width, height, space, icc }, interpolate).ok() + let raw = Raw { color: Arc::new(samples), alpha: alpha.map(Arc::new), width, height, space, bits: BitsPerComponent::Eight, icc }; + Image::from_custom(raw, interpolate).ok() } /// Most pixels an image may have to be embedded: twice what the app reads (64 million), so every image /// it holds is still written. pub(crate) const MAX_EMBED_PIXELS: u64 = 1 << 27; -/// The most bytes a CMYK profile carried by an image is written with (16 MiB). +/// The most bytes an ICC profile carried by an image is written with (16 MiB). const MAX_ICC: usize = 16 << 20; /// The CMYK ICC profile image `blob` carries ([`ImageBlob::cmyk_icc_profile`]), when it is one a -/// CMYK image can be tagged with: at most [`MAX_ICC`] bytes, the size its header declares, the -/// `acsp` signature, an input, display, output or colour space profile of CMYK colours, and a tag -/// table whose tags lie within it. `None` for other images and other profiles. +/// CMYK image can be tagged with ([`valid_icc`]). `None` for other images and other profiles. pub(crate) fn cmyk_icc(blob: &ImageBlob) -> Option> { - blob.cmyk_icc_profile().filter(|icc| valid_cmyk_icc(icc)) + blob.cmyk_icc_profile().filter(|icc| valid_icc(icc, *b"CMYK")) } -/// Is `icc` a CMYK profile as [`cmyk_icc`] describes? -fn valid_cmyk_icc(icc: &[u8]) -> bool { +/// Is `icc` a profile an image of colour space `space` (`GRAY`, `RGB ` or `CMYK`) can be tagged +/// with: at most [`MAX_ICC`] bytes, the size its header declares, the `acsp` signature, an input, +/// display, output or colour space profile of `space` colours, and a tag table whose tags lie +/// within it? +pub(crate) fn valid_icc(icc: &[u8], space: [u8; 4]) -> bool { let be = |at: usize| icc.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes); let fits = |at: u32, len: u32| u64::from(at) + u64::from(len) <= icc.len() as u64; if icc.len() > MAX_ICC || be(0).and_then(|n| usize::try_from(n).ok()) != Some(icc.len()) { @@ -131,7 +196,7 @@ fn valid_cmyk_icc(icc: &[u8]) -> bool { } let class = icc.get(12..16); if icc.get(36..40) != Some(b"acsp".as_slice()) - || icc.get(16..20) != Some(b"CMYK".as_slice()) + || icc.get(16..20) != Some(space.as_slice()) || ![b"scnr", b"mntr", b"prtr", b"spac"].iter().any(|c| class == Some(c.as_slice())) { return false; @@ -151,7 +216,7 @@ pub(crate) fn from_rgba_in(mut rgba: Vec, width: u32, height: u32, interpola if let Some(p) = pixels { p.rgb_in_place(&mut rgba); } - from_rgba(&rgba, width, height, interpolate, pixels) + from_rgba(&rgba, width, height, interpolate, pixels, None) } /// A `width` × `height` image of CMYK ink amounts `inks` (four bytes a pixel), converted by @@ -306,9 +371,17 @@ fn resample_channels(img: DynamicImage, r: &Rule, (w, h): (u32, u32)) -> Dynamic /// Encoded image `bytes` placed `size` points wide and high, as the Compression settings `c` ask: /// resampled when its resolution is above the threshold, compressed with ZIP or JPEG, its colours -/// converted by `convert` (colour images). `interpolate` lets viewers smooth it. An image that -/// can't be decoded is kept as it is. -pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, interpolate: bool, convert: Option<&Pixels>) -> Recoded { +/// 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). +/// `interpolate` lets viewers smooth it. An image that can't be decoded is kept as it is. +pub(crate) fn recode( + bytes: &[u8], + size: (f64, f64), + c: &CompressionSettings, + interpolate: bool, + convert: Option<&Pixels>, + profiles: bool, +) -> Recoded { let keep = Recoded { image: None, warning: None }; let Ok(reader) = ImageReader::new(Cursor::new(bytes)).with_guessed_format() else { return keep }; let jpeg = reader.format() == Some(ImageFormat::Jpeg); @@ -337,6 +410,11 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in return Recoded { image: None, warning: rule.instead }; } let Some(img) = pixels.or_else(|| decoded(bytes)) else { return keep }; + // Pixels that keep their colours keep the profile they are in; converted ones are in the + // destination's. + let want = if kind == Kind::Color { *b"RGB " } else { *b"GRAY" }; + let icc = (profiles && convert.is_none()).then(|| source_icc(bytes)).flatten().filter(|icc| valid_icc(icc, want)); + let rgb_icc = icc.is_some() && kind == Kind::Color; let mut rgba = resample(img, &rule, sized(&rule, dims, size)).into_rgba8(); if kind == Kind::Mono { // Resampling greys the edges: back to black and white. @@ -351,16 +429,18 @@ pub(crate) fn recode(bytes: &[u8], size: (f64, f64), c: &CompressionSettings, in let (width, height) = rgba.dimensions(); let opaque = rgba.pixels().all(|p| p[3] == 255); let jpeg = jpeg_quality(&rule, jpeg).filter(|_| opaque).and_then(|q| { - // Grey pixels stay grey; colour ones go to CMYK when the output converts to CMYK. - let grey = kind != Kind::Color || neutral(&rgba); + // Grey pixels stay grey, unless they keep an RGB profile; colour ones go to CMYK when the + // output converts to CMYK. + let grey = kind != Kind::Color || (neutral(&rgba) && !rgb_icc); let (samples, space) = match convert.filter(|_| !grey).and_then(|p| p.cmyk(&rgba)) { Some(cmyk) => (cmyk, ImageColorspace::Cmyk), None if grey => (rgba.pixels().map(|p| p[0]).collect(), ImageColorspace::Luma), None => (rgba.pixels().flat_map(|p| [p[0], p[1], p[2]]).collect(), ImageColorspace::Rgb), }; - to_jpeg(&samples, space, width, height, q, interpolate, None) + let icc = icc_for(icc.clone(), space); + to_jpeg(&samples, space, width, height, q, interpolate, icc.as_deref().map(Vec::as_slice)) }); - let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert)); + let image = jpeg.or_else(|| from_rgba(rgba.as_raw(), width, height, interpolate, convert, icc)); Recoded { image, warning: rule.instead } } @@ -514,7 +594,11 @@ fn to_jpeg(samples: &[u8], space: ImageColorspace, width: u32, height: u32, qual } ImageColorspace::Rgb | ImageColorspace::Luma => { let t = if space == ImageColorspace::Rgb { ExtendedColorType::Rgb8 } else { ExtendedColorType::L8 }; - image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality).encode(samples, width, height, t).ok()?; + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality); + if let Some(icc) = icc { + image::ImageEncoder::set_icc_profile(&mut encoder, icc.to_vec()).ok()?; + } + encoder.encode(samples, width, height, t).ok()?; } ImageColorspace::DeviceN => return None, } diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 076c3c08c9..400bc0b0a8 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -5,7 +5,7 @@ use std::io::Cursor; -use craft_pdf::syntax::object::{Name, Object}; +use craft_pdf::syntax::object::{Array, Name, Object, Stream}; use image::{DynamicImage, ImageFormat}; use serde_json::{Value, json}; use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind}; @@ -266,6 +266,292 @@ fn images_declaring_more_than_the_allowance_are_not_decoded() { assert_eq!(crate::images::mask_alpha(&blob, 60_000, 60_000, false), None); assert_eq!(crate::images::mask_alpha(&blob, 2, 2, false), None, "another size is not decoded at all"); let c: CompressionSettings = serde_json::from_value(json!({"gray": {"downsample": "bicubic", "ppi": 72, "abovePpi": 100}})).unwrap(); - let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None); + let r = crate::images::recode(&png, (10.0, 10.0), &c, false, None, true); assert!(r.image.is_none(), "kept as it is"); } + +/// A version 2.1 display ICC profile for colour space `space` (`RGB ` or `GRAY`), `len` bytes in +/// all, with an empty tag table, every byte after the tag count different from its neighbors. +fn icc_profile(space: &[u8; 4], len: usize) -> Vec { + let mut icc: Vec = (0..len).map(|i| (i % 251) as u8).collect(); + icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes()); + icc[8..12].copy_from_slice(&[2, 0x10, 0, 0]); + icc[12..16].copy_from_slice(b"mntr"); + icc[16..20].copy_from_slice(space); + icc[36..40].copy_from_slice(b"acsp"); + icc[128..132].copy_from_slice(&0u32.to_be_bytes()); + icc +} + +/// `img` encoded as `format` carrying ICC profile `icc`. +fn tagged(img: &DynamicImage, icc: &[u8], format: ImageFormat) -> Vec { + use image::ImageEncoder as _; + let mut out = Vec::new(); + match format { + ImageFormat::Tiff => { + let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out)); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + } + ImageFormat::Jpeg => { + let mut enc = image::codecs::jpeg::JpegEncoder::new(&mut out); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + } + _ => { + let mut enc = image::codecs::png::PngEncoder::new(&mut out); + enc.set_icc_profile(icc.to_vec()).unwrap(); + img.write_with_encoder(enc).unwrap(); + } + } + out +} + +/// An image XObject as it is written. +#[derive(Debug, PartialEq)] +struct Written { + /// Its colour space's name: `ICCBased` for an ICC-based one. + space: String, + /// The profile an ICC-based colour space holds. + icc: Option>, + bits: u8, + filter: String, + smask: bool, +} + +/// Each image XObject of `pdf` other than soft masks. +fn image_spaces(pdf: &[u8]) -> Vec { + let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap(); + let images: Vec> = file + .objects() + .into_iter() + .filter_map(|o| match o { + Object::Stream(s) if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s), + _ => None, + }) + .collect(); + let masks: Vec> = images.iter().filter_map(|s| s.dict().get::>(b"SMask")).map(|m| m.raw_data().to_vec()).collect(); + let mut out = vec![]; + for s in images.iter().filter(|s| !masks.contains(&s.raw_data().to_vec())) { + let d = s.dict(); + let (space, icc) = match (d.get::>(b"ColorSpace"), d.get::>(b"ColorSpace")) { + (Some(n), _) => (n.as_str().to_string(), None), + (_, Some(a)) => { + let mut it = a.flex_iter(); + let name = it.next::>().unwrap().as_str().to_string(); + (name, it.next::>().map(|s| s.decoded().unwrap().into_owned())) + } + _ => (String::new(), None), + }; + let filter = d.get::>(b"Filter").map(|n| n.as_str().to_string()).unwrap_or_default(); + let (bits, smask) = (d.get::(b"BitsPerComponent").unwrap_or(0), d.get::>(b"SMask").is_some()); + out.push(Written { space, icc, bits, filter, smask }); + } + out +} + +/// The decoded samples of each image XObject of `pdf` other than soft masks. +fn image_samples(pdf: &[u8]) -> Vec> { + let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap(); + let images: Vec> = file + .objects() + .into_iter() + .filter_map(|o| match o { + Object::Stream(s) if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s), + _ => None, + }) + .collect(); + let masks: Vec> = images.iter().filter_map(|s| s.dict().get::>(b"SMask")).map(|m| m.raw_data().to_vec()).collect(); + images.iter().filter(|s| !masks.contains(&s.raw_data().to_vec())).map(|s| s.decoded().unwrap().into_owned()).collect() +} + +/// The raw (still encoded) data of each image XObject of `pdf`. +fn image_data(pdf: &[u8]) -> Vec> { + let file = craft_pdf::syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap(); + file.objects() + .into_iter() + .filter_map(|o| match o { + Object::Stream(s) if s.dict().get::>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => Some(s.raw_data().to_vec()), + _ => None, + }) + .collect() +} + +/// A PNG or JPEG embedded as it is whose gray or RGB profile is malformed is written without it, +/// the JPEG with its JPEG data unchanged: a profile whose header declares another size, one without +/// the `acsp` signature, one whose tag table runs past its end, and one cut short after 64 bytes. +#[test] +fn a_malformed_profile_is_left_out_of_a_png_or_jpeg_kept_as_it_is() { + for (space, img, device) in [(b"RGB ", colour(), "DeviceRGB"), (b"GRAY", colour().grayscale(), "DeviceGray")] { + let mut malformed = [icc_profile(space, 600), icc_profile(space, 600), icc_profile(space, 600), icc_profile(space, 600)]; + malformed[0][..4].copy_from_slice(&601u32.to_be_bytes()); + malformed[1][36..40].copy_from_slice(b"xxxx"); + malformed[2][128..132].copy_from_slice(&100u32.to_be_bytes()); + malformed[3].truncate(64); + malformed[3][..4].copy_from_slice(&64u32.to_be_bytes()); + for (i, icc) in malformed.iter().enumerate() { + for (format, mime, filter) in [(ImageFormat::Png, "image/png", "FlateDecode"), (ImageFormat::Jpeg, "image/jpeg", "DCTDecode")] { + let what = format!("{device}, {format:?}, malformed profile {i}"); + let bytes = tagged(&img, icc, format); + let mut settings = PdfSettings::default(); + settings.compression.compress_text = false; + let pdf = export_with_report(&doc(bytes.clone(), mime), &PdfOptions { settings, ..Default::default() }).unwrap().bytes; + let spaces = image_spaces(&pdf); + let plain = spaces.len() == 1 && spaces[0].space == device && spaces[0].icc.is_none() && spaces[0].filter == filter; + assert!(plain, "{what}: {spaces:?}"); + if format == ImageFormat::Jpeg { + assert!(image_data(&pdf) == [bytes], "{what}: the JPEG data unchanged"); + } + } + } + } +} + +/// In PDF/X-1a a tagged gray JPEG kept as JPEG is written with its JPEG data, without its profile. +#[test] +fn pdf_x1a_keeps_a_tagged_gray_jpeg_as_jpeg() { + let jpeg = tagged(&colour().grayscale(), &icc_profile(b"GRAY", 300), ImageFormat::Jpeg); + let d = doc(jpeg.clone(), "image/jpeg"); + for compression in [json!({}), json!({"gray": {"compression": "jpeg"}})] { + let mut settings: PdfSettings = + serde_json::from_value(json!({"standard": "pdfX1a", "compatibility": "1.3", "compression": compression.clone()})).unwrap(); + settings.compression.compress_text = false; + let bytes = export_with_report(&d, &PdfOptions { settings, ..Default::default() }).unwrap().bytes; + crate::pdfx::verify(&bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("{compression}: {e}")); + let spaces = image_spaces(&bytes); + let dct = spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none() && spaces[0].filter == "DCTDecode"; + assert!(dct, "{compression}: {spaces:?}"); + assert!(image_data(&bytes) == [jpeg.clone()], "{compression}: the JPEG data unchanged"); + } +} + +/// A gray or RGB TIFF that carries an ICC profile of its colour space is written in an ICC-based +/// colour space holding the same profile, at 16 bits a sample from PDF 1.5 on, with its alpha as +/// a soft mask; and so is a tagged TIFF or PNG that is resampled or compressed with JPEG. Pixels +/// the Output settings convert, and a profile of another colour space, are written without it. +#[test] +fn tagged_tiffs_keep_their_icc_profile() { + let (rgb, gray) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300)); + let mut clear = colour().to_rgba8(); + clear.put_pixel(0, 0, image::Rgba([10, 20, 30, 0])); + let tiff = |img: &DynamicImage, icc: &[u8]| doc(tagged(img, icc, ImageFormat::Tiff), "image/tiff"); + let export = |d: &Document, settings: Value| { + let mut settings: PdfSettings = serde_json::from_value(settings).unwrap(); + settings.compression.compress_text = false; + let r = export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap(); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + image_spaces(&r.bytes) + }; + let icc_based = |icc: &[u8], bits: u8, filter: &str, smask: bool| { + vec![Written { space: "ICCBased".into(), icc: Some(icc.to_vec()), bits, filter: filter.into(), smask }] + }; + let flate = "FlateDecode"; + let cases = [ + ("RGB", tiff(&colour(), &rgb), json!({}), icc_based(&rgb, 8, flate, false)), + ("gray", tiff(&colour().grayscale(), &gray), json!({}), icc_based(&gray, 8, flate, false)), + ( + "RGB, 16 bits", + tiff(&DynamicImage::ImageRgb16(colour().to_rgb16()), &rgb), + json!({"compatibility": "1.7"}), + icc_based(&rgb, 16, flate, false), + ), + ( + "RGB, 16 bits, PDF 1.4", + tiff(&DynamicImage::ImageRgb16(colour().to_rgb16()), &rgb), + json!({"compatibility": "1.4"}), + icc_based(&rgb, 8, flate, false), + ), + ("RGBA", tiff(&clear.clone().into(), &rgb), json!({}), icc_based(&rgb, 8, flate, true)), + ( + "RGB, resampled", + tiff(&colour(), &rgb), + json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}), + icc_based(&rgb, 8, flate, false), + ), + ( + "gray, resampled", + tiff(&colour().grayscale(), &gray), + json!({"compression": {"gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}), + icc_based(&gray, 8, flate, false), + ), + ("RGB, JPEG", tiff(&colour(), &rgb), json!({"compression": {"color": {"compression": "jpeg"}}}), icc_based(&rgb, 8, "DCTDecode", false)), + ( + "gray, JPEG", + tiff(&colour().grayscale(), &gray), + json!({"compression": {"gray": {"compression": "jpeg"}}}), + icc_based(&gray, 8, "DCTDecode", false), + ), + ( + "PNG, resampled", + doc(tagged(&colour(), &rgb, ImageFormat::Png), "image/png"), + json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}}), + icc_based(&rgb, 8, flate, false), + ), + ]; + for (what, d, settings, want) in cases { + assert_eq!(export(&d, settings), want, "{what}"); + } + // 16-bit samples are written big-endian from PDF 1.5 on, and reduced to 8 bits before it. + // Their high and low bytes differ, so a swapped or truncated stream does not match. + let deep = DynamicImage::ImageRgb16(image::ImageBuffer::from_fn(600, 600, |x, y| { + image::Rgb([((x * 109 + y) % 65_521) as u16, ((y * 257 + 3) ^ 0x5a) as u16, ((x * y) % 65_521) as u16]) + })); + let sixteen: Vec = deep.to_rgb16().iter().flat_map(|v| v.to_be_bytes()).collect(); + for (compatibility, want) in [("1.7", sixteen), ("1.4", deep.to_rgb8().into_raw())] { + let mut settings: PdfSettings = serde_json::from_value(json!({ "compatibility": compatibility })).unwrap(); + settings.compression.compress_text = false; + let r = export_with_report(&tiff(&deep, &rgb), &PdfOptions { settings, ..Default::default() }).unwrap(); + assert!(image_samples(&r.bytes) == [want], "16-bit samples, PDF {compatibility}"); + } + // A gray image in an RGB profile stays RGB to keep it, resampled too. + let neutral = tiff(&DynamicImage::ImageRgb8(colour().grayscale().to_rgb8()), &rgb); + for settings in [json!({}), json!({"compression": {"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}})] { + assert_eq!(export(&neutral, settings.clone()), icc_based(&rgb, 8, flate, false), "neutral RGB, {settings}"); + } + // A profile of another colour space is left out. + let spaces = export(&tiff(&colour(), &gray), json!({})); + assert!(spaces.len() == 1 && spaces[0].space == "DeviceRGB" && spaces[0].icc.is_none(), "RGB in a gray profile: {spaces:?}"); + // A malformed profile is left out, the image kept as it is, resampled or compressed with JPEG: + // one whose header declares another size, one without the `acsp` signature, and one whose tag + // table runs past its end. + let mut malformed = [rgb.clone(), rgb.clone(), rgb.clone()]; + malformed[0][..4].copy_from_slice(&601u32.to_be_bytes()); + malformed[1][36..40].copy_from_slice(b"xxxx"); + malformed[2][128..132].copy_from_slice(&100u32.to_be_bytes()); + let compressions = + [json!({}), json!({"color": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}), json!({"color": {"compression": "jpeg"}})]; + for (i, icc) in malformed.iter().enumerate() { + for compression in &compressions { + let spaces = export(&tiff(&colour(), icc), json!({ "compression": compression })); + assert!( + spaces.len() == 1 && spaces[0].space == "DeviceRGB" && spaces[0].icc.is_none(), + "malformed profile {i}, {compression}: {spaces:?}" + ); + } + } + // Converted pixels are in the destination's colours, not the image's profile. + for destination in [vectorcraft_color::cms::DISPLAY_P3, vectorcraft_color::cms::GENERIC_CMYK] { + let spaces = export(&tiff(&colour(), &rgb), json!({"output": {"conversion": "destination", "destination": destination}})); + assert!(spaces.len() == 1 && spaces[0].icc.as_deref() != Some(rgb.as_slice()), "converted to {destination}: {spaces:?}"); + } + // PDF/X-1a allows no ICC-based color spaces: a tagged gray TIFF (8 or 16 bits), PNG or JPEG is + // written in DeviceGray, kept as it is, resampled or compressed with JPEG, and the file passes + // the PDF/X-1a check. + let compressions = [json!({}), json!({"gray": {"downsample": "bicubic", "ppi": 150, "abovePpi": 225}}), json!({"gray": {"compression": "jpeg"}})]; + let tiff16 = tiff(&DynamicImage::ImageLuma16(colour().to_luma16()), &gray); + let png = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Png), "image/png"); + let jpeg = doc(tagged(&colour().grayscale(), &gray, ImageFormat::Jpeg), "image/jpeg"); + for (format, d) in [("TIFF", tiff(&colour().grayscale(), &gray)), ("TIFF, 16 bits", tiff16), ("PNG", png), ("JPEG", jpeg)] { + for compression in &compressions { + let mut settings: PdfSettings = + serde_json::from_value(json!({"standard": "pdfX1a", "compatibility": "1.3", "compression": compression.clone()})).unwrap(); + settings.compression.compress_text = false; + let r = export_with_report(&d, &PdfOptions { settings, ..Default::default() }); + let bytes = r.unwrap_or_else(|e| panic!("PDF/X-1a, {format}, {compression}: {e}")).bytes; + crate::pdfx::verify(&bytes, Standard::PdfX1a).unwrap_or_else(|e| panic!("PDF/X-1a, {format}, {compression}: {e}")); + let spaces = image_spaces(&bytes); + let gray = spaces.len() == 1 && spaces[0].space == "DeviceGray" && spaces[0].icc.is_none(); + assert!(gray, "PDF/X-1a, {format}, {compression}: {spaces:?}"); + } + } +} diff --git a/crates/render/src/encode/png.rs b/crates/render/src/encode/png.rs index 6a62034e10..d393e23fa7 100644 --- a/crates/render/src/encode/png.rs +++ b/crates/render/src/encode/png.rs @@ -28,16 +28,12 @@ const ADAM7: [(u32, u32, u32, u32); 7] = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, /// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores). pub fn pixels_per_metre(ppi: f64) -> u32 { - (ppi / 0.0254).round().clamp(1.0, u32::MAX as f64) as u32 + vectorcraft_doc::ppi::pixels_per_metre(ppi) } /// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch. pub fn phys_chunk(x: f64, y: f64) -> Vec { - let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes()); - let mut out = Vec::with_capacity(21); - // x, y, unit 1 = metre. - chunk(&mut out, b"pHYs", &[x.as_slice(), y.as_slice(), &[1]].concat()); - out + vectorcraft_doc::ppi::phys_chunk(x, y) } /// Encode straight-alpha RGBA8 pixels (`width`×`height`, row-major) as a PNG file. diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 087512bf90..c17f689922 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -43,6 +43,7 @@ pub(super) use prepass::Edits; use prepass::{Extras, labels, prepass}; pub use prepass::{MAX_FOREIGN, MAX_FOREIGN_VALUE}; +mod budget; mod css; mod css_transform; mod depth; @@ -136,10 +137,14 @@ pub(crate) fn import_finding( return Err(too_deep()); } let xml = parse(svg)?; + // Before the style cascade of `depth::height` and the prepass, which keeps the declarations of + // each element it reads; measured again below on the text usvg reads when that differs. + let styles = budget::check(&xml, budget::MAX_COPIED_STYLES, depth::MAX_ELEMENT_DEPTH)?; let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; let (svg, found) = prepass(svg, &scan.markers, &xml, opts)?; + let rewritten = matches!(svg, Cow::Owned(_)); // The prepass's edits are in the text: the XML is read again only when it made any. let xml = match &svg { Cow::Borrowed(_) => xml, @@ -154,7 +159,14 @@ pub(crate) fn import_finding( let mut warnings = found.warnings; let text_xml = found.text_source.as_deref().map(parse).transpose()?; let (src, slots) = text::prepare(svg, &xml, text_xml.as_ref(), units.dpi, &mut warnings); + // Before usvg copies what ``s show and the style values of each copy: the text usvg reads. + let styles = match &src { + Cow::Borrowed(_) if !rewritten => styles, + Cow::Borrowed(_) => budget::check(&xml, budget::MAX_COPIED_STYLES, usize::MAX)?, + Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::MAX_COPIED_STYLES, usize::MAX)?, + }; let files = found.files; + files.copied_styles(styles); let tree = { let opt = usvg::Options { dpi: units.dpi as f32, @@ -164,6 +176,9 @@ pub(crate) fn import_finding( }; usvg::Tree::from_str(&src, &opt).map_err(|e| SvgError::Parse(e.to_string()))? }; + if let Some(err) = files.refused() { + return Err(err); + } let size = tree.size(); let k = units.k; let mut doc = Document::new(size.width() as f64 * k, size.height() as f64 * k); diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs new file mode 100644 index 0000000000..ec4de17eca --- /dev/null +++ b/crates/svg/src/import/budget.rs @@ -0,0 +1,502 @@ +//! What usvg makes of an SVG, measured in the XML before usvg runs: how many elements it makes, +//! and how many bytes of style values it copies into them. +//! +//! usvg makes an element of each SVG element, and of each element a `` shows a copy of, by +//! copying what the `` refers to. Each copy gets its own copy of every declaration the style +//! sheets and the `style` attribute give the element, so a long style on an element that ``s +//! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more +//! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after +//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or +//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead. +//! +//! The copies are counted, never made: each element's count is worked out once and added up, so a +//! `` of an element costs one addition, however many elements its copy holds. References +//! follow usvg 0.48.1 (`parser/svgtree/parse.rs`): an id names the first element that has it, an +//! unprefixed `href` wins over `xlink:href`, and a `` of itself, of the `` its own copy +//! starts from, or of an element holding a `` of the element or of the ``, is left out. +//! Any other loop of references makes usvg copy without end, so an SVG with one is refused. usvg +//! looks for those ``s inside an element only in the SVG namespace: in an SVG without one, a +//! `` that leads back to the `` its copy starts from is refused here too, though usvg +//! would leave it out. +//! +//! The style sheets' rules are matched against each element once, as usvg matches them against +//! each copy. + +use std::collections::{HashMap, HashSet}; + +use usvg::roxmltree; + +use super::{MAX_NODES, SVG_NS, XNode}; +use crate::{MAX_ELEMENT_DEPTH, SvgError}; + +/// Most elements usvg may make of an SVG: [`MAX_NODES`], and below the 1,000,000 elements past +/// which usvg stops (its count includes a root of its own). +pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 }; + +/// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it +/// shows, all together: VectorCraft's own limit. +pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20; + +/// What usvg keeps for each value it copies besides its bytes (the count and length of a shared +/// string). +const COPY: u64 = 16; + +/// The longhands a `font` shorthand resets before setting the ones it gives, and the most bytes of +/// each reset value (`normal`). +const FONT_RESETS: u64 = 12; +const RESET_VALUE: u64 = 6; + +/// The longhands a `font` shorthand sets from its own text. +const FONT_PARTS: u64 = 6; + +const XLINK_NS: &str = "http://www.w3.org/1999/xlink"; + +/// The elements usvg reads (`EId` in usvg's `parser/svgtree/names.rs`); it skips the others with +/// everything inside them. +const ELEMENTS: [&str; 53] = [ + "a", + "circle", + "clipPath", + "defs", + "ellipse", + "feBlend", + "feColorMatrix", + "feComponentTransfer", + "feComposite", + "feConvolveMatrix", + "feDiffuseLighting", + "feDisplacementMap", + "feDistantLight", + "feDropShadow", + "feFlood", + "feFuncA", + "feFuncB", + "feFuncG", + "feFuncR", + "feGaussianBlur", + "feImage", + "feMerge", + "feMergeNode", + "feMorphology", + "feOffset", + "fePointLight", + "feSpecularLighting", + "feSpotLight", + "feTile", + "feTurbulence", + "filter", + "g", + "image", + "line", + "linearGradient", + "marker", + "mask", + "path", + "pattern", + "polygon", + "polyline", + "radialGradient", + "rect", + "stop", + "style", + "svg", + "switch", + "symbol", + "text", + "textPath", + "tref", + "tspan", + "use", +]; + +/// The name of element `n` when usvg reads it: in the SVG namespace or none, and one of +/// [`ELEMENTS`]. +fn svg_name<'a>(n: XNode<'a, '_>) -> Option<&'a str> { + let name = n.tag_name(); + (n.is_element() && matches!(name.namespace(), None | Some(SVG_NS)) && ELEMENTS.contains(&name.name())).then(|| name.name()) +} + +/// An element as the style sheets' selectors see it, as usvg matches them. +struct Element<'a, 'i>(XNode<'a, 'i>); + +impl simplecss::Element for Element<'_, '_> { + fn parent_element(&self) -> Option { + self.0.parent_element().map(Self) + } + + fn prev_sibling_element(&self) -> Option { + self.0.prev_sibling_element().map(Self) + } + + fn has_local_name(&self, name: &str) -> bool { + self.0.tag_name().name() == name + } + + fn attribute_matches(&self, name: &str, operator: simplecss::AttributeOperator<'_>) -> bool { + self.0.attribute(name).is_some_and(|value| operator.matches(value)) + } + + fn pseudo_class_matches(&self, class: simplecss::PseudoClass<'_>) -> bool { + matches!(class, simplecss::PseudoClass::FirstChild) && self.0.prev_sibling_element().is_none() + } +} + +/// The bytes usvg copies for one declaration: three markers for `marker`, the resets and longhands +/// for `font`, its value for any other. Counted for every declaration, the ones usvg then drops (a +/// property it doesn't read, a value an earlier one overrides) too. +fn copied(declaration: &simplecss::Declaration) -> u64 { + let len = declaration.value.len() as u64; + match declaration.name { + "marker" => 3 * (COPY + len), + "font" => (FONT_RESETS + FONT_PARTS) * COPY + FONT_RESETS * RESET_VALUE + len, + _ => COPY + len, + } +} + +/// What usvg makes of one element: elements (text nodes included) and bytes of copied styles. +#[derive(Clone, Copy, Default)] +struct Cost { + elements: u64, + bytes: u64, +} + +impl Cost { + fn add(self, other: Cost) -> Cost { + Cost { elements: self.elements.saturating_add(other.elements), bytes: self.bytes.saturating_add(other.bytes) } + } +} + +/// What a `` shows: nothing, the element it refers to with all it holds, or only that +/// element (a `` whose own reference leads back to the `` showing it). +enum Shows<'a, 'i> { + Nothing, + All(XNode<'a, 'i>), + Bare(XNode<'a, 'i>), +} + +struct Measure<'a, 'i> { + /// The first element of each id. + ids: HashMap<&'a str, XNode<'a, 'i>>, + sheet: simplecss::StyleSheet<'a>, + /// The elements that hold a `` of themselves. + holds_use_of_itself: HashSet, + /// The ``s of each element, by the element. + used_by: HashMap>>, + /// The bytes of text in each element a `` shows. + tref_text: HashMap, +} + +impl<'a, 'i> Measure<'a, 'i> { + fn new(xml: &'a roxmltree::Document<'i>) -> Self { + let mut ids = HashMap::new(); + for n in xml.descendants() { + if let Some(id) = n.attribute("id") { + ids.entry(id).or_insert(n); + } + } + // The style sheets usvg reads: `{groups}"))); + assert_eq!(bytes, 4 * 19 + 20); + // A style sheet of another type is not read; the style element itself makes nothing. + assert_eq!(cost(&svg(&format!("{groups}"))), (5, 0)); + // `marker` sets three properties; `font` resets twelve and sets six from its text. + let (_, marker) = cost(&svg("")); + let (_, font) = cost(&svg("")); + assert_eq!((marker, font), (3 * (16 + 7), 18 * 16 + 12 * 6 + 6)); + } + + #[test] + fn references_usvg_leaves_out_copy_nothing() { + // A use of itself, of a group holding it, of what isn't there or isn't SVG. + let (n, _) = cost(&svg("")); + assert_eq!(n, 1 + 1 + 3 + 1 + 1); + // Two uses of each other: each shows the other alone. + assert_eq!(cost(&svg("")).0, 1 + 2 + 2); + // A group holding a use of the use that shows it: that use shows nothing, and the one the + // group holds shows it alone. + let back = svg(""); + assert_eq!(cost(&back).0, 1 + 3 + 1); + // The unprefixed href wins, and an id names its first element. + let first = svg(""); + assert_eq!(cost(&first).0, 1 + 3 + 1 + 1 + 2 + 4); + } + + #[test] + fn a_loop_usvg_copies_without_end_is_refused_as_usvg_refuses_it() { + let looped = svg(""); + assert_eq!(past(&looped, u64::MAX, u64::MAX), Some(Past::Depth)); + assert!(usvg::Tree::from_str(&looped, &usvg::Options::default()).is_err()); + // Without the loop, usvg reads it. + let open = svg(""); + assert!(past(&open, u64::MAX, u64::MAX).is_none() && usvg::Tree::from_str(&open, &usvg::Options::default()).is_ok()); + } + + /// A chain of ``s nested past the depth is too deep, as `depth::height` finds it, before + /// what the chain makes is added up; one within the depth `depth::height` gives is not. + #[test] + fn copies_nested_past_the_depth_are_too_deep() { + let links: String = (0..3000).map(|i| format!("", i + 1)).collect(); + let deep = svg(&format!("{links}")); + let xml = roxmltree::Document::parse(&deep).unwrap(); + assert_eq!(measure(&xml, u64::MAX, u64::MAX, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth)); + assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none()); + assert!(matches!(check(&xml, MAX_COPIED_STYLES, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); + for text in [chain(5, ""), svg("")] { + let xml = roxmltree::Document::parse(&text).unwrap(); + let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0); + assert!(measure(&xml, u64::MAX, u64::MAX, height).is_ok(), "{height} {text}"); + } + } + + #[test] + fn text_counts_its_runs_and_what_trefs_show() { + let (n, bytes) = cost(&svg("abcdxyz")); + // svg, g (its text is not counted outside a text), text, its runs "xy" and "z", tspan, tref and its text. + assert_eq!(n, 1 + 1 + 1 + 2 + 1 + 1 + 1); + assert_eq!(bytes, (16 + 2) + (16 + 1) + (16 + 4)); + } + + /// A long style sheet rule that matches many elements is refused before the import's own style + /// cascade (which keeps the declarations of each element) reads them, in an SVG and in an SVG + /// image it shows. + #[test] + fn a_long_rule_on_many_elements_is_refused_before_the_cascade_reads_it() { + let groups = svg(&format!("{}", "a".repeat(100_000), "".repeat(1000))); + let image = svg(&format!(r#""#, crate::base64_encode(groups.as_bytes()))); + for text in [groups, image] { + let before = super::super::css::selector_tests(); + let err = super::super::import(&text, &crate::ImportOptions::default(), MAX_NODES).err(); + assert!(matches!(err, Some(SvgError::StylesTooLarge(64))), "{err:?}"); + assert_eq!(super::super::css::selector_tests(), before); + } + } +} diff --git a/crates/svg/src/import/css.rs b/crates/svg/src/import/css.rs index fd864a547e..7ddfb1bbd5 100644 --- a/crates/svg/src/import/css.rs +++ b/crates/svg/src/import/css.rs @@ -129,7 +129,7 @@ thread_local! { /// [`SELECTOR_TESTS`] of this thread. #[cfg(test)] -fn selector_tests() -> u64 { +pub(super) fn selector_tests() -> u64 { SELECTOR_TESTS.get() } diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index d2b5504f9d..691ea950f1 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -21,7 +21,7 @@ use usvg::{ImageHrefResolver, ImageKind, roxmltree}; use vectorcraft_doc::LinkInfo; use vectorcraft_doc::links::missing_placeholder; -use super::{Edits, depth, href}; +use super::{Edits, budget, depth, href}; use crate::{ImportOptions, MAX_ELEMENT_DEPTH, MAX_SVGZ, SvgError}; /// Most nested SVG images an imported SVG may decode (#3564). @@ -74,6 +74,12 @@ pub(in crate::import) struct Files { /// The CMYK TIFF stored in place of a turned CMYK image, by the address of the PNG usvg got /// (kept here too, so the address stays its own). cmyk: Mutex>, + /// The bytes of style values usvg copies into the elements of the SVG and of the SVG images + /// read so far ([`budget`]). + styles: AtomicU64, + /// Why an SVG image refused the whole SVG: what usvg would make of it is past [`budget`]'s + /// limits. The first one. + refused: Mutex>, } /// Encoded image bytes, shared. @@ -479,6 +485,17 @@ impl Files { notes } + /// The SVG holding the images copies `bytes` of style values ([`budget::check`]): its images + /// copy at most what is left. + pub(in crate::import) fn copied_styles(&self, bytes: u64) { + self.styles.store(bytes, Ordering::Relaxed); + } + + /// The error of the first SVG image past [`budget`]'s limits, which refuses the SVG holding it. + pub(in crate::import) fn refused(&self) -> Option { + self.refused.lock().ok().and_then(|r| r.clone()) + } + fn note_text(&self, svg: &str) { if svg.contains(">, opts: &usvg::Options) -> Option { + // The SVG holding it is refused already: no more images are read. + if self.refused().is_some() { + return None; + } // Measured as the SVG holding it is (`import`): the text before the XML reader. let used = self.depth.load(Ordering::Relaxed); let left = MAX_ELEMENT_DEPTH.saturating_sub(used); @@ -566,9 +587,25 @@ impl Files { return leave_out(&self.too_deep, true); } let xml = super::parse(text).ok()?; + // What usvg would make of it, measured as the SVG holding it is (`import`), before the + // style cascade of `depth::height`; its copied styles count with theirs while usvg reads + // it, and only when it decodes. Too deep, it is left out; past the other limits, the whole + // SVG is refused. + let spent = self.styles.load(Ordering::Relaxed); + let bytes = match budget::check(&xml, budget::MAX_COPIED_STYLES.saturating_sub(spent), left) { + Ok(bytes) => bytes, + Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true), + Err(e) => { + if let Ok(mut refused) = self.refused.lock() { + refused.get_or_insert(e); + } + return None; + } + }; let Some(height) = depth::height(&xml, left) else { return leave_out(&self.too_deep, true) }; // usvg's parser would overflow on it, as on the SVG holding it (`import`). super::convolve_matrices_ok(&xml).ok()?; + self.styles.store(spent.saturating_add(bytes), Ordering::Relaxed); self.depth.store(used + height, Ordering::Relaxed); let within = self.within.lock().ok().map(|mut w| w.push(file)).is_some(); // usvg's `Tree::from_data_nested`, except that hrefs to files go to the resolver. @@ -592,7 +629,11 @@ impl Files { w.pop(); } self.depth.store(used, Ordering::Relaxed); - let tree = tree.ok()?; + let Ok(tree) = tree else { + // Left out: neither it nor the images inside it count. + self.styles.store(spent, Ordering::Relaxed); + return None; + }; self.note_text(text); Some(ImageKind::SVG(tree)) } @@ -615,10 +656,11 @@ fn raster(format: image::ImageFormat) -> Option { /// orientation ([`vectorcraft_doc::cmyk::exif_orientation`], read for PNG, JPEG, GIF, WebP and /// TIFF) leaves the pixels as stored. Otherwise the pixels are read ([`decoded`], /// [`tiff_pixels`]), turned or flipped as the orientation says, and written as PNG, so usvg sizes -/// and fits the image as it is shown. A CMYK TIFF also keeps its inks as a CMYK TIFF -/// ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG or TIFF that is turned keeps them -/// turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when the pixels can't be read, and for -/// a TIFF with more strips or tiles than the decoder can count +/// and fits the image as it is shown, with the resolution the file declares +/// ([`vectorcraft_doc::ppi::resolution`]), its axes swapped by a quarter turn. A CMYK TIFF also +/// keeps its inks as a CMYK TIFF ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]), and a CMYK JPEG +/// or TIFF that is turned keeps them turned ([`vectorcraft_doc::cmyk::turned_cmyk`]). `None` when +/// the pixels can't be read, and for a TIFF with more strips or tiles than the decoder can count /// ([`vectorcraft_doc::cmyk::oversized_tiff`]), before any decoder opens it. fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { use image::ImageFormat as F; @@ -634,9 +676,13 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { } let tiff = image::guess_format(&bytes).ok() == Some(F::Tiff); let mut img = if tiff { tiff_pixels(&bytes)? } else { decoded(&bytes, format)? }; + let ppi = vectorcraft_doc::ppi::resolution(&bytes); + // The resolution describes the stored pixels; a quarter turn swaps its axes. + let quarter = orientation.is_some_and(|o| o.to_exif() >= 5); + let shown_ppi = ppi.map(|(x, y)| if quarter { (y, x) } else { (x, y) }); let cmyk = match orientation { - Some(o) if matches!(format, F::Jpeg | F::Tiff) => vectorcraft_doc::cmyk::turned_cmyk(&bytes, o, None).map(|(tiff, _)| tiff), - None if tiff => vectorcraft_doc::cmyk::stored_cmyk_tiff(&bytes, None), + Some(o) if matches!(format, F::Jpeg | F::Tiff) => vectorcraft_doc::cmyk::turned_cmyk(&bytes, o, shown_ppi).map(|(tiff, _)| tiff), + None if tiff => vectorcraft_doc::cmyk::stored_cmyk_tiff(&bytes, ppi), _ => None, }; if let Some(orientation) = orientation { @@ -644,6 +690,9 @@ fn shown(bytes: Arc>, format: image::ImageFormat) -> Option { } let mut png = Vec::new(); img.write_to(&mut std::io::Cursor::new(&mut png), F::Png).ok()?; + if let Some(ppi) = shown_ppi { + png = vectorcraft_doc::ppi::with_png_resolution(&png, ppi); + } Some(Shown { kind: ImageKind::PNG, bytes: Arc::new(png), cmyk }) } diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index b035e6cd10..daf3288920 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -366,6 +366,10 @@ pub enum SvgError { /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} nested SVG images")] TooManyImages(usize), + /// The style values the reader would copy into the elements the SVG expands to, `` + /// copies and SVG images included, add up to more than this many megabytes. + #[error("the SVG's styles expand to more than {0} MB")] + StylesTooLarge(usize), } /// Export a document as an SVG string (linked images are not returned: see [`export_full`]). diff --git a/crates/svg/tests/it/image_orientation.rs b/crates/svg/tests/it/image_orientation.rs index 549a40a3bf..d9de61290b 100644 --- a/crates/svg/tests/it/image_orientation.rs +++ b/crates/svg/tests/it/image_orientation.rs @@ -69,13 +69,21 @@ fn jpeg(orientation: Option) -> Vec { /// an Orientation tag (274) of `orientation`. Its RowsPerStrip (278) value is at byte [`ROWS_AT`] /// and its PlanarConfiguration (284, 1) value at [`PLANAR_AT`]. fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec { - let entries: u32 = if samples == 2 { 12 } else { 11 }; + tiff_at(w, h, samples, data, orientation, None) +} + +/// [`tiff`], declaring `ppi` (horizontal, vertical pixels per inch) when given, with XResolution +/// (282), YResolution (283) and ResolutionUnit (296, inches). +fn tiff_at(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16, ppi: Option<(u32, u32)>) -> Vec { + let entries = 11 + u32::from(samples == 2) + 3 * u32::from(ppi.is_some()); let ifd_end = 8 + 2 + entries * 12 + 4; let bits_at = ifd_end; - let data_at = bits_at + if samples > 2 { 2 * u32::from(samples) } else { 0 }; + let ppi_at = bits_at + if samples > 2 { 2 * u32::from(samples) } else { 0 }; + let data_at = ppi_at + if ppi.is_some() { 16 } else { 0 }; let entry = |tag: u16, kind: u16, count: u32, value: u32| { [&tag.to_le_bytes()[..], &kind.to_le_bytes(), &count.to_le_bytes(), &value.to_le_bytes()].concat() }; + let resolution = |tags: [(u16, u16, u32); 2]| ppi.map(|_| tags.map(|(tag, kind, value)| entry(tag, kind, 1, value))).into_iter().flatten(); // Two SHORTs fit in the entry; more are written after the directory. let bits = match samples { 1 => 8, @@ -97,9 +105,11 @@ fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec entry(277, 3, 1, u32::from(samples)), entry(278, 4, 1, h), entry(279, 4, 1, u32::try_from(data.len()).unwrap()), - entry(284, 3, 1, 1), ] .into_iter() + .chain(resolution([(282, 5, ppi_at), (283, 5, ppi_at + 8)])) + .chain([entry(284, 3, 1, 1)]) + .chain(ppi.map(|_| entry(296, 3, 1, 2))) .chain(extra) { out.extend(e); @@ -110,6 +120,11 @@ fn tiff(w: u32, h: u32, samples: u16, data: &[u8], orientation: u16) -> Vec out.extend(8u16.to_le_bytes()); } } + if let Some((x, y)) = ppi { + for v in [x, 1, y, 1] { + out.extend(v.to_le_bytes()); + } + } assert_eq!(out.len(), data_at as usize); out.extend(data); out @@ -277,6 +292,76 @@ fn a_turned_jpeg_in_an_svg_image_imports_upright() { assert!(red(px.get_pixel(4, 3)) && !red(px.get_pixel(4, 12))); } +/// [`jpeg`] with its JFIF segment declaring `x` × `y` pixels per inch. +fn jpeg_at(orientation: Option, (x, y): (u16, u16)) -> Vec { + let mut jpg = jpeg(orientation); + let jfif = jpg.windows(5).position(|w| w == b"JFIF\0").unwrap(); + jpg[jfif + 7] = 1; + jpg[jfif + 8..jfif + 10].copy_from_slice(&x.to_be_bytes()); + jpg[jfif + 10..jfif + 12].copy_from_slice(&y.to_be_bytes()); + jpg +} + +/// The resolution the stored image of `im` declares. +fn stored_ppi(d: &Document, im: &ImageObject) -> Option<(f64, f64)> { + vectorcraft_doc::ppi::resolution(&d.images[&im.key].bytes) +} + +/// A raster that import writes again as PNG keeps the resolution its file declares, linked, as a +/// data URL and inside an SVG shown as an image: its axes swapped when the image turns a quarter, +/// in their order when it turns a half or is flipped. +#[test] +fn a_turned_raster_keeps_its_resolution() { + let dir = folder("ppi"); + for (orientation, ppi) in [(6, (150.0, 300.0)), (8, (150.0, 300.0)), (3, (300.0, 150.0)), (2, (300.0, 150.0))] { + let jpg = jpeg_at(Some(orientation), (300, 150)); + std::fs::write(dir.join("photo.jpg"), &jpg).unwrap(); + let data = format!("data:image/jpeg;base64,{}", base64_encode(&jpg)); + let inner = format!(r#""#); + let nested = format!("data:image/svg+xml;base64,{}", base64_encode(inner.as_bytes())); + for href in ["photo.jpg", data.as_str(), nested.as_str()] { + let (d, im) = import_one(&format!(r#""#), Some(&dir)); + let what = format!("orientation {orientation}, {}", &href[..href.len().min(20)]); + assert_eq!(d.images[&im.key].mime, "image/png", "{what}"); + assert_eq!(stored_ppi(&d, &im), Some(ppi), "{what}"); + } + } + let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 1, &[0, 0, 255, 255, 0, 0, 255, 255], 6, Some((300, 150))))); + let (d, im) = import_one(&format!(r#""#), None); + assert_eq!((im.width, im.height), (2, 4)); + assert_eq!(stored_ppi(&d, &im), Some((150.0, 300.0)), "a turned TIFF"); +} + +/// A TIFF that is not turned is written as PNG with the resolution it declares; a raster that +/// declares none is stored without one. +#[test] +fn an_upright_tiff_keeps_its_resolution() { + let gray = [0, 0, 255, 255, 0, 0, 255, 255]; + let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 1, &gray, 1, Some((300, 150))))); + let (d, im) = import_one(&format!(r#""#), None); + assert_eq!(d.images[&im.key].mime, "image/png"); + assert_eq!(stored_ppi(&d, &im), Some((300.0, 150.0))); + for bytes in [tiff(4, 2, 1, &gray, 1), jpeg(Some(6))] { + let href = format!("data:;base64,{}", base64_encode(&bytes)); + let (d, im) = import_one(&format!(r#""#), None); + assert_eq!(stored_ppi(&d, &im), None, "no resolution is made up"); + } +} + +/// A CMYK TIFF stored with its inks keeps its resolution, swapped when it turns a quarter. +#[test] +fn a_cmyk_tiff_keeps_its_resolution_turned_or_not() { + let (c, none) = ([255u8, 0, 0, 0], [0u8; 4]); + let data: Vec = [c, c, none, none, c, c, none, none].concat(); + for (orientation, ppi) in [(1, (300.0, 150.0)), (6, (150.0, 300.0))] { + let href = format!("data:image/tiff;base64,{}", base64_encode(&tiff_at(4, 2, 4, &data, orientation, Some((300, 150))))); + let (d, im) = import_one(&format!(r#""#), None); + assert_eq!(d.images[&im.key].mime, "image/tiff", "orientation {orientation}"); + assert!(d.images[&im.key].cmyk().is_some(), "orientation {orientation}: CMYK inks"); + assert_eq!(stored_ppi(&d, &im), Some(ppi), "orientation {orientation}"); + } +} + /// A turned JPEG that a linked SVG file links to is turned too. #[test] fn a_turned_jpeg_linked_from_a_linked_svg_file_imports_upright() { diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 69e5cafa21..6276f5ee77 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -851,6 +851,66 @@ fn nested_image_within_budget_imports_and_use_fan_out_is_refused() { assert!(matches!(err, SvgError::TooLarge(15)), "{err:?}"); } +/// Groups `g0` to `g{levels}`: `g0` a rectangle styled `style`, each other two ``s of the +/// one before; one `` of the last shown. +fn use_chain(levels: usize, style: &str) -> String { + let links: String = (1..=levels).map(|i| format!(r##""##, i - 1)).collect(); + svg(&format!(r##"{links}"##)) +} + +/// A style value of 100,000 bytes. +fn long_style() -> String { + format!("font-family:{}", "a".repeat(100_000)) +} + +/// A long style that a chain of ``s copies, or that a style sheet rule gives to many +/// elements, is refused before usvg copies it; short styles import, a rule that matches nothing +/// costing nothing. +#[test] +fn styles_that_expand_past_the_limit_are_refused() { + let err = import_with(&use_chain(10, &long_style()), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); + assert_eq!(err.to_string(), "the SVG's styles expand to more than 64 MB"); + // 1,000 groups that one rule gives the long style, without any ``. + let sheet = svg(&format!("{}", long_style(), "".repeat(1000))); + let err = import_with(&sheet, &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); + + // The chain with a short style shows its 1,024 rectangles. + let (d, _) = import_with(&use_chain(10, "fill:red"), &ImportOptions::default()).unwrap(); + assert_eq!(art(&d).iter().filter(|n| n.children().is_none()).count(), 1024); + // 5,000 rectangles of a class with short rules, beside a long rule that matches none of them. + let rules = format!(".a{{fill:#123456;stroke:#654321;stroke-width:2;opacity:.5}} .b{{{}}}", long_style()); + let classed = svg(&format!("{}", r#""#.repeat(5000))); + let (d, _) = import_with(&classed, &ImportOptions::default()).unwrap(); + assert_eq!(art(&d).len(), 5000); +} + +/// A chain of ``s that makes more elements than usvg reads is refused before usvg makes them. +#[test] +fn a_use_chain_past_the_elements_usvg_reads_is_refused() { + let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); +} + +/// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images +/// share the limit with the SVG showing them. +#[test] +fn svg_images_whose_styles_expand_past_the_limit_refuse_the_svg() { + let err = import_with(&svg(&image_of("image/svg+xml", &use_chain(10, &long_style()))), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); + // Each image copies its long style 383 times (about 38 MB): one imports, two together don't. + let image = image_of("image/svg+xml", &use_chain(7, &long_style())); + let (d, _) = import_with(&svg(&image), &ImportOptions::default()).unwrap(); + assert!(!art(&d).is_empty()); + let err = import_with(&svg(&image.repeat(2)), &ImportOptions::default()).unwrap_err(); + assert!(matches!(err, SvgError::StylesTooLarge(64)), "{err:?}"); + // An image that doesn't decode (no size) is left out, and what it would copy doesn't count. + let sizeless = use_chain(7, &long_style()).replacen(r#"width="200" height="120""#, r#"width="0" height="0""#, 1); + let (d, _) = import_with(&svg(&format!("{}{image}", image_of("image/svg+xml", &sizeless).repeat(2))), &ImportOptions::default()).unwrap(); + assert!(!art(&d).is_empty()); +} + /// Nested SVG images exceeding `MAX_NESTED_SVG_IMAGES` are left out with a warning note (#3564). #[test] fn nested_svg_images_past_count_cap_are_left_out() { diff --git a/crates/testkit/src/strategies.rs b/crates/testkit/src/strategies.rs index 153ede8f02..c2543d4374 100644 --- a/crates/testkit/src/strategies.rs +++ b/crates/testkit/src/strategies.rs @@ -2,7 +2,7 @@ use proptest::prelude::*; use serde_json::{Value, json}; -use vectorcraft_engine::cmd::{Location, key_location, location_in, location_keys}; +use vectorcraft_engine::cmd::{Location, ParamsPlace, key_location, location_keys}; use vectorcraft_engine::{CommandSpec, Session, command_specs}; use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath}; @@ -518,20 +518,8 @@ pub fn command_param_keys(spec: &CommandSpec) -> Vec { keys } -/// Parameter-name keys that name a file or folder in some command ([`key_location`]): fuzzing these -/// with arbitrary strings could write files anywhere, so callers substitute a temp path. -pub fn is_path_key(k: &str) -> bool { - key_location(k).is_some() -} - -/// Path keys that name a folder a command reads, creates or writes files into ([`key_location`]): -/// `folder`, `folders`, `dir`, `directory`, `destinationFolder` and `sourceFolder`. -pub fn is_folder_key(k: &str) -> bool { - key_location(k) == Some(Location::Folder) -} - -/// The location to send under the path key `k`: `safe_path` for a file, a folder next to it (in -/// the same temp folder) for a folder key. +/// The location to send under the path key `k` ([`key_location`]): `safe_path` for a file, a folder +/// next to it (in the same temp folder) for a folder key. pub fn safe_location(k: &str, safe_path: &str) -> String { location(key_location(k).unwrap_or(Location::File), safe_path) } @@ -542,55 +530,74 @@ fn location(l: Location, safe_path: &str) -> String { if l == Location::Folder { format!("{safe_path}-folder") } else { safe_path.to_string() } } -/// `v` with every string in it that can name a place on disk sent to the temp location: `v` -/// itself and the members of arrays in it, at any depth, when `kind` is `Some`, and in an object -/// at any depth, the strings under a path key ([`is_path_key`]). Other values keep their junk -/// shape. -fn redirect(kind: Option, v: &Value, safe_path: &str) -> Value { +/// `v`, found at `place` in a command's params, with every string in it that can name a place on +/// disk sent to the temp location: `v` itself and the members of arrays in it, at any depth, when +/// `kind` is `Some`, and in an object at any depth, the strings under a key that names a file or a +/// folder there ([`ParamsPlace::member`]: a call or a recorded step inside `v` keeps its command's +/// meaning). Other values keep their junk shape. +fn redirect(place: ParamsPlace, kind: Option, v: &Value, safe_path: &str) -> Value { match v { Value::String(_) => kind.map_or_else(|| v.clone(), |l| json!(location(l, safe_path))), - Value::Array(a) => Value::Array(a.iter().map(|x| redirect(kind, x, safe_path)).collect()), - Value::Object(o) => Value::Object(o.iter().map(|(k, x)| (k.clone(), redirect(key_location(k), x, safe_path))).collect()), + Value::Array(a) => { + let step = ParamsPlace::step(a); + Value::Array(a.iter().enumerate().map(|(i, x)| redirect(place.item(i, step), kind, x, safe_path)).collect()) + } + Value::Object(o) => { + let carried = ParamsPlace::carried(o); + let member = |k: &String, x: &Value| { + let (below, l) = place.member(k, carried); + (k.clone(), redirect(below, l, x, safe_path)) + }; + Value::Object(o.iter().map(|(k, x)| member(k, x)).collect()) + } _ => v.clone(), } } -/// `v`, with its strings sent to the temp location when `k` is a path key in any command -/// ([`is_path_key`]), and the strings under path keys in objects inside it too. -pub fn safe_value(k: &str, v: &Value, safe_path: &str) -> Value { - redirect(key_location(k), v, safe_path) +/// `v`, sent under key `k` at `place`, as [`redirect`] makes it. +fn redirect_under(place: ParamsPlace, k: &str, v: &Value, safe_path: &str) -> Value { + let (below, kind) = place.member(k, None); + redirect(below, kind, v, safe_path) } -/// `v` as [`safe_value`] makes it for command `spec` ([`location_in`]): a key that names part of -/// the document in it keeps its strings. +/// `v`, with its strings sent to the temp location when `k` is a path key in a command that gives it +/// no other meaning ([`key_location`]), and the strings under path keys in objects inside it too. +pub fn safe_value(k: &str, v: &Value, safe_path: &str) -> Value { + redirect_under(ParamsPlace::top(None), k, v, safe_path) +} + +/// `v` as [`safe_value`] makes it for command `spec` ([`vectorcraft_engine::cmd::location_in`]): a key that names part of +/// the document in it keeps its strings, at the top level and below. pub fn safe_value_for_command(spec: &CommandSpec, k: &str, v: &Value, safe_path: &str) -> Value { - redirect(location_in(spec, k), v, safe_path) + redirect_under(ParamsPlace::top(Some(spec)), k, v, safe_path) } /// A deterministic list of junk param objects for `doc` (the command's params doc): each /// documented key set to each junk value, all keys junk at once, wrong top-level types. A string -/// under a key that names a file or folder in any command ([`is_path_key`]) is a temp location. +/// under a key that names a file or folder in a command that gives it no other meaning +/// ([`key_location`]) is a temp location. pub fn junk_params(doc: &str, safe_path: &str) -> Vec { - junk_params_with(¶m_keys(doc), |k, v| safe_value(k, v, safe_path), key_location, safe_path) + junk_params_with(¶m_keys(doc), ParamsPlace::top(None), safe_path) } /// [`junk_params`] for command `spec`, with the keys of its schema and its file and folder keys too /// ([`command_param_keys`]), and a string under each key that names a file or folder in it -/// ([`location_in`]) a temp location, as are the strings in an array of them and under the path +/// ([`vectorcraft_engine::cmd::location_in`]) a temp location, as are the strings in an array of them and under the path /// keys of objects in one (`paths: [{ids, path}]`), which it also sends. pub fn junk_params_for_command(spec: &CommandSpec, safe_path: &str) -> Vec { - junk_params_with(&command_param_keys(spec), |k, v| safe_value_for_command(spec, k, v, safe_path), |k| location_in(spec, k), safe_path) + junk_params_with(&command_param_keys(spec), ParamsPlace::top(Some(spec)), safe_path) } -/// The junk cases for `keys`: `safe(k, v)` is what is sent for junk value `v` under `k`, and -/// `kind(k)` what `k` names on disk, if anything, whose keys also get a list of locations and a -/// list of objects with a `path`. -fn junk_params_with(keys: &[String], safe: impl Fn(&str, &Value) -> Value, kind: impl Fn(&str) -> Option, safe_path: &str) -> Vec { +/// The junk cases for `keys` at `place`, the top of a command's params: what is sent for a junk value +/// under a key is [`redirect_under`] it, and a key that names a file or a folder there also gets a +/// list of locations and a list of objects with a `path`. +fn junk_params_with(keys: &[String], place: ParamsPlace, safe_path: &str) -> Vec { let junk = junk_values(); let mut out = vec![Value::Null, json!([]), json!("str"), json!(42), json!({"unknownKey": 1})]; for k in keys { + let (below, kind) = place.member(k, None); for (i, v) in junk.iter().enumerate() { - let v = safe(k, v); + let v = redirect(below, kind, v, safe_path); // Sparse: one key at a time with every junk value, plus a few combos. let mut o = serde_json::Map::new(); o.insert(k.clone(), v.clone()); @@ -598,17 +605,62 @@ fn junk_params_with(keys: &[String], safe: impl Fn(&str, &Value) -> Value, kind: if i % 5 == 0 { let mut all = serde_json::Map::new(); for k2 in keys { - let v2 = kind(k2).map_or_else(|| v.clone(), |l| json!(location(l, safe_path))); + let v2 = place.member(k2, None).1.map_or_else(|| v.clone(), |l| json!(location(l, safe_path))); all.insert(k2.clone(), v2); } out.push(Value::Object(all)); } } - if let Some(l) = kind(k) { + if let Some(l) = kind { for v in [json!(["junk", "", 1]), json!([{"ids": [1], "path": "junk"}, {"path": null}])] { - out.push(json!({ k.as_str(): redirect(Some(l), &v, safe_path) })); + out.push(json!({ k.as_str(): redirect(below, Some(l), &v, safe_path) })); } } } out } + +#[cfg(test)] +mod tests { + use super::*; + + /// The strings the sweeps send keep the meaning the command gives their key, at every depth: an + /// export's folder grouping and a web link stay as sent, also inside a `command.batch` step and + /// a recorded step, and a real file or folder key there goes to the temp location. A key that names + /// part of the document in a recorded step's command stays, and the same key in a command that + /// doesn't take it as a param names a file. + #[test] + fn nested_locations_keep_command_meaning() { + let spec = |id: &str| command_specs().iter().find(|c| c.id == id).unwrap_or_else(|| panic!("no command {id}")); + let safe = "/tmp/sweep/out.bin"; + let settings = json!({"folders": "rows", "formats": [{"format": "png", "folder": "junk"}]}); + assert_eq!( + safe_value_for_command(spec("document.exportPresets.save"), "settings", &settings, safe), + json!({"folders": "rows", "formats": [{"format": "png", "folder": "/tmp/sweep/out.bin-folder"}]}) + ); + let steps = json!([ + {"command": "attributes.set", "params": {"url": "https://example.com/a"}}, + {"command": "document.save", "params": {"path": "junk"}}, + {"command": "object.path.simplify", "params": {"wholePaths": "junk"}}, + ]); + assert_eq!( + safe_value_for_command(spec("command.batch"), "commands", &steps, safe), + json!([ + {"command": "attributes.set", "params": {"url": "https://example.com/a"}}, + {"command": "document.save", "params": {"path": safe}}, + {"command": "object.path.simplify", "params": {"wholePaths": "junk"}}, + ]) + ); + let recorded = json!([ + ["text.createInPath", {"path": "junk"}], + ["object.setLiveShape", {"path": "junk"}], + ["document.compare", {"diffPath": "junk"}], + ]); + assert_eq!( + safe_value("steps", &recorded, safe), + json!([["text.createInPath", {"path": "junk"}], ["object.setLiveShape", {"path": safe}], ["document.compare", {"diffPath": safe}]]) + ); + assert_eq!(safe_value("url", &json!("https://example.com/a"), safe), json!("https://example.com/a")); + assert_eq!(safe_value("destinationFolder", &json!("junk"), safe), json!("/tmp/sweep/out.bin-folder")); + } +} diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index d43e17ad99..fadb0165d5 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -53,6 +53,15 @@ impl Metrics { } } +/// What a line band was placed below: the baseline of the line above it and the em box top that +/// line left for the next one (both `None` for a cell's first band), and the space pending between. +#[derive(Clone, Copy, Default)] +pub(super) struct Above { + pub(super) prev: Option, + pub(super) next_top: Option, + pub(super) pending: f64, +} + /// Where the next line goes: the region being filled and the previous baseline in it. #[derive(Clone)] pub(super) struct Pen<'r> { @@ -64,6 +73,8 @@ pub(super) struct Pen<'r> { pub(super) fb_min: f64, /// Further spans at the current baseline (text wrapping on both sides of an object). pub(super) queued: Vec<(f64, f64, f64)>, + /// What the line band at the current baseline was placed below (see [`Above`]). + pub(super) above: Above, /// Leading measured from em box top to em box top: where the next line's em box top goes. pub(super) model: LeadingModel, pub(super) next_top: Option, @@ -108,16 +119,21 @@ impl Pen<'_> { /// [`Pen::place`], skipping lines of a non-rectangular frame narrower than `min`. fn place_at_least(&mut self, est: Metrics, ind_l: f64, ind_r: f64, min: f64) -> Option<(f64, f64, f64, bool)> { let Some(regions) = self.regions else { - let b = self.prev.map_or(0.0, |b| self.next_baseline(b, est)); + let b = self.prev.map_or(0.0, |b| self.next_baseline(b, self.next_top, self.pending, est)); return Some((b, f64::NEG_INFINITY, f64::INFINITY, false)); }; // A further span was measured across the height of the line set before it on its baseline. // This line gets the part of it that is free across its own height: a taller line can // reach a wrap object the line before it stayed clear of. A span with no such part is - // left empty, and so is a part the line's height made narrower than `min`. + // left empty, and so is a part the line's height made narrower than `min`. A span on a + // baseline nearer the line above the band than this line's own leading sets it is left + // empty too: a taller line would reach into that line. while !self.queued.is_empty() { let (b, x0, x1) = self.queued.remove(0); let Some(r) = regions.get(self.ri) else { return Some((b, x0, x1, true)) }; + if b + EPS < self.band_baseline(r, est) { + continue; + } let mut free = r.spans(b - est.asc, b + est.desc).into_iter().filter_map(|(s, e)| { let (s, e) = (s.max(x0), e.min(x1)); let room = e - s - ind_l - ind_r; @@ -132,11 +148,8 @@ impl Pen<'_> { } loop { let r = regions.get(self.ri)?; - let mut baseline = match self.prev { - None if self.model == LeadingModel::EmBoxTop => r.top() + r.shift + est.top.max(self.fb_min), - None => r.top() + r.shift + est.first_baseline(self.fb, self.fb_min), - Some(b) => self.next_baseline(b, est) + r.gap, - }; + self.above = Above { prev: self.prev, next_top: self.next_top, pending: self.pending }; + let mut baseline = self.band_baseline(r, est); // The baseline moves down the cell a lead at a time, or a `MAX_STEPS`th of the cell's // height when that is more, in at most `MAX_STEPS` steps. let step = est.lead.max(1.0).max(r.cell.height() / MAX_STEPS as f64); @@ -188,13 +201,30 @@ impl Pen<'_> { pub(super) fn bottom(&self) -> f64 { self.regions.and_then(|r| r.get(self.ri)).map_or(f64::INFINITY, |r| r.bottom()) } - /// The baseline of the line after the one at `prev`, for a line of metrics `est`. - fn next_baseline(&self, prev: f64, est: Metrics) -> f64 { - match (self.model, self.next_top) { - (LeadingModel::EmBoxTop, Some(top)) => top + est.top + self.pending, - _ => prev + est.lead + self.pending, + /// The baseline of the line after the one at `prev`, which left the next em box top at + /// `next_top`, for a line of metrics `est` with `pending` space between them. + fn next_baseline(&self, prev: f64, next_top: Option, pending: f64, est: Metrics) -> f64 { + match (self.model, next_top) { + (LeadingModel::EmBoxTop, Some(top)) => top + est.top + pending, + _ => prev + est.lead + pending, } } + /// The highest baseline in cell `r` for a line of metrics `est` in the current line band: as + /// far below the line above the band ([`Pen::above`]) as its own leading sets it, or at the + /// cell's first baseline. + fn band_baseline(&self, r: &Region, est: Metrics) -> f64 { + let Above { prev, next_top, pending } = self.above; + match prev { + None if self.model == LeadingModel::EmBoxTop => r.top() + r.shift + est.top.max(self.fb_min), + None => r.top() + r.shift + est.first_baseline(self.fb, self.fb_min), + Some(b) => self.next_baseline(b, next_top, pending, est) + r.gap, + } + } + /// A line of metrics `m` set in a further span at baseline `b` is no nearer the line above + /// the band than its own leading sets it. + pub(super) fn clears_above(&self, b: f64, m: Metrics) -> bool { + self.regions.and_then(|r| r.get(self.ri)).is_none_or(|r| b + EPS >= self.band_baseline(r, m)) + } /// A line was set at `baseline` with metrics `m`: where the next one goes from. pub(super) fn settled(&mut self, baseline: f64, m: Metrics) { self.prev = Some(baseline); @@ -214,18 +244,30 @@ pub(super) fn tab_advance<'t, 'g>( ) -> (f64, &'t str) { use vectorcraft_doc::TabAlign; let rel = x - origin; - let seg: Vec<&SGlyph> = rest.into_iter().take_while(|g| g.ch != '\t' && g.ch != '\u{2028}').collect(); - let width: f64 = seg.iter().map(|g| g.adv).sum(); - let target = |pos: f64, align: TabAlign, on: char| match align { - TabAlign::Left => pos, - TabAlign::Right => pos - width, - TabAlign::Center => pos - width / 2.0, - TabAlign::Decimal => pos - seg.iter().take_while(|g| g.ch != on).map(|g| g.adv).sum::(), - }; - let explicit = tabs.iter().find_map(|t| { - let at = target(t.position, t.align, t.align_on); - (at > rel + 1e-6).then_some((at, t.leader.as_str())) - }); + // The text after the tab is read only when a right, center or decimal stop is reached, since + // only those align it. A tab to a default or left stop reads none of it. + let mut rest = Some(rest); + let mut seg: Vec<&SGlyph> = Vec::new(); + let mut width = 0.0; + let mut explicit = None; + for t in tabs { + if t.align != TabAlign::Left + && let Some(r) = rest.take() + { + seg = r.into_iter().take_while(|g| g.ch != '\t' && g.ch != '\u{2028}').collect(); + width = seg.iter().map(|g| g.adv).sum(); + } + let at = match t.align { + TabAlign::Left => t.position, + TabAlign::Right => t.position - width, + TabAlign::Center => t.position - width / 2.0, + TabAlign::Decimal => t.position - seg.iter().take_while(|g| g.ch != t.align_on).map(|g| g.adv).sum::(), + }; + if at > rel + 1e-6 { + explicit = Some((at, t.leader.as_str())); + break; + } + } let (at, leader) = explicit.unwrap_or_else(|| { let last = tabs.iter().map(|t| t.position).fold(0.0, f64::max).max(0.0); let base = rel.max(last); @@ -263,7 +305,8 @@ const MAX_DRAWN_CHECKS: usize = 256; /// Most breaks, or hyphenation points, [`break_line`] measures as drawn one by one when a glyph of /// the line has a negative advance: a later break can then be drawn narrower than an earlier one, -/// and bisecting can miss the latest break that fits. +/// and bisecting can miss the latest break that fits. It is also the most legal breaks such a line +/// reads past where it first overflows in the order of its text. const MAX_DRAWN_CHECKS_STEPPING_BACK: usize = 1024; /// Most copies of a leader drawn in one tab: a tiny type size and a far stop must not make @@ -369,7 +412,11 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins /// while the least it can be drawn at fits `width`, then ends at the latest legal break where it /// fits as drawn (past [`MAX_DRAWN_CHECKS`] breaks back from the latest, or /// [`MAX_DRAWN_CHECKS_STEPPING_BACK`] when a glyph of the line has a negative advance, the earlier -/// ones without a hyphen are bisected); hyphenation points are measured the same way. +/// ones without a hyphen are bisected); hyphenation points are measured the same way. Once such a +/// line holds a glyph with a negative advance and has been wider than `width` in the order of its +/// text, it reads at most [`MAX_DRAWN_CHECKS_STEPPING_BACK`] legal breaks further, and a forced +/// line break right after the last of them, and ends at the latest of the breaks read that fits as +/// drawn. #[allow(clippy::too_many_arguments)] pub(super) fn break_line( text: &str, @@ -439,6 +486,11 @@ pub(super) fn break_line( } }; let mut last_break: Option<(usize, bool)> = None; + // Whether the line, once it holds a tab and is measured as drawn, has been wider in the order of + // its text than `width`, and how many legal breaks it has read since then with a glyph stepping + // back: past MAX_DRAWN_CHECKS_STEPPING_BACK of them the line stops reading. + let mut overflowed = false; + let mut breaks_past_overflow = 0usize; // A list marker (length 0) is a cluster of its own; the line holds it and at least the first // cluster after it. let first = i + g.get(i..).unwrap_or_default().iter().take_while(|h| h.len == 0).count(); @@ -489,6 +541,7 @@ pub(super) fn break_line( // there are tabs. let stops_reached = if back + cluster_back > 0.0 { f64::NEG_INFINITY } else { nth_stop(tabs_read) - x_start }; let measured = if tabbed && fits.is_some() { (ink + cluster_ink).max(stops_reached) } else { x + cluster_width }; + overflowed |= tabbed && fits.is_some() && j > first && !gl.is_space() && x + cluster_width - end_credit > width + EPS; if j > first && !gl.is_space() && measured - end_credit > width + EPS { // It ends the line with the spaces after it. if burasagari != Burasagari::None && hangs(gl) && kinsoku_allows(g, cluster_end - 1, kinsoku) { @@ -517,6 +570,15 @@ pub(super) fn break_line( if fits.is_some() { breaks.push((cluster_end, hyphenated)); } + // A line with a glyph stepping back stops reading MAX_DRAWN_CHECKS_STEPPING_BACK + // breaks past where it first overflowed in the order of its text, and ends at the + // latest break read that fits as drawn: each of those breaks is measured one by one. + // A soft hyphen ending the text draws no hyphen there, as at the end of the text below. + // A break right before a forced line break reads on to it: the line ends there. + breaks_past_overflow += usize::from(overflowed && back > 0.0); + if breaks_past_overflow >= MAX_DRAWN_CHECKS_STEPPING_BACK && g.get(cluster_end).is_none_or(|n| n.ch != '\u{2028}') { + return settle(tabbed, checks(back), (cluster_end, hyphenated && cluster_end < g.len()), &breaks); + } } } j = cluster_end; @@ -967,6 +1029,7 @@ fn a_pen_out_of_baseline_steps_finds_no_room() { fb: FirstBaseline::Ascent, fb_min: 0.0, queued: vec![], + above: Default::default(), model: LeadingModel::default(), next_top: None, no_room_for: f64::INFINITY, diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 5cf7a87224..30b615c5fc 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -177,6 +177,7 @@ pub(super) fn flow(cx: &mut Ctx<'_>, paras: &[Range], t: &TextObject, reg fb: cx.opts.first_baseline, fb_min: cx.opts.first_baseline_min, queued: vec![], + above: Default::default(), model: t.para_at(0).leading_model, next_top: None, no_room_for: f64::INFINITY, @@ -538,6 +539,11 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC } } let m = metrics(end); + if same_baseline && !pen.clears_above(baseline, m) { + // A glyph taller than the first one sets the line lower than the span's baseline: the + // span is left empty, and the line goes in the next span or on the next baseline. + continue; + } baseline += if !settle || same_baseline || (pen.regions.is_none() && first_in_region) { 0.0 } else if pen.model == LeadingModel::EmBoxTop { diff --git a/crates/text/src/layout/shaped.rs b/crates/text/src/layout/shaped.rs index 63005364fb..61c28b1465 100644 --- a/crates/text/src/layout/shaped.rs +++ b/crates/text/src/layout/shaped.rs @@ -91,8 +91,9 @@ struct Placed<'r> { /// What a line's placement depends on: its first glyph, whether it is the paragraph's first line, /// the pen's cell, baselines, pending space, narrowest word without room and further spans, the -/// span of the line above and whether the line is past the frame's end. -type Key = (usize, bool, usize, Option, Option, u64, u64, Vec<[u64; 3]>, Option, bool); +/// span of the line above, whether the line is past the frame's end, and what the further spans' +/// band was placed below. +type Key = (usize, bool, usize, Option, Option, u64, u64, Vec<[u64; 3]>, Option, bool, (Option, Option, u64)); fn key(pos: usize, first: bool, pen: &Pen<'_>, span: Option, past: bool) -> Key { ( @@ -106,6 +107,7 @@ fn key(pos: usize, first: bool, pen: &Pen<'_>, span: Option, past: bool) -> pen.queued.iter().map(|&(b, x0, x1)| [b.to_bits(), x0.to_bits(), x1.to_bits()]).collect(), span.map(f64::to_bits), past, + (pen.above.prev.map(f64::to_bits), pen.above.next_top.map(f64::to_bits), pen.above.pending.to_bits()), ) } diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 1878ce962d..451e029478 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -646,6 +646,149 @@ fn a_negative_advance_after_a_tab_keeps_a_fitting_line_whole() { assert_eq!(ended, (5, false)); } +/// A tabbed line of glyphs with negative advances, past the frame in the order of its text: `a`, +/// a tab to the default stop at 36 pt, `y` stepping back 1 pt, then `n` times `b` (1 pt), `z` +/// (−1 pt) and a space, so its glyphs other than the tab never fill the frame. Its breaks end the +/// line before glyph 2 and before 6 + 3u for each u. +fn stepping_back_tabbed_line(n: usize) -> (String, Vec) { + let text = format!("a\ty{}", "bz ".repeat(n)); + let specs: Vec<_> = text + .char_indices() + .map(|(byte, ch)| { + let adv = match ch { + 'y' | 'z' => -1.0, + ' ' => 0.0, + _ => 1.0, + }; + (byte, ch.len_utf8(), adv, ch) + }) + .collect(); + let glyphs = synthetic_glyphs(&specs); + (text, glyphs) +} + +/// A tabbed line with glyphs stepping back stops reading a bounded number of breaks past where it +/// overflows in the order of its text: a long paragraph is not read to its end to set one line. +#[test] +fn a_tabbed_line_stepping_back_stops_reading_past_its_overflow() { + let (text, glyphs) = stepping_back_tabbed_line(2000); + // The latest break the line reads is the first it measures as drawn. + let furthest = std::cell::Cell::new(0); + let measured = std::cell::Cell::new(0usize); + let drawn_fits = |end: usize, _hyphenated: bool| { + furthest.set(furthest.get().max(end)); + measured.set(measured.get() + 1); + end <= 10 + }; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits); + let ended = + break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits); + assert_eq!(ended, (9, false)); + // 1,024 breaks past the overflow at `y`: the break before glyph 6 + 3 × 1,023. + assert_eq!(furthest.get(), 3075, "read up to glyph {} of {}", furthest.get(), glyphs.len()); + assert!(measured.get() <= 1100, "measured {} breaks as drawn", measured.get()); +} + +/// Where a tabbed line with glyphs stepping back stops reading, it ends at the latest break read +/// that fits as drawn, even when a break past those fits too. +#[test] +fn a_tabbed_line_stepping_back_ends_at_the_latest_break_read_that_fits() { + let (text, glyphs) = stepping_back_tabbed_line(1500); + let end = |drawn_fits: &dyn Fn(usize, bool) -> bool| { + break_line( + &text, + &glyphs, + 0, + 30.0, + &[], + 0.0, + None, + Burasagari::None, + Kinsoku::None, + KinsokuShoriType::PushOutOnly, + false, + false, + &[], + Some(drawn_fits), + ) + }; + // The break before glyph 4002 is past the 1,024 breaks read after the overflow (up to 3075). + assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 4002), (9, false)); + // A break among those read keeps its place. + assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 600), (600, false)); + assert_eq!(end(&|end: usize, _: bool| end <= 10 || end == 3075), (3075, false)); +} + +/// A tabbed line with glyphs stepping back that stops reading at a soft hyphen ending the text ends +/// there without a hyphen, as a line that reads to the end of the text does. +#[test] +fn a_tabbed_line_stepping_back_ends_at_a_final_soft_hyphen_without_a_hyphen() { + // The 1,023 spaces and the soft hyphen are the 1,024 breaks the line reads past its overflow. + let text = format!("a\ty{}b\u{00AD}", "bz ".repeat(1023)); + let specs: Vec<_> = text + .char_indices() + .map(|(byte, ch)| { + let adv = match ch { + 'y' | 'z' => -1.0, + ' ' | '\u{00AD}' => 0.0, + _ => 1.0, + }; + (byte, ch.len_utf8(), adv, ch) + }) + .collect(); + let glyphs = synthetic_glyphs(&specs); + let len = glyphs.len(); + let drawn_fits = |end: usize, _hyphenated: bool| end <= 10 || end == len; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits); + let ended = + break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits); + assert_eq!(ended, (len, false)); +} + +/// A tabbed line with glyphs stepping back whose last break read comes right before a forced line +/// break ends after the forced break, so the next line does not start with it and draw empty. +#[test] +fn a_tabbed_line_stepping_back_keeps_a_forced_break_after_its_last_break_read() { + // The 1,024th space is the 1,024th break past the overflow, and glyph 3075 after it is U+2028. + let text = format!("a\ty{}\u{2028}bbb", "bz ".repeat(1024)); + let specs: Vec<_> = text + .char_indices() + .map(|(byte, ch)| { + let adv = match ch { + 'y' | 'z' => -1.0, + ' ' | '\u{2028}' => 0.0, + _ => 1.0, + }; + (byte, ch.len_utf8(), adv, ch) + }) + .collect(); + let glyphs = synthetic_glyphs(&specs); + assert_eq!(glyphs[3075].ch, '\u{2028}'); + let drawn_fits = |end: usize, _hyphenated: bool| end <= 10 || end >= 3075; + let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&drawn_fits); + let ended = + break_line(&text, &glyphs, 0, 30.0, &[], 0.0, None, Burasagari::None, Kinsoku::None, KinsokuShoriType::PushOutOnly, false, false, &[], fits); + assert_eq!(ended, (3076, false)); +} + +/// A tab to a default or left stop does not read the text after it, which only right, center and +/// decimal stops align: the first tab of a long paragraph does not read the paragraph to its end. +#[test] +fn a_tab_to_a_default_or_left_stop_reads_no_text_after_it() { + use vectorcraft_doc::{TabAlign, TabStop}; + let (_, glyphs) = stepping_back_tabbed_line(2000); + let read = std::cell::Cell::new(0usize); + let rest = || glyphs[2..].iter().inspect(|_| read.set(read.get() + 1)); + let left = [TabStop { position: 100.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }]; + assert_eq!(tab_advance(&[], 0.0, 1.0, rest()).0, 35.0); + assert_eq!(tab_advance(&left, 0.0, 1.0, rest()).0, 99.0); + assert_eq!(read.get(), 0, "read {} glyphs after the tab", read.get()); + // A right stop reads up to the next tab and aligns that text on the stop. + let right = [TabStop { position: 100.0, align: TabAlign::Right, leader: String::new(), align_on: '.' }]; + let short = synthetic_glyphs(&[(0, 1, 2.0, 'b'), (1, 1, 3.0, 'b'), (2, 1, 0.0, '\t'), (3, 1, 7.0, 'b')]); + assert_eq!(tab_advance(&right, 0.0, 1.0, short.iter()).0, 94.0); +} + /// A long tabbed line with a glyph that steps back ends at the latest break that fits as drawn, even /// where a later break than one that does not fit fits again. #[test] @@ -911,7 +1054,8 @@ fn a_further_span_is_measured_across_the_height_of_its_line() { wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false }, }; let small = breaking::Metrics { asc: 10.0, desc: 3.0, lead: 14.0, cap: 7.0, xh: 5.0, top: 10.0 }; - let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 42.0, cap: 21.0, xh: 15.0, top: 30.0 }; + // The tall line is set at the small line's leading, so it may share the small line's baseline. + let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 14.0, cap: 21.0, xh: 15.0, top: 30.0 }; // An object down the middle of the frame splits every line in two, and `above` lies right of // it over y 20 to 40. A small line after a baseline of 50 is set at 64, over y 54 to 67, clear // of `above`; a tall line in the span right of it on that baseline covers y 34 to 73. @@ -926,6 +1070,7 @@ fn a_further_span_is_measured_across_the_height_of_its_line() { fb: FirstBaseline::Ascent, fb_min: 0.0, queued: vec![], + above: Default::default(), model: LeadingModel::RomanBaseline, next_top: None, no_room_for: f64::INFINITY, @@ -946,17 +1091,72 @@ fn a_further_span_is_measured_across_the_height_of_its_line() { assert!(near(right, (64.0, 220.0, 300.0, true)), "{right:?}"); // That part is 80 wide: a tall line that starts with a wider word goes on the next baseline. let (_, right) = set(Rect::new(300.0, 20.0, 400.0, 40.0), 100.0); - assert!(near(right, (106.0, 0.0, 180.0, false)), "{right:?}"); + assert!(near(right, (78.0, 0.0, 180.0, false)), "{right:?}"); // `above` covers the whole span: the tall line goes on the next baseline, left of the object. let (left, right) = set(Rect::new(220.0, 20.0, 400.0, 40.0), 0.0); assert!(near(left, (64.0, 0.0, 180.0, false)), "{left:?}"); - assert!(near(right, (106.0, 0.0, 180.0, false)), "{right:?}"); + assert!(near(right, (78.0, 0.0, 180.0, false)), "{right:?}"); // `above` lies below the tall line: the span is as wide for it as for the small line, and it // takes the span whatever its first word, as a further span always did. let (_, right) = set(Rect::new(300.0, 300.0, 400.0, 320.0), 200.0); assert!(near(right, (64.0, 220.0, 400.0, true)), "{right:?}"); } +/// A further span goes only to a line whose own leading sets it no higher than the span's +/// baseline: a taller line leaves the span empty and goes on the next baseline, so its ascent does +/// not reach into the line above the band. In a cell's first band, a taller line leaves a span +/// whose baseline is above its own first baseline in the cell. +#[test] +fn a_further_span_is_left_to_a_line_its_leading_sets_there() { + use std::cell::Cell; + use std::rc::Rc; + let frame = Rect::new(0.0, 0.0, 400.0, 400.0).to_path(0.1); + let wraps = [vectorcraft_doc::WrapShape { + path: PathData::from_bezpath(&Rect::new(180.0, 0.0, 220.0, 400.0).to_path(0.1)), + wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false }, + }]; + let regions = region::Region::cells(&frame, &LayoutOptions::default(), &wraps); + let small = breaking::Metrics { asc: 10.0, desc: 3.0, lead: 14.0, cap: 7.0, xh: 5.0, top: 10.0 }; + let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 42.0, cap: 21.0, xh: 15.0, top: 30.0 }; + let set = |prev: Option, model: LeadingModel, next: breaking::Metrics| { + let mut pen = breaking::Pen { + regions: Some(®ions), + ri: 0, + prev, + pending: 0.0, + fb: FirstBaseline::Ascent, + fb_min: 0.0, + queued: vec![], + above: Default::default(), + model, + next_top: prev.map(|b| b - small.top + small.lead), + no_room_for: f64::INFINITY, + steps_left: Rc::new(Cell::new(breaking::MAX_TOTAL_STEPS)), + search: Default::default(), + }; + let left = pen.place(small, 0.0, 0.0, 0.0); + let at = left.map_or(f64::NAN, |l| l.0); + pen.settled(at, small); + let ok = pen.clears_above(at, next); + (left, pen.place(next, 0.0, 0.0, 0.0), ok) + }; + let near = |got: Option<(f64, f64, f64, bool)>, want: (f64, f64, f64, bool)| { + got.is_some_and(|g| (g.0 - want.0).abs() < 0.01 && (g.1 - want.1).abs() < 0.01 && (g.2 - want.2).abs() < 0.01 && g.3 == want.3) + }; + // The next baseline for the tall line after the small one at 64, and after the small one at 10. + for (model, after_64, after_10) in [(LeadingModel::RomanBaseline, 106.0, 52.0), (LeadingModel::EmBoxTop, 98.0, 44.0)] { + // After a line at 50, the small line is set at 64. A small line takes the span right of the + // object on that baseline; a tall line, which its leading sets lower, goes on the next one. + let (left, right, ok) = set(Some(50.0), model, small); + assert!(near(left, (64.0, 0.0, 180.0, false)) && near(right, (64.0, 220.0, 400.0, true)) && ok, "{model:?}: {left:?} {right:?}"); + let (_, right, ok) = set(Some(50.0), model, tall); + assert!(near(right, (after_64, 0.0, 180.0, false)) && !ok, "{model:?}: {right:?}"); + // The cell's first band: the small line at 10, the tall line on the next baseline. + let (left, right, ok) = set(None, model, tall); + assert!(near(left, (10.0, 0.0, 180.0, false)) && near(right, (after_10, 0.0, 180.0, false)) && !ok, "{model:?}: {left:?} {right:?}"); + } +} + /// The every-line composer's searches for the paragraphs of one frame share one budget: each takes /// the lines it tried and the baseline steps it spent from it, the layout's own steps stay as they /// were, and once the budget runs out the next paragraph's search stops (it is broken line by line). @@ -990,6 +1190,7 @@ fn shaped_composition_searches_share_the_frame_budget() { fb: FirstBaseline::Ascent, fb_min: 0.0, queued: vec![], + above: Default::default(), model: LeadingModel::default(), next_top: None, no_room_for: f64::INFINITY, diff --git a/crates/text/src/tests/combos.rs b/crates/text/src/tests/combos.rs index cdb5a31fee..a2d837e286 100644 --- a/crates/text/src/tests/combos.rs +++ b/crates/text/src/tests/combos.rs @@ -443,6 +443,36 @@ fn composer_x_mixed_sizes_around_text_wrap() { assert_eq!(every, greedy); } +#[test] +fn composer_x_taller_line_in_a_further_span() { + // A wrap object down the middle of the frame splits every line in two. The 36 pt word falls in + // the span right of it on the second baseline, after a 12 pt line left of it: the line that + // holds it is set as far below the line above it as its own leading sets it, and its ascent + // stays clear of that line, with either composer. + let w = x_width(); + let object = Rect::new(w, -10.0, w + 40.0, 310.0); + for composer in [Composer::SingleLine, Composer::EveryLine] { + let mut runs = vec![run(&format!("{RAG} Then draw a card for each creature destroyed this way. "), sans(12.0))]; + runs.extend(with_x(sans(36.0))); + let mut t = area(runs, Rect::new(0.0, 0.0, 2.0 * w + 40.0, 300.0)); + t.wrap = vec![vectorcraft_doc::WrapShape { path: PathData::from_bezpath(&object.to_path(0.1)), wrap: Default::default() }]; + t.para.composer = composer; + let l = layout(db(), &t); + assert!(!l.overflow, "{composer:?}: {:?}", l.lines); + let tall: Vec<_> = l.lines.iter().filter(|line| line.ascent > 30.0).collect(); + assert_eq!(tall.len(), 1, "{composer:?}: {:?}", l.lines); + for line in tall { + for above in l.lines.iter().filter(|a| a.baseline < line.baseline - 0.01) { + let beside = above.avail.0 < line.avail.1 && line.avail.0 < above.avail.1; + assert!( + !beside || line.baseline - line.ascent >= above.baseline + above.descent - 0.01, + "{composer:?}: {line:?} reaches into {above:?}" + ); + } + } + } +} + #[test] fn composer_x_mixed_sizes_in_a_frame_that_widens() { // A frame as wide as "Destroy all" down to 20 pt and as wide as the first line of diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index bb066c0e8a..4290bc1c75 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -21,7 +21,10 @@ mod caps; mod mesh; pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh}; mod shadow; -pub use shadow::{MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, TOO_COMPLEX_SHADOW}; +pub use shadow::{ + MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, SolidFaces, TOO_COMPLEX_SHADOW, extrude_shadowed, inflate_shadowed, + plane_shadowed, revolve_facets_shadowed, revolve_shadowed, +}; use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveDeriv}; use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2}; @@ -961,21 +964,136 @@ fn revolve_face_limit(o: Revolve) -> usize { /// [`revolve`], or with `mesh` the surface's faces before projection, kept there instead of drawn, /// each turned out of the region `rule` fills. -fn revolve_faces( +fn revolve_faces(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve, mesh: Option<&mut Vec>) -> Result, String> { + let draw = mesh.is_none(); + revolve_sweep(path, rule, bounds, options, draw, mesh).map(|(faces, _)| faces) +} + +#[cfg(test)] +thread_local! { + /// How many Revolve surfaces this thread has swept, for the tests. + pub(crate) static REVOLVED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// One contour's profile as a sweep takes it: its points, the tangents at the ends of each edge, +/// and whether each edge walls a hole. +#[derive(Default)] +struct Swept { + points: Vec, + tangents: Vec<[Vec2; 2]>, + holes: Vec, +} + +/// Where a sweep places a profile: about the axis at `axis` and the middle height `center_y`, +/// turned through `sweep` radians in `steps` steps, with the sanitized options `o`. +struct Sweeping { + o: Revolve, + axis: f64, + center_y: f64, + sweep: f64, + steps: usize, +} + +impl Sweeping { + /// Profile point `p` turned to the end of step `step`, in view space. + fn vertex(&self, p: Point, step: usize) -> V3 { + let (s, c) = (self.sweep * step as f64 / self.steps as f64).sin_cos(); + self.o.rotate(V3((p.x - self.axis) * c, p.y - self.center_y, (p.x - self.axis) * s)) + } +} + +/// The end `index` (0 the first, 1 the last) of `profile` and the way its cap faces along the axis: +/// the sign of the end's y less its neighbor's, or with the two level, -1 for an end above the +/// middle height `center_y` and 1 otherwise. +fn cap_outward(profile: &[Point], index: usize, center_y: f64) -> Option<(Point, f64)> { + let neighbours = if index == 0 { profile.first().zip(profile.get(1)) } else { profile.last().zip(profile.get(profile.len().saturating_sub(2))) }; + neighbours.map(|(end, neighbour)| { + let dy = end.y - neighbour.y; + let outward = if dy.abs() > 1e-10 { + dy.signum() + } else if end.y < center_y { + -1.0 + } else { + 1.0 + }; + (*end, outward) + }) +} + +/// Keep for a mesh the faces of one contour's profile `s`, which runs round the region it sweeps as +/// `turn` says (its holes' walls turned the other way): a quad for each edge at each step, then for +/// each end in `caps` (0 the first, 1 the last) the disk, or for a sweep of less than a full turn +/// the sector with its center on the axis. `keep` keeps one face with its outward normal; its +/// error, or an edge with invalid coordinates, stops the faces. +fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: impl FnMut(Vec, V3) -> Result<(), String>) -> Result<(), String> { + let (o, steps) = (at.o, at.steps); + for (pair, hole) in s.points.windows(2).zip(&s.holes) { + let [a, b] = pair else { continue }; + let turn = if *hole { -turn } else { turn }; + if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { + return Err("Revolve profile contains invalid coordinates".into()); + } + for j in 0..steps { + let [v0, v1, v2, v3] = [at.vertex(*a, j), at.vertex(*b, j), at.vertex(*b, j + 1), at.vertex(*a, j + 1)]; + // The edge's outward normal in the profile's plane (distance from the axis, height), + // swept to the middle of the step. + let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); + let (sin, cos) = (at.sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); + keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)))?; + } + } + for &index in caps { + let Some((end, outward)) = cap_outward(&s.points, index, at.center_y) else { continue }; + let mut cap: Vec = (0..=steps).map(|j| at.vertex(end, j)).collect(); + if o.angle >= 360.0 { + cap.pop(); + } else { + cap.insert(0, o.rotate(V3(0.0, end.y - at.center_y, 0.0))); + } + keep(cap, o.rotate(V3(0.0, outward, 0.0)))?; + } + Ok(()) +} + +/// Keep no more faces for a mesh after error `e`, which is the result when no face is drawn. +fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec>, lost: &mut Option, e: String) -> Result<(), String> { + if !draw { + return Err(e); + } + *mesh = None; + lost.get_or_insert(e); + Ok(()) +} + +/// [`revolve`]'s faces when `draw`, and with `mesh` the surface's faces before projection kept +/// there from the same sweep, each turned out of the region `rule` fills. While faces are drawn, an +/// error keeping faces for the mesh stops only the mesh: the error comes back beside the faces +/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result. +fn revolve_sweep( path: &PathData, rule: FillRule, bounds: Rect, options: Revolve, + draw: bool, mut mesh: Option<&mut Vec>, -) -> Result, String> { +) -> Result<(Vec, Option), String> { + #[cfg(test)] + REVOLVED.with(|n| n.set(n.get() + 1)); let o = options.sanitized(); let curve_samples = match o.curve_samples { Some(samples) => samples.clamp(1, CURVE_SAMPLES), None => revolve_curve_samples([path], o)?, }; + let mut lost = None; // For a mesh, each piece of a closed contour's edge is cut where it crosses another contour, so // each part's normal turns toward a hole only where it walls one. - let mut search = if mesh.is_some() { Some(HoleSearch::new(path, rule)?) } else { None }; + let mut search = None; + if mesh.is_some() { + match HoleSearch::new(path, rule) { + Ok(s) => search = Some(s), + Err(e) => lose_mesh(draw, &mut mesh, &mut lost, e)?, + } + } let face_limit = revolve_face_limit(o); // A face kept for a mesh: its normal follows from its corners. let keep = |mesh: &mut Vec, face: Vec, normal: V3| { @@ -1013,10 +1131,8 @@ fn revolve_faces( // Only the longest contour of a compound profile carries the graphics. let surface_contour = o.map_surface.then(|| longest_contour(path, axis)).flatten(); let mut faces = Vec::new(); - let vertex = |p: Point, step: usize| { - let (s, c) = (sweep * step as f64 / steps as f64).sin_cos(); - o.rotate(V3((p.x - axis) * c, p.y - center_y, (p.x - axis) * s)) - }; + let at = Sweeping { o, axis, center_y, sweep, steps }; + let vertex = |p: Point, step: usize| at.vertex(p, step); let normal = |tangent: Vec2, step: usize| { let (s, c) = (sweep * step as f64 / steps as f64).sin_cos(); o.rotate(V3(tangent.y * c, -tangent.x, tangent.y * s).unit()) @@ -1032,17 +1148,26 @@ fn revolve_faces( } Ok(()) }; - let mut count = 0; + // The points of the profile drawn, and of the profile kept for the mesh, which takes the parts + // its edges are cut into. + let (mut count, mut kept_count) = (0, 0); let mut curve_budget = 0; for (contour, sp) in path.subpaths.iter().enumerate() { - let mut profile = Vec::new(); - let mut tangents = Vec::new(); - let mut hole_edges = Vec::new(); + let (mut drawn, mut kept) = (Swept::default(), Swept::default()); if let Some(first) = sp.anchors.first() { - profile.push(first.p); - count += 1; - if count > MAX_PROFILE_POINTS { - return Err(TOO_COMPLEX_PROFILE.into()); + if draw { + drawn.points.push(first.p); + count += 1; + if count > MAX_PROFILE_POINTS { + return Err(TOO_COMPLEX_PROFILE.into()); + } + } + if mesh.is_some() { + kept.points.push(first.p); + kept_count += 1; + if kept_count > MAX_PROFILE_POINTS { + lose_mesh(draw, &mut mesh, &mut lost, TOO_COMPLEX_PROFILE.into())?; + } } } let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; @@ -1074,22 +1199,40 @@ fn revolve_faces( let v = d.eval(t.clamp(1e-7, 1.0 - 1e-7)).to_vec2(); if v.hypot2() > 1e-20 { v } else { b - a } }; - let a = profile.last().copied().unwrap_or(b); - let parts = match search.as_mut() { - Some(search) => search.parts(contour, a, b)?, - None => vec![(b, false)], - }; - for (end, hole) in parts { - tangents.push([tangent(t0), tangent(t1)]); - hole_edges.push(hole); - profile.push(end); + let ends = [tangent(t0), tangent(t1)]; + if draw { + drawn.tangents.push(ends); + drawn.holes.push(false); + drawn.points.push(b); count += 1; if count > MAX_PROFILE_POINTS { return Err(TOO_COMPLEX_PROFILE.into()); } } + let Some(search) = search.as_mut().filter(|_| mesh.is_some()) else { continue }; + let a = kept.points.last().copied().unwrap_or(b); + let parts = match search.parts(contour, a, b) { + Ok(parts) => parts, + Err(e) => { + lose_mesh(draw, &mut mesh, &mut lost, e)?; + continue; + } + }; + for (end, hole) in parts { + kept.tangents.push(ends); + kept.holes.push(hole); + kept.points.push(end); + kept_count += 1; + if kept_count > MAX_PROFILE_POINTS { + lose_mesh(draw, &mut mesh, &mut lost, TOO_COMPLEX_PROFILE.into())?; + break; + } + } } } + // The two profiles start and end at the same points: the parts of the last edge end where + // it does. + let profile = if draw { &drawn.points } else { &kept.points }; let ends = o.cap_ends && !sp.closed && profile.len() >= 2 && profile.first().zip(profile.last()).is_some_and(|(a, b)| a.distance(*b) > 1e-10); let mut rings = [None, None]; if ends { @@ -1101,33 +1244,49 @@ fn revolve_faces( } } } - // For a mesh: which way the profile runs round the region it sweeps (closed against the - // axis at its ends when it is open), so the faces' normals point out of the solid. - let turn = { - let mut ring: Vec<(f64, f64)> = profile.iter().map(|p| (p.x - axis, p.y)).collect(); - if let (false, Some(first), Some(last)) = (sp.closed, profile.first(), profile.last()) { - ring.extend([(0.0, last.y), (0.0, first.y)]); + // Which way a profile runs round the region it sweeps (closed against the axis at its ends + // when it is open), so the faces' normals point out of the solid. A closed contour that does + // not touch the axis has its side cut opposite the middle of its outer side; an anchor goes + // there, so no face runs across the cut. That one anchor is not counted against the limit + // on the profile's points. + let prepare = |s: &mut Swept| { + let turn = { + let mut ring: Vec<(f64, f64)> = s.points.iter().map(|p| (p.x - axis, p.y)).collect(); + if let (false, Some(first), Some(last)) = (sp.closed, s.points.first(), s.points.last()) { + ring.extend([(0.0, last.y), (0.0, first.y)]); + } + let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum(); + if area < 0.0 { -1.0 } else { 1.0 } + }; + if sp.closed + && surface_contour == Some(contour) + && let Some((k, t)) = ring_cut(&s.points, axis) + && let (Some(a), Some(b), Some([ta, tb]), Some(hole)) = + (s.points.get(k), s.points.get(k + 1), s.tangents.get(k).copied(), s.holes.get(k).copied()) + { + let point = *a + (*b - *a) * t; + let middle = ta + (tb - ta) * t; + s.points.insert(k + 1, point); + s.tangents.splice(k..=k, [[ta, middle], [middle, tb]]); + s.holes.insert(k + 1, hole); } - let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum(); - if area < 0.0 { -1.0 } else { 1.0 } + turn }; - // A closed contour that does not touch the axis has its side cut opposite the middle of its - // outer side; an anchor goes there, so no face runs across the cut. That one anchor is not - // counted against the limit on the profile's points. - if sp.closed - && surface_contour == Some(contour) - && let Some((k, t)) = ring_cut(&profile, axis) - && let (Some(a), Some(b), Some([ta, tb]), Some(hole)) = - (profile.get(k), profile.get(k + 1), tangents.get(k).copied(), hole_edges.get(k).copied()) - { - let point = *a + (*b - *a) * t; - let middle = ta + (tb - ta) * t; - profile.insert(k + 1, point); - tangents.splice(k..=k, [[ta, middle], [middle, tb]]); - hole_edges.insert(k + 1, hole); + if let Some(m) = mesh.as_deref_mut() { + let turn = prepare(&mut kept); + let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); + let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal)); + if let Err(e) = kept { + lose_mesh(draw, &mut mesh, &mut lost, e)?; + } } - let along = along_profile(&profile, axis, sp.closed); - for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(tangents).zip(hole_edges).enumerate() { + if !draw { + continue; + } + let turn = prepare(&mut drawn); + let profile = &drawn.points; + let along = along_profile(profile, axis, sp.closed); + for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() { let [a, b] = pair else { continue }; let turn = if hole { -turn } else { turn }; let [va, vb] = along.get(i).copied().unwrap_or_default(); @@ -1136,14 +1295,6 @@ fn revolve_faces( } for j in 0..steps { let [v0, v1, v2, v3] = [vertex(*a, j), vertex(*b, j), vertex(*b, j + 1), vertex(*a, j + 1)]; - if let Some(mesh) = mesh.as_deref_mut() { - // The edge's outward normal in the profile's plane (distance from the axis, - // height), swept to the middle of the step. - let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); - let (s, c) = (sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); - keep(mesh, vec![v0, v1, v2, v3], o.rotate(V3(dy * c, -dr, dy * s)))?; - continue; - } let first = (i == 0).then(|| rings.first().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten(); let last = (i + 2 == profile.len()).then(|| rings.last().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten(); // Where the corners lie on the unrolled side surface, and whether the face shows @@ -1186,28 +1337,7 @@ fn revolve_faces( } } for (index, ring) in rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|r| (i, r))) { - let neighbours = - if index == 0 { profile.first().zip(profile.get(1)) } else { profile.last().zip(profile.get(profile.len().saturating_sub(2))) }; - if let Some((end, neighbour)) = neighbours { - let dy = end.y - neighbour.y; - let outward = if dy.abs() > 1e-10 { - dy.signum() - } else if end.y < center_y { - -1.0 - } else { - 1.0 - }; - if let Some(mesh) = mesh.as_deref_mut() { - // The disk, or for a partial sweep the sector with its centre on the axis. - let mut cap: Vec = (0..=steps).map(|j| vertex(*end, j)).collect(); - if o.angle >= 360.0 { - cap.pop(); - } else { - cap.insert(0, o.rotate(V3(0.0, end.y - center_y, 0.0))); - } - keep(mesh, cap, o.rotate(V3(0.0, outward, 0.0)))?; - continue; - } + if let Some((_, outward)) = cap_outward(profile, index, center_y) { // Keep the original tessellation work budget, even though each cap // now produces only one curved vector face. emit(ring.face(bounds, o, light, outward)?, steps)?; @@ -1215,7 +1345,7 @@ fn revolve_faces( } } faces.sort_by(|a, b| a.depth.total_cmp(&b.depth)); - Ok(faces) + Ok((faces, lost)) } #[cfg(test)] diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 2d32850423..b580ddcd5f 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -12,7 +12,7 @@ use std::ops::Range; use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; use crate::solid::{Face3, Keep, extrude_faces, inflate_faces, plane_faces}; -use crate::{Extrude, Inflate, MAX_SOLID_FACES, Revolve, V3, View, finite, perspective_scale}; +use crate::{Extrude, Face, Facet, Inflate, MAX_SOLID_FACES, Revolve, V3, View, finite, perspective_scale}; /// Where the shadow falls. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -203,6 +203,14 @@ impl ShadowCaster { self.add(faces, Some(crate::revolve_projection(bounds, o))) } + /// Add the faces of a solid kept by the build that drew it ([`extrude_shadowed`], + /// [`plane_shadowed`], [`inflate_shadowed`], [`revolve_shadowed`]): the faces + /// [`ShadowCaster::extrude`], [`ShadowCaster::plane`], [`ShadowCaster::inflate`] or + /// [`ShadowCaster::revolve`] adds for that solid, or the error it gives. + pub fn add_solid(&mut self, solid: SolidFaces) -> Result, String> { + self.add(solid.faces?, solid.projection) + } + /// The shadow of the faces gathered, on the page, filled with the nonzero rule: `None` when /// there are none, when the first light lights nothing (Shading is off or its intensity is 0) /// or does not reach the plane (it is behind the object for a shadow behind it, or below the @@ -291,6 +299,56 @@ impl ShadowCaster { } } +/// A solid's faces before projection, kept by the build that drew it, for its shadow +/// ([`ShadowCaster::add_solid`]): the faces, or the error keeping them gave, and the projection the +/// solid was drawn with. +#[derive(Clone, Debug)] +pub struct SolidFaces { + faces: Result, String>, + projection: Option, +} + +/// Extrude & Bevel's solid ([`crate::extrude`]) and, from the same build, the faces +/// [`ShadowCaster::extrude`] adds for it. An error where [`crate::extrude`] gives one. +pub fn extrude_shadowed(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, view: View) -> Result<(Vec, SolidFaces), String> { + let (facets, faces, projection) = extrude_faces(path, rule, bounds, options, view, Keep::Both)?; + Ok((facets, SolidFaces { faces, projection })) +} + +/// Rotate's plane ([`crate::plane`]) and, from the same build, the face [`ShadowCaster::plane`] +/// adds for it. An error where [`crate::plane`] gives one. +pub fn plane_shadowed(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result<(Vec, SolidFaces), String> { + let (facets, faces, projection) = plane_faces(path, rule, bounds, view, Keep::Both)?; + Ok((facets, SolidFaces { faces, projection })) +} + +/// Inflate's solids for several shapes of one object ([`crate::inflate_each`]) and, from the same +/// builds, the faces [`ShadowCaster::inflate`] adds for each, each solid built as the iterator +/// reaches it. An error where [`crate::inflate_each`] gives one. +pub fn inflate_shadowed( + shapes: &[(&PathData, FillRule)], + bounds: Rect, + options: Inflate, + view: View, +) -> impl Iterator, SolidFaces), String>> + use<> { + inflate_faces(shapes, bounds, options, view, Keep::Both).map(|r| r.map(|(facets, faces, projection)| (facets, SolidFaces { faces, projection }))) +} + +/// Revolve's surface ([`crate::revolve`]) and, from the same sweep, the faces +/// [`ShadowCaster::revolve`] adds for it with the nonzero fill rule. An error where +/// [`crate::revolve`] gives one. +pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { + let mut kept = vec![]; + let (faces, lost) = crate::revolve_sweep(path, FillRule::NonZero, bounds, options, true, Some(&mut kept))?; + let projection = Some(crate::revolve_projection(bounds, options.sanitized())); + Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection })) +} + +/// [`revolve_shadowed`] with the faces as facets, as [`crate::revolve_facets`] gives them. +pub fn revolve_facets_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { + revolve_shadowed(path, bounds, options).map(|(faces, kept)| (faces.into_iter().map(Facet::of_face).collect(), kept)) +} + /// Whether `area`, the signed area of a polygon with corners `points`, is within rounding of /// nothing for its size (the square of its bounds' diagonal), or not a number, so the polygon draws /// nothing. A long, narrow polygon keeps an area well above that. diff --git a/crates/three-d/src/shadow/tests.rs b/crates/three-d/src/shadow/tests.rs index 00aedc3a53..1e3f5c437b 100644 --- a/crates/three-d/src/shadow/tests.rs +++ b/crates/three-d/src/shadow/tests.rs @@ -186,6 +186,247 @@ fn every_effect_casts_a_shadow() { assert!(b.x1 > 100.0 && b.x0 < 100.0 + 1e-6, "{b:?}"); } +/// The faces `caster` gathered and the projection it keeps, every number to the bit. +fn gathered(caster: &ShadowCaster) -> String { + format!("{:?} {:?}", caster.faces, caster.projection) +} + +/// What a solid kept for its shadow casts ([`casts`]). +fn cast_from(solid: SolidFaces) -> Result<(String, Option, Option), String> { + let mut caster = ShadowCaster::new(); + caster.add_solid(solid)?; + Ok(casts(&caster)) +} + +/// The faces `caster` gathered, and the shadows they cast behind and below. +fn casts(caster: &ShadowCaster) -> (String, Option, Option) { + let below = Shadow { position: ShadowPosition::Below, distance: 0.3, ..Shadow::default() }; + (gathered(caster), caster.path(Shadow::default()), caster.path(below)) +} + +/// A star of `points` points about (100, 100), its edges curved, with a square hole. +fn star(points: usize) -> PathData { + let mut b = BezPath::new(); + for k in 0..2 * points { + let (s, c) = (k as f64 * std::f64::consts::PI / points as f64).sin_cos(); + let r = if k % 2 == 0 { 90.0 } else { 45.0 }; + let p = (100.0 + r * c, 100.0 + r * s); + if k == 0 { b.move_to(p) } else { b.curve_to((p.0 + 3.0, p.1), (p.0, p.1 + 3.0), p) } + } + b.close_path(); + rect(&mut b, 90.0, 90.0, 20.0, 20.0); + PathData::from_bezpath(&b) +} + +/// A closed rectangle from (`x`, `y`), `w` wide and `h` high. +fn rect(b: &mut BezPath, x: f64, y: f64, w: f64, h: f64) { + b.move_to((x, y)); + b.line_to((x + w, y)); + b.line_to((x + w, y + h)); + b.line_to((x, y + h)); + b.close_path(); +} + +/// The views the solids are compared in: straight on, turned, with perspective, and with colored +/// lights. +fn views() -> Vec { + let turned = View { rotation_x: -25.0, rotation_y: 35.0, rotation_z: 10.0, ..View::default() }; + vec![front(), turned, View { perspective: 60.0, ..turned }, View { light_color: [1.0, 0.5, 0.25], ..turned }] +} + +/// Extrude & Bevel built once for its facets and its shadow gives the facets [`crate::extrude`] +/// gives and casts what [`ShadowCaster::extrude`] casts, to the bit, errors included. +#[test] +fn an_extruded_solid_and_its_shadow_match_the_two_built_apart() { + use crate::{Bevel, BevelShape}; + let bevel = Bevel { shape: BevelShape::Rounded, width: 6.0, height: 5.0, ..Bevel::default() }; + let options = [ + Extrude::default(), + Extrude { depth: 0.0, ..Extrude::default() }, + Extrude { cap: false, ..Extrude::default() }, + Extrude { hidden: true, ..Extrude::default() }, + Extrude { twist: 90.0, taper: 0.6, ..Extrude::default() }, + Extrude { bevel: Some(bevel), ..Extrude::default() }, + Extrude { bevel: Some(Bevel { both_sides: true, inside: true, ..bevel }), twist: 45.0, ..Extrude::default() }, + ]; + let path = star(7); + let r = path.bounds().unwrap(); + for view in views() { + for o in options { + let (facets, faces) = extrude_shadowed(&path, FillRule::NonZero, r, o, view).unwrap(); + let apart = crate::extrude(&path, FillRule::NonZero, r, o, view).unwrap(); + assert_eq!(format!("{facets:?}"), format!("{apart:?}"), "{o:?} {view:?}"); + let mut caster = ShadowCaster::new(); + caster.extrude(&path, FillRule::NonZero, r, o, view).unwrap(); + assert!(!caster.is_empty()); + assert_eq!(cast_from(faces), Ok(casts(&caster)), "{o:?} {view:?}"); + } + } + let flat = Rect::new(0.0, 0.0, f64::INFINITY, 10.0); + let error = crate::extrude(&path, FillRule::NonZero, flat, Extrude::default(), front()).err(); + assert!(error.is_some()); + assert_eq!(extrude_shadowed(&path, FillRule::NonZero, flat, Extrude::default(), front()).err(), error); +} + +/// Rotate's plane built once for its facet and its shadow matches the two built apart. +#[test] +fn a_rotated_plane_and_its_shadow_match_the_two_built_apart() { + let path = star(5); + let r = path.bounds().unwrap(); + for view in views() { + for rule in [FillRule::NonZero, FillRule::EvenOdd] { + let (facets, faces) = plane_shadowed(&path, rule, r, view).unwrap(); + assert_eq!(format!("{facets:?}"), format!("{:?}", crate::plane(&path, rule, r, view).unwrap()), "{view:?}"); + let mut caster = ShadowCaster::new(); + caster.plane(&path, rule, r, view).unwrap(); + assert_eq!(cast_from(faces), Ok(casts(&caster)), "{view:?}"); + } + } +} + +/// Inflate's solids built once for their facets and shadows match the two built apart: several +/// puffs under one eye, both sides, open backs, and twisted sides cut finer than room is left for. +#[test] +fn inflated_solids_and_their_shadows_match_the_two_built_apart() { + let star = star(5); + let box_ = square(200.0, 20.0, 60.0); + let ring: Vec = (0..600) + .map(|k| { + let (s, c) = (k as f64 * std::f64::consts::TAU / 600.0).sin_cos(); + Point::new(100.0 + 90.0 * c, 100.0 + 90.0 * s) + }) + .collect(); + let ring = PathData::single(vectorcraft_geom::SubPath::polyline(&ring, true)); + let sets = [vec![(&star, FillRule::NonZero), (&box_, FillRule::NonZero), (&star, FillRule::EvenOdd)], vec![(&ring, FillRule::NonZero)]]; + let bounds = Rect::new(0.0, 0.0, 280.0, 200.0); + let options = [ + Inflate::default(), + Inflate { depth: 30.0, both_sides: true, ..Inflate::default() }, + Inflate { depth: 20.0, cap: false, volume: 80.0, ..Inflate::default() }, + Inflate { depth: 40.0, twist: 360.0, taper: 0.7, both_sides: true, ..Inflate::default() }, + // Thin and barely twisted: the star's sides want more pieces than room is left after its + // front and back, and the shadow, which keeps the faces turned away, has less room left. + Inflate { depth: 0.1, twist: 0.1, both_sides: true, ..Inflate::default() }, + ]; + for shapes in &sets { + for view in views() { + for o in options { + let built: Vec<_> = inflate_shadowed(shapes, bounds, o, view).collect(); + let facets: Vec<_> = crate::inflate_each(shapes, bounds, o, view).collect(); + let mut caster = ShadowCaster::new(); + let added = caster.inflate(shapes, &vec![true; shapes.len()], bounds, o, view); + assert!(added.iter().all(Result::is_ok)); + assert_eq!(built.len(), shapes.len()); + let mut one = ShadowCaster::new(); + for (b, f) in built.into_iter().zip(&facets) { + let ((facets, faces), f) = (b.unwrap(), f.as_ref().unwrap()); + assert_eq!(format!("{facets:?}"), format!("{f:?}"), "{o:?} {view:?}"); + one.add_solid(faces).unwrap(); + } + assert_eq!(casts(&one), casts(&caster), "{o:?} {view:?}"); + } + } + } +} + +/// Revolve's surface swept once for its faces and its shadow gives the faces [`crate::revolve`] +/// gives and casts what [`ShadowCaster::revolve`] casts, to the bit: an open profile with caps, +/// closed contours that cross (their walls cut where they do), a hole, partial sweeps, smooth and +/// flat shading, and the cut side that graphics take. +#[test] +fn a_revolved_surface_and_its_shadow_match_the_two_swept_apart() { + let mut open = BezPath::new(); + open.move_to((120.0, 0.0)); + open.curve_to((160.0, 20.0), (100.0, 60.0), (140.0, 90.0)); + open.line_to((125.0, 120.0)); + let mut crossing = BezPath::new(); + rect(&mut crossing, 110.0, 0.0, 60.0, 80.0); + rect(&mut crossing, 150.0, 40.0, 40.0, 80.0); + let mut holed = BezPath::new(); + holed.move_to((110.0, 0.0)); + holed.curve_to((200.0, 0.0), (200.0, 120.0), (110.0, 120.0)); + holed.close_path(); + rect(&mut holed, 130.0, 40.0, 20.0, 30.0); + let paths = [open, crossing, holed].map(|b| PathData::from_bezpath(&b)); + let turned = Revolve { rotation_x: -20.0, rotation_y: 30.0, ..Revolve::default() }; + let options = [ + Revolve::default(), + turned, + Revolve { angle: 200.0, perspective: 40.0, ..turned }, + Revolve { smooth_shading: false, segments: 12, ..turned }, + Revolve { cap_ends: false, offset: 15.0, ..turned }, + Revolve { map_surface: true, edge: crate::Edge::Right, ..turned }, + Revolve { map_surface: true, angle: 300.0, curve_samples: Some(5), ..turned }, + ]; + for path in &paths { + let bounds = path.bounds().unwrap(); + for o in options { + let (faces, kept) = revolve_shadowed(path, bounds, o).unwrap(); + assert_eq!(format!("{faces:?}"), format!("{:?}", crate::revolve(path, bounds, o).unwrap()), "{o:?}"); + let (facets, also) = revolve_facets_shadowed(path, bounds, o).unwrap(); + assert_eq!(format!("{facets:?}"), format!("{:?}", crate::revolve_facets(path, bounds, o).unwrap()), "{o:?}"); + assert_eq!(cast_from(also), cast_from(kept.clone()), "{o:?}"); + let mut caster = ShadowCaster::new(); + caster.revolve(path, FillRule::NonZero, bounds, o).unwrap(); + assert!(!caster.is_empty()); + assert_eq!(cast_from(kept), Ok(casts(&caster)), "{o:?}"); + } + } +} + +/// A surface whose shadow is past the limit on the profile's points (its walls cut where they +/// cross another contour) still draws every face, and its shadow gives the error the shadow swept +/// alone gives. +#[test] +fn a_surface_whose_shadow_is_too_complex_still_draws() { + let mut b = BezPath::new(); + b.move_to((110.0, 0.0)); + for i in 1..6000 { + b.line_to((110.0 + f64::from(i) * 0.02, if i % 2 == 0 { 0.0 } else { 10.0 })); + } + b.line_to((110.0, 20.0)); + b.close_path(); + rect(&mut b, 100.0, 4.0, 140.0, 2.0); + let path = PathData::from_bezpath(&b); + let bounds = path.bounds().unwrap(); + let o = Revolve { segments: 4, smooth_shading: false, ..Revolve::default() }; + let (faces, kept) = revolve_shadowed(&path, bounds, o).unwrap(); + let drawn = crate::revolve(&path, bounds, o).unwrap(); + assert!(!drawn.is_empty()); + assert!(faces == drawn); + let alone = ShadowCaster::new().revolve(&path, FillRule::NonZero, bounds, o).unwrap_err(); + assert!(alone.contains("too complex"), "{alone}"); + assert_eq!(cast_from(kept).unwrap_err(), alone); +} + +/// One build gives the facets and the faces of the shadow: each solid is built once. +#[test] +fn a_solid_and_its_shadow_are_built_once() { + let path = star(5); + let r = path.bounds().unwrap(); + let count = |n: &'static std::thread::LocalKey>| n.with(std::cell::Cell::get); + let start = count(&crate::solid::EXTRUDED); + let (facets, faces) = extrude_shadowed(&path, FillRule::NonZero, r, Extrude::default(), front()).unwrap(); + assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some())); + assert_eq!(count(&crate::solid::EXTRUDED), start + 1); + let start = count(&crate::solid::PLANES); + let (facets, faces) = plane_shadowed(&path, FillRule::NonZero, r, front()).unwrap(); + assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some())); + assert_eq!(count(&crate::solid::PLANES), start + 1); + let start = count(&crate::solid::INFLATED); + let box_ = square(200.0, 20.0, 60.0); + let shapes = [(&path, FillRule::NonZero), (&box_, FillRule::NonZero)]; + for solid in inflate_shadowed(&shapes, Rect::new(0.0, 0.0, 280.0, 200.0), Inflate::default(), front()) { + let (facets, faces) = solid.unwrap(); + assert!(!facets.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some())); + } + assert_eq!(count(&crate::solid::INFLATED), start + 2); + let start = count(&crate::REVOLVED); + let (drawn, faces) = revolve_shadowed(&path, r, Revolve::default()).unwrap(); + assert!(!drawn.is_empty() && cast_from(faces).is_ok_and(|c| c.1.is_some())); + assert_eq!(count(&crate::REVOLVED), start + 1); +} + /// An Inflate shape that casts nothing still places the eye with its puff, but its solid is not /// built (nor, with no volume, its puff solved); the shapes that cast keep the very faces and /// projection they have when every shape casts. diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 6badd8048a..18ef7d6d1b 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -23,6 +23,8 @@ mod rings; #[cfg(test)] pub(crate) use build::EXTRUDED; #[cfg(test)] +pub(crate) use build::PLANES; +#[cfg(test)] use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, plane}; diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index f3fda46685..d734161343 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -705,6 +705,13 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Ok(b.finish()) } +#[cfg(test)] +thread_local! { + /// How many Rotate planes (and Extrude & Bevel solids with no depth) this thread has built, for + /// the tests. + pub(crate) static PLANES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Rotate: the flat art turned in 3D about the centre of `bounds` (which may be larger than the /// shape's own, so that every part of one object turns about the same point). pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Result, String> { @@ -713,6 +720,8 @@ pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Resul /// [`plane`], keeping its facet, its face before projection, or both, as `keep` asks. pub(crate) fn plane_faces(path: &PathData, rule: FillRule, bounds: Rect, view: View, keep: Keep) -> Result { + #[cfg(test)] + PLANES.with(|n| n.set(n.get() + 1)); check_bounds(bounds)?; let rings = solid_rings_traced(path, rule, bounds.width().max(bounds.height()), MAX_PLANE_POINTS, CURVE_PIECES)?; let camera = Camera::new(view, bounds, 0.0); diff --git a/crates/tools/src/builder/lookup.rs b/crates/tools/src/builder/lookup.rs index f577732ade..8e17823332 100644 --- a/crates/tools/src/builder/lookup.rs +++ b/crates/tools/src/builder/lookup.rs @@ -505,8 +505,8 @@ fn collect_members<'a>(n: &'a Node, builder: bool, out: &mut Vec<&'a Node>) { NodeKind::Path { guide: true, .. } | NodeKind::Path { clipping: true, .. } => {} NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push(n), NodeKind::Group { .. } if builder && is_live_paint(n) => { - out.extend(faces(n).into_iter().filter(|f| !f.visible || f.locked || !f.appearance.fill_paint().is_none()).map(|f| &**f)); - out.extend(edges(n).into_iter().filter(|e| !e.visible || e.locked || !e.appearance.stroke_paint().is_none()).map(|e| &**e)); + out.extend(faces(n).into_iter().filter(|f| !f.visible || f.locked || (f.opacity > 0.0 && f.appearance.has_drawn_fill())).map(|f| &**f)); + out.extend(edges(n).into_iter().filter(|e| !e.visible || e.locked || (e.opacity > 0.0 && e.appearance.has_drawn_stroke())).map(|e| &**e)); } NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { for c in children { @@ -587,9 +587,12 @@ fn shapes_of<'a>(doc: &'a Document, roots: &[NodeId], builder: bool) -> (Vec(doc: &'a Document, roots: &[NodeId], open_filled_as_closed: bool) -> (Vec, Vec<&'a Node>) { let (mut shapes, leaves) = shapes_of(doc, roots, true); @@ -600,7 +603,7 @@ pub fn shape_builder_shapes<'a>(doc: &'a Document, roots: &[NodeId], open_filled s.path.subpaths = s.path.subpaths.iter().flat_map(|sp| sp.cut_at(&start)).collect(); continue; } - if !open_filled_as_closed || l.appearance.fill_paint().is_none() { + if !open_filled_as_closed || !l.appearance.has_drawn_fill() { continue; } for sp in s.path.subpaths.iter_mut().filter(|sp| !sp.closed) { diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index 74ec31f69a..6b524e9af9 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -364,7 +364,8 @@ impl BuilderMap { } /// What a merge needs of each input besides the map: its outline as drawn ([`node_outline`]) and -/// whether its fill closes its open subpaths (Consider Open Filled Paths as Closed, and a fill). +/// whether its fill closes its open subpaths (Consider Open Filled Paths as Closed, and a fill row +/// that draws). #[derive(Clone, Debug, PartialEq)] pub struct MergeInput { pub outline: Option, @@ -375,7 +376,7 @@ pub struct MergeInput { pub fn merge_inputs(leaves: &[&Node], open_filled_as_closed: bool) -> Vec { leaves .iter() - .map(|l| MergeInput { outline: node_outline(l).map(|o| o.0), fill_closes: open_filled_as_closed && !l.appearance.fill_paint().is_none() }) + .map(|l| MergeInput { outline: node_outline(l).map(|o| o.0), fill_closes: open_filled_as_closed && l.appearance.has_drawn_fill() }) .collect() } diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index e6db6069c7..1e8f57ffc9 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -329,6 +329,8 @@ pub struct ToolContext<'a> { pub screen: Option, /// Where the Plane Switching Widget sits (Perspective Grid Options); None while it's hidden. pub plane_widget: Option, + /// What Automatic Plane Positioning takes a point from (Perspective Grid Options). + pub plane_targets: distort::perspective::widget::PlaneTargets, /// General › Use Precise Cursors, or Caps Lock while it is on: the drawing tools' pointers are /// crosshairs ([`crate::Cursor::precise`]), and the Blob Brush and the Eraser show no tip outline. pub precise_cursors: bool, diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rs index 2e9ecb558b..72cb02b6db 100644 --- a/crates/tools/src/distort/perspective.rs +++ b/crates/tools/src/distort/perspective.rs @@ -26,6 +26,7 @@ use crate::bbox::{Handle as BoxHandle, scale_for_drag}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; pub mod define; +pub mod infer; pub mod view; pub mod widget; pub use define::{GridDefinition, Rgb, Station}; @@ -183,6 +184,11 @@ pub struct PerspectiveGrid { /// Horizontal extent of the right plane (points, plane units); None: `extent`, as the left. #[serde(default, skip_serializing_if = "Option::is_none")] pub extent_right: Option, + /// Automatic Plane Positioning: the point (x, y and z in the grid's frame, points, as + /// [`Axis`] names them) the active plane passes through for now, while the other planes hide + /// ([`infer`]). View state. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub inferred: Option<[f64; 3]>, } impl PerspectiveGrid { @@ -224,11 +230,18 @@ impl PerspectiveGrid { snap: true, rulers: false, extent_right: None, + inferred: None, } } - /// Where `plane` is along its normal (points; 0: its place in the grid's definition). + /// Where `plane` is along its normal (points; 0: its place in the grid's definition): for the + /// active plane held by Automatic Plane Positioning, where that holds it. pub fn offset(&self, plane: Plane) -> f64 { + self.inferred_offset(plane).unwrap_or_else(|| self.placed_offset(plane)) + } + + /// Where `plane` was moved along its normal, Automatic Plane Positioning aside. + pub fn placed_offset(&self, plane: Plane) -> f64 { match plane { Plane::Left => self.left_offset, Plane::Right => self.right_offset, @@ -325,7 +338,8 @@ impl PerspectiveGrid { let mut v = serde_json::to_value(self).map_err(|e| e.to_string())?; if let (Some(o), Some(p)) = (v.as_object_mut(), patch.as_object()) { for (k, val) in p { - if k == "ids" || k == "attached" { + // Automatic Plane Positioning's point is `perspective.plane.infer`'s to set. + if k == "ids" || k == "attached" || k == "inferred" { continue; } o.insert(k.clone(), val.clone()); @@ -333,6 +347,7 @@ impl PerspectiveGrid { } let mut g: Self = serde_json::from_value(v).map_err(|e| e.to_string())?; g.reconcile(self, patch); + g.keep_positioning_valid(); g.validate()?; Ok(g) } @@ -354,7 +369,7 @@ impl PerspectiveGrid { self.extent, self.height, ]; - if nums.iter().any(|v| !v.is_finite() || v.abs() > 4.0e6) { + if nums.iter().chain(self.inferred.iter().flatten()).any(|v| !v.is_finite() || v.abs() > 4.0e6) { return Err("grid values must be finite".into()); } if self.distance <= 0.0 || self.cell <= 0.0 || self.extent <= 0.0 || self.height <= 0.0 { @@ -563,10 +578,31 @@ impl PerspectiveGrid { let Some(h) = self.homography(plane) else { return vec![] }; let d = self.domain(plane); let mut out = vec![]; + let (w, h_len) = (d.width(), d.height()); + let Some(((su, nu), (sv, nv))) = self.line_steps(plane) else { return out }; + for i in 0..=nu { + let u = i as f64 * su; + if let (Some(a), Some(b)) = (h.apply(Point::new(u, 0.0)), h.apply(Point::new(u, h_len))) { + out.push((a, b)); + } + } + for i in 0..=nv { + let v = i as f64 * sv; + if let (Some(a), Some(b)) = (h.apply(Point::new(0.0, v)), h.apply(Point::new(w, v))) { + out.push((a, b)); + } + } + out + } + + /// How the gridlines of `plane` are spaced as drawn: (step, the number of the last line) along + /// its u and its v axis. `None` for a grid without lines. + pub(crate) fn line_steps(&self, plane: Plane) -> Option<((f64, usize), (f64, usize))> { + let d = self.domain(plane); // A stored grid is not checked: no spacing, or an extent that isn't a number, has no lines. let (w, h_len) = (d.width(), d.height()); if !(self.cell.is_finite() && self.cell > 0.0 && w.is_finite() && h_len.is_finite()) { - return out; + return None; } let step = |len: f64| { let mut s = self.cell; @@ -580,19 +616,7 @@ impl PerspectiveGrid { // tolerance can inflate the count when the whole domain is far smaller than it, so the // bound is capped on its own, before any loop runs. let count = |len: f64, s: f64| ((len + 1e-9) / s).floor().clamp(0.0, 120.0) as usize; - for i in 0..=count(w, su) { - let u = i as f64 * su; - if let (Some(a), Some(b)) = (h.apply(Point::new(u, 0.0)), h.apply(Point::new(u, h_len))) { - out.push((a, b)); - } - } - for i in 0..=count(h_len, sv) { - let v = i as f64 * sv; - if let (Some(a), Some(b)) = (h.apply(Point::new(0.0, v)), h.apply(Point::new(w, v))) { - out.push((a, b)); - } - } - out + Some(((su, count(w, su)), (sv, count(h_len, sv)))) } /// Plane Switching widget geometry in the first artboard's top-left corner (headless): (plane, @@ -611,10 +635,10 @@ impl PerspectiveGrid { } /// The left, right and horizontal plane widgets: where each sits (on its plane: the middle of a - /// wall's ground edge, the middle of the horizontal plane). + /// wall's ground edge, the middle of the horizontal plane). A hidden plane has none. pub fn plane_widgets(&self) -> Vec<(Plane, Point)> { let e = self.extent / 2.0; - Plane::ALL + self.shown_planes() .into_iter() .filter_map(|pl| { let q = if pl == Plane::Ground { Point::new(e, e) } else { Point::new(e, 0.0) }; @@ -793,7 +817,7 @@ pub fn grid_overlays_in(doc: &Document, tol: f64, place: Option &'static str { + match self { + Self::Anchor => "anchor", + Self::Gridline => "gridline", + } + } +} + +impl Axis { + /// Where the axis' coordinate is in a point of the grid's frame. + fn index(self) -> usize { + match self { + Self::X => 0, + Self::Y => 1, + Self::Z => 2, + } + } +} + +/// Call `f` with each shown object in perspective that isn't inside another one, its plane and +/// its depth: its own record, else the one grid `g` stored before attachments were kept on the +/// objects ([`PerspectiveGrid::attachment_of`]). +fn each_attached<'a>(g: &PerspectiveGrid, n: &'a Node, f: &mut dyn FnMut(&'a Node, Plane, f64)) { + if !n.visible { + return; + } + match attachment(n).or_else(|| g.attached_plane(n.id).map(|p| (p, 0.0))) { + Some((pl, depth)) => f(n, pl, depth), + None => n.children().into_iter().flatten().for_each(|c| each_attached(g, c, f)), + } +} + +/// Call `f` with `n` and each node inside it, leaving out hidden nodes and what they hold. +fn each_shown<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) { + if !n.visible { + return; + } + f(n); + n.children().into_iter().flatten().for_each(|c| each_shown(c, f)); +} + +impl PerspectiveGrid { + /// Where Automatic Plane Positioning holds `plane`: the active plane only. + pub(super) fn inferred_offset(&self, plane: Plane) -> Option { + let p = self.inferred?; + if plane != self.plane { + return None; + } + let [.., n] = self.axes(plane)?; + Some(p[n.index()]) + } + + /// The planes that show: all three, or only the active one while Automatic Plane Positioning + /// holds it. + pub fn shown_planes(&self) -> Vec { + match self.inferred { + Some(_) if self.plane != Plane::None => vec![self.plane], + _ => Plane::ALL.to_vec(), + } + } + + /// The point of the grid's frame at plane coordinates `q` on `plane` at `depth`. + fn frame_point(&self, plane: Plane, depth: f64, q: Point) -> Option<[f64; 3]> { + let [u, v, n] = self.axes(plane)?; + let mut out = [0.0; 3]; + out[u.index()] = q.x; + out[v.index()] = q.y; + out[n.index()] = depth; + Some(out) + } + + /// The anchor point of shown art in perspective nearest `p` within `tol`: (distance, frame point). + fn anchor_near(&self, doc: &Document, p: Point, tol: f64) -> Option<(f64, [f64; 3])> { + let mut best: Option<(f64, [f64; 3])> = None; + let mut visit = |n: &Node, plane: Plane, depth: f64| { + // The plane's inverse map, worked out only once an anchor is within reach. + let mut hi = None; + each_shown(n, &mut |c| { + let NodeKind::Path { path, .. } = &c.kind else { return }; + for a in path.subpaths.iter().flat_map(|sp| sp.anchors.iter()) { + let d = a.p.distance(p); + if !(d <= tol && best.is_none_or(|b| d < b.0)) { + continue; + } + let inv = hi.get_or_insert_with(|| self.homography_at(plane, depth).and_then(|h| h.inverse())); + if let Some(at) = inv.as_ref().and_then(|m| m.apply(a.p)).and_then(|q| self.frame_point(plane, depth, q)) { + best = Some((d, at)); + } + } + }); + }; + for l in &doc.layers { + each_attached(self, l, &mut visit); + } + best + } + + /// The gridline intersection of a shown plane nearest `p` within `tol`: (distance, frame point). + fn intersection_near(&self, p: Point, tol: f64) -> Option<(f64, [f64; 3])> { + let mut best: Option<(f64, [f64; 3])> = None; + for plane in self.shown_planes() { + let depth = self.offset(plane); + let Some(h) = self.homography_at(plane, depth) else { continue }; + let Some(q) = h.inverse().and_then(|hi| hi.apply(p)) else { continue }; + let Some(((su, nu), (sv, nv))) = self.line_steps(plane) else { continue }; + // The drawn lines nearest the pointer along each axis, and their neighbors: the + // projection skews and shrinks the cells, so the intersection nearest on the page can be + // one over from the nearest in the plane. + let near = |v: f64, step: f64, last: usize| { + let i = (v / step).round().clamp(0.0, last as f64) as i64; + (i - 2..=i + 2).filter(move |k| (0..=last as i64).contains(k)).map(move |k| k as f64 * step) + }; + for (u, v) in near(q.x, su, nu).flat_map(|u| near(q.y, sv, nv).map(move |v| (u, v))) { + let q = Point::new(u, v); + let Some(d) = h.apply(q).map(|at| at.distance(p)) else { continue }; + if d <= tol + && best.is_none_or(|b| d < b.0) + && let Some(at) = self.frame_point(plane, depth, q) + { + best = Some((d, at)); + } + } + } + best + } + + /// What Automatic Plane Positioning finds within `tol` of page point `p`: the nearest anchor + /// point of shown art in perspective, else the nearest gridline intersection of a shown plane, + /// as a point of the grid's frame. `None` while the grid is hidden or has no active plane. + pub fn infer_at(&self, doc: &Document, p: Point, tol: f64, targets: PlaneTargets) -> Option<(InferSource, [f64; 3])> { + if !self.visible || self.plane == Plane::None || !(tol.is_finite() && p.x.is_finite() && p.y.is_finite()) { + return None; + } + let anchor = if targets.anchors { self.anchor_near(doc, p, tol) } else { None }; + let found = match anchor { + Some((_, at)) => Some((InferSource::Anchor, at)), + None if targets.gridlines => self.intersection_near(p, tol).map(|(_, at)| (InferSource::Gridline, at)), + None => None, + }; + found.filter(|(_, at)| at.iter().all(|v| v.is_finite())) + } + + /// Put a plane that Automatic Plane Positioning holds in the grid stored in `doc` back in its + /// place. Returns whether one was held. + pub fn end_positioning(doc: &mut Document) -> bool { + if !Self::positioning(doc) { + return false; + } + doc.unknown.get_mut(DOC_KEY).and_then(|v| v.as_object_mut()).is_some_and(|o| o.remove("inferred").is_some()) + } + + /// Drop the point Automatic Plane Positioning holds when the grid no longer shows, has no + /// active plane, or would put the active plane behind the viewer through it. + pub fn keep_positioning_valid(&mut self) { + if self.inferred.is_some() && (!self.visible || self.plane == Plane::None || self.validate().is_err()) { + self.inferred = None; + } + } + + /// Whether Automatic Plane Positioning holds a plane of the grid stored in `doc`. + pub fn positioning(doc: &Document) -> bool { + doc.unknown.get(DOC_KEY).and_then(|v| v.get("inferred")).is_some_and(|v| !v.is_null()) + } +} + +/// The Perspective Selection tool's step for Shift held over `p` with no button down: the command +/// that moves the active plane through the anchor point or gridline intersection there, unless +/// the plane is held through that point already. +pub(super) fn hover_action(cx: &ToolContext, g: &PerspectiveGrid, p: Point) -> Option { + let tol = cx.tol(HIT_PX); + let (_, at) = g.infer_at(cx.doc, p, tol, cx.plane_targets)?; + if g.inferred.is_some_and(|held| held.iter().zip(&at).all(|(a, b)| (a - b).abs() <= 1e-9)) { + return None; + } + Some(Action::Exec("perspective.plane.infer".into(), json!({"at": [p.x, p.y], "tolerance": tol}))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + use crate::{Mods, PointerEvent, PointerKind, Tool, ToolKey}; + use vectorcraft_doc::Selection; + use vectorcraft_geom::Rect; + + fn grid() -> PerspectiveGrid { + PerspectiveGrid::preset(2, Rect::new(0.0, 0.0, 800.0, 600.0)) + } + + #[test] + fn a_gridline_intersection_gives_the_frame_point_the_planes_pass_through() { + let mut g = grid(); + let (d, cell) = (Document::new(800.0, 600.0), g.cell); + // Three cells along and two up the left wall (two-point: u recedes along Z, v is Y). + let p = g.to_page(Plane::Left, Point::new(3.0 * cell, 2.0 * cell)).unwrap(); + let (source, at) = g.infer_at(&d, p, 1.0, PlaneTargets::ALL).unwrap(); + assert_eq!(source, InferSource::Gridline); + for (got, want) in at.iter().zip([0.0, 2.0 * cell, 3.0 * cell]) { + assert!((got - want).abs() < 1e-6, "{at:?}"); + } + // Held, the active plane lies at the point's coordinate along its normal, the other planes + // hide, and their own places stay. + g.inferred = Some(at); + g.plane = Plane::Ground; + assert!((g.offset(Plane::Ground) - 2.0 * cell).abs() < 1e-6); + assert_eq!((g.placed_offset(Plane::Ground), g.offset(Plane::Left)), (0.0, 0.0)); + assert_eq!(g.shown_planes(), vec![Plane::Ground]); + assert_eq!(g.plane_widgets().len(), 1); + // The plane drawn there passes through the point the pointer was over. + let back = g.to_page(Plane::Ground, Point::new(0.0, 3.0 * cell)).unwrap(); + assert!((back - p).hypot() < 1e-6, "{back:?} {p:?}"); + // Another plane made active passes through it too. + g.plane = Plane::Right; + assert!((g.offset(Plane::Right) - 3.0 * cell).abs() < 1e-6); + assert_eq!(g.offset(Plane::Ground), 0.0); + // With no active plane nothing is held. + g.plane = Plane::None; + assert_eq!(g.shown_planes(), Plane::ALL.to_vec()); + } + + #[test] + fn the_pointer_must_be_within_reach_of_a_target_that_is_on() { + // Only the right wall shows, in its own place: the other planes' lines are out of the way. + let g = PerspectiveGrid { plane: Plane::Right, inferred: Some([0.0; 3]), ..grid() }; + let (d, cell) = (Document::new(800.0, 600.0), g.cell); + let on = g.to_page(Plane::Right, Point::new(2.0 * cell, cell)).unwrap(); + let mid = g.to_page(Plane::Right, Point::new(2.5 * cell, 1.5 * cell)).unwrap(); + assert!(g.infer_at(&d, on + vectorcraft_geom::Vec2::new(2.0, 0.0), 3.0, PlaneTargets::ALL).is_some()); + assert!(g.infer_at(&d, mid, 3.0, PlaneTargets::ALL).is_none(), "the middle of a cell is no intersection"); + assert!(g.infer_at(&d, on, 3.0, PlaneTargets { anchors: true, gridlines: false }).is_none()); + assert!(g.infer_at(&d, on, f64::NAN, PlaneTargets::ALL).is_none()); + assert!(g.infer_at(&d, Point::new(f64::INFINITY, 0.0), 3.0, PlaneTargets::ALL).is_none()); + // Hidden, or without an active plane, the grid gives no point. + assert!(PerspectiveGrid { visible: false, ..g.clone() }.infer_at(&d, on, 3.0, PlaneTargets::ALL).is_none()); + assert!(PerspectiveGrid { plane: Plane::None, ..g.clone() }.infer_at(&d, on, 3.0, PlaneTargets::ALL).is_none()); + // Beyond the plane's last line there is no intersection. + let past = g.to_page(Plane::Right, Point::new(g.right_extent() + 5.0 * cell, cell)).unwrap(); + assert!(g.infer_at(&d, past, 3.0, PlaneTargets::ALL).is_none()); + } + + #[test] + fn a_hidden_path_inside_art_in_perspective_has_no_anchor_to_take() { + let g = PerspectiveGrid { plane: Plane::Right, ..grid() }; + let mut d = Document::new(800.0, 600.0); + g.store(&mut d); + // A group on the right wall holding one small square, a corner in the middle of a cell. + let at = g.to_page(Plane::Right, Point::new(2.5 * g.cell, 1.5 * g.cell)).unwrap(); + let (layer, group, square) = (d.layers[0].id, d.alloc_id(), d.alloc_id()); + let mut path = Node::path(square, vectorcraft_geom::shapes::rectangle(Rect::new(at.x, at.y, at.x + 2.0, at.y + 2.0)), Default::default()); + path.visible = false; + let mut art = Node::group(group, vec![std::sync::Arc::new(path)]); + super::super::set_attachment(&mut art, Plane::Right, 0.0); + d.insert(Some(layer), 0, art).unwrap(); + let anchors = PlaneTargets { anchors: true, gridlines: false }; + assert!(g.infer_at(&d, at, 0.5, anchors).is_none(), "the square is hidden"); + d.node_mut(square).unwrap().visible = true; + let (source, point) = g.infer_at(&d, at, 0.5, anchors).unwrap(); + assert_eq!(source, InferSource::Anchor); + for (got, want) in point.iter().zip([2.5 * g.cell, 1.5 * g.cell, 0.0]) { + assert!((got - want).abs() < 1e-6, "{point:?}"); + } + // A grid stored before attachments were kept on the objects lists them itself. + let mut d = Document::new(800.0, 600.0); + let (layer, square) = (d.layers[0].id, d.alloc_id()); + d.insert( + Some(layer), + 0, + Node::path(square, vectorcraft_geom::shapes::rectangle(Rect::new(at.x, at.y, at.x + 2.0, at.y + 2.0)), Default::default()), + ) + .unwrap(); + assert!(g.infer_at(&d, at, 0.5, anchors).is_none(), "not in perspective"); + let mut legacy = g.clone(); + legacy.attached.insert(square.0.to_string(), Plane::Right); + assert_eq!(legacy.infer_at(&d, at, 0.5, anchors).map(|f| f.0), Some(InferSource::Anchor)); + } + + #[test] + fn the_stored_point_ends_with_end_positioning() { + let mut d = Document::new(800.0, 600.0); + let mut g = grid(); + g.store(&mut d); + assert!(!PerspectiveGrid::positioning(&d)); + assert!(!PerspectiveGrid::end_positioning(&mut d)); + g.inferred = Some([1.0, 2.0, 3.0]); + g.store(&mut d); + assert!(PerspectiveGrid::positioning(&d)); + assert_eq!(PerspectiveGrid::current(&d).inferred, Some([1.0, 2.0, 3.0])); + // `perspective.grid.set` leaves the point as it is. + assert_eq!(g.merged(&json!({"inferred": [9, 9, 9], "cell": 25})).unwrap().inferred, Some([1.0, 2.0, 3.0])); + assert!(PerspectiveGrid { inferred: Some([f64::NAN, 0.0, 0.0]), ..g.clone() }.validate().is_err()); + assert!(PerspectiveGrid::end_positioning(&mut d)); + assert_eq!(PerspectiveGrid::current(&d), PerspectiveGrid { inferred: None, ..g }); + } + + #[test] + fn shift_over_an_intersection_asks_for_the_plane_once() { + let mut d = Document::new(800.0, 600.0); + let mut g = grid(); + g.store(&mut d); + let (s, p) = (Selection::default(), paint()); + let at = g.to_page(Plane::Left, Point::new(2.0 * g.cell, 3.0 * g.cell)).unwrap(); + let shift = Mods { shift: true, ..Default::default() }; + let hover = |d: &Document, mods: Mods| { + let c = cx(d, &s, &p); + let mut t = super::super::PerspectiveSelectionTool::default(); + t.pointer(&c, &PointerEvent { mods, ..PointerEvent::new(PointerKind::Move, at.x, at.y) }) + }; + assert!(hover(&d, Mods::default()).is_empty(), "without Shift the pointer only hovers"); + let acts = hover(&d, shift); + let [Action::Exec(cmd, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert_eq!((cmd.as_str(), &v["at"]), ("perspective.plane.infer", &json!([at.x, at.y]))); + // Held through that point already, the hover asks for nothing more. + g.inferred = g.infer_at(&d, at, 1.0, PlaneTargets::ALL).map(|f| f.1); + g.store(&mut d); + assert!(hover(&d, shift).is_empty()); + // Escape puts the plane back. + let c = cx(&d, &s, &p); + let mut t = super::super::PerspectiveSelectionTool::default(); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Exec("perspective.plane.infer".into(), json!({"clear": true}))]); + } +} diff --git a/crates/tools/src/distort/perspective/tools.rs b/crates/tools/src/distort/perspective/tools.rs index 915e4a8835..1716a4593d 100644 --- a/crates/tools/src/distort/perspective/tools.rs +++ b/crates/tools/src/distort/perspective/tools.rs @@ -289,6 +289,9 @@ impl Tool for PerspectiveSelectionTool { _ => vec![], } } + // Automatic Plane Positioning: Shift held over an anchor point of art in perspective or + // over a gridline intersection, with no button down. During a drag Shift constrains. + (PointerKind::Move, SelDrag::Idle) if m.shift => super::infer::hover_action(cx, &g, p).into_iter().collect(), (_, d) => { self.drag = d; vec![] @@ -296,7 +299,8 @@ impl Tool for PerspectiveSelectionTool { } } /// Escape during a move, a resize or a plane widget drag cancels it: the objects and the plane - /// go back to the start of the drag. + /// go back to the start of the drag. With no drag, Escape puts a plane that Automatic Plane + /// Positioning holds back in its place. fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { if key == ToolKey::Escape && self.busy() { self.measure = None; @@ -305,6 +309,9 @@ impl Tool for PerspectiveSelectionTool { _ => vec![Action::Cancel], }; } + if key == ToolKey::Escape && PerspectiveGrid::current(cx.doc).inferred.is_some() { + return vec![Action::Exec("perspective.plane.infer".into(), json!({"clear": true}))]; + } if let (ToolKey::Digit(5), SelDrag::Move { perp, began, shift, .. }) = (key, &mut self.drag) { *perp = !*perp; *shift = mods.shift; diff --git a/crates/tools/src/distort/perspective/widget.rs b/crates/tools/src/distort/perspective/widget.rs index 4af1173e83..c5bdf05542 100644 --- a/crates/tools/src/distort/perspective/widget.rs +++ b/crates/tools/src/distort/perspective/widget.rs @@ -50,17 +50,44 @@ impl WidgetCorner { } } -/// Perspective Grid Options: whether the Plane Switching Widget shows, and where. +/// Perspective Grid Options: whether the Plane Switching Widget shows, and where, and what +/// Automatic Plane Positioning takes a point from ([`super::infer`]). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct WidgetOptions { pub show: bool, pub position: WidgetCorner, + /// Automatic Plane Positioning › Anchor Point of Perspective Artwork. + pub anchor_point: bool, + /// Automatic Plane Positioning › Intersection of Gridlines. + pub gridline_intersection: bool, } impl Default for WidgetOptions { fn default() -> Self { - Self { show: true, position: WidgetCorner::TopLeft } + Self { show: true, position: WidgetCorner::TopLeft, anchor_point: true, gridline_intersection: true } + } +} + +impl WidgetOptions { + /// What Automatic Plane Positioning takes a point from. + pub fn targets(self) -> PlaneTargets { + PlaneTargets { anchors: self.anchor_point, gridlines: self.gridline_intersection } + } +} + +/// What Automatic Plane Positioning takes a point from: the anchor points of art in perspective, +/// the gridline intersections of the planes that show. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PlaneTargets { + pub anchors: bool, + pub gridlines: bool, +} + +impl PlaneTargets { + pub const ALL: Self = Self { anchors: true, gridlines: true }; + pub fn any(self) -> bool { + self.anchors || self.gridlines } } diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index c3191c4363..1bf6a9488b 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -6,9 +6,9 @@ //! points with straight segments and the release fits them; Alt on release (or ending near the start) closes the path, and starting //! near an end of a selected open path continues it. Shift held at the press draws a straight //! Pencil line at 45° steps from the Constrain Angle instead, and Alt held at the press (with Alt -//! key toggles to Smooth Tool off) draws a straight line at any angle. The Pencil's new path starts and ends on -//! Smart Guides ([`DrawSnap`]: an anchor, a path, in line with the art), hovering too; the points -//! between follow the hand. The Paintbrush records the pen pressure of each point (a stroke a pen +//! key toggles to Smooth Tool off) draws a straight line at any angle. The Pencil ignores Smart +//! Guides and Snap to Point: it shows no Smart Guides, hovering or drawing, and its ends follow the +//! hand. Snap to Grid and Snap to Pixel still move its ends (`grid_snaps`). The Paintbrush records the pen pressure of each point (a stroke a pen //! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and //! the pen's tilt and barrel rotation where the pen reads them (`[x, y, pressure, tiltX, tiltY, //! rotation]` points, `null` for what a point lacks) for brushes that vary with them. The Blob @@ -860,27 +860,29 @@ impl GestureTool { } } - /// Do the ends of its strokes snap (the Pencil)? - fn snaps(&self) -> bool { - self.id == "pencil" - } - /// Does a straight Knife cut snap to anchors and paths? Only with Smart Guides on, which Snap to - /// Pixel (for drawing) and Snap to Grid turn off (`PointSnap::new`). Its ends snap as the - /// Pencil's straight line's do: the press, and the release unless Shift keeps it on a 45° step. + /// Pixel (for drawing) and Snap to Grid turn off (`PointSnap::new`). Its ends snap: the press, + /// and the release unless Shift keeps it on a 45° step. fn knife_snaps(&self, cx: &ToolContext) -> bool { self.id == "knife" && self.straight && cx.smart_guides && !cx.snaps_to_pixel(crate::PixelOp::Drawing) && !cx.snap_to_grid } - /// Does the end of a straight line snap: the Pencil's Alt line's, or a straight Knife cut's - /// without Shift? + /// Do the Pencil's ends snap? Only to the grid or to pixels, with View → Snap to Grid or Snap + /// to Pixel on: those are separate from Smart Guides (and turn them off), and the grid case is + /// its own question (#2958). Smart Guides and Snap to Point never move them. + fn grid_snaps(&self, cx: &ToolContext) -> bool { + self.id == "pencil" && (cx.snap_to_grid || cx.snaps_to_pixel(crate::PixelOp::Drawing)) + } + + /// Does the end of a straight line without Shift snap: the Pencil's Alt line's to the grid or + /// pixels, a straight Knife cut's to anchors and paths? fn line_end_snaps(&self, cx: &ToolContext) -> bool { - self.straight && self.unconstrained && (self.snaps() || self.knife_snaps(cx)) + self.straight && self.unconstrained && (self.grid_snaps(cx) || self.knife_snaps(cx)) } /// Where a stroke or straight line released at `p` ends: where it snaps when its end snaps. fn release_end(&mut self, cx: &ToolContext, p: Point) -> Point { - if (self.snaps() && !self.smoothing && !self.straight) || self.line_end_snaps(cx) { self.snap.drag(cx, p, None) } else { p } + if (self.grid_snaps(cx) && !self.smoothing && !self.straight) || self.line_end_snaps(cx) { self.snap.drag(cx, p, None) } else { p } } /// Is a straight line with its end at `end` back at its press point (within a pixel), so that @@ -1299,10 +1301,6 @@ impl Tool for GestureTool { self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p); } match ev.kind { - PointerKind::Move if self.snaps() => { - self.snap.hover(cx, p, &[], None); - vec![] - } PointerKind::Down => { self.active = true; self.began = false; @@ -1326,11 +1324,12 @@ impl Tool for GestureTool { _ => vec![], }; self.redraw = if self.draws_path() && !self.smoothing && self.extend.is_none() { self.find_redraw(cx, p) } else { None }; - // A path continued starts at its end, one redrawn on it; a new one where it snaps. - // A straight line is constrained from the end it continues, so it starts there. + // A path continued starts at its end, one redrawn on it; a new one at the press, + // or on the grid or a pixel when they snap. A straight line is constrained from the + // end it continues, so it starts there. let start = if let Some((_, _, end)) = extend.filter(|_| self.straight) { end - } else if self.snaps() && !self.smoothing && self.extend.is_none() && self.redraw.is_none() { + } else if self.grid_snaps(cx) && !self.smoothing && self.extend.is_none() && self.redraw.is_none() { self.snap.press(cx, p, &[], None) } else if self.knife_snaps(cx) { // A straight Knife cut, its overlay and Shift's 45° steps start from the snapped point. @@ -1354,13 +1353,13 @@ impl Tool for GestureTool { self.moved |= self.points.first().is_some_and(|start| p.distance(*start) > vectorcraft_geom::EPS); let p = self.constrained(cx, p, ev.mods); let mut end = p; - if self.snaps() && !self.smoothing && !self.straight { - // Where the stroke would end: shown, taken on release. + if self.grid_snaps(cx) && !self.smoothing && !self.straight { + // Where the stroke would end on the grid or a pixel: taken on release. end = self.snap.drag(cx, p, None); } let p = if self.line_end_snaps(cx) { - // Alt's line ends where a stroke would, and a Knife cut's on the anchors and - // paths its press snaps to: shown, taken on release. + // Alt's line ends on the grid or a pixel when they snap, and a Knife cut on the + // anchors and paths its press snaps to: shown, taken on release. self.snap.drag(cx, p, None) } else { p @@ -1382,7 +1381,7 @@ impl Tool for GestureTool { } else if self.points.last().is_some_and(|l| l.distance(p) < cx.tol(1.0)) || self.points.len() >= crate::MAX_STROKE_SAMPLES { // A release here keeps the last point unless it snaps (`Up`), so the ring // follows the point `finish` will test. - let kept = self.points.last().copied().filter(|l| l.distance(p) < cx.tol(1.0) && !self.snaps()); + let kept = self.points.last().copied().filter(|l| l.distance(p) < cx.tol(1.0) && !self.grid_snaps(cx)); let release_end = kept.unwrap_or(end); self.near_start = self.release_closes_near_start(cx, release_end); self.connects = self.connects_at(cx, release_end).is_some(); @@ -1439,7 +1438,7 @@ impl Tool for GestureTool { } } else if self.points.last().is_some_and(|l| l.distance(p) >= cx.tol(1.0)) { self.push(end, ev); - } else if self.snaps() + } else if self.grid_snaps(cx) && !self.smoothing && self.points.len() > 1 && let Some(last) = self.points.last_mut() diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 33d6520b84..b62226692a 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -22,25 +22,67 @@ fn drag_held(t: &mut GestureTool, cx: &ToolContext, pts: &[(f64, f64)], m: Mods) v } -/// The Pencil's new path starts and ends on Smart Guides (#506), the points between where -/// the hand went. +/// The Pencil follows the hand from the press to the release: it ignores Smart Guides and Snap to Point and shows no +/// Smart Guides, hovering or drawing over the art, with Smart Guides on or with only Snap to Point. #[test] -fn pencil_ends_snap_to_smart_guides() { +fn pencil_follows_the_hand_and_shows_no_smart_guides() { let (d, _) = doc_with_rect(); let s = Selection::default(); let p = paint(); - let cx = cx(&d, &s, &p); - let mut t = GestureTool::new("pencil"); - let acts = drag(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0), (250.0, 320.0), (198.0, 203.0)], Mods::default()); - let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; - assert_eq!(v["points"], json!([[100.0, 100.0], [151.0, 300.0], [250.0, 320.0], [200.0, 200.0]])); + let on = cx(&d, &s, &p); + let snap_to_point = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + // Near the corners at (100, 100) and (200, 200), within Snap to Point's 2 px of them. + let hand = [(101.0, 99.0), (151.0, 300.0), (250.0, 320.0), (199.0, 201.0)]; + for cx in [&on, &snap_to_point] { + let mut t = GestureTool::new("pencil"); + t.pointer(cx, &PointerEvent::new(PointerKind::Move, hand[0].0, hand[0].1)); + assert!(t.overlays(cx).is_empty(), "hovering: {:?}", t.overlays(cx)); + t.pointer(cx, &PointerEvent::new(PointerKind::Down, hand[0].0, hand[0].1)); + for &(x, y) in &hand[1..] { + t.pointer(cx, &PointerEvent::new(PointerKind::Drag, x, y)); + assert!(t.snap.guides().is_empty(), "drawing: {:?}", t.snap.guides()); + } + let last = hand[hand.len() - 1]; + let acts = t.pointer(cx, &PointerEvent::new(PointerKind::Up, last.0, last.1)); + let Some(Action::Preview(_, v)) = acts.first() else { panic!("{acts:?}") }; + assert_eq!(v["points"], json!(hand.map(|(x, y)| [x, y]))); + } // The Paintbrush follows the hand all the way. let mut t = GestureTool::new("paintbrush"); - let acts = drag(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0)], Mods::default()); + let acts = drag(&mut t, &on, &[(102.0, 98.0), (151.0, 300.0)], Mods::default()); let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; assert_eq!(v["points"][0], json!([102.0, 98.0])); } +/// Snap to Grid and Snap to Pixel are not Smart Guides: they still move the Pencil's ends (and an +/// Alt line's), while the points between follow the hand. +#[test] +fn pencil_ends_still_snap_to_the_grid_and_pixels() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let grid = ToolContext { snap_to_grid: true, ..cx(&d, &s, &p) }; + let pixel = ToolContext { snap_to_pixel: true, ..cx(&d, &s, &p) }; + let on = |cx: &ToolContext, q: (f64, f64)| match cx.snap_to_grid { + true => vectorcraft_geom::snap::snap_point_to_grid(Point::new(q.0, q.1), cx.grid_step()), + false => Point::new(q.0.round(), q.1.round()), + }; + let hand = [(301.3, 302.6), (351.4, 420.2), (447.7, 452.9)]; + for cx in [&grid, &pixel] { + let (first, last) = (on(cx, hand[0]), on(cx, hand[2])); + assert!(first != Point::new(hand[0].0, hand[0].1) && last != Point::new(hand[2].0, hand[2].1)); + let mut t = GestureTool::new("pencil"); + let acts = drag(&mut t, cx, &hand, Mods::default()); + let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; + assert_eq!(v["points"], json!([[first.x, first.y], [351.4, 420.2], [last.x, last.y]])); + // Alt's straight line ends on the grid or a pixel too. + let mut t = GestureTool::new("pencil"); + let acts = drag_held(&mut t, cx, &[hand[0], hand[2]], Mods { alt: true, ..Mods::default() }); + let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; + assert_eq!(v["points"][1], json!([last.x, last.y])); + } +} + /// #852: the Paintbrush sends each point's pen pressure; a mouse (always fully pressed) and /// the Pencil send plain points. #[test] @@ -693,10 +735,10 @@ fn pencil_shift_draws_a_straight_line_at_45_degree_steps() { } } -/// #3799: a Shift line leaves no Smart Guides of its press on screen while it is dragged -/// (its end doesn't snap), and Alt at its release leaves it open. +/// #3799: a Shift line shows no Smart Guides, at its press or while it is dragged, and Alt at its +/// release leaves it open. #[test] -fn pencil_shift_line_drops_the_press_guides_and_stays_open_with_alt() { +fn pencil_shift_line_shows_no_guides_and_stays_open_with_alt() { let (d, _) = doc_with_rect(); let s = Selection::default(); let p = paint(); @@ -704,7 +746,7 @@ fn pencil_shift_line_drops_the_press_guides_and_stays_open_with_alt() { let shift = Mods { shift: true, ..Default::default() }; let mut t = GestureTool::new("pencil"); t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 102.0, 98.0).with_mods(shift)); - assert!(!t.overlays(&cx).is_empty(), "the press snaps to the corner and shows it"); + assert!(t.snap.guides().is_empty(), "the press: {:?}", t.snap.guides()); t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 300.0, 140.0).with_mods(shift)); assert!(t.overlays(&cx).is_empty(), "{:?}", t.overlays(&cx)); let shift_alt = Mods { shift: true, alt: true, ..Default::default() }; @@ -1745,10 +1787,11 @@ fn paintbrush_alt_with_a_two_anchor_curve_selected_smooths() { } } -/// #3799: Alt's line starts and ends on Smart Guides as a stroke does, and pressed on an end of -/// a selected open path it continues the path from that end to the pointer. +/// #3799: Alt's line runs from the press to the pointer as a stroke does, snapping to nothing, +/// and pressed on an end of a selected open path it continues the path from that end to the +/// pointer. #[test] -fn pencil_alt_line_snaps_its_ends_and_continues_a_selected_path() { +fn pencil_alt_line_follows_the_hand_and_continues_a_selected_path() { let (mut d, _) = doc_with_rect(); let alt = Mods { alt: true, ..Default::default() }; let p = paint(); @@ -1758,7 +1801,7 @@ fn pencil_alt_line_snaps_its_ends_and_continues_a_selected_path() { let mut t = GestureTool::new("pencil"); let acts = drag_held(&mut t, &cx, &[(102.0, 98.0), (151.0, 300.0), (198.0, 203.0)], alt); let Some(Action::Preview(_, v)) = acts.last().and_then(|a| a.first()) else { panic!("{acts:?}") }; - assert_eq!(v["points"], json!([[100.0, 100.0], [200.0, 200.0]])); + assert_eq!(v["points"], json!([[102.0, 98.0], [198.0, 203.0]])); } let l = d.layers[0].id; let id = d.alloc_id(); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 15fec287b5..29cf0466e1 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -604,6 +604,7 @@ pub(crate) mod testutil { construction_angles: guides::construction_angles(guides::DEFAULT_CONSTRUCTION_ANGLES), screen: None, plane_widget: Some(Default::default()), + plane_targets: distort::perspective::widget::PlaneTargets::ALL, precise_cursors: false, global_edit: &[], } diff --git a/crates/trace/src/quantize/cut_edge.rs b/crates/trace/src/quantize/cut_edge.rs index 265c0d9b2c..4578fbe7fc 100644 --- a/crates/trace/src/quantize/cut_edge.rs +++ b/crates/trace/src/quantize/cut_edge.rs @@ -398,7 +398,7 @@ fn settled_wide_strips(q: &Quantized, img: &Raster, own: &[bool], gray: bool, co /// stay more than 0.065 as far as a single color does. So is a sepia, single-hue or duotone /// picture whose tones follow one curve through the color cube (19 in 20 of its opaque pixels on /// it, see [`on_one_curve`]). Neither is, however far eight colors stay, when sixteen colors stay -/// at most a fifth as far as eight do. That exception holds for flat art of up to sixteen clean +/// at most a tenth as far as eight do. That exception holds for flat art of up to sixteen clean /// levels, gray or tinted, where sixteen colors come within about a level of every pixel. On gray /// and tinted photos sixteen colors stay 0.18 to 0.57 as far as eight do, and on most anti-aliased /// or noisy gray flat art 0.24 to 0.5 as far, so the exception holds for neither. @@ -437,9 +437,9 @@ pub(crate) fn continuous_tone(img: &Raster) -> bool { } let one_line = || 20 * neutral >= 19 * opaque || 20 * on_one_curve(img) >= 19 * opaque; if eight > 0.1 * one { - return !(unsaid(16) <= 0.2 * eight && one_line()); + return !(unsaid(16) <= 0.1 * eight && one_line()); } - unsaid(16) > 0.2 * eight && one_line() + unsaid(16) > 0.1 * eight && one_line() } /// How far (levels) a pixel may lie from the tone curve of its picture and still count as on it, diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 80eb322bbc..59f92021c0 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -2033,6 +2033,16 @@ fn a_gray_photo_is_continuous_tone_as_its_color_original_is() { } } +/// A gray photo with little or no noise (a render, a denoised scan) is continuous tone, as its +/// color original is. Sixteen colors stay 0.19 as far from its pixels as eight do. +#[test] +fn a_clean_gray_photo_is_continuous_tone_as_its_color_original_is() { + for noise in [0.0, 1.0, 2.0, 3.0] { + assert!(quantize::continuous_tone(&photo_scene(noise, false)), "color, noise {noise}"); + assert!(quantize::continuous_tone(&photo_scene(noise, true)), "gray, noise {noise}"); + } +} + /// Sepia: dark brown to cream. const SEPIA: [[f64; 3]; 2] = [[45.0, 28.0, 15.0], [250.0, 235.0, 205.0]]; /// A single blue hue: navy to pale blue. diff --git a/crates/ui-egui/src/addons/cutting.rs b/crates/ui-egui/src/addons/cutting.rs index 15a6790872..314a25fd0c 100644 --- a/crates/ui-egui/src/addons/cutting.rs +++ b/crates/ui-egui/src/addons/cutting.rs @@ -3,6 +3,7 @@ //! of `addon.cutting.bridges`. Weed Box and Lines… opens it on the options of `addon.cutting.weed`, //! with a Preview, and runs the command on OK. A Spacing above 0 is sent instead of the Count. //! Banner Hems and Grommets… opens it on the options of `addon.cutting.banner`, with a Preview. +//! Nest Shapes… opens it on the options of `addon.cutting.nest`, with a Preview. use serde_json::json; @@ -18,6 +19,8 @@ pub const WEED: &str = "addon.cutting.weed"; pub const WEED_DIRECTIONS: &[(&str, &str)] = &[("Horizontal", "horizontal"), ("Vertical", "vertical"), ("Both", "both")]; /// Banner Hems and Grommets' command. pub const BANNER: &str = "addon.cutting.banner"; +/// Nest Shapes' command. +pub const NEST: &str = "addon.cutting.nest"; /// Object › Plug-ins › Cutting Tools. pub fn menu() -> Vec { @@ -36,6 +39,11 @@ pub fn menu() -> Vec { "diameter": 27, "weight": 0.3, "swatch": "[Registration]" }), ), + Item::Cmd( + "Nest Shapes…", + NEST, + json!({"roll": false, "width": 0, "height": 0, "margin": 18, "spacing": 9, "rotate": false, "usePreviewBounds": true}), + ), ] } diff --git a/crates/ui-egui/src/addons/cutting/tests.rs b/crates/ui-egui/src/addons/cutting/tests.rs index 99580b369c..7e2787996f 100644 --- a/crates/ui-egui/src/addons/cutting/tests.rs +++ b/crates/ui-egui/src/addons/cutting/tests.rs @@ -210,3 +210,57 @@ fn banner_hems_and_grommets_previews_cancels_and_runs_on_ok() { // 528 pt along the top and bottom need 6 gaps, 328 pt down the sides 4: 20 grommets. assert_eq!(count(&app), nodes + 1 + 4 + 20 * 4); } + +/// Object › Plug-ins › Cutting Tools › Nest Shapes… opens the command dialog on its defaults with +/// Preview off, previews the packed objects, puts them back on Cancel and keeps them as one step +/// on OK. +#[test] +fn nest_shapes_previews_cancels_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 700, "y": 100, "width": 50, "height": 40})).unwrap()["id"].clone(); + let b = app.run("shape.rectangle", json!({"x": 800, "y": 100, "width": 60, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (start, n) = (app.session.doc().unwrap().doc.clone(), steps(&app)); + let open = |app: &mut VectorcraftApp| { + let entries = menus::menu_entries(app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Cutting Tools"] && e.label == "Nest Shapes…").unwrap(); + assert!(item.enabled); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + + open(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog opens"); + assert_eq!((d.str("__command"), d.str("__label")), (super::NEST.to_string(), "Nest Shapes".to_string())); + assert_eq!((d.bool("roll"), d.bool("rotate"), d.bool("usePreviewBounds"), d.bool("preview")), (false, false, true, false)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Nest Shapes", "Roll", "Width", "Height", "Margin", "Spacing", "Rotate", "Use Preview Bounds", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let german = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + crate::i18n::set_current(crate::i18n::Lang::EN); + for s in ["Formen verschachteln", "Rolle"] { + assert!(german.contains(s), "{s} in {german}"); + } + assert_eq!(app.session.doc().unwrap().doc, start, "no preview without the checkbox"); + + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_ne!(app.session.doc().unwrap().doc, start, "previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel puts the objects back"); + assert_eq!(steps(&app), n, "and adds no undo step"); + + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "margin".into(), json!("0 pt")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), n + 1, "one undo step"); + let doc = &app.session.doc().unwrap().doc; + let left = |id: &serde_json::Value| doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().geometric_bounds().unwrap().x0; + // The taller object goes first, its 1 pt stroke at the artboard's corner, and the other 9 pt to + // the right of its stroke. + assert_eq!((left(&a), left(&b)), (0.5, 0.5 + 51.0 + 9.0)); +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 26f67a0365..acc642cc0d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -41,6 +41,7 @@ use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; use std::sync::mpsc::Sender; use serde_json::{Value, json}; +use vectorcraft_engine::cmd::ParamsPlace; use vectorcraft_render::encode::{RasterExportOptions, RasterFormat}; use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; @@ -427,17 +428,19 @@ impl Hiding { } /// The paths outside the read roots that `v`'s strings and keys name at any depth, written as paths -/// ([`unreadable_path_like`]) or held by a path param -/// ([`vectorcraft_engine::file_access::is_path_key`]), a relative one too, each as a hidden library id -/// (`loaded/`) with `loaded/` shown. A reply hides them as it hides a hidden library's -/// path, with that file name also for a hidden library shown as `loaded/ (2)`, so that it -/// reads the same whether or not a library was loaded from one of them. +/// ([`unreadable_path_like`]) or held by a path param, a relative one too, each as a hidden library id +/// (`loaded/`) with `loaded/` shown. A param is a path param as the command it is +/// for reads it ([`ParamsPlace`]: `engine.execute`'s `params`, a `command.batch` step's and a +/// recorded step's), so a web link or an export's folder grouping is not one. A reply hides them as +/// it hides a hidden library's path, with that file name also for a hidden library shown as +/// `loaded/ (2)`, so that it reads the same whether or not a library was loaded from one +/// of them. fn sent_paths(v: &Value, out: &mut Vec<(String, String)>) { - collect_sent_paths(v, false, out); + collect_sent_paths(v, ParamsPlace::top(None), false, out); } -/// [`sent_paths`] on `v`, which a path param holds when `path_param` is set. -fn collect_sent_paths(v: &Value, path_param: bool, out: &mut Vec<(String, String)>) { +/// [`sent_paths`] on `v`, found at `place`, which a path param holds when `path_param` is set. +fn collect_sent_paths(v: &Value, place: ParamsPlace, path_param: bool, out: &mut Vec<(String, String)>) { fn add(s: &str, path_param: bool, out: &mut Vec<(String, String)>) { if !unreadable_path_like(s) && !(path_param && !readable_value(s)) { return; @@ -459,11 +462,18 @@ fn collect_sent_paths(v: &Value, path_param: bool, out: &mut Vec<(String, String } match v { Value::String(s) => add(s, path_param, out), - Value::Array(items) => items.iter().for_each(|item| collect_sent_paths(item, path_param, out)), + Value::Array(items) => { + let step = ParamsPlace::step(items); + for (i, item) in items.iter().enumerate() { + collect_sent_paths(item, place.item(i, step), path_param, out); + } + } Value::Object(fields) => { + let carried = ParamsPlace::carried(fields); for (key, item) in fields { add(key, false, out); - collect_sent_paths(item, vectorcraft_engine::file_access::is_path_key(key), out); + let (below, location) = place.member(key, carried); + collect_sent_paths(item, below, location.is_some(), out); } } _ => {} @@ -1057,7 +1067,7 @@ fn steps_mut(set: &mut Value) -> impl Iterator) { leave_out_unreadable_pref_steps(command, params); - leave_out_unreadable_params(params); + leave_out_unreadable_params(params, ParamsPlace::of(command)); } /// Takes out of the params of a step running `command` the folder preferences' values the request @@ -1087,39 +1097,46 @@ fn leave_out_unreadable_pref_steps(command: &str, params: &mut serde_json::Map) { - use vectorcraft_engine::file_access::is_path_key; +/// Takes out of a recorded step's params at `place`, at any depth (the commands of a `command.batch` +/// step), the paths the request may not read: the value of a path param as the command reads it +/// ([`ParamsPlace`]: `path`, `file`, `diffPath`, `destinationFolder` and the like, but not a key that +/// names part of the document in that command), each path of a list under such a param, and under +/// any other param, as a key too, a string written as a path ([`unreadable_path_like`]). A web link, +/// a choice or a switch whose name ends like a path param's (`alignToPath`, `linksFolder`) stays, and +/// so does an empty or blank value, which names no path. +fn leave_out_unreadable_params(params: &mut serde_json::Map, place: ParamsPlace) { let shown = |p: &str| p.trim().is_empty() || readable_value(p); + let carried = ParamsPlace::carried(params); params.retain(|key, v| { !unreadable_path_like(key) && match v.as_str() { - Some(p) => !unreadable_path_like(p) && !(is_path_key(key) && !shown(p)), + Some(p) => !unreadable_path_like(p) && !(place.member(key, carried).1.is_some() && !shown(p)), None => true, } }); + let carried = ParamsPlace::carried(params); for (key, v) in params.iter_mut() { + let (below, location) = place.member(key, carried); if let Value::Array(paths) = v - && is_path_key(key) + && location.is_some() { paths.retain(|p| p.as_str().is_none_or(shown)); } - leave_out_unreadable_values(v); + leave_out_unreadable_values(v, below); } } -/// [`leave_out_unreadable_params`] on each object `v` holds, and a string written as a path that the -/// request may not read ([`unreadable_path_like`]) taken out of each list. -fn leave_out_unreadable_values(v: &mut Value) { +/// [`leave_out_unreadable_params`] on each object `v`, found at `place`, holds, and a string written +/// as a path that the request may not read ([`unreadable_path_like`]) taken out of each list. +fn leave_out_unreadable_values(v: &mut Value, place: ParamsPlace) { match v { - Value::Object(fields) => leave_out_unreadable_params(fields), + Value::Object(fields) => leave_out_unreadable_params(fields, place), Value::Array(items) => { items.retain(|item| !item.as_str().is_some_and(unreadable_path_like)); - items.iter_mut().for_each(leave_out_unreadable_values); + let step = ParamsPlace::step(items); + for (i, item) in items.iter_mut().enumerate() { + leave_out_unreadable_values(item, place.item(i, step)); + } } _ => {} } @@ -1284,7 +1301,7 @@ fn hide_in_reply(app: &VectorcraftApp, reply: &mut Value, sent: &Value, before: return; } let mut given = Vec::new(); - written_paths(sent, false, &mut given); + written_paths(sent, ParamsPlace::top(None), false, &mut given); let kept = kept_written_paths(reply, &given); let mut hiding = unreadable_library_ids(app); hiding.merge(before); @@ -1294,10 +1311,10 @@ fn hide_in_reply(app: &VectorcraftApp, reply: &mut Value, sent: &Value, before: // first folder on the way to it that is a file or is missing. let current = vectorcraft_engine::cmd::recovery::folder(&app.session).map(|(f, _)| f); for folder in app.recovery.named.iter().chain(current.as_ref()) { - collect_sent_paths(&json!(folder), true, &mut paths); + collect_sent_paths(&json!(folder), ParamsPlace::top(None), true, &mut paths); for on_the_way in std::path::Path::new(folder).ancestors().skip(1).map(|p| p.to_string_lossy()) { if !on_the_way.is_empty() && writes_whole_path(reply, &on_the_way) { - collect_sent_paths(&json!(on_the_way), true, &mut paths); + collect_sent_paths(&json!(on_the_way), ParamsPlace::top(None), true, &mut paths); } } } @@ -1326,16 +1343,24 @@ fn writes_whole_path(v: &Value, path: &str) -> bool { } } -/// The strings that `v`'s path params hold at any depth ([`vectorcraft_engine::file_access::is_path_key`]) -/// that name a file inside the write roots; `v` is a path param's value when `path_param` is set. -fn written_paths(v: &Value, path_param: bool, out: &mut Vec) { - use vectorcraft_engine::file_access::{Access, current, is_path_key}; +/// The strings that `v`'s path params hold at any depth, as the command they are for reads them +/// ([`ParamsPlace`]), that name a file inside the write roots; `v`, found at `place`, is a path +/// param's value when `path_param` is set. +fn written_paths(v: &Value, place: ParamsPlace, path_param: bool, out: &mut Vec) { + use vectorcraft_engine::file_access::{Access, current}; match v { Value::String(s) if path_param && !s.is_empty() && current().is_some_and(|r| r.check(s, Access::Write).is_ok()) => out.push(s.clone()), - Value::Array(items) => items.iter().for_each(|item| written_paths(item, path_param, out)), + Value::Array(items) => { + let step = ParamsPlace::step(items); + for (i, item) in items.iter().enumerate() { + written_paths(item, place.item(i, step), path_param, out); + } + } Value::Object(fields) => { + let carried = ParamsPlace::carried(fields); for (key, item) in fields { - written_paths(item, is_path_key(key), out); + let (below, location) = place.member(key, carried); + written_paths(item, below, location.is_some(), out); } } _ => {} diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index d914c3624d..7aa73e8a7e 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -306,7 +306,7 @@ fn a_spaced_absolute_path_outside_the_read_root_is_left_out() { assert!(super::unreadable_path_like(" /outside/root/x")); assert!(super::unreadable_path_like("\tfile:///outside/root/x ")); assert!(!super::unreadable_path_like(&inside), "{inside}"); - super::leave_out_unreadable_params(params.as_object_mut().unwrap()); + super::leave_out_unreadable_params(params.as_object_mut().unwrap(), vectorcraft_engine::cmd::ParamsPlace::top(None)); }); assert_eq!(params, json!({"keep": inside, "list": []})); } @@ -337,10 +337,74 @@ fn a_url_naming_another_host_stays_without_a_read_root() { assert!(super::readable_value("file://host/share/a.svg")); let mut params = json!({"path": "file://host/share/a.svg", "list": ["file://host/share/b.svg"]}); let fields = params.as_object_mut().unwrap(); - super::leave_out_unreadable_params(fields); + super::leave_out_unreadable_params(fields, vectorcraft_engine::cmd::ParamsPlace::top(None)); assert_eq!(params, json!({"path": "file://host/share/a.svg", "list": ["file://host/share/b.svg"]})); } +/// Under a read root, a recorded step loses a relative path outside it under a key that names a file +/// or a folder as its command reads it (also inside a `command.batch` step), and a `file:` URL outside +/// it under any key. A web link, a choice or a switch whose name ends like a path key's, and a key +/// that names part of the document in its command, keep their values; the same key in a command that +/// doesn't take it as a param names a file. +#[test] +fn recorded_steps_filter_only_unreadable_locations() { + use vectorcraft_engine::cmd::ParamsPlace; + let root = std::env::temp_dir().join(format!("vc-recorded-locations-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&root], &[]).unwrap(); + let steps = [ + ("document.compare", json!({"diffPath": "elsewhere/a.svg", "directory": "elsewhere", "keep": 1})), + ("attributes.set", json!({"url": "https://example.com/elsewhere/a.html", "note": "kept"})), + ("object.slice.options", json!({"url": "file:///elsewhere/a.html"})), + ("object.path.simplify", json!({"wholePaths": "elsewhere/a", "alignToPath": "elsewhere/b", "linksFolder": "elsewhere/c"})), + ("document.exportPresets.save", json!({"settings": {"folders": "item/format", "formats": [{"folder": "elsewhere/png"}]}})), + ("text.createInPath", json!({"path": "elsewhere/shape"})), + ("object.setLiveShape", json!({"path": "elsewhere/shape"})), + ("command.batch", json!({"commands": [{"command": "document.save", "params": {"path": "elsewhere/b.svg"}}]})), + ]; + let filtered: Vec = vectorcraft_engine::file_access::confine(roots.as_ref(), || { + steps + .iter() + .map(|(id, params)| { + let mut params = params.clone(); + super::leave_out_unreadable_params(params.as_object_mut().unwrap(), ParamsPlace::of(id)); + params + }) + .collect() + }); + let _ = std::fs::remove_dir_all(root); + let want = [ + json!({"keep": 1}), + json!({"url": "https://example.com/elsewhere/a.html", "note": "kept"}), + json!({}), + json!({"wholePaths": "elsewhere/a", "alignToPath": "elsewhere/b", "linksFolder": "elsewhere/c"}), + json!({"settings": {"folders": "item/format", "formats": [{}]}}), + json!({"path": "elsewhere/shape"}), + json!({}), + json!({"commands": [{"command": "document.save", "params": {}}]}), + ]; + assert_eq!(filtered, want); +} + +/// A request's relative path outside the read root is hidden in a reply where the command it calls +/// reads it as a file, and a web link or a key that names part of the document there is not. +#[test] +fn a_request_sends_paths_as_its_command_reads_them() { + let root = std::env::temp_dir().join(format!("vc-sent-command-paths-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&root], &[]).unwrap(); + let mut sent = Vec::new(); + vectorcraft_engine::file_access::confine(roots.as_ref(), || { + super::sent_paths(&json!({"command": "attributes.set", "params": {"url": "https://example.com/a/page.html"}}), &mut sent); + super::sent_paths(&json!({"command": "object.path.simplify", "params": {"wholePaths": "out/w.svg"}}), &mut sent); + super::sent_paths(&json!({"command": "document.compare", "params": {"diffPath": "out/d.svg"}}), &mut sent); + super::sent_paths(&json!({"command": "file.place", "params": {"directory": "out/folder"}}), &mut sent); + }); + let _ = std::fs::remove_dir_all(root); + let pair = |path: &str, name: &str| (format!("loaded/{path}"), format!("loaded/{name}")); + assert_eq!(sent, [pair("out/d.svg", "d.svg"), pair("out/folder", "folder")]); +} + /// A hidden path quoted with `{:?}` is hidden with its quotes and control characters escaped. #[test] fn a_reply_hides_a_quoted_path_with_escaped_quotes() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5afad21b0d..04e58d452e 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -122,6 +122,7 @@ pub(crate) mod shapes; pub mod shortcut_import; pub(crate) mod simplify_slider; pub mod slices; +pub mod smart_punctuation; pub(crate) mod smooth_slider; pub mod spot_colors; pub mod svg_filter; @@ -159,7 +160,7 @@ pub use export_for_screens::open as open_export_for_screens; pub(crate) use export_for_screens::{ KIND as EXPORT_FOR_SCREENS, PresetPick as ScreenPresetPick, export_preset as screen_export_preset, formats as screen_formats, import_presets as screen_import_presets, open_assets as open_export_for_screens_assets, preset_list as screen_preset_list, - saved_options as screen_saved_options, saved_rows as screen_saved_rows, + saved_options as screen_saved_options, saved_rows as screen_saved_rows, settings_format as screen_settings_format, }; pub(crate) use form::{humanize, number_list_text, plugin_color_button, read_number_list, unit_suffix}; pub use new_document::{create_without_dialog as new_document_without_dialog, open as open_new_document, preset_card}; @@ -430,6 +431,7 @@ registry! { VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, + SmartPunctuation: [smart_punctuation::KIND] => smart_punctuation::SPEC, PerspectiveGrid: [perspective_grid::KIND] => perspective_grid::SPEC, Envelope: [envelope::WARP, envelope::MESH, envelope::OPTIONS] => envelope::SPEC, LiquifyOptions: [liquify::KIND] => liquify::SPEC, diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6656b45bf5..35890cd18e 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -65,8 +65,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// grid options lists one, and the radial and mirror pages do not. Type on a Path Options does /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and -/// Cutting Tools › Weed Box and Lines and Banner Hems and Grommets. (Cancel rolls a preview back -/// whichever dialog started it.) +/// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes. (Cancel rolls a +/// preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), @@ -75,7 +75,8 @@ fn previews(d: &Dialog) -> bool { | crate::addons::image::REMOVE_BACKGROUND | crate::addons::image::COLOR_MASK | crate::addons::cutting::WEED - | crate::addons::cutting::BANNER => true, + | crate::addons::cutting::BANNER + | crate::addons::cutting::NEST => true, _ => false, } } @@ -123,6 +124,7 @@ fn lengths(command: &str) -> &'static [&'static str] { "perspective.grid.set" => &["cell", "distance"], crate::addons::cutting::WEED => &["margin", "spacing", "gap", "weight"], crate::addons::cutting::BANNER => &["hem", "spacing", "grommetInset", "diameter", "weight"], + crate::addons::cutting::NEST => &["width", "height", "margin", "spacing"], "object.repeat.options" => &["radius", "hSpacing", "vSpacing"], "text.areaOptions" => &["width", "height", "gutter", "rowGutter", "inset", "firstBaselineMin", "lineGap"], "type.pathOptions" => &["spacing"], @@ -150,6 +152,7 @@ fn order(command: &str) -> &'static [&'static str] { crate::addons::cutting::BANNER => { &["hem", "top", "right", "bottom", "left", "grommets", "spacing", "grommetInset", "diameter", "weight", "swatch"] } + crate::addons::cutting::NEST => &["roll", "width", "height", "margin", "spacing", "rotate", "usePreviewBounds"], // The public Trap options' order. "object.pathfinder.trap" => &["thickness", "heightWidth", "tintReduction", "trapsWithProcessColor", "reverseTraps"], "addon.color.printFixes" => &["inkLimit", "excludePureBlack", "removeWhiteOverprint", "overprintBlack", "textOnly", "fill", "stroke"], @@ -517,7 +520,7 @@ mod tests { } /// Text Wrap Options › Offset is a distance, and its range is the one `object.textWrap.options` - /// keeps an Offset to. + /// accepts: the command takes the range's ends and refuses an Offset outside them. #[test] fn text_wrap_offset_is_a_distance_within_the_commands_range() { assert!(lengths("object.textWrap.options").contains(&"offset")); @@ -531,8 +534,11 @@ mod tests { s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); s.execute("select.all", &json!({})).unwrap(); s.execute("object.textWrap.make", &json!({})).unwrap(); - for (sent, end) in [(5000.0, *range.end()), (-5000.0, *range.start())] { - assert_eq!(s.execute("object.textWrap.options", &json!({ "offset": sent })).unwrap()["offset"], json!(end)); + for end in [*range.end(), *range.start()] { + assert_eq!(s.execute("object.textWrap.options", &json!({ "offset": end })).unwrap()["offset"], json!(end)); + } + for sent in [5000.0, -5000.0] { + assert!(s.execute("object.textWrap.options", &json!({ "offset": sent })).is_err(), "{sent}"); } } diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index 54c98052bf..ecd9ca6996 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -156,7 +156,8 @@ pub fn open(app: &mut VectorcraftApp) { // `folders: "format"`, any other sorting a folder per scale. let folders = get("folders").and_then(Value::as_str); let subfolders = match folders { - Some("none") => false, + // An export reads empty folders as none. + Some("none" | "") => false, Some(_) => true, None => flag("subfolders", saved.is_empty() || preset.is_some()), }; @@ -955,14 +956,7 @@ pub(crate) fn formats(ui: &mut egui::Ui, d: &mut Dialog, mut menu: Option &'static str { + rows.first() + .and_then(|r| r["format"].as_str()) + .and_then(fileio::format) + .map(|f| f.id) + .filter(|f| SETTINGS.iter().any(|(id, _)| id == f)) + .unwrap_or("png") +} + /// Format Settings: the options of format `id` that apply to every row of it, then Done. fn format_settings(ui: &mut egui::Ui, d: &mut Dialog, id: &str) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 1baa838d90..4820680a09 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -2,7 +2,8 @@ //! asks which pages (a preview with page navigation), the box to crop to and the password. //! //! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the -//! one placed; 1-based), `allPages` and `range` (open), `cropTo` and `password`. `__locked` is set +//! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for +//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set //! until the password is accepted: OK then unlocks the file. `__place` keeps the other `file.place` //! params (Link, Template, `at`…). The file's bytes stay out of the fields, in //! [`crate::state::UiState::dialog_file`]. @@ -142,6 +143,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Option { Some(d.str("password")).filter(|p| !p.is_empty()) } +/// Can the pages open linked: the file was read from a path (a linked page is read from its +/// file again) and opens without a password (`document.open`'s `linkPages` refuses one). +fn can_link(d: &Dialog) -> bool { + d.fields.get("path").and_then(Value::as_str).is_some() && password(d).is_none() +} + +/// Import PDF Pages as Links is checked, and can be. +fn links_on(d: &Dialog) -> bool { + d.bool("linkPages") && can_link(d) +} + /// OK: unlock the file with the password, else open the pages or place the page. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let file = app.ui.dialog_file.clone().ok_or("the PDF is no longer loaded")?; @@ -213,6 +226,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if !d.bool("allPages") && !range.trim().is_empty() { p["pages"] = json!(range); } + if links_on(&d) { + p["linkPages"] = json!(true); + } io::open_document(app, &name, &file.bytes, path, &p).map(|_| ()) }; match r { @@ -291,6 +307,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } }); widgets::dim_label(ui, tl!("e.g. 1-3, 5")); + ui.add_space(10.0); + if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) { + d.fields.insert("linkPages".into(), json!(!d.bool("linkPages"))); + } } }); }); diff --git a/crates/ui-egui/src/dialogs/perspective_options.rs b/crates/ui-egui/src/dialogs/perspective_options.rs index 91e74de0e2..901023fabc 100644 --- a/crates/ui-egui/src/dialogs/perspective_options.rs +++ b/crates/ui-egui/src/dialogs/perspective_options.rs @@ -1,8 +1,9 @@ //! Perspective Grid Options (double-click the Perspective Grid tool): whether the Plane Switching -//! Widget shows and which corner of the window it sits in. OK runs `perspective.widget.options` -//! (the options live in the preferences). +//! Widget shows and which corner of the window it sits in, and what Automatic Plane Positioning +//! takes a point from. OK runs `perspective.widget.options` (the options live in the preferences). //! -//! Fields: `show` (bool) and `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`). +//! Fields: `show` (bool), `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`), +//! `anchorPoint` (bool) and `gridlineIntersection` (bool). use serde_json::{Value, json}; use vectorcraft_tools::distort::perspective::widget::WidgetCorner; @@ -38,5 +39,13 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(8.0); let corners: Vec<(&str, &str)> = WidgetCorner::ALL.iter().map(|c| (c.id(), c.label())).collect(); ui.add_enabled_ui(on, |ui| form::choice(ui, d, "position", tl!("Widget Position:"), (110.0, 160.0), &corners)); + ui.add_space(8.0); + widgets::section_header(ui, tl!("Automatic Plane Positioning")); + for (key, label) in [("anchorPoint", tl!("Anchor Point of Perspective Artwork")), ("gridlineIntersection", tl!("Intersection of Gridlines"))] { + let on = d.bool(key); + if widgets::check(ui, label, on, true) { + d.fields.insert(key.into(), json!(!on)); + } + } false } diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs new file mode 100644 index 0000000000..1ebe084e02 --- /dev/null +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -0,0 +1,169 @@ +//! Type › Smart Punctuation…: which keyboard characters to replace with their typographic forms, +//! where (the selected type or the whole document) and whether to report how many of each were +//! replaced. OK runs `type.smartPunctuation` as one undo step, and the dialog opens on the fields +//! confirmed last. +//! +//! Fields: the switches `fiLigatures`, `flLigatures`, `quotes`, `spaces`, `dashes`, `ellipsis` and +//! `fractions`, `scope` (`selection` or `document`) and `report`. + +use serde_json::{Value, json}; + +use super::{DialogResult, DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Smart Punctuation. +pub const KIND: &str = "smartPunctuation"; + +const CMD: &str = "type.smartPunctuation"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Smart Punctuation").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +/// The replacement options in the dialog's order: (field, the key of their count in the +/// command's reply, label). +fn options() -> [(&'static str, &'static str, &'static str); 7] { + [ + ("fiLigatures", "fiLigatures", tl!("ff, fi, ffi Ligatures")), + ("flLigatures", "flLigatures", tl!("ff, fl, ffl Ligatures")), + ("quotes", "quotes", tl!("Smart Quotes")), + ("spaces", "spaces", tl!("Smart Spaces")), + ("dashes", "dashes", tl!("En, Em Dashes")), + ("ellipsis", "ellipses", tl!("Ellipses")), + ("fractions", "fractions", tl!("Expert Fractions")), + ] +} + +/// The fields the menu item opens with: those confirmed last, else quotes, dashes and ellipses on +/// (the command's defaults). With nothing selected, the whole document. +pub fn fields(app: &VectorcraftApp) -> Value { + let mut f = match &app.ui.smart_punctuation { + Value::Object(o) => Value::Object(o.clone()), + _ => json!({ + "fiLigatures": false, + "flLigatures": false, + "quotes": true, + "spaces": false, + "dashes": true, + "ellipsis": true, + "fractions": false, + "scope": "selection", + "report": false, + }), + }; + if !has_selection(app) { + f["scope"] = json!("document"); + } + f +} + +fn has_selection(app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|d| !d.selection.is_empty()) +} + +/// The command's parameters: the switches and the scope. +fn params(d: &Dialog) -> Value { + let mut p = serde_json::Map::new(); + for (key, ..) in options() { + p.insert(key.into(), json!(d.bool(key))); + } + p.insert("scope".into(), json!(if d.str("scope") == "document" { "document" } else { "selection" })); + Value::Object(p) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + for (key, _, label) in options() { + form::check(ui, d, key, label); + } + ui.add_space(8.0); + widgets::section_header(ui, tl!("Replace In")); + let selected = has_selection(app); + let scope = d.str("scope"); + for (value, label, enabled) in [("selection", tl!("Selected Text Only"), selected), ("document", tl!("Entire Document"), true)] { + let on = if selected { scope == value } else { value == "document" }; + if widgets::radio(ui, label, on, enabled) { + d.fields.insert("scope".into(), json!(value)); + } + } + ui.add_space(8.0); + form::check(ui, d, "report", tl!("Report Results")); + false +} + +/// Runs the command, keeps the fields for the next time, and with Report Results on lists how many +/// of each chosen replacement it made. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let r = run_and_close(app, CMD, params(d))?; + app.ui.smart_punctuation = Value::Object(d.fields.clone()); + if d.bool("report") { + let lines: Vec = options() + .into_iter() + .filter(|(key, ..)| d.bool(key)) + .map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0))) + .collect(); + super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n")); + } + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app_with_text(text: &str) -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 40, "text": text, "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap(); + (app, id) + } + + fn plain(app: &VectorcraftApp, id: u64) -> String { + match &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.plain_text(), + _ => String::new(), + } + } + + /// The menu item opens the dialog; OK replaces in one undo step, reports each chosen + /// replacement's count, and the next opening starts from the fields confirmed. + #[test] + fn menu_item_opens_the_dialog_and_ok_reports_the_counts() { + let (mut app, id) = app_with_text("\"Hi\". 1/2 -- off"); + app.run("select.set", json!({"ids": [id]})).unwrap(); + crate::menus::invoke(&mut app, CMD, json!({})); + let d = app.ui.dialog.as_mut().expect("Smart Punctuation opens"); + assert_eq!((d.kind.as_str(), d.str("scope")), (KIND, "selection".to_string())); + for key in ["spaces", "fractions", "fiLigatures", "report"] { + d.fields.insert(key.into(), json!(true)); + } + d.fields.insert("ellipsis".into(), json!(false)); + let undo = app.session.doc().unwrap().history.undo.len(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(plain(&app, id), "“Hi”. ½ – o\u{FB00}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + let told = app.ui.dialog.as_ref().expect("Report Results shows the counts"); + assert_eq!(told.kind, crate::dialogs::confirm::MESSAGE); + assert_eq!(told.str("detail"), "ff, fi, ffi Ligatures: 1\nSmart Quotes: 2\nSmart Spaces: 1\nEn, Em Dashes: 1\nExpert Fractions: 1"); + app.ui.dialog = None; + crate::menus::invoke(&mut app, CMD, json!({})); + let again = app.ui.dialog.as_ref().unwrap(); + assert!(again.bool("fractions") && again.bool("report") && !again.bool("ellipsis")); + } + + /// With nothing selected the dialog replaces in the entire document, and without Report + /// Results it shows no message. An unchanged document keeps its undo history. + #[test] + fn with_nothing_selected_the_whole_document_is_replaced() { + let (mut app, id) = app_with_text("a--b"); + app.run("select.none", json!({})).unwrap(); + crate::menus::invoke(&mut app, CMD, json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("scope"), "document"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(plain(&app, id), "a–b"); + assert!(app.ui.dialog.is_none()); + let undo = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, CMD, json!({})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo); + } +} diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 0a1f5b5f7e..62e783c267 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -83,6 +83,47 @@ fn all_pages_and_a_crop_box() { assert_eq!(artboard_widths(&app), [10.0, 40.0, 30.0]); } +/// Each layer's objects in the active document: placed documents (true) or not. +fn placed_pages(app: &VectorcraftApp) -> Vec { + let doc = &app.session.active().unwrap().doc; + doc.layers.iter().flat_map(|l| l.children().cloned().unwrap_or_default()).map(|n| matches!(n.kind, NodeKind::PlacedDocument(_))).collect() +} + +#[test] +fn import_pdf_pages_as_links_opens_each_page_linked() { + let dir = vectorcraft_testkit::TempDir::new("import-pdf-link-pages"); + let path = dir.join("three.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, three_pages()).unwrap(); + let mut app = app(); + io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap(); + assert_eq!(field(&app, "linkPages"), false, "off by default"); + frame(&mut app); + set(&mut app, "linkPages", json!(true)); + set(&mut app, "allPages", json!(false)); + set(&mut app, "range", json!("1, 3")); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(artboard_widths(&app), [100.0, 300.0]); + assert_eq!(placed_pages(&app), [true, true]); + // A file given without its path, or opened with a password, can't link its pages: they open as art. + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + set(&mut app, "linkPages", json!(true)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(placed_pages(&app), [false, false, false]); + let two = pdf(&[PdfPage::new(10.0, 10.0, "0 g 0 0 5 5 re f"), PdfPage::new(20.0, 10.0, "0 g 0 0 5 5 re f")], Some("pw")); + let locked = dir.join("two.pdf").to_string_lossy().into_owned(); + std::fs::write(&locked, &two).unwrap(); + io::open_bytes(&mut app, &locked, &two, Some(locked.clone())).unwrap(); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + set(&mut app, "linkPages", json!(true)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(placed_pages(&app), [false, false]); +} + #[test] fn single_page_pdfs_open_directly() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_perspective.rs b/crates/ui-egui/src/dialogs/tests_perspective.rs index 97255bd22d..38aaf67770 100644 --- a/crates/ui-egui/src/dialogs/tests_perspective.rs +++ b/crates/ui-egui/src/dialogs/tests_perspective.rs @@ -250,6 +250,26 @@ fn double_clicking_the_tool_opens_perspective_grid_options() { assert!(!app.session.prefs.perspective_widget.show); } +#[test] +fn perspective_grid_options_hold_automatic_plane_positioning() { + let mut app = app(); + app.run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap(); + assert_eq!((field(&app, "anchorPoint"), field(&app, "gridlineIntersection")), (json!(true), json!(true)), "both on by default"); + frame(&mut app); + set(&mut app, "gridlineIntersection", json!(false)); + frame(&mut app); + super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), None); + let o = app.session.prefs.perspective_widget; + assert!(o.anchor_point && !o.gridline_intersection && o.show); + // The dialog opens on what was set, and a value that is not true or false is refused. + app.run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap(); + assert_eq!(field(&app, "gridlineIntersection"), json!(false)); + set(&mut app, "anchorPoint", json!("off")); + assert!(super::confirm(&mut app).is_err()); + assert!(app.session.prefs.perspective_widget.anchor_point); +} + #[test] fn digit_keys_switch_planes_and_the_widget_follows_the_window() { let mut app = app(); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 8db6de2f96..377df81a72 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -317,7 +317,7 @@ pub static LANGUAGES: [LangInfo; 29] = [ complete_menus: true, catalog: OnceLock::new(), }, - // Danish; every `da-*` locale (`da-DK`, `da_DK.UTF-8`…) resolves here. + // Danish: the whole interface and the status and error messages; every `da-*` locale (`da-DK`, `da_DK.UTF-8`…) resolves here. LangInfo { code: "da", name: "Dansk", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 1e801cff32..fb3080c8c2 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1287,6 +1287,7 @@ font-technology Variable Променливи Format Формат Format Options Опции за формат Format Settings Настройки на формата + Format Settings… Настройки на формата… Format: Формат: Formats: Формати: Fractional Widths Дробни ширини @@ -1633,6 +1634,7 @@ font-technology Variable Променливи Images: Изображения: Import Keyboard Shortcuts… Импортиране на клавишни комбинации… Import PDF Импортиране на PDF + Import PDF pages as links Импортиране на страниците на PDF като връзки Import PDF Presets Импортиране на PDF предварителни настройки Import Perspective Grid Presets Импортиране на предварителни настройки за перспективна мрежа Import Print Presets Импортиране на предварителни настройки за печат @@ -3351,6 +3353,18 @@ digits Malayalam Малаялам Smart Guides (View → Smart Guides) Интелигентни водачи (Изглед → Интелигентни водачи) Smart Guides (⌘U) Интелигентни водачи (⌘U) Smart Punctuation… Интелигентна пунктуация… + Smart Punctuation Интелигентна пунктуация + ff, fi, ffi Ligatures Лигатури ff, fi, ffi + ff, fl, ffl Ligatures Лигатури ff, fl, ffl + Smart Quotes Интелигентни кавички + Smart Spaces Интелигентни интервали + En, Em Dashes Средни и дълги тирета + Ellipses Многоточия + Expert Fractions Експертни дроби + Replace In Замяна в + Selected Text Only Само избрания текст + Entire Document Целия документ + Report Results Отчет за резултатите Smooth Гладък Corner Ъгъл Relative Относителен @@ -3381,6 +3395,7 @@ digits Malayalam Малаялам Solid Плътен Sort by Kind Сортиране по вид Sort by Name Сортиране по име + Sort by Size Сортиране по размер Sort by Status Сортиране по състояние Source code on GitHub Изходен код в GitHub Source Sans 3 Source Sans 3 @@ -6899,3 +6914,6 @@ breakText Glyphs Глифи Grommets Капси Grommet Inset Отстъп на капсите от ръба Diameter Диаметър + Nest Shapes… Подреждане на форми… + Nest Shapes Подреждане на форми + Roll Ролка diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index ec09c33484..118609f801 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -421,6 +421,18 @@ Title Case Svaka Riječ Velikim Slovom Sentence case Veliko početno slovo rečenice Smart Punctuation… Pametna interpunkcija… + Smart Punctuation Pametna interpunkcija + ff, fi, ffi Ligatures Ligature ff, fi, ffi + ff, fl, ffl Ligatures Ligature ff, fl, ffl + Smart Quotes Pametni navodnici + Smart Spaces Pametni razmaci + En, Em Dashes Srednje i duge crtice + Ellipses Tri tačke + Expert Fractions Stručni razlomci + Replace In Zamijeni u + Selected Text Only Samo odabrani tekst + Entire Document Cijeli dokument + Report Results Izvještaj o rezultatima Create Outlines Kreiraj obrise Optical Margin Alignment Optičko poravnanje margina Dynamic Text Dinamički tekst @@ -2249,6 +2261,7 @@ digits Malayalam Malajalam @msg paths entry {i} needs path and ids (object ids no other entry has) unos {i} u paths treba path i ids (ID-ove objekata koje nema nijedan drugi unos) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder uzima path: u folderu te datoteke traže se ostale nedostajuće veze Show Missing Prikaži nedostajuće + Sort by Size Sortiraj po veličini Sort by Status Sortiraj po statusu Clear Overrides Očisti zamjene Create New {kind} Style Kreiraj novi {kind} stil @@ -2503,6 +2516,7 @@ digits Malayalam Malajalam Export Asset Izvezi resurs Export to: Izvezi u: Format Settings Postavke formata + Format Settings… Postavke formata… Formats: Formati: Full Document Cijeli dokument Include Bleed Uključi napust @@ -2601,6 +2615,7 @@ digits Malayalam Malajalam e.g. 1-3, 5 npr. 1-3, 5 First Page Prva stranica Import PDF Uvezi PDF + Import PDF pages as links Uvezi stranice PDF-a kao veze Last Page Posljednja stranica Next Page Sljedeća stranica of {count} od {count} @@ -6952,3 +6967,6 @@ shape Open Otvoren Grommets Ušice Grommet Inset Udaljenost ušica od ruba Diameter Prečnik + Nest Shapes… Slaganje oblika… + Nest Shapes Slaganje oblika + Roll Rolna diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d08acc4b56..206ac8412d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1797,6 +1797,7 @@ digits Malayalam Malaiàlam Format Format Format Options Opcions de format Format Settings Configuració de format + Format Settings… Configuració de format… Format: Format: Formats: Formats: Fractional Widths Amplades fraccionàries @@ -2104,6 +2105,7 @@ digits Malayalam Malaiàlam Import Library… Importa biblioteca… Import Matches Importa coincidències Import PDF Importa PDF + Import PDF pages as links Importa les pàgines del PDF com a enllaços Import PDF Presets Importa preajustos de PDF Import Perspective Grid Presets Importa preajustos de quadrícula de perspectiva Import Print Presets Importa preajustos d’impressió @@ -4375,6 +4377,18 @@ digits Malayalam Malaiàlam Smart Guides (View → Smart Guides) Guies intel·ligents (Visualitza → Guies intel·ligents) Smart Guides (⌘U) Guies intel·ligents (⌘U) Smart Punctuation… Puntuació intel·ligent… + Smart Punctuation Puntuació intel·ligent + ff, fi, ffi Ligatures Lligadures ff, fi, ffi + ff, fl, ffl Ligatures Lligadures ff, fl, ffl + Smart Quotes Cometes intel·ligents + Smart Spaces Espais intel·ligents + En, Em Dashes Ratlles en i em + Ellipses Punts suspensius + Expert Fractions Fraccions expertes + Replace In Reemplaça a + Selected Text Only Només el text seleccionat + Entire Document Tot el document + Report Results Informa dels resultats Smooth Suavitza Smooth Color Color suau Smooth Tool Eina de suavitzat @@ -4410,6 +4424,7 @@ digits Malayalam Malaiàlam Sort by Luminance Ordena per lluminositat Sort by Name Ordena per nom Sort by Popularity Ordena per popularitat + Sort by Size Ordena per mida Sort by Status Ordena per estat Sort Swatches Ordena les mostres Source code on GitHub Codi font a GitHub @@ -6335,6 +6350,7 @@ digits Malayalam Malaiàlam @msg the spine has no segments l’espina no té segments @msg the stroke has no weight el traç no té gruix @msg the SVG's elements are nested more than {0} deep els elements de l’SVG estan imbricats a més de {0} nivells de profunditat +@msg the SVG's styles expand to more than {0} MB els estils de l’SVG s’expandeixen a més de {0} MB @msg the target layer is locked or hidden la capa de destinació està blocada o amagada @msg the thumbnail image is malformed la imatge de la miniatura està mal formada @msg the top object must be a path, compound path or text object to use as a clipping mask l’objecte superior ha de ser un traçat, un traçat compost o un objecte de text per fer-lo servir com a màscara de retall @@ -7507,6 +7523,9 @@ breakText Glyphs Glifs Grommets Ullets Grommet Inset Distància dels ullets a la vora Diameter Diàmetre + Nest Shapes… Encaixa les formes… + Nest Shapes Encaixa les formes + Roll Rotlle # Status and error messages of image export, color profiles and libraries, 3D effects, path operations and scripts. @msg 3D effects require finite coordinates within 100 million points Els efectes 3D requereixen coordenades finites dins de 100 milions de punts @msg 3D effects require one to ten lights Els efectes 3D requereixen d’un a deu llums diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 54082ffcfd..3b9c300980 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -428,6 +428,18 @@ Title Case Velká Počáteční Písmena Sentence case Velké první písmeno věty Smart Punctuation… Inteligentní interpunkce… + Smart Punctuation Inteligentní interpunkce + ff, fi, ffi Ligatures Ligatury ff, fi, ffi + ff, fl, ffl Ligatures Ligatury ff, fl, ffl + Smart Quotes Inteligentní uvozovky + Smart Spaces Inteligentní mezery + En, Em Dashes Krátké a dlouhé pomlčky + Ellipses Výpustky + Expert Fractions Odborné zlomky + Replace In Nahradit v + Selected Text Only Pouze vybraný text + Entire Document Celý dokument + Report Results Zobrazit výsledky Create Outlines Převést na křivky Optical Margin Alignment Optické zarovnání okrajů Dynamic Text Dynamický text @@ -2280,6 +2292,7 @@ digits Malayalam Malajálamské @msg paths entry {i} needs path and ids (object ids no other entry has) položka {i} v paths potřebuje path a ids (ID objektů, které nemá žádná jiná položka) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder bere path: ve složce tohoto souboru se hledají ostatní chybějící propojení Show Missing Zobrazit chybějící + Sort by Size Seřadit podle velikosti Sort by Status Seřadit podle stavu Clear Overrides Vymazat přepsání Create New {kind} Style Vytvořit nový styl ({kind}) @@ -2536,6 +2549,7 @@ digits Malayalam Malajálamské Export Asset Exportovat prvek Export to: Exportovat do: Format Settings Nastavení formátu + Format Settings… Nastavení formátu… Formats: Formáty: Full Document Celý dokument Include Bleed Zahrnout spadávku @@ -2636,6 +2650,7 @@ digits Malayalam Malajálamské e.g. 1-3, 5 např. 1-3, 5 First Page První stránka Import PDF Importovat PDF + Import PDF pages as links Importovat stránky PDF jako propojení Last Page Poslední stránka Next Page Další stránka of {count} z {count} @@ -7629,6 +7644,9 @@ breakText Glyphs Glyfy Grommets Průchodky Grommet Inset Odstup průchodek od okraje Diameter Průměr + Nest Shapes… Skládat tvary… + Nest Shapes Skládat tvary + Roll Role @msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions 'caller', 'callee' a 'arguments' nelze použít u funkcí ve striktním režimu @msg A profile supports one Revolve effect. Edit the existing effect's options instead. Profil podporuje jeden efekt Rotační těleso. Upravte místo toho volby stávajícího efektu. @msg Add Points at Crossings: a path went missing Přidat body v křížení: jedna cesta se ztratila @@ -9014,6 +9032,7 @@ breakText Glyphs Glyfy @msg the RTF file is too large to place as type (at most {_1} MB) soubor RTF je příliš velký na umístění jako text (nejvýše {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG se rozvine na více než {0} vnořených obrázků SVG @msg the SVG expands to more than {0} objects SVG se rozvine na více než {0} objektů +@msg the SVG's styles expand to more than {0} MB styly SVG se rozvinou na více než {0} MB @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes soubor SVG je větší než {MAX_IMPORT_BYTES} bajtů @msg the SVG has no drawable objects SVG nemá žádné vykreslitelné objekty @msg the SVGZ file unpacks to more than {_1} MB soubor SVGZ se rozbalí na více než {_1} MB diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index dd5aba4de6..59ce36d15f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -25,6 +25,615 @@ @msg {key} must be [x, y] with finite coordinates {key} skal være [x, y] med endelige koordinater @msg ids must contain 1–10000 object ids ids skal indeholde 1–10000 objekt-id’er +# Status and error messages: 3D assets, type on a path, scripts and their File and $ objects, presets, +# PDF page sizes, Objects on Path, plug-ins, file readers and data sets. Names in backticks, command ids, +# double-quoted values and bare true, false and null stay as the English writes them; names the user +# gave are quoted »…«, and numbers use a period between thousands (2.048). +@msg {what} can't be exported in 3D: {e} {what} kan ikke eksporteres i 3D: {e} +@msg asset {id} isn't a 3D asset aktiv {id} er ikke et 3D-aktiv +@msg asset {id} is a 3D asset: assets.export3D writes it aktiv {id} er et 3D-aktiv: assets.export3D skriver det +@msg no 3D assets yet: collect an object with a 3D effect first (assets.add3D) ingen 3D-aktiver endnu: saml først et objekt med en 3D-effekt (assets.add3D) +@msg select an object with a 3D effect (or give its ids) markér et objekt med en 3D-effekt (eller angiv dets id’er) +@msg select point type or type on a path markér punkttekst eller tekst på en kurve +@msg type on a path in a thread cannot use Dynamic Text: {frames} tekst på en kurve i en tekstkæde kan ikke bruge dynamisk tekst: {frames} +@msg type on an open or compound path cannot be centered on its top or bottom: {open} tekst på en åben eller sammensat kurve kan ikke centreres på dens top eller bund: {open} +@msg type on a path with no length or no height cannot be centered: {flat} tekst på en kurve uden længde eller højde kan ikke centreres: {flat} +@msg type on a path in a thread cannot be centered on its top or bottom: {frames} tekst på en kurve i en tekstkæde kan ikke centreres på dens top eller bund: {frames} +@msg select type on a closed path markér tekst på en lukket kurve +@msg `Custom` stands for changed settings: save the preset under another name `Custom` står for ændrede indstillinger: gem forudindstillingen under et andet navn +@msg the selection has no gradient fill markeringen har ingen gradientudfyldning +@msg the selection has no gradient stroke markeringen har ingen gradientstreg +@msg the selection has no pattern fill markeringen har ingen mønsterudfyldning +@msg the selection has no pattern stroke markeringen har ingen mønsterstreg +@msg no gradient swatch `{name}` ingen gradientfarveprøve `{name}` +@msg no pattern swatch `{name}` ingen mønsterfarveprøve `{name}` +@msg the library item is damaged bibliotekselementet er beskadiget +@msg its zlib compression is damaged dens zlib-komprimering er beskadiget +@msg its Zstandard compression is damaged dens Zstandard-komprimering er beskadiget +@msg it decompresses to more than {_1} MB den udpakkes til mere end {_1} MB +@msg its editing data is for a different page dens redigeringsdata er til en anden side +@msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` skal være "emBox", "capHeight", "xHeight" eller "icfBox" +@msg Choose a .js or .jsx script Vælg et .js- eller .jsx-script +@msg Ran {name} Kørte {name} +@msg The script was stopped and its changes were undone Scriptet blev stoppet, og dets ændringer blev fortrudt +@msg a script is running: stop it or wait for it to finish et script kører: stop det, eller vent, til det er færdigt +@msg this is a compiled script, which cannot be run; use its source text dette er et kompileret script, som ikke kan køres; brug dets kildetekst +@msg the script is not UTF-8 text scriptet er ikke UTF-8-tekst +@msg the script is too large to run scriptet er for stort til at blive kørt +@msg a drag or an undo group is open; finish it before running a script en trækning eller en fortrydelsesgruppe er åben; afslut den, før du kører et script +@msg the script left a document that cannot be kept scriptet efterlod et dokument, der ikke kan beholdes +@msg the script is no longer in the Scripts folder scriptet ligger ikke længere i mappen Scripter +@msg the script's run is no longer available scriptets kørsel er ikke længere tilgængelig +@msg a failed command changed undo steps that could not be put back, so the script was stopped en mislykket kommando ændrede fortrydelsestrin, der ikke kunne genskabes, så scriptet blev stoppet +@msg a recovery copy could not be written, so the script was not run en gendannelseskopi kunne ikke skrives, så scriptet blev ikke kørt +@msg Script file access denied Scriptets filadgang blev nægtet +@msg Script file exceeds 8 MiB Scriptfilen er større end 8 MiB +@msg Script file is not open Scriptfilen er ikke åben +@msg Script file cannot be decoded Scriptfilen kan ikke afkodes +@msg Script file is not a regular file Scriptfilen er ikke en almindelig fil +@msg Script file does not exist Scriptfilen findes ikke +@msg Script file could not be read Scriptfilen kunne ikke læses +@msg Script folder has more than 2,048 entries Scriptmappen har mere end 2.048 elementer +@msg Script file open mode must be r, w, e or a Scriptfilens åbningstilstand skal være r, w, e eller a +@msg Script file writing is not available Skrivning af scriptfiler er ikke tilgængelig +@msg Script file dialogs are not available Scriptfildialoger er ikke tilgængelige +@msg Script files cannot be opened in another application Scriptfiler kan ikke åbnes i et andet program +@msg Script file access is unavailable on the web Scriptets filadgang er ikke tilgængelig på nettet +@msg Script has 256 files open Scriptet har 256 filer åbne +@msg Script file path exceeds 32,767 characters Scriptfilens sti er længere end 32.767 tegn +@msg Script folder mask takes too many steps to match Scriptmappens maske kræver for mange trin at matche +@msg the script opened more file data than one run may open (32 MiB) scriptet åbnede flere fildata, end én kørsel må åbne (32 MiB) +@msg File.seek: takes a position and a mode File.seek: tager en position og en tilstand +@msg vc.run: give a command id, as a string vc.run: angiv et kommando-id som en streng +@msg vc.run: takes a command id and an object of parameters vc.run: tager et kommando-id og et objekt med parametre +@msg vc.run: the parameters must be an object vc.run: parametrene skal være et objekt +@msg vc.run: the result{place} is too large for a script vc.run: resultatet{place} er for stort til et script +@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 {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) +@msg {name}: line {line}, column {column} of {file}: {e} (limit) {name}: linje {line}, kolonne {column} i {file}: {e} (grænse) +@msg {name}: line {line}, column {column}: {e} (limit) {name}: linje {line}, kolonne {column}: {e} (grænse) +@msg {name}: {e} (limit) {name}: {e} (grænse) +@msg {name}: line {line}, column {column} of {file}: {e} (syntax) {name}: linje {line}, kolonne {column} i {file}: {e} (syntaksfejl) +@msg {name}: line {line}, column {column}: {e} (syntax) {name}: linje {line}, kolonne {column}: {e} (syntaksfejl) +@msg {name}: {e} (syntax) {name}: {e} (syntaksfejl) +@msg {name}: line {line}, column {column} of {file}: {e} (stopped) {name}: linje {line}, kolonne {column} i {file}: {e} (stoppet) +@msg {name}: line {line}, column {column}: {e} (stopped) {name}: linje {line}, kolonne {column}: {e} (stoppet) +@msg {name}: {e} (stopped) {name}: {e} (stoppet) +@msg {name}: line {line}, column {column} of {file}: {e} (internal) {name}: linje {line}, kolonne {column} i {file}: {e} (intern fejl) +@msg {name}: line {line}, column {column}: {e} (internal) {name}: linje {line}, kolonne {column}: {e} (intern fejl) +@msg {name}: {e} (internal) {name}: {e} (intern fejl) +@msg {e} (these files stay written: {paths}) {e} (disse filer forbliver skrevet: {paths}) +@msg $.{name}: give a name, as a string $.{name}: angiv et navn som en streng +@msg $.locale: give a locale such as "en" or "de_DE", or null for the interface's $.locale: angiv en landestandard som "en" eller "de_DE", eller null for brugerfladens +@msg $.localize: give true or false $.localize: angiv true eller false +@msg $.flags: only 512, which turns localization on, or 0 can be set $.flags: kun 512, som slår lokalisering til, eller 0 kan angives +@msg $.flags: give a number $.flags: angiv et tal +@msg $.appEncoding: scripts here read and write UTF-8 only $.appEncoding: scripter her læser og skriver kun UTF-8 +@msg $.appEncoding: give an encoding's name, as a string $.appEncoding: angiv navnet på en tegnkodning som en streng +@msg $.memCache: the memory cache size cannot be set $.memCache: hukommelsescachens størrelse kan ikke angives +@msg $.setenv: give a value, as a string $.setenv: angiv en værdi som en streng +@msg $.setenv: only {_1} can be set $.setenv: kun {_1} kan angives +@msg $.setenv: a value has at most {MAX_ENV_BYTES} letters, digits and _ . - @ $.setenv: en værdi har højst {MAX_ENV_BYTES} bogstaver, cifre og _ . - @ +@msg $.sleep: give a number of milliseconds from 0 to {MAX_SLEEP_MS} $.sleep: angiv et antal millisekunder fra 0 til {MAX_SLEEP_MS} +@msg $.sleep: give a number of milliseconds $.sleep: angiv et antal millisekunder +@msg $.sleep: a run cannot wait inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code $.sleep: en kørsel kan ikke vente i et tilbagekald fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode +@msg $.bp: scripts here have no debugger $.bp: scripter her har ingen debugger +@msg $.colorPicker: scripts cannot show a dialog yet $.colorPicker: scripter kan endnu ikke vise en dialog +@msg {name}: give a message {name}: angiv en meddelelse +@msg {name}: give the text the field starts with {name}: angiv den tekst, feltet starter med +@msg {name}: the message is longer than 16 KiB {name}: meddelelsen er længere end 16 KiB +@msg {name}: the title is longer than 256 bytes {name}: titlen er længere end 256 byte +@msg {name}: the text the field starts with is longer than 16 KiB {name}: den tekst, feltet starter med, er længere end 16 KiB +@msg {name}: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en dialog kan ikke åbne i et tilbagekald fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode +@msg {name}: the next answer in `answers` is for {_1}, not {name} {name}: det næste svar i `answers` er til {_1}, ikke til {name} +@msg {name}: `answers` has no answer left for this dialog {name}: `answers` har intet svar tilbage til denne dialog +@msg vc.document{place} is too large for a script vc.document{place} er for stort til et script +@msg vc.log: the log of this run is full vc.log: loggen for denne kørsel er fuld +@msg this function's script run has ended denne funktions scriptkørsel er afsluttet +@msg the script made more host calls than one run may make scriptet foretog flere værtskald, end én kørsel må foretage +@msg the script passed more data to and from commands than one run may pass scriptet sendte flere data til og fra kommandoer, end én kørsel må sende +@msg the script added more objects and data to the documents than one run may add scriptet tilføjede flere objekter og data til dokumenterne, end én kørsel må tilføje +@msg {what}: the object is not a File or a Folder {what}: objektet er ikke en File eller en Folder +@msg {what}: the count must be a finite number, 0 or more {what}: antallet skal være et endeligt tal, 0 eller mere +@msg File.seek: the position must be a finite number File.seek: positionen skal være et endeligt tal +@msg File.seek: the mode must be 0, 1 or 2 File.seek: tilstanden skal være 0, 1 eller 2 +@msg script file is compiled: {value} scriptfilen er kompileret: {value} +@msg `name` must be the name of a script engine `name` skal være navnet på en scriptmotor +@msg the main script engine is new for each run and is never kept, so it cannot be dropped hovedscriptmotoren er ny ved hver kørsel og bevares aldrig, så den kan ikke fjernes +@msg there is no script engine named {name} der findes ingen scriptmotor med navnet {name} +@msg Running a script Kører et script +@msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e} +@msg Plug-ins can't be loaded from {path}: {e} Plug-ins kan ikke indlæses fra {path}: {e} +@msg select a path markér en kurve +@msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Gem skriver {_1}, ikke {_2}: brug file.saveAsTemplate til at skrive det +@msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 skriver ældre .ai-filer, ikke .ait-skabeloner +@msg `groupColors` must be an array `groupColors` skal være et array +@msg `preserve` must be an object `preserve` skal være et objekt +@msg `{key}` must be an array `{key}` skal være et array +@msg `{key}` must be a #rrggbb color `{key}` skal være en #rrggbb-farve +@msg `{key}` must be a #rrggbb color or a layer color name `{key}` skal være en #rrggbb-farve eller navnet på en lagfarve +@msg unknown Live Paint option `{key}` ukendt Live Paint-indstilling `{key}` +@msg unknown Shape Builder option `{key}` ukendt Formbygger-indstilling `{key}` +@msg `{key}` must be a profile name or null `{key}` skal være et profilnavn eller null +@msg `top` and `below` can't both be true `top` og `below` kan ikke begge være true +@msg `select` must be true or false `select` skal være true eller false +@msg `minAnchors` and `maxAnchors` must be whole numbers `minAnchors` og `maxAnchors` skal være heltal +@msg `{key}` must be a number not below 0 `{key}` skal være et tal, der ikke er under 0 +@msg `{key}` must be four numbers not below 0: [tl, tr, br, bl] `{key}` skal være fire tal, der ikke er under 0: [tl, tr, br, bl] +@msg `{key}` must be [x, y, width, height]: four finite numbers, width and height not negative `{key}` skal være [x, y, width, height]: fire endelige tal, hvor width og height ikke er negative +@msg `{min_key}` is greater than `{max_key}` `{min_key}` er større end `{max_key}` +@msg give at least one of `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` angiv mindst én af `name`, `kind`, `text`, `within`, `intersects`, `minWidth`, `maxWidth`, `minHeight`, `maxHeight`, `minThickness`, `maxThickness`, `minArea`, `maxArea`, `minAnchors`, `maxAnchors` +@msg a process color can't colorize a grayscale image with transparency: use a spot color, black or white en procesfarve kan ikke farvelægge et gråtonebillede med gennemsigtighed: brug en staffagefarve, sort eller hvid +@msg a key object sits on that point et nøgleobjekt ligger på det punkt +@msg `name` is empty `name` er tom +@msg `newName` is empty `newName` er tom +@msg `{name}` is a built-in preset and can't change: save it under another name `{name}` er en indbygget forudindstilling og kan ikke ændres: gem den under et andet navn +@msg `{name}` is a built-in preset and stays `{name}` er en indbygget forudindstilling og bevares +@msg a spine keeps at least two points en rygrad beholder mindst to punkter +@msg `guideLabel` is null, a layer color's name or #rrggbb `guideLabel` er null, navnet på en lagfarve eller #rrggbb +@msg the Simplify slider is not open skyderen Forenkl er ikke åben +@msg the Smooth slider is not open skyderen Udglat er ikke åben +@msg handle must be in or out handle skal være in eller out +@msg index must be ≥ 0 index skal være ≥ 0 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller siden for tegneflade {n} er {size}, længere end PDF's sidegrænse på 14.400 pt (200 in): den skrives med en UserUnit på {unit}, så programmer, der ignorerer UserUnit, viser den så mange gange mindre +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller: turn on Write pages longer than 200 in at full size in points siden for tegneflade {n} er {size}, længere end PDF's sidegrænse på 14.400 pt (200 in): den skrives med en UserUnit på {unit}, så programmer, der ignorerer UserUnit, viser den så mange gange mindre: slå Skriv sider længere end 200 in i fuld størrelse i punkter til +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in siden for tegneflade {n} er {size}, længere end PDF's sidegrænse på 14.400 pt (200 in): {label}-sider skrives uden en UserUnit, i punkter, og programmer, der overholder grænsen, beskærer siden til 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 har ingen UserUnit, som en side længere end 14.400 pt (200 in) har brug for for at bevare sin størrelse: filen skrives som PDF 1.6 +@msg PDF 1.4 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to stay within PDF/A-2's page limit of 14,400 units: the file is written as PDF 1.6 PDF 1.4 har ingen UserUnit, som en side længere end 14.400 pt (200 in) har brug for for at holde sig inden for PDF/A-2's sidegrænse på 14.400 enheder: filen skrives som PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units siden for tegneflade {n} er {size}, for lang og smal til PDF's sidelængder på 3 til 14.400 enheder: den skrives med en UserUnit på {unit}, som holder den korte side på 3 enheder eller mere, og programmer, der overholder grænsen, beskærer den lange side til 14.400 enheder +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-filer rummer reelle tal op til {max}, og siden for tegneflade {n}, der er {side} pt lang, kræver større: vælg PDF 1.6 eller nyere uden en PDF/X-standard, eller en mindre tegneflade +@msg line {line}: value for `{var}` must be true or false linje {line}: værdien for `{var}` skal være true eller false +@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes linje {line}: værdien for `{var}` er længere end {MAX_GRAPH_CSV} byte +@msg a bristle brush name can have at most {max} characters: `{name}` has {count} navnet på en børstepensel kan have højst {max} tegn: `{name}` har {count} +@msg `{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file `{file}` er ikke et VectorCraft-dokument, en PDF eller en PDF-kompatibel .ai-fil +@msg no saved preset named `{name}` ingen gemt forudindstilling med navnet `{name}` +@msg no saved preset named `{name}` to rename ingen gemt forudindstilling med navnet `{name}` at omdøbe +@msg `{ID}`: the reference would be larger than {MAX_BYTES} bytes `{ID}`: referencen ville være større end {MAX_BYTES} byte +@msg the artboard is locked tegnefladen er låst +@msg no such spine point intet sådant rygradpunkt +@msg `with` must be a list of at most 10000 spine point indexes `with` skal være en liste med højst 10000 rygradpunktindekser +@msg `with` moves points, not a handle `with` flytter punkter, ikke et håndtag +@msg no such spine segment intet sådant rygradsegment +@msg node {_1} is on a locked artboard node {_1} ligger på en låst tegneflade +@msg not a blend ikke en blanding +@msg not a PICT file ikke en PICT-fil +@msg thumbnail: no page {n} (the file has 1) miniature: ingen side {n} (filen har 1) +@msg select a blend or give `id` markér en blanding, eller angiv `id` +@msg select an Objects on Path group markér en gruppe med objekter på kurve +@msg choose the object to detach with its Select/Move widget vælg det objekt, der skal frigøres, med dets Markér/Flyt-kontrol +@msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects en kurve i en sammensat kurve, blanding, kuvert, gentagelse eller sammenfletningsgruppe kan ikke modtage objekter +@msg a clipping path can't take objects en beskæringskurve kan ikke modtage objekter +@msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objekter i en blanding, kuvert, gentagelse eller sammenfletningsgruppe kan ikke knyttes til en kurve +@msg a clipping path can't be attached to a path en beskæringskurve kan ikke knyttes til en kurve +@msg `background` must be edges, corners or colors `background` skal være edges, corners eller colors +@msg `match` must be distance or channels `match` skal være distance eller channels +@msg `{key}` must be from 0 to 100 `{key}` skal være fra 0 til 100 +@msg `colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue `colors` skal angive 1 til 16 farver, hver som hex (#rrggbb eller #rgb) eller black, white, red, green eller blue +@msg the linked image shows its preview: embed or relink it first det sammenkædede billede viser sin forhåndsvisning: integrér det, eller genopret linket først +@msg a CMYK image has no transparency to set et CMYK-billede har ingen gennemsigtighed at angive +@msg every pixel matches the background: no image would be left hver pixel matcher baggrunden: der ville ikke være noget billede tilbage +@msg an image of {w} × {h} pixels is too large to change et billede på {w} × {h} pixels er for stort til at ændre +@msg select an image with a color mask markér et billede med en farvemaske +@msg the color mask's settings are out of range farvemaskens indstillinger er uden for området +@msg a CMYK image can't take a color mask et CMYK-billede kan ikke få en farvemaske +@msg the mask would hide every pixel masken ville skjule hver pixel +@msg Recolor completed; {locked} and {hidden} were left unchanged Omfarvning fuldført; {locked} og {hidden} blev ikke ændret +@msg Recolor completed; {objects} were left unchanged Omfarvning fuldført; {objects} blev ikke ændret +@msg Recolor completed; {objects} was left unchanged Omfarvning fuldført; {objects} blev ikke ændret +@msg 1 locked object 1 låst objekt +@msg {n} locked objects {n} låste objekter +@msg 1 hidden object 1 skjult objekt +@msg {n} hidden objects {n} skjulte objekter +@msg t, dx and dy must be finite t, dx og dy skal være endelige +@msg the blend has no spine blandingen har ingen rygrad +@msg the spine has no segments rygraden har ingen segmenter +@msg panels can't be shown in Presentation Mode paneler kan ikke vises i Præsentationstilstand +@msg unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets) ukendt forudindstilling `{name}`: ikke en indbygget eller gemt forudindstilling (se imageTrace.presets) +@msg variables are locked variablerne er låst +@msg more than {MAX_CSV_ROWS} data sets: Import Data Sets reads at most {MAX_CSV_ROWS} mere end {MAX_CSV_ROWS} datasæt: Importér datasæt læser højst {MAX_CSV_ROWS} +@msg more than {MAX_CSV_COLS} variables: Import Data Sets reads at most {MAX_CSV_COLS} mere end {MAX_CSV_COLS} variabler: Importér datasæt læser højst {MAX_CSV_COLS} +@msg `{key}: {top}` and `options.{key}: {inner}` disagree: give the option once `{key}: {top}` og `options.{key}: {inner}` er uenige: angiv indstillingen én gang +@msg x and y must be finite x og y skal være endelige +@msg {_1} is an exporter (File › Export › Export As…) {_1} er en eksportør (Filer › Eksportér › Eksportér som…) +@msg `documentData` is {size} bytes (limit {MAX_DOCUMENT_DATA}) `documentData` fylder {size} byte (grænse {MAX_DOCUMENT_DATA}) +@msg a mask that covers several layers comes in as a clipping group in each layer it covers en maske, der dækker flere lag, indlæses som en beskæringsgruppe i hvert lag, den dækker +@msg a graph's records don't end where they should: its art was read as it is en grafs poster slutter ikke, hvor de skal: dens grafik blev læst, som den er +@msg `{w}` takes no operands `{w}` tager ingen operander +@msg a wraparound group is inside a compound path en ombrydningsgruppe ligger i en sammensat kurve +@msg it ends inside a multi-layer mask den slutter inde i en maske over flere lag +@msg a multi-layer mask's operators are out of order operatorerne i en maske over flere lag står i forkert rækkefølge +@msg a multi-layer mask needs one clipping path en maske over flere lag kræver én beskæringskurve +@msg a group crosses a multi-layer mask en gruppe krydser en maske over flere lag +@msg graphs come in as plain art, without their data or settings grafer indlæses som almindelig grafik uden deres data eller indstillinger +@msg the active document changed while the question was open; nothing was deleted det aktive dokument ændrede sig, mens spørgsmålet var åbent; intet blev slettet +@msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Linket ligger i et symbol, et grafdesign, et mønster eller en opacitetsmaske og har ingen plads på lærredet +@msg source must be the id of a Shaper Group's original shape source skal være id’et for en shapergruppes oprindelige form +@msg group must be the id of a Shaper Group group skal være id’et for en shapergruppe +@msg the shape is not an editable original shape of that Shaper Group formen er ikke en redigerbar oprindelig form i den shapergruppe +@msg id {value} is a layer, not an object id {value} er et lag, ikke et objekt +@msg id {value} is a layer, not an object; move layers with layer.move id {value} er et lag, ikke et objekt; flyt lag med layer.move +@msg the PCX file is cut short PCX-filen er afkortet +@msg the PCX file's header is damaged PCX-filens header er beskadiget +@msg PCX files with {bits}-bit pixels in {planes} planes can't be read PCX-filer med {bits}-bit-pixels i {planes} planer kan ikke læses +@msg the Pixar file is cut short Pixar-filen er afkortet +@msg the Pixar file's header is damaged Pixar-filens header er beskadiget +@msg the Pixar file's image data is damaged Pixar-filens billeddata er beskadigede +@msg the JPEG 2000 file can't be read JPEG 2000-filen kan ikke læses +@msg the JPEG 2000 file has an unsupported color space or JPX content JPEG 2000-filen har et farverum eller JPX-indhold, der ikke understøttes +@msg the HEIC or HEIF file can't be read HEIC- eller HEIF-filen kan ikke læses +@msg the HEIC or HEIF file holds a kind of image that can't be read HEIC- eller HEIF-filen indeholder en billedtype, der ikke kan læses +@msg HEIC and HEIF images can't be opened in this build HEIC- og HEIF-billeder kan ikke åbnes i denne version +@msg the JPEG XL file is cut short JPEG XL-filen er afkortet +@msg the JPEG XL container is too large to read JPEG XL-containeren er for stor til at blive læst +@msg CMYK JPEG XL images can't be read CMYK-billeder i JPEG XL kan ikke læses +@msg the JPEG XL file can't be read: {e} JPEG XL-filen kan ikke læses: {e} +@msg Extrude & Bevel Ekstrudér og facet +@msg Revolve Omdrej +@msg Inflate Pust op +@msg Rotate Rotér +@msg Extrude & Bevel (Classic) Ekstrudér og facet (klassisk) +@msg Revolve (Classic) Omdrej (klassisk) +@msg Rotate (Classic) Rotér (klassisk) +@msg This effect Denne effekt +@msg clipping paths beskæringskurver +@msg other objects andre objekter +@msg {label} requires a group holding a shape with at least two anchors {label} kræver en gruppe, der indeholder en form med mindst to ankerpunkter +@msg Revolve requires a group holding a shape with at least two anchors Omdrej kræver en gruppe, der indeholder en form med mindst to ankerpunkter +@msg Revolve requires a shape with at least two anchors Omdrej kræver en form med mindst to ankerpunkter +@msg {label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first. {label} på en gruppe kræver kurver, sammensatte kurver, tekst, grupper, beskæringsgrupper, blandinger og symbolforekomster: frigør eller udvid først dens {what}. +@msg {label} on a group takes at most {MAX_MEMBERS} objects {label} på en gruppe tager højst {MAX_MEMBERS} objekter +@msg A 3D effect on a group or layer goes on the group itself, not on its fill or stroke En 3D-effekt på en gruppe eller et lag anvendes på selve gruppen, ikke på dens udfyldning eller streg +@msg a 3D effect on a group's fill or stroke draws nothing en 3D-effekt på en gruppes udfyldning eller streg tegner intet +@msg a 3D effect on a group's fill or stroke draws nothing to export en 3D-effekt på en gruppes udfyldning eller streg tegner intet at eksportere +@msg The 3D object is too complex to export 3D-objektet er for komplekst til at blive eksporteret +@msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Ekstrudér og facet, Omdrej, Pust op eller Rotér) +@msg its 3D effect builds no solid dens 3D-effekt danner intet legeme +@msg bevel must be none or one of {_1} bevel skal være none eller en af {_1} +@msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kan ikke danne legemer af denne grafik: dens symbolforekomster, blandinger og beskæringsgrupper indeholder for mange objekter +@msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kan ikke danne et legeme af forekomsten af symbolet "{symbol}": symbolets grafik er ikke tilgængelig +@msg {_1}: the clipping path is too complex to cut the art with {_1}: beskæringskurven er for kompleks til at skære grafikken med +@msg {_1} takes at most {MAX_MEMBERS} objects {_1} tager højst {MAX_MEMBERS} objekter +@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} kan ikke danne legemer af grafik, der er indlejret mere end {MAX_DEPTH} niveauer dybt +@msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Omdrej-malingen er for kompleks til denne overflade; reducér Segmenter, eller forenkl gradienten +@msg Revolve edge must be left or right Omdrej: edge skal være left eller right +@msg Revolve cap must be a boolean Omdrej: cap skal være en boolesk værdi +@msg the revolved object has no fill or stroke det omdrejede objekt har ingen udfyldning eller streg +@msg lightColor must be an opaque RGB color in #rrggbb form lightColor skal være en uigennemsigtig RGB-farve i formen #rrggbb +@msg lights must contain one to ten lights lights skal indeholde et til ti lys +@msg each light must be an object hvert lys skal være et objekt +@msg unknown light setting: use color, intensity, rotation, height, softness or behind ukendt lysindstilling: brug color, intensity, rotation, height, softness eller behind +@msg light {key} must be a number from {min} to {max} lys: {key} skal være et tal fra {min} til {max} +@msg light color must use opaque #rrggbb lys: color skal bruge uigennemsigtig #rrggbb +@msg light behind must be true or false lys: behind skal være true eller false +@msg shadow must be true or false shadow skal være true eller false +@msg shadowPosition must be behind or below shadowPosition skal være behind eller below +@msg {key} must be a number from {min} to {max} {key} skal være et tal fra {min} til {max} +@msg each of `{GRAPHICS}` must be an object hvert element i `{GRAPHICS}` skal være et objekt +@msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` elementer i `{GRAPHICS}` tager symbol, face, x, y, scale og rotation, ikke `{k}` +@msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol hvert element i `{GRAPHICS}` kræver `symbol`, navnet på et symbol +@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`: face skal være front eller back +@msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`: {key} skal være et tal fra {lo} til {hi} +@msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array +@msg Graphics map onto the Plane, Extrude and Revolve object types Grafik kortlægges på objekttyperne Plan, Ekstrudér og Omdrej +@msg Revolve maps graphics onto its side: map them onto the front Omdrej kortlægger grafik på siden: kortlæg den på forsiden +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikken er for kompleks til denne overflade: forenkl symbolernes grafik, eller reducér Segmenter +@msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tager højst {MAX_GRAPHICS} grafikelementer +@msg A plane has one face: map its graphics onto the front Et plan har én flade: kortlæg dets grafik på forsiden +@msg The graphics are too complex: simplify the symbols' art Grafikken er for kompleks: forenkl symbolernes grafik +@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Et grafikelements grafik må højst være indlejret {MAX_LEVELS} niveauer dybt: forenkl symbolets grafik +@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Et grafikelements grafik må højst indlejre symboler {MAX_NESTING} niveauer dybt: forenkl symbolets grafik +@msg A graphic's art holds too many objects: simplify the symbol's art Et grafikelements grafik indeholder for mange objekter: forenkl symbolets grafik +@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Et grafikelement tegner højst {MAX_PIECES} udfyldninger og streger: forenkl symbolets grafik +@msg `surface` must be one of {_1} `surface` skal være en af {_1} +@msg {label} draws the source art for this object instead of its 3D surface {label} tegner kildegrafikken for dette objekt i stedet for dets 3D-overflade +@msg {label} draws no faces for this object {label} tegner ingen flader for dette objekt +@msg the wireframe has more than {MAX_WIRE_EDGES} edges trådmodellen har mere end {MAX_WIRE_EDGES} kanter +@msg the params must be an object, not {got} parametrene skal være et objekt, ikke {got} +@msg unknown parameter `{path}`; the object takes no keys ukendt parameter `{path}`; objektet tager ingen nøgler +@msg unknown parameter `{path}`; it takes: {keys} ukendt parameter `{path}`; den tager: {keys} +@msg missing `{path}` `{path}` mangler +@msg `{path}` must be {expected}, not {got} `{path}` skal være {expected}, ikke {got} +@msg `{path}` is nested too deeply `{path}` er indlejret for dybt +@msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: ikke et PNG-, JPEG-, WebP-, TIFF- eller BMP-billede +@msg the image is {iw} × {ih} pixels and the artboard at that width is {rw} × {rh} pixels: their proportions differ billedet er {iw} × {ih} pixels, og tegnefladen i den bredde er {rw} × {rh} pixels: deres proportioner er forskellige +@msg `threshold` must be a number from 0 to 1 `threshold` skal være et tal fra 0 til 1 +@msg background {v}: a color such as "#808080" baggrund {v}: en farve som "#808080" +@msg comparing with an image file isn't available in the browser sammenligning med en billedfil er ikke tilgængelig i browseren +@msg columns {first} and {column} both name the variable `{name}` kolonnerne {first} og {column} angiver begge variablen `{name}` +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for intet i datasættet {name} blev anvendt: intet objekt er bundet til en variabel, som det har en værdi for +@msg no bound object reports a value (locked objects and embedded images report none) intet bundet objekt rapporterer en værdi (låste objekter og integrerede billeder rapporterer ingen) +@msg Edit Original opens image and document files only; “{name}” is not one Redigér original åbner kun billed- og dokumentfiler; »{name}« er ikke en sådan +@msg only http, https and mailto URLs open in the browser, not “{url}” kun http-, https- og mailto-URL’er åbnes i browseren, ikke »{url}« +@msg {id} opens another app: only the person at the keyboard can run it {id} åbner et andet program: kun personen ved tastaturet kan køre den +@msg “{name}” is not a file »{name}« er ikke en fil +@msg a mask has more than one art block en maske har mere end én grafikblok +@msg mask art ends outside a mask dictionary maskegrafik slutter uden for en maskeordbog +@msg cancelled; nothing was changed annulleret; intet blev ændret +@msg a linked image can't become a gradient mesh: embed it first et sammenkædet billede kan ikke blive et gradientnet: integrér det først +@msg the image has no usable size or position billedet har ingen brugbar størrelse eller position +@msg the image's pixels can't be read billedets pixels kan ikke læses +@msg Persistent libraries not found: {files} Vedvarende biblioteker blev ikke fundet: {files} +@msg `{given}` isn't a library panel (see window.swatchLibrary) `{given}` er ikke et bibliotekspanel (se window.swatchLibrary) +@msg library panel `{given}` isn't open bibliotekspanelet `{given}` er ikke åbent +@msg too many changed shortcuts for mange ændrede genveje +@msg library panel `{given}` isn't missing its library bibliotekspanelet `{given}` mangler ikke sit bibliotek +@msg too many library panels were opened in this session der blev åbnet for mange bibliotekspaneler i denne session +@msg The image is {_1} × {_2} pixels, more than {LARGE_TRACE_SIDE} on a side: it is traced, but more slowly. A lower-fidelity preset or a smaller copy of the image traces faster. Billedet er {_1} × {_2} pixels, mere end {LARGE_TRACE_SIDE} på en side: det spores, men langsommere. En forudindstilling med lavere præcision eller en mindre kopi af billedet spores hurtigere. +@msg The image was traced at {_1} × {_2} pixels, scaled down from {_3} × {_4} ({_5} megapixels at most). Billedet blev sporet ved {_1} × {_2} pixels, skaleret ned fra {_3} × {_4} (højst {_5} megapixel). +@msg byColor must be true or false byColor skal være true eller false +@msg byColor can't split Auto Grouping groups: trace without Auto Grouping byColor kan ikke opdele grupper fra Autogruppering: spor uden Autogruppering +@msg byColor can't regroup a trace with a live Pathfinder effect: expand without byColor byColor kan ikke omgruppere en sporing med en live Pathfinder-effekt: udvid uden byColor +@msg Flat Logo mode does not use keepColors: it traces the colors named in logoColors, or the colors it finds. Tilstanden Fladt logo bruger ikke keepColors: den sporer de farver, logoColors angiver, eller de farver, den finder. +@msg Nothing was traced: none of the colors the trace found matches keepColors ({_1}). Intet blev sporet: ingen af de farver, sporingen fandt, matcher keepColors ({_1}). +@msg Nothing was traced: Ignore Color leaves out every area of the colors keepColors lists. Intet blev sporet: Ignorér farve udelader alle områder med de farver, keepColors angiver. +@msg Nothing was traced: the colors that match keepColors produce no paths. Intet blev sporet: de farver, der matcher keepColors, danner ingen kurver. +@msg keepColors: none of the colors the trace found matches {c}, so nothing of it is traced. keepColors: ingen af de farver, sporingen fandt, matcher {c}, så intet af den spores. +@msg `colorGroup` needs `library: "document"` `colorGroup` kræver `library: "document"` +@msg `colorGroup` needs `palette: "documentLibrary"` `colorGroup` kræver `palette: "documentLibrary"` +@msg `colorGroup` needs `mode: "color"` `colorGroup` kræver `mode: "color"` +@msg no color group `{name}` in the document (see swatch.list) ingen farvegruppe `{name}` i dokumentet (se swatch.list) +@msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. Fladt logo sporede billedet ved {_1} × {_2} pixels, udjævnet ned fra {_3} × {_4}. +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} beholder 1 af dokumentets {n} tegneflader: filen genåbnes med én. Slå Bevar redigeringsfunktioner til for at beholde dem alle. +@msg `spread` must be pad, repeat or reflect `spread` skal være pad, repeat eller reflect +@msg `repeats` must be a whole number from 1 to {MAX_REPEATS} `repeats` skal være et heltal fra 1 til {MAX_REPEATS} +@msg `spread` applies to linear, radial, conic and diamond gradients `spread` gælder for lineære, radiale, koniske og diamantformede gradienter +@msg {_1} finished, but the document or the plug-in changed meanwhile: run it again {_1} blev færdig, men dokumentet eller plug-in'et ændrede sig i mellemtiden: kør det igen +@msg Running “{name}”… Kører »{name}«… +@msg a live effect runs while the document is drawn, so it can't be `heavy` en live-effekt kører, mens dokumentet tegnes, så den kan ikke være `heavy` +@msg an exporter always gets an export's budget: leave `budget` out en eksportør får altid et eksportbudget: udelad `budget` +@msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants »{_1}« beder om et tungt budget (hver kørsel op til {minutes} minutter og {times} gange de sædvanlige instruktioner): en person skal godkende det i skrivebordsappen, eller send `allowHeavy: true` i en session startet med --allow-plugin-grants +@msg `name` must be 1-64 printable characters `name` skal være 1-64 tegn, der kan udskrives +@msg `version`, `description` or `author` is too long `version`, `description` eller `author` er for lang +@msg `warnings` must be a list of strings `warnings` skal være en liste med strenge +@msg `{k}` must be one of {_1} `{k}` skal være en af {_1} +@msg `{k}` must be {what} `{k}` skal være {what} +@msg an exporter declares 1 to {MAX_EXTENSIONS} `extensions` en eksportør angiver 1 til {MAX_EXTENSIONS} `extensions` +@msg at most {MAX_UNGROUPED} parameters outside groups: give the others a `group` højst {MAX_UNGROUPED} parametre uden for grupper: giv de andre en `group` +@msg can't encode the input kan ikke kode inputtet +@msg expected {{"dataBase64": "…"}} forventet: {{"dataBase64": "…"}} +@msg expected {{"objects": [...]}} forventet: {{"objects": [...]}} +@msg export `{name}`: {e} eksport `{name}`: {e} +@msg extension {e} is listed twice filtypenavnet {e} er angivet to gange +@msg extension {e}: use 1-16 lower-case letters and digits, without the dot filtypenavn {e}: brug 1-16 små bogstaver og cifre uden punktum +@msg invalid id {_1}: use 1-64 characters from A-Z a-z 0-9 . _ - ugyldigt id {_1}: brug 1-64 tegn fra A-Z a-z 0-9 . _ - +@msg invalid parameter name {k} ugyldigt parameternavn {k} +@msg manifest is not UTF-8 manifestet er ikke UTF-8 +@msg manifest is too long (limit {MAX_MANIFEST_BYTES} bytes) manifestet er for langt (grænse {MAX_MANIFEST_BYTES} byte) +@msg manifest is {_1} bytes (limit {MAX_MANIFEST_BYTES}) manifestet fylder {_1} byte (grænse {MAX_MANIFEST_BYTES}) +@msg module is {_1} bytes (limit {_2}) modulet fylder {_1} byte (grænse {_2}) +@msg needs approval: it asks for {0}, which the user grants when installing it on its own kræver godkendelse: det beder om {0}, som brugeren tildeler, når det installeres for sig selv +@msg not JSON: {e} ikke JSON: {e} +@msg not a WebAssembly binary (missing \0asm header) ikke en WebAssembly-binærfil (headeren \0asm mangler) +@msg parameter `{k}`: {what} parameteren `{k}`: {what} +@msg parameter `{name}`: {what} parameteren `{name}`: {what} +@msg plug-in parameters must be a JSON object plug-in-parametrene skal være et JSON-objekt +@msg the module must export its linear memory as `memory` modulet skal eksportere sin lineære hukommelse som `memory` +@msg the objects to change are no longer in the document de objekter, der skal ændres, er ikke længere i dokumentet +@msg the runtime panicked runtime-miljøet gik i panik +@msg unexpected host trap uventet trap i værten +@msg vc_abi_version returned {v}; this host implements version {ABI_VERSION} vc_abi_version returnerede {v}; denne vært implementerer version {ABI_VERSION} +@msg vc_alloc returned 0 (out of memory) vc_alloc returnerede 0 (ikke mere hukommelse) +@msg vc_alloc returned a block outside memory vc_alloc returnerede en blok uden for hukommelsen +@msg vc_run returned error code {packed} vc_run returnerede fejlkoden {packed} +@msg {_1} is not a file {_1} er ikke en fil +@msg {_1} is {_2} bytes (limit {_3}) {_1} fylder {_2} byte (grænse {_3}) +@msg {_1} objects (limit {MAX_OBJECTS}) {_1} objekter (grænse {MAX_OBJECTS}) +@msg {at}: {msg} {at}: {msg} +@msg {what} points outside memory {what} peger uden for hukommelsen +@msg `angle` must be a number `angle` skal være et tal +@msg `aspect` must be from 0.01 to 100 `aspect` skal være fra 0,01 til 100 +@msg `cap` must be "butt", "round" or "square" `cap` skal være "butt", "round" eller "square" +@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` skal være "nonzero" eller "evenodd" +@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` skal være en https://-adresse på højst {MAX_HELP_URL} byte +@msg `help` must be 1-{MAX_HELP} printable characters `help` skal være 1-{MAX_HELP} tegn, der kan udskrives +@msg `id` must be an effect id of 1-{MAX_EFFECT_ID} bytes `id` skal være et effekt-id på 1-{MAX_EFFECT_ID} byte +@msg `id` must be the id of an input object `id` skal være id’et for et inputobjekt +@msg `join` must be "miter", "round" or "bevel" `join` skal være "miter", "round" eller "bevel" +@msg `label` and `group` must be 1-{MAX_LABEL} printable characters `label` og `group` skal være 1-{MAX_LABEL} tegn, der kan udskrives +@msg `maxLength` must be 1-{MAX_TEXT}, and the default no longer `maxLength` skal være 1-{MAX_TEXT}, og standardværdien må ikke være længere +@msg `minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many `minItems` og `maxItems` skal være 0-{MAX_LIST}, `maxItems` mindst 1, og standardværdien skal have så mange +@msg `name` must be a string `name` skal være en streng +@msg `opacity` must be a number `opacity` skal være et tal +@msg `type` must be "path" or "compound" `type` skal være "path" eller "compound" +@msg `unit` must be 1-{MAX_UNIT} printable characters `unit` skal være 1-{MAX_UNIT} tegn, der kan udskrives +@msg `visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}` `visibleWhen` angiver 1 til {MAX_CONDITION_VALUES} værdier for `{other}` +@msg `visibleWhen` names `{other}`, which isn't a parameter declared before this one `visibleWhen` angiver `{other}`, som ikke er en parameter, der er erklæret før denne +@msg `visibleWhen` names at most {MAX_CONDITIONS} parameters `visibleWhen` angiver højst {MAX_CONDITIONS} parametre +@msg `visibleWhen` takes `{other}`'s values, of a checkbox or a choice `visibleWhen` tager værdierne for `{other}`, fra et afkrydsningsfelt eller et valg +@msg `visible` must be true or false `visible` skal være true eller false +@msg `{key}` must be a number from {_1} to {_2} `{key}` skal være et tal fra {_1} til {_2} +@msg `{key}` must be an array of at most {MAX_ITEMS} entries `{key}` skal være et array med højst {MAX_ITEMS} elementer +@msg a color default must be a color object or a hex string such as "#3a7bd5" en standardfarve skal være et farveobjekt eller en hex-streng som "#3a7bd5" +@msg a color object or a hex string such as "#3a7bd5" et farveobjekt eller en hex-streng som "#3a7bd5" +@msg a freeform gradient holds at most {MAX_ITEMS} points and lines en friformsgradient indeholder højst {MAX_ITEMS} punkter og linjer +@msg a freeform gradient line names a point it doesn't have en linje i en friformsgradient angiver et punkt, som gradienten ikke har +@msg a gradient needs 1-{MAX_ITEMS} stops en gradient kræver 1-{MAX_ITEMS} farvestop +@msg a list of numbers en liste med tal +@msg a list of {min_items} to {max_items} numbers en liste med {min_items} til {max_items} tal +@msg a new object needs a `path` et nyt objekt kræver en `path` +@msg a number et tal +@msg a painted live effect returns only `objects` en malet live-effekt returnerer kun `objects` +@msg a painted live effect's piece has only `path`, `fillRule`, `fills` and `strokes` et stykke fra en malet live-effekt har kun `path`, `fillRule`, `fills` og `strokes` +@msg a read-only object was left out et skrivebeskyttet objekt blev udeladt +@msg a read-only object was left out: return it, as {{"id": …}} alone or as it was given et skrivebeskyttet objekt blev udeladt: returnér det, som {{"id": …}} alene eller som det blev givet +@msg a string en streng +@msg a stroke has only `paint`, `width`, `join`, `cap` and `miterLimit` en streg har kun `paint`, `width`, `join`, `cap` og `miterLimit` +@msg a stroke must be {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} en streg skal være {{"paint", "width"?, "join"?, "cap"?, "miterLimit"?}} +@msg an effect must be {{"id", "params"?, "visible"?}} en effekt skal være {{"id", "params"?, "visible"?}} +@msg an effect on a fill returns only `fills` en effekt på en udfyldning returnerer kun `fills` +@msg an effect on a stroke returns only `strokes` en effekt på en streg returnerer kun `strokes` +@msg an object must be a JSON object et objekt skal være et JSON-objekt +@msg bad range ugyldigt interval +@msg choices must be 1-64 non-empty, printable strings valgmulighederne skal være 1-64 ikke-tomme strenge, der kan udskrives +@msg coordinate out of range (limit ±{MAX_COORD} pt) koordinat uden for området (grænse ±{MAX_COORD} pt) +@msg default is not one of the options standardværdien er ikke en af valgmulighederne +@msg each piece needs a `path` hvert stykke kræver en `path` +@msg is listed twice er angivet to gange +@msg pattern transform out of range mønstertransformation uden for området +@msg read-only field '{field}' changed det skrivebeskyttede felt '{field}' blev ændret +@msg stops must be in order of `offset` farvestoppene skal stå i rækkefølge efter `offset` +@msg the document has no pattern {pattern} dokumentet har intet mønster {pattern} +@msg the document has no swatch {n} dokumentet har ingen farveprøve {n} +@msg the output outputtet +@msg the path has no anchor points kurven har ingen ankerpunkter +@msg too many anchor points (limit {MAX_ANCHORS}) for mange ankerpunkter (grænse {MAX_ANCHORS}) +@msg true or false true eller false +@msg a number >= {_1} et tal >= {_1} +@msg a number > {_1} et tal > {_1} +@msg a number <= {_1} et tal <= {_1} +@msg a number < {_1} et tal < {_1} +@msg a number {_1} to {_2} et tal fra {_1} til {_2} +@msg a number >= {_1} and < {_2} et tal >= {_1} og < {_2} +@msg a number > {_1} and <= {_2} et tal > {_1} og <= {_2} +@msg a number > {_1} and < {_2} et tal > {_1} og < {_2} +@msg a number ({_1}) et tal ({_1}) +@msg a number >= {_1} ({_2}) et tal >= {_1} ({_2}) +@msg a number > {_1} ({_2}) et tal > {_1} ({_2}) +@msg a number <= {_1} ({_2}) et tal <= {_1} ({_2}) +@msg a number < {_1} ({_2}) et tal < {_1} ({_2}) +@msg a number {_1} to {_2} ({_3}) et tal fra {_1} til {_2} ({_3}) +@msg a number >= {_1} and < {_2} ({_3}) et tal >= {_1} og < {_2} ({_3}) +@msg a number > {_1} and <= {_2} ({_3}) et tal > {_1} og <= {_2} ({_3}) +@msg a number > {_1} and < {_2} ({_3}) et tal > {_1} og < {_2} ({_3}) +@msg an integer et heltal +@msg an integer >= {_1} et heltal >= {_1} +@msg an integer <= {_1} et heltal <= {_1} +@msg an integer {_1} to {_2} et heltal fra {_1} til {_2} +@msg one of {_1} en af {_1} +@msg an object id (a non-negative integer) et objekt-id (et ikke-negativt heltal) +@msg a list of object ids en liste med objekt-id’er +@msg a color (a string, [r, g, b] or an object) en farve (en streng, [r, g, b] eller et objekt) +@msg [x, y] (two numbers) [x, y] (to tal) +@msg an object et objekt +@msg a list en liste +@msg unknown key `{k}`; the keys here are {_1} ukendt nøgle `{k}`; nøglerne her er {_1} +@msg {_1} is listed twice {_1} er angivet to gange +@msg {_1} is not the id of an input object {_1} er ikke id’et for et inputobjekt +@msg {_1} is read-only {_1} er skrivebeskyttet +@msg {what} must be from {lo} to {hi} {what} skal være fra {lo} til {hi} +@msg a color component en farvekomponent +@msg a plate en plade +@msg Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself. Automatiseringen bad om at installere dette plug-in. Vælg selv Objekt › Plug-ins › Installér plug-in… for at installere det. +@msg “{name}” is another module than the plug-in with id {_1} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees »{name}« er et andet modul end plug-in'et med id {_1} og ville få de indstillinger og den cache, der er gemt til det: installér det med `replace: true`, når brugeren accepterer +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call »{name}« angiver `{id}` i `commandAllowlist`, som et plug-in ikke må kalde +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: manifestets `commandAllowlist` angiver den ikke +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: id’et eller argumenterne ligger uden for modulets hukommelse +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: id’et eller argumenterne er ikke UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumenterne er ikke et JSON-objekt +@msg only a filter with the usual budget declares `commandAllowlist` kun et filter med det sædvanlige budget angiver `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) kommandokald ({MAX_CALLS} kald og {MAX_CALL_BYTES} byte pr. kørsel) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) kommandokaldets størrelse (vc_call `{shown}`: {len} byte, grænse {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` højst {MAX_ALLOWED_COMMANDS} kommandoer i `commandAllowlist` +@msg a plug-in may not call this command et plug-in må ikke kalde denne kommando +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` kræver tilladelsen `commands`, og `commands` kræver en `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` angiver `{shown}`, som ikke er et kommando-id eller er angivet to gange +@msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} tilladelsen `{permission}` kræver plug-in-API-niveau {PROGRESS_API}: angiv `api` {PROGRESS_API} +@msg the module imports `env.{name}` with another type than the host's: it is {signature} modulet importerer `env.{name}` med en anden type end værtens: den er {signature} +@msg the module imports `env.{name}`, which a plug-in may use only at plug-in API level {PROGRESS_API} (`api` {PROGRESS_API}) and with the permission `{permission}` modulet importerer `env.{name}`, som et plug-in kun må bruge på plug-in-API-niveau {PROGRESS_API} (`api` {PROGRESS_API}) og med tilladelsen `{permission}` +@msg the module imports `{from}.{name}`, which the host doesn't offer: a plug-in may import only the `env.vc_*` functions that docs/plugins.md lists (plug-in API level 2), and no WASI, files or network modulet importerer `{from}.{name}`, som værten ikke tilbyder: et plug-in må kun importere de `env.vc_*`-funktioner, som docs/plugins.md angiver (plug-in-API-niveau 2), og ingen WASI, filer eller netværk +@msg `api` is {_1}; this host implements plug-in API levels 1 to {API_LEVEL} `api` er {_1}; denne vært implementerer plug-in-API-niveau 1 til {API_LEVEL} +@msg `paintOutput` may only be true `paintOutput` må kun være true +@msg `paintOutput` is only for a live effect (`kind` "effect") at `api` 2 `paintOutput` er kun til en live-effekt (`kind` "effect") ved `api` 2 +@msg `grant` must be a list of permission names `grant` skal være en liste med tilladelsesnavne +@msg `grant` names an unknown permission `{shown}` `grant` angiver en ukendt tilladelse `{shown}` +@msg a plug-in of kind `{_1}` needs the permission `{_2}` et plug-in af typen `{_1}` kræver tilladelsen `{_2}` +@msg at most {MAX_PERMISSIONS} `permissions` højst {MAX_PERMISSIONS} `permissions` +@msg permission `{shown}` doesn't apply to a plug-in of kind `{_1}` tilladelsen `{shown}` gælder ikke for et plug-in af typen `{_1}` +@msg permission `{shown}` is listed twice tilladelsen `{shown}` er angivet to gange +@msg only a filter declares `inputs` kun et filter angiver `inputs` +@msg `inputs` names an unknown object kind `{shown}`: use type, image or symbolInstance `inputs` angiver en ukendt objekttype `{shown}`: brug type, image eller symbolInstance +@msg `inputs` lists `{shown}` twice `inputs` angiver `{shown}` to gange +@msg `inputs` needs `api` 2 or later `inputs` kræver `api` 2 eller nyere +@msg `inputs` needs the permission `doc.read` `inputs` kræver tilladelsen `doc.read` +@msg memory budget (object {_1} needs {size} bytes of input, {left} left) hukommelsesbudget (objekt {_1} kræver {size} byte input, {left} tilbage) +@msg object budget (more than {MAX_OBJECTS} read-only objects) objektbudget (mere end {MAX_OBJECTS} skrivebeskyttede objekter) +@msg instruction budget instruktionsbudget +@msg time budget tidsbudget +@msg memory budget (the selection is too large to hand over) hukommelsesbudget (markeringen er for stor til at blive overdraget) +@msg output size ({what} is {len} bytes, limit {max}) outputstørrelse ({what} fylder {len} byte, grænse {max}) +@msg the plug-in's grant can't be removed from the plug-in store plug-in'ets tilladelse kan ikke fjernes fra plug-in-lageret +@msg permission `{shown}` is reserved for a later plug-in API; this host doesn't grant it tilladelsen `{shown}` er reserveret til et senere plug-in-API; denne vært tildeler den ikke +@msg unknown permission `{shown}` ukendt tilladelse `{shown}` +@msg “{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants »{name}« beder om tilladelserne {asked}: en person skal godkende dem i skrivebordsappen, eller send `grant` i en session startet med --allow-plugin-grants +@msg `grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app `grant` og `allowHeavy` virker kun i en session startet med --allow-plugin-grants: godkend plug-in'et i skrivebordsappen +@msg Only the person at the keyboard can approve installing a plug-in Kun personen ved tastaturet kan godkende installation af et plug-in +@msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed »{name}« fik ikke tildelt `{p}`, som dets output kræver: intet blev ændret +@msg a heavy filter runs in the background, so it can't declare `commands` et tungt filter kører i baggrunden, så det kan ikke angive `commands` +@msg at most {MAX_COMMANDS} `commands` højst {MAX_COMMANDS} `commands` +@msg command {name} is declared twice kommandoen {name} er erklæret to gange +@msg command {name}: `label` must be 1-64 printable characters kommandoen {name}: `label` skal være 1-64 tegn, der kan udskrives +@msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommandoen {name}: brug et id på 1-{MAX_COMMAND_ID} tegn fra a-z 0-9 _, der starter med et bogstav +@msg command {name}: {e} kommandoen {name}: {e} +@msg manifest: {e} manifest: {e} +@msg manifest: {e} at line {line} column {column} manifest: {e} på linje {line} kolonne {column} +@msg `commands` must be a list of commands, each with an `id` and a `label` `commands` skal være en liste med kommandoer, hver med et `id` og et `label` +@msg command {name} must be an object with an `id` and a `label` kommandoen {name} skal være et objekt med et `id` og et `label` +@msg missing field `{key}` feltet `{key}` mangler +@msg duplicate field `{key}` dobbelt felt `{key}` +@msg only a filter or a live effect declares `commands` kun et filter eller en live-effekt angiver `commands` +@msg “{name}” › {label}: {e} »{name}« › {label}: {e} +@msg the module doesn't have the SHA-256 `hash` gives: nothing was installed modulet har ikke den SHA-256, som `hash` angiver: intet blev installeret +@msg select one object markér ét objekt +@msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again ingen lignende objekter fundet (roterede eller spejlede kopier matches ikke); ændr Indstillinger for global redigering, og prøv igen +@msg Global Edit is off Global redigering er slået fra +@msg only an object of the Global Edit other than the one it started from can be left out kun et objekt i den globale redigering, bortset fra det, den startede fra, kan udelades +@msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all eller et interval som 1, 3-5, ikke {v} +@msg `{_1}` has no symbols to place `{_1}` har ingen symboler at placere +@msg missing `library` (see symbol.libraries) `library` mangler (se symbol.libraries) +@msg no symbol `{n}` intet symbol `{n}` +@msg no symbol `{n}` in `{_1}` intet symbol `{n}` i `{_1}` +@msg no symbol library `{key}` (see symbol.libraries) intet symbolbibliotek `{key}` (se symbol.libraries) +@msg the document has no symbols to save dokumentet har ingen symboler at gemme +@msg `{_1}` has no brushes to apply `{_1}` har ingen pensler at anvende +@msg missing `library` (see brush.libraries) `library` mangler (se brush.libraries) +@msg no brush `{n}` ingen pensel `{n}` +@msg no brush `{n}` in `{_1}` ingen pensel `{n}` i `{_1}` +@msg no brush library `{key}` (see brush.libraries) intet penselbibliotek `{key}` (se brush.libraries) +@msg the document has no brushes to save dokumentet har ingen pensler at gemme +@msg a {width}×{height} screenshot's byte count overflows bytetallet for et skærmbillede på {width}×{height} løber over +@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot vinduets {what} ({points} punkter × {scale} DPI) kan ikke give et skærmbillede en størrelse +@msg {label} must be a number {label} skal være et tal +@msg {label} must be a number of at least 0.1 {label} skal være et tal på mindst 0,1 +@msg {label} must be a number from {min} to {max} {label} skal være et tal fra {min} til {max} +@msg {label} must be a whole number from {min} to {max} {label} skal være et heltal fra {min} til {max} +@msg features lists at most {max} tags features angiver højst {max} tags +@msg unknown OpenType feature `{t}` ukendt OpenType-funktion `{t}` +@msg {label} must be a number above 0 and at most {max} {label} skal være et tal over 0 og højst {max} +@msg {label} must be at most {max} characters {label} må højst være {max} tegn +@msg {label} must be one character {label} skal være ét tegn +@msg at most {max} tab stops højst {max} tabulatorstop +@msg unknown align `{other}` ukendt justering `{other}` +@msg no character style `{name}` ingen tegnstil `{name}` +@msg {_1} is an importer (File › Open With) {_1} er en importør (Filer › Åbn med) +@msg missing `importer` (see document.formats) `importer` mangler (se document.formats) +@msg `importer` must be a plug-in format id (see document.formats) `importer` skal være id’et for et plug-in-format (se document.formats) +@msg “{shown}” opens {_1} files, not `{_2}` »{shown}« åbner {_1}-filer, ikke `{_2}` +@msg `{_1}` is a plug-in of kind `{_2}`, not an importer `{_1}` er et plug-in af typen `{_2}`, ikke en importør +@msg `{_1}` is a plug-in of kind `{_2}`, not an exporter `{_1}` er et plug-in af typen `{_2}`, ikke en eksportør +@msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` er en importør: åbn en fil med document.open {{"importer": "{_2}"}} +@msg `{_1}` is an exporter: export with document.export {{"format": "{_2}"}} `{_1}` er en eksportør: eksportér med document.export {{"format": "{_2}"}} +@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` er en live-effekt: anvend den med effect.apply {{"effect": "{_2}"}} +@msg the importer returned no objects importøren returnerede ingen objekter +@msg an importer returns `objects` and `warnings`, not `{key}` en importør returnerer `objects` og `warnings`, ikke `{key}` +@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads filen er større end de {MAX_INPUT_BYTES} byte, en importør læser +@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` en importør angiver 1 til {MAX_EXTENSIONS} `extensions` +@msg only an exporter or an importer declares `extensions` kun en eksportør eller en importør angiver `extensions` +@msg an importer always gets an import's budget: leave `budget` out en importør får altid et importbudget: udelad `budget` +@msg only paths and compound paths can be aligned to the pixel grid kun kurver og sammensatte kurver kan justeres til pixelgitteret +@msg `first` and `last` must be numbers of lines the console holds, first before last `first` og `last` skal være numre på linjer, som konsollen indeholder, first før last +@msg no plug-in effect is deferred ingen plug-in-effekt er udskudt +@msgplural Opened with {n} plug-in effect deferred. Effect › Refresh Deferred Effects runs it.|Opened with {n} plug-in effects deferred. Effect › Refresh Deferred Effects runs them. Åbnede med {n} udskudt plug-in-effekt. Effekt › Opdatér udskudte effekter kører den.|Åbnede med {n} udskudte plug-in-effekter. Effekt › Opdatér udskudte effekter kører dem. +@msg The selected art has no islands to bridge Den markerede grafik har ingen øer at bygge bro over +@msg No bridge of this width fits across the selected art Ingen bro med denne bredde passer hen over den markerede grafik +@msg Some islands could not be joined to the area around the art Nogle øer kunne ikke forbindes med området omkring grafikken +@msg `width` must be from {lo} to {hi} pt `width` skal være fra {lo} til {hi} pt +@msg `count` must be a whole number from 1 to {MAX_BRIDGES_PER_ISLAND} `count` skal være et heltal fra 1 til {MAX_BRIDGES_PER_ISLAND} + File Filer New… Ny… New Without Dialog Ny uden dialog @@ -389,6 +998,18 @@ Title Case Stort bogstav i hvert ord Sentence case Stort begyndelsesbogstav Smart Punctuation… Smart tegnsætning… + Smart Punctuation Smart tegnsætning + ff, fi, ffi Ligatures Ligaturer ff, fi, ffi + ff, fl, ffl Ligatures Ligaturer ff, fl, ffl + Smart Quotes Smarte anførselstegn + Smart Spaces Smarte mellemrum + En, Em Dashes Korte og lange tankestreger + Ellipses Udeladelsesprikker + Expert Fractions Ekspertbrøker + Replace In Erstat i + Selected Text Only Kun markeret tekst + Entire Document Hele dokumentet + Report Results Rapportér resultater Create Outlines Opret konturer Optical Margin Alignment Optisk marginjustering Dynamic Text Dynamisk tekst @@ -2080,6 +2701,7 @@ digits Malayalam Malayalam @msg paths entry {i} needs path and ids (object ids no other entry has) post {i} i paths skal have path og ids (objekt-id'er, som ingen anden post har) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder tager path: der søges efter de andre manglende links i den fils mappe Show Missing Vis manglende + Sort by Size Sortér efter størrelse Sort by Status Sortér efter status Clear Overrides Ryd tilsidesættelser Create New {kind} Style Opret ny {kind}-typografi @@ -2329,6 +2951,7 @@ digits Malayalam Malayalam Export Asset Eksportér aktiv Export to: Eksportér til: Format Settings Formatindstillinger + Format Settings… Formatindstillinger… Formats: Formater: Full Document Hele dokumentet Include Bleed Medtag beskæring @@ -2418,6 +3041,7 @@ digits Malayalam Malayalam e.g. 1-3, 5 f.eks. 1-3, 5 First Page Første side Import PDF Importér PDF + Import PDF pages as links Importér PDF-sider som links Last Page Sidste side Next Page Næste side of {count} af {count} @@ -4598,6 +5222,7 @@ imageTrace Outline Kontur @msg no action set to save intet handlingssæt at gemme @msg the action set file can't be read in full handlingssætfilen kan ikke læses helt @msgplural Loaded “{name}”: {n} step was left out|Loaded “{name}”: {n} steps were left out Indlæste »{name}«: {n} trin blev udeladt|Indlæste »{name}«: {n} trin blev udeladt +@msgplural Loaded “{name}”: {n} step has an unknown command and was kept: “{action}”, step {step}, `{command}`|Loaded “{name}”: {n} steps have unknown commands and were kept; the first: “{action}”, step {step}, `{command}` Indlæste »{name}«: {n} trin har en ukendt kommando og blev beholdt: »{action}«, trin {step}, `{command}`|Indlæste »{name}«: {n} trin har ukendte kommandoer og blev beholdt; det første: »{action}«, trin {step}, `{command}` @msg not an action set file ikke en handlingssætfil @msg the action set file is larger than 8 MiB handlingssætfilen er større end 8 MiB @msg the action set file holds more than 1,000 actions handlingssætfilen indeholder mere end 1.000 handlinger @@ -6914,3 +7539,6 @@ breakText Glyphs Glyffer Grommets Maljer Grommet Inset Maljernes afstand fra kanten Diameter Diameter + Nest Shapes… Pak figurer tæt… + Nest Shapes Pak figurer tæt + Roll Rulle diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 698d16a546..ddc01a8016 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1332,6 +1332,7 @@ file-filter Templates Vorlagen Format Format Format Options Formatoptionen Format Settings Formateinstellungen + Format Settings… Formateinstellungen… Format: Format: Formats: Formate: Fractional Widths Gebrochene Breiten @@ -1692,6 +1693,7 @@ file-filter Templates Vorlagen Images: Bilder: Import Keyboard Shortcuts… Tastaturbefehle importieren… Import PDF PDF importieren + Import PDF pages as links PDF-Seiten als Verknüpfungen importieren Import PDF Presets PDF-Vorgaben importieren Import Perspective Grid Presets Vorgaben für Perspektivenraster importieren Import Print Presets Druckvorgaben importieren @@ -3414,6 +3416,18 @@ effect Points Punkte Smart Guides (View → Smart Guides) Intelligente Hilfslinien (Ansicht → Intelligente Hilfslinien) Smart Guides (⌘U) Intelligente Hilfslinien (⌘U) Smart Punctuation… Typografische Satzzeichen… + Smart Punctuation Typografische Satzzeichen + ff, fi, ffi Ligatures Ligaturen ff, fi, ffi + ff, fl, ffl Ligatures Ligaturen ff, fl, ffl + Smart Quotes Typografische Anführungszeichen + Smart Spaces Intelligente Leerzeichen + En, Em Dashes Halbgeviert- und Geviertstriche + Ellipses Auslassungspunkte + Expert Fractions Expertenbrüche + Replace In Ersetzen in + Selected Text Only Nur ausgewählter Text + Entire Document Gesamtes Dokument + Report Results Ergebnisse anzeigen Smooth Glatt Corner Ecke Relative Relativ @@ -3444,6 +3458,7 @@ effect Points Punkte Solid Gefüllt Sort by Kind Nach Art sortieren Sort by Name Nach Name sortieren + Sort by Size Nach Größe sortieren Sort by Status Nach Status sortieren Source code on GitHub Quellcode auf GitHub Source Sans 3 Source Sans 3 @@ -8582,6 +8597,7 @@ breakText Glyphs Glyphen @msg the RTF file is too large to place as type (at most {_1} MB) die RTF-Datei ist zu groß, um als Text platziert zu werden (höchstens {_1} MB) @msg the SVG expands to more than {0} nested SVG images das SVG wird zu mehr als {0} verschachtelten SVG-Bildern erweitert @msg the SVG expands to more than {0} objects das SVG wird zu mehr als {0} Objekten erweitert +@msg the SVG's styles expand to more than {0} MB die Stile des SVG werden auf mehr als {0} MB erweitert @msg the SVG has no drawable objects das SVG hat keine zeichenbaren Objekte @msg the SVGZ file unpacks to more than {_1} MB die SVGZ-Datei wird auf mehr als {_1} MB entpackt @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place das Word-Dokument hat mehr als {MAX_PAGES} Seiten an Eigenschaften, zu viele zum Platzieren @@ -9042,3 +9058,6 @@ breakText Glyphs Glyphen Grommets Ösen Grommet Inset Randabstand der Ösen Diameter Durchmesser + Nest Shapes… Formen verschachteln… + Nest Shapes Formen verschachteln + Roll Rolle diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e9d33f4b2f..340a705829 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1265,6 +1265,7 @@ font-technology Variable Μεταβλητές Format Μορφή Format Options Επιλογές μορφής Format Settings Ρυθμίσεις μορφής + Format Settings… Ρυθμίσεις μορφής… Format: Μορφή: Formats: Μορφές: Fractional Widths Κλασματικά πλάτη @@ -1607,6 +1608,7 @@ font-technology Variable Μεταβλητές Images: Εικόνες: Import Keyboard Shortcuts… Εισαγωγή συντομεύσεων πληκτρολογίου… Import PDF Εισαγωγή PDF + Import PDF pages as links Εισαγωγή σελίδων PDF ως συνδέσμων Import PDF Presets Εισαγωγή προεπιλογών PDF Import Perspective Grid Presets Εισαγωγή προεπιλογών πλέγματος προοπτικής Import Print Presets Εισαγωγή προεπιλογών εκτύπωσης @@ -3984,6 +3986,18 @@ digits Malayalam Μαλαγιάλαμ Smart Guides (View → Smart Guides) Έξυπνοι οδηγοί (Προβολή → Έξυπνοι οδηγοί) Smart Guides (⌘U) Έξυπνοι οδηγοί (⌘U) Smart Punctuation… Έξυπνη στίξη… + Smart Punctuation Έξυπνη στίξη + ff, fi, ffi Ligatures Συμπλέγματα ff, fi, ffi + ff, fl, ffl Ligatures Συμπλέγματα ff, fl, ffl + Smart Quotes Έξυπνα εισαγωγικά + Smart Spaces Έξυπνα διαστήματα + En, Em Dashes Παύλες en και em + Ellipses Αποσιωπητικά + Expert Fractions Κλάσματα ειδικών + Replace In Αντικατάσταση σε + Selected Text Only Μόνο επιλεγμένο κείμενο + Entire Document Ολόκληρο το έγγραφο + Report Results Αναφορά αποτελεσμάτων Smooth Color Ομαλό χρώμα Smooth Tool Εξομάλυνση (Smooth Tool) Snap Curves To Lines Προσκόλληση καμπυλών σε γραμμές @@ -4000,6 +4014,7 @@ digits Malayalam Μαλαγιάλαμ Social Square Post 1080×1080 Τετράγωνη δημοσίευση κοινωνικών δικτύων 1080×1080 Sort by Kind Ταξινόμηση κατά είδος Sort by Name Ταξινόμηση κατά όνομα + Sort by Size Ταξινόμηση κατά μέγεθος Sort by Status Ταξινόμηση κατά κατάσταση Source code on GitHub Πηγαίος κώδικας στο GitHub Space After Paragraph Διάστημα μετά την παράγραφο @@ -4805,6 +4820,7 @@ digits Malayalam Μαλαγιάλαμ @msg result would exceed the canvas (coordinates out of range) το αποτέλεσμα θα υπερέβαινε τον καμβά (συντεταγμένες εκτός εύρους) @msg objects can't be nested more than 32 deep τα αντικείμενα δεν μπορούν να έχουν ένθεση μεγαλύτερη των 32 επιπέδων @msg the SVG's elements are nested more than {0} deep τα στοιχεία SVG έχουν ένθεση μεγαλύτερη των {0} επιπέδων +@msg the SVG's styles expand to more than {0} MB τα στυλ του SVG επεκτείνονται σε περισσότερα από {0} MB @msg scale must be a number from {_1} to {_2}, not {_3} το scale πρέπει να είναι αριθμός από {_1} έως {_2}, όχι {_3} @msg scale must be a number from {_1} to {_2}, not {s} το scale πρέπει να είναι αριθμός από {_1} έως {_2}, όχι {s} @msg select (or target) objects whose appearance isn't basic επιλέξτε (ή στοχεύστε) αντικείμενα των οποίων η εμφάνιση δεν είναι βασική @@ -7479,6 +7495,9 @@ breakText Glyphs Γλύφοι Grommets Τρουκς Grommet Inset Απόσταση τρουκς από την άκρη Diameter Διάμετρος + Nest Shapes… Ένθεση σχημάτων… + Nest Shapes Ένθεση σχημάτων + Roll Ρολό # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books, DXF import and PDF export. @msg 3D effects require finite coordinates within 100 million points Τα εφέ 3D απαιτούν πεπερασμένες συντεταγμένες εντός 100 εκατομμυρίων τυπογραφικών στιγμών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6bdd83737b..8c77601902 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1341,6 +1341,7 @@ font-technology Variable Variables Format Formato Format Options Opciones de formato Format Settings Ajustes de formato + Format Settings… Ajustes de formato… Format: Formato: Formats: Formatos: Fractional Widths Anchuras fraccionarias @@ -1688,6 +1689,7 @@ font-technology Variable Variables Images: Imágenes: Import Keyboard Shortcuts… Importar métodos abreviados de teclado… Import PDF Importar PDF + Import PDF pages as links Importar páginas PDF como vínculos Import PDF Presets Importar preajustes de PDF Import Perspective Grid Presets Importar preajustes de cuadrícula de perspectiva Import Print Presets Importar preajustes de impresión @@ -3444,6 +3446,18 @@ digits Malayalam Malayálam Smart Guides (View → Smart Guides) Guías inteligentes (Ver → Guías inteligentes) Smart Guides (⌘U) Guías inteligentes (⌘U) Smart Punctuation… Puntuación inteligente… + Smart Punctuation Puntuación inteligente + ff, fi, ffi Ligatures Ligaduras ff, fi, ffi + ff, fl, ffl Ligatures Ligaduras ff, fl, ffl + Smart Quotes Comillas inteligentes + Smart Spaces Espacios inteligentes + En, Em Dashes Semirrayas y rayas + Ellipses Puntos suspensivos + Expert Fractions Fracciones expertas + Replace In Reemplazar en + Selected Text Only Solo el texto seleccionado + Entire Document Todo el documento + Report Results Informar de los resultados Smooth Suavizar Corner Vértice Relative Relativo @@ -3474,6 +3488,7 @@ digits Malayalam Malayálam Solid Sólido Sort by Kind Ordenar por tipo Sort by Name Ordenar por nombre + Sort by Size Ordenar por tamaño Sort by Status Ordenar por estado Source code on GitHub Código fuente en GitHub Source Sans 3 Source Sans 3 @@ -4849,6 +4864,7 @@ axis Both Ambos @msg result would exceed the canvas (coordinates out of range) el resultado excedería el lienzo (coordenadas fuera de rango) @msg objects can't be nested more than 32 deep los objetos no pueden anidarse a más de 32 niveles @msg the SVG's elements are nested more than {0} deep los elementos del SVG están anidados a más de {0} niveles +@msg the SVG's styles expand to more than {0} MB los estilos del SVG se expanden a más de {0} MB @msg scale must be a number from {_1} to {_2}, not {_3} scale debe ser un número de {_1} a {_2}, no {_3} @msg scale must be a number from {_1} to {_2}, not {s} scale debe ser un número de {_1} a {_2}, no {s} @msg select (or target) objects whose appearance isn't basic selecciona (o apunta a) objetos cuya apariencia no sea básica @@ -7586,3 +7602,6 @@ breakText Glyphs Glifos Grommets Ojales Grommet Inset Distancia de los ojales al borde Diameter Diámetro + Nest Shapes… Anidar formas… + Nest Shapes Anidar formas + Roll Rollo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 7e79a26998..5bcdf356e6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -425,6 +425,18 @@ Title Case Otsikon kirjainkoko Sentence case Virkkeen kirjainkoko Smart Punctuation… Älykäs välimerkitys… + Smart Punctuation Älykäs välimerkitys + ff, fi, ffi Ligatures Ligatuurit ff, fi, ffi + ff, fl, ffl Ligatures Ligatuurit ff, fl, ffl + Smart Quotes Älykkäät lainausmerkit + Smart Spaces Älykkäät välilyönnit + En, Em Dashes Lyhyet ja pitkät ajatusviivat + Ellipses Kolme pistettä + Expert Fractions Erikoismurtoluvut + Replace In Korvaa kohteessa + Selected Text Only Vain valittu teksti + Entire Document Koko asiakirja + Report Results Näytä tulokset Create Outlines Muunna ääriviivoiksi Optical Margin Alignment Optinen reunustasaus Dynamic Text Dynaaminen teksti @@ -2241,6 +2253,7 @@ digits Malayalam Malajalam @msg paths entry {i} needs path and ids (object ids no other entry has) paths-merkintä {i} tarvitsee path- ja ids-arvot (objektitunnukset, joita millään muulla merkinnällä ei ole) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder ottaa path-arvon: muita puuttuvia linkkejä haetaan tämän tiedoston kansiosta Show Missing Näytä puuttuvat + Sort by Size Lajittele koon mukaan Sort by Status Lajittele tilan mukaan Clear Overrides Tyhjennä ohitukset Create New {kind} Style Luo uusi tyyli: {kind} @@ -2491,6 +2504,7 @@ digits Malayalam Malajalam Export Asset Vie resurssi Export to: Vie kohteeseen: Format Settings Muotoasetukset + Format Settings… Muotoasetukset… Formats: Muodot: Full Document Koko asiakirja Include Bleed Sisällytä leikkuuvara @@ -2580,6 +2594,7 @@ digits Malayalam Malajalam e.g. 1-3, 5 esim. 1-3, 5 First Page Ensimmäinen sivu Import PDF Tuo PDF + Import PDF pages as links Tuo PDF-sivut linkkeinä Last Page Viimeinen sivu Next Page Seuraava sivu of {count} / {count} @@ -5064,6 +5079,7 @@ imageTrace Outline Ääriviiva @msg result would exceed the canvas (coordinates out of range) tulos ylittäisi kankaan (koordinaatit alueen ulkopuolella) @msg objects can't be nested more than 32 deep objekteja ei voi sisäkkäistää yli 32 tason syvyyteen @msg the SVG's elements are nested more than {0} deep elementit ovat SVG-tiedostossa sisäkkäin yli {0} tason syvyydessä +@msg the SVG's styles expand to more than {0} MB SVG-tiedoston tyylit laajenevat yli {0} megatavuksi @msg scale must be a number from {_1} to {_2}, not {_3} scale-arvon on oltava luku väliltä {_1}–{_2}, ei {_3} @msg scale must be a number from {_1} to {_2}, not {s} scale-arvon on oltava luku väliltä {_1}–{_2}, ei {s} @msg select (or target) objects whose appearance isn't basic valitse (tai kohdista) objektit, joiden ulkoasu ei ole perusulkoasu @@ -7561,6 +7577,9 @@ breakText Glyphs Merkit Grommets Purjerenkaat Grommet Inset Purjerenkaiden etäisyys reunasta Diameter Halkaisija + Nest Shapes… Sijoittele muodot… + Nest Shapes Sijoittele muodot + Roll Rulla # Messages of the effects, 3D, image and PDF export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points 3D-tehosteet vaativat äärelliset koordinaatit 100 miljoonan pisteen rajoissa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index d25cc7069c..90882cf105 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1335,6 +1335,7 @@ font-technology Variable Variables Format Format Format Options Options de format Format Settings Paramètres de format + Format Settings… Paramètres de format… Format: Format : Formats: Formats : Fractional Widths Largeurs fractionnaires @@ -1682,6 +1683,7 @@ font-technology Variable Variables Images: Images : Import Keyboard Shortcuts… Importer des raccourcis clavier… Import PDF Importer un PDF + Import PDF pages as links Importer les pages PDF comme liens Import PDF Presets Importer des paramètres prédéfinis PDF Import Perspective Grid Presets Importer des paramètres prédéfinis de grille de perspective Import Print Presets Importer des paramètres prédéfinis d’impression @@ -3436,6 +3438,18 @@ digits Malayalam Malayalam Smart Guides (View → Smart Guides) Repères commentés (Affichage → Repères commentés) Smart Guides (⌘U) Repères commentés (⌘U) Smart Punctuation… Ponctuation typographique… + Smart Punctuation Ponctuation typographique + ff, fi, ffi Ligatures Ligatures ff, fi, ffi + ff, fl, ffl Ligatures Ligatures ff, fl, ffl + Smart Quotes Guillemets typographiques + Smart Spaces Espaces typographiques + En, Em Dashes Tirets demi-cadratin et cadratin + Ellipses Points de suspension + Expert Fractions Fractions expertes + Replace In Remplacer dans + Selected Text Only Texte sélectionné uniquement + Entire Document Document entier + Report Results Afficher les résultats Smooth Lisser Corner Angle Relative Relatif @@ -3466,6 +3480,7 @@ digits Malayalam Malayalam Solid Plein Sort by Kind Trier par type Sort by Name Trier par nom + Sort by Size Trier par taille Sort by Status Trier par état Source code on GitHub Code source sur GitHub Source Sans 3 Source Sans 3 @@ -8878,6 +8893,7 @@ breakText Glyphs Glyphes @msg the RTF file is too large to place as type (at most {_1} MB) le fichier RTF est trop volumineux pour être importé comme texte (au plus {_1} Mo) @msg the SVG expands to more than {0} nested SVG images le SVG se développe en plus de {0} images SVG imbriquées @msg the SVG expands to more than {0} objects le SVG se développe en plus de {0} objets +@msg the SVG's styles expand to more than {0} MB les styles du SVG se développent en plus de {0} Mo @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes le fichier SVG dépasse {MAX_IMPORT_BYTES} octets @msg the SVG has no drawable objects le SVG n’a aucun objet dessinable @msg the SVGZ file unpacks to more than {_1} MB le fichier SVGZ se décompresse en plus de {_1} Mo @@ -9312,6 +9328,9 @@ breakText Glyphs Glyphes Grommets Œillets Grommet Inset Distance des œillets au bord Diameter Diamètre + Nest Shapes… Imbriquer les formes… + Nest Shapes Imbriquer les formes + Roll Rouleau # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Les effets 3D exigent des coordonnées finies comprises dans 100 millions de points diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index a36ac35c7a..0e9ed1997e 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1457,6 +1457,7 @@ Format Options ફોર્મેટ વિકલ્પો Format Presets ફોર્મેટ પ્રીસેટ્સ Format Settings ફોર્મેટ સેટિંગ્સ + Format Settings… ફોર્મેટ સેટિંગ્સ… Format: ફોર્મેટ: Formats: ફોર્મેટ્સ: Fractional Widths અપૂર્ણાંક પહોળાઈ @@ -1711,6 +1712,7 @@ Import Library લાઇબ્રેરી આયાત કરો Import Matches આયાત મેળ Import PDF PDF આયાત કરો + Import PDF pages as links PDF પેજને લિંક તરીકે આયાત કરો Import PDF Presets PDF આયાત પ્રીસેટ્સ Import Perspective Grid Presets પર્સ્પેક્ટિવ ગ્રિડ પ્રીસેટ્સ આયાત કરો Import Preferences પસંદગીઓ આયાત કરો @@ -3564,6 +3566,18 @@ Smart Pen Panel સ્માર્ટ પેન પેનલ Smart Pen Tool સ્માર્ટ પેન ટૂલ Smart Punctuation… સ્માર્ટ વિરામચિહ્નો… + Smart Punctuation સ્માર્ટ વિરામચિહ્નો + ff, fi, ffi Ligatures ff, fi, ffi લિગેચર + ff, fl, ffl Ligatures ff, fl, ffl લિગેચર + Smart Quotes સ્માર્ટ અવતરણચિહ્નો + Smart Spaces સ્માર્ટ જગ્યાઓ + En, Em Dashes En અને Em ડૅશ + Ellipses એલિપ્સિસ + Expert Fractions નિષ્ણાત અપૂર્ણાંકો + Replace In આમાં બદલો + Selected Text Only માત્ર પસંદ કરેલું લખાણ + Entire Document આખો દસ્તાવેજ + Report Results પરિણામોનો અહેવાલ Smooth સ્મૂધ Smooth Anchors… એન્કર સ્મૂધ કરો… Smooth Tool સ્મૂધ ટૂલ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 53b75479c0..81ae59c690 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1993,6 +1993,7 @@ antiAlias Sharp शार्प Format Options फ़ॉर्मेट ऑप्शन्स Format Presets फ़ॉर्मैट प्रीसेट Format Settings फ़ॉर्मैट सेटिंग + Format Settings… फ़ॉर्मैट सेटिंग… Format: फ़ॉर्मेट: Formats: फ़ॉर्मैट: Fractional Widths आंशिक चौड़ाई @@ -2332,6 +2333,7 @@ antiAlias Sharp शार्प Import Library… आयात लाइब्रेरी… Import Matches आयात मैच Import PDF PDF आयात करें + Import PDF pages as links PDF पृष्ठों को लिंक के रूप में आयात करें Import PDF Presets PDF प्रीसेट्स इम्पोर्ट करें Import Perspective Grid Presets आयात पर्सपेक्टिव ग्रिड प्रीसेट Import Preset… प्रीसेट इम्पोर्ट करें… @@ -4729,6 +4731,18 @@ antiAlias Sharp शार्प Smart Pen Panel स्मार्ट पेन पैनल Smart Pen Tool स्मार्ट पेन टूल Smart Punctuation… स्मार्ट विराम-चिह्न… + Smart Punctuation स्मार्ट विराम-चिह्न + ff, fi, ffi Ligatures ff, fi, ffi लिगेचर + ff, fl, ffl Ligatures ff, fl, ffl लिगेचर + Smart Quotes स्मार्ट उद्धरण-चिह्न + Smart Spaces स्मार्ट स्पेस + En, Em Dashes एन और एम डैश + Ellipses दीर्घविराम + Expert Fractions विशेषज्ञ भिन्न + Replace In इसमें रिप्लेस करें + Selected Text Only केवल सिलेक्ट किया गया टेक्स्ट + Entire Document पूरा डॉक्यूमेंट + Report Results परिणाम रिपोर्ट करें Smooth स्मूथ Smooth Anchors चिकना एंकर Smooth Anchors… चिकना एंकर… @@ -4768,6 +4782,7 @@ antiAlias Sharp शार्प Sort by Luminance द्वारा क्रमबद्ध Luminance Sort by Name नाम से क्रमबद्ध करें Sort by Popularity लोकप्रियता द्वारा क्रमबद्ध + Sort by Size आकार द्वारा क्रमबद्ध Sort by Status स्थिति द्वारा क्रमबद्ध Sort By: द्वारा क्रमबद्ध: Sort Objects ऑब्जेक्ट्स को क्रमबद्ध करें @@ -8283,6 +8298,7 @@ antiAlias Sharp शार्प @msg the subpath is closed or too short to close सबपैथ बंद है या बंद करने के लिए बहुत कम है @msg the SVG expands to more than {0} nested SVG images SVG {0} नेस्टेड SVG इमेज से अधिक का विस्तार करता है @msg the SVG expands to more than {0} objects SVG {0} ऑब्जेक्ट्स से अधिक का विस्तार करता है +@msg the SVG's styles expand to more than {0} MB SVG की शैलियाँ {0} MB से अधिक तक विस्तारित होती हैं @msg the SVG has no drawable objects SVG में कोई आकर्षक ऑब्जेक्ट नहीं है @msg the SVG's elements are nested more than {0} deep SVG के तत्वों को {0} से अधिक गहरा घोंसला दिया जाता है @msg the SVGZ file unpacks to more than {_1} MB SVGZ फ़ाइल ने {_1} MB से अधिक के लिए अनपैक किया @@ -8906,3 +8922,6 @@ theme Appearance अपीयरेंस Grommets आईलेट Grommet Inset किनारे से आईलेट की दूरी Diameter व्यास + Nest Shapes… आकृतियाँ सटाकर रखें… + Nest Shapes आकृतियाँ सटाकर रखें + Roll रोल diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index bea893c5ff..a218a2ce15 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1666,6 +1666,7 @@ file-filter Templates Sablonok Format Formátum Format Options Formátumbeállítások Format Settings Formátumbeállítások + Format Settings… Formátumbeállítások… Format: Formátum: Formats: Formátumok: Fractional Widths Tört szélességek @@ -2106,6 +2107,7 @@ file-filter Templates Sablonok Import Library Könyvtár importálása Import Library… Könyvtár importálása… Import PDF PDF importálása + Import PDF pages as links PDF-oldalak importálása csatolásként Import PDF Presets PDF-előbeállítások importálása Import Perspective Grid Presets Perspektivikus rács előbeállításainak importálása Import Print Presets Nyomtatási előbeállítások importálása @@ -4096,6 +4098,18 @@ mark-style Japanese Japán Smart Guides (View → Smart Guides) Intelligens segédvonalak (Nézet → Intelligens segédvonalak) Smart Guides (⌘U) Intelligens segédvonalak (⌘U) Smart Punctuation… Intelligens írásjelek… + Smart Punctuation Intelligens írásjelek + ff, fi, ffi Ligatures ff, fi, ffi ligatúrák + ff, fl, ffl Ligatures ff, fl, ffl ligatúrák + Smart Quotes Intelligens idézőjelek + Smart Spaces Intelligens szóközök + En, Em Dashes Gondolatjelek és nagykötőjelek + Ellipses Három pont + Expert Fractions Szakértői törtek + Replace In Csere helye + Selected Text Only Csak a kijelölt szöveg + Entire Document Teljes dokumentum + Report Results Eredmények jelentése Smooth Simítás Smooth Color Sima színátmenet Smooth Tool Simítás @@ -4126,6 +4140,7 @@ mark-style Japanese Japán Sort by Luminance Rendezés fénysűrűség szerint Sort by Name Rendezés név szerint Sort by Popularity Rendezés gyakoriság szerint + Sort by Size Rendezés méret szerint Sort by Status Rendezés állapot szerint Source code on GitHub Forráskód a GitHubon Source Image Forráskép @@ -7497,6 +7512,10 @@ breakText Glyphs Glifák Grommets Ringlik Grommet Inset Ringlik távolsága a széltől Diameter Átmérő + Nest Shapes… Alakzatok elrendezése… + Nest Shapes Alakzatok elrendezése + Roll Tekercs + # Status and error messages of commands, scripts, file import and export, and plug-ins. @msg 'caller', 'callee' and 'arguments' cannot be used on strict mode functions a 'caller', a 'callee' és az 'arguments' nem használható szigorú módú függvényeken @msg A profile supports one Revolve effect. Edit the existing effect's options instead. Egy profilon egy Forgatás tengely körül effektus lehet. Inkább a meglévő effektus beállításait szerkeszd. @@ -8883,6 +8902,7 @@ breakText Glyphs Glifák @msg the RTF file is too large to place as type (at most {_1} MB) az RTF-fájl túl nagy ahhoz, hogy szövegként elhelyezhető legyen (legfeljebb {_1} MB) @msg the SVG expands to more than {0} nested SVG images az SVG kibontva több mint {0} beágyazott SVG-képet tartalmaz @msg the SVG expands to more than {0} objects az SVG kibontva több mint {0} objektumot tartalmaz +@msg the SVG's styles expand to more than {0} MB az SVG stílusai kibontva több mint {0} MB-ot foglalnak @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes az SVG-fájl nagyobb, mint {MAX_IMPORT_BYTES} bájt @msg the SVG has no drawable objects az SVG-ben nincsenek kirajzolható objektumok @msg the SVGZ file unpacks to more than {_1} MB az SVGZ-fájl kicsomagolva nagyobb, mint {_1} MB diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 92d97e00d9..fdf06cc9ee 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -389,6 +389,18 @@ Title Case Huruf besar di awal kata Sentence case Huruf besar di awal kalimat Smart Punctuation… Tanda baca cerdas… + Smart Punctuation Tanda baca cerdas + ff, fi, ffi Ligatures Ligatur ff, fi, ffi + ff, fl, ffl Ligatures Ligatur ff, fl, ffl + Smart Quotes Tanda kutip cerdas + Smart Spaces Spasi cerdas + En, Em Dashes Tanda pisah en dan em + Ellipses Elipsis + Expert Fractions Pecahan ahli + Replace In Ganti di + Selected Text Only Hanya teks terpilih + Entire Document Seluruh dokumen + Report Results Laporkan hasil Create Outlines Buat garis luar Optical Margin Alignment Perataan margin optik Dynamic Text Teks dinamis @@ -2080,6 +2092,7 @@ digits Malayalam Malayalam @msg paths entry {i} needs path and ids (object ids no other entry has) entri paths {i} memerlukan path dan ids (id objek yang tidak dimiliki entri lain) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder menerima path: tautan hilang lainnya dicari di folder file tersebut Show Missing Tampilkan yang hilang + Sort by Size Urutkan berdasarkan ukuran Sort by Status Urutkan berdasarkan status Clear Overrides Hapus penimpaan Create New {kind} Style Buat gaya {kind} baru @@ -2329,6 +2342,7 @@ digits Malayalam Malayalam Export Asset Ekspor aset Export to: Ekspor ke: Format Settings Pengaturan format + Format Settings… Pengaturan format… Formats: Format: Full Document Dokumen penuh Include Bleed Sertakan bleed @@ -2418,6 +2432,7 @@ digits Malayalam Malayalam e.g. 1-3, 5 mis. 1-3, 5 First Page Halaman pertama Import PDF Impor PDF + Import PDF pages as links Impor halaman PDF sebagai tautan Last Page Halaman terakhir Next Page Halaman berikutnya of {count} dari {count} @@ -6914,3 +6929,6 @@ breakText Glyphs Glif Grommets Mata ayam Grommet Inset Jarak mata ayam dari tepi Diameter Diameter + Nest Shapes… Susun Bentuk… + Nest Shapes Susun Bentuk + Roll Gulungan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 6fb07b1a01..2b5a6bf3da 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1362,6 +1362,7 @@ file-filter Templates Modelli Format Formato Format Options Opzioni formato Format Settings Impostazioni formato + Format Settings… Impostazioni formato… Format: Formato: Formats: Formati: Fractional Widths Larghezze frazionarie @@ -1723,6 +1724,7 @@ file-filter Templates Modelli Images: Immagini: Import Keyboard Shortcuts… Importa scelte rapide da tastiera… Import PDF Importa PDF + Import PDF pages as links Importa le pagine PDF come collegamenti Import PDF Presets Importa preset PDF Import Perspective Grid Presets Importa preset griglia prospettica Import Print Presets Importa preset di stampa @@ -3489,6 +3491,18 @@ digits Malayalam Malayalam Smart Guides (View → Smart Guides) Guide sensibili (Visualizza → Guide sensibili) Smart Guides (⌘U) Guide sensibili (⌘U) Smart Punctuation… Punteggiatura intelligente… + Smart Punctuation Punteggiatura intelligente + ff, fi, ffi Ligatures Legature ff, fi, ffi + ff, fl, ffl Ligatures Legature ff, fl, ffl + Smart Quotes Virgolette intelligenti + Smart Spaces Spazi intelligenti + En, Em Dashes Trattini medi e lineette + Ellipses Puntini di sospensione + Expert Fractions Frazioni esperte + Replace In Sostituisci in + Selected Text Only Solo testo selezionato + Entire Document Intero documento + Report Results Mostra risultati Smooth Smussa Corner Angolo Relative Relativo @@ -3519,6 +3533,7 @@ digits Malayalam Malayalam Solid Pieno Sort by Kind Ordina per tipo Sort by Name Ordina per nome + Sort by Size Ordina per dimensione Sort by Status Ordina per stato Source code on GitHub Codice sorgente su GitHub Source Sans 3 Source Sans 3 @@ -8630,6 +8645,7 @@ breakText Glyphs Glifi @msg the RTF file is too large to place as type (at most {_1} MB) il file RTF è troppo grande per essere inserito come testo (al massimo {_1} MB) @msg the SVG expands to more than {0} nested SVG images l'SVG si espande in più di {0} immagini SVG annidate @msg the SVG expands to more than {0} objects l'SVG si espande in più di {0} oggetti +@msg the SVG's styles expand to more than {0} MB gli stili dell'SVG si espandono a oltre {0} MB @msg the SVG has no drawable objects l'SVG non ha oggetti disegnabili @msg the SVGZ file unpacks to more than {_1} MB il file SVGZ si decomprime in più di {_1} MB @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place il documento Word ha più di {MAX_PAGES} pagine di proprietà, troppe per essere inserito @@ -9075,3 +9091,6 @@ breakText Glyphs Glifi Grommets Occhielli Grommet Inset Distanza degli occhielli dal bordo Diameter Diametro + Nest Shapes… Annida forme… + Nest Shapes Annida forme + Roll Rotolo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6b59f5a370..87ec6c8b05 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -463,6 +463,18 @@ digits Malayalam マラヤーラム数字 Title Case 単語の先頭のみ大文字 Sentence case 文頭のみ大文字 Smart Punctuation… 欧文用字形の自動置換… + Smart Punctuation 欧文用字形の自動置換 + ff, fi, ffi Ligatures ff、fi、ffi 合字 + ff, fl, ffl Ligatures ff、fl、ffl 合字 + Smart Quotes スマート引用符 + Smart Spaces スマートスペース + En, Em Dashes EN ダッシュと EM ダッシュ + Ellipses 省略記号 + Expert Fractions エキスパート分数 + Replace In 置換範囲 + Selected Text Only 選択したテキストのみ + Entire Document ドキュメント全体 + Report Results 結果を表示 Create Outlines アウトラインを作成 Optical Margin Alignment 最適なマージン揃え Dynamic Text ダイナミックテキスト @@ -1837,6 +1849,7 @@ antiAlias Sharp シャープ Format 形式 Format Options 形式オプション Format Settings 形式の設定 + Format Settings… 形式の設定… Format: 形式: Formats: 形式: Fractions 分数 @@ -2074,6 +2087,7 @@ antiAlias Sharp シャープ Images: イメージ: Import Keyboard Shortcuts… キーボードショートカットを読み込み… Import PDF PDF を読み込み + Import PDF pages as links PDF ページをリンクとして読み込み Import PDF Presets PDF プリセットを読み込み Import Perspective Grid Presets 遠近グリッドプリセットを読み込み Import Print Presets プリントプリセットを読み込み @@ -4026,6 +4040,7 @@ file-filter Templates テンプレート Small Thumbnails 小さいサムネール Smooth Color スムーズカラー Social Square Post 1080×1080 ソーシャル正方形投稿 1080×1080 + Sort by Size サイズ順に並べ替え Sort by Status 状態順に並べ替え Specified Distance 距離 Specified Steps ステップ数 @@ -7838,6 +7853,7 @@ axis Y Axis Y 軸 @msg the RTF file is too large to place as type (at most {_1} MB) RTF ファイルが大きすぎて、文字として配置できません (最大 {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG を展開すると、入れ子の SVG 画像が {0} 個を超えます @msg the SVG expands to more than {0} objects SVG を展開すると、オブジェクトが {0} 個を超えます +@msg the SVG's styles expand to more than {0} MB SVG のスタイルを展開すると {0} MB を超えます @msg the SVG has no drawable objects SVG に描画できるオブジェクトがありません @msg the SVGZ file unpacks to more than {_1} MB SVGZ ファイルを展開すると {_1} MB を超えます @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word 文書のプロパティが {MAX_PAGES} ページを超えており、多すぎて配置できません @@ -9013,6 +9029,9 @@ breakText Glyphs 字形 Grommets ハトメ Grommet Inset 端からハトメまでの距離 Diameter 直径 + Nest Shapes… 図形のネスティング… + Nest Shapes 図形のネスティング + Roll ロール # Messages no catalog translated yet: image export and color profiles, color books and swatch exchange files, 3D and Revolve, and script, zip, line and file errors. @msg 3D effects require finite coordinates within 100 million points 3D 効果には 1 億ポイント以内の有限の座標が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9bd5c4f040..fc6913b8c1 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -354,6 +354,18 @@ Title Case სათაურის რეგისტრი Sentence case წინადადების რეგისტრი Smart Punctuation… ჭკვიანი პუნქტუაცია… + Smart Punctuation ჭკვიანი პუნქტუაცია + ff, fi, ffi Ligatures ლიგატურები ff, fi, ffi + ff, fl, ffl Ligatures ლიგატურები ff, fl, ffl + Smart Quotes ჭკვიანი ბრჭყალები + Smart Spaces ჭკვიანი ჰარები + En, Em Dashes მოკლე და გრძელი ტირეები + Ellipses მრავალწერტილები + Expert Fractions ექსპერტული წილადები + Replace In ჩანაცვლების არე + Selected Text Only მხოლოდ მონიშნული ტექსტი + Entire Document მთელი დოკუმენტი + Report Results შედეგების ანგარიში Create Outlines კონტურებად გარდაქმნა Optical Margin Alignment ოპტიკური არშიის სწორება Dynamic Text დინამიკური ტექსტი @@ -2008,6 +2020,7 @@ digits Malayalam მალაიალამური @msg paths entry {i} needs path and ids (object ids no other entry has) paths-ის ჩანაწერს {i} სჭირდება path და ids (ობიექტის ID-ები, რომლებიც სხვა ჩანაწერს არ აქვს) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder იღებს path-ს: სხვა დაკარგული ბმულები ამ ფაილის საქაღალდეში იძებნება Show Missing დაკარგულების ჩვენება + Sort by Size ზომის მიხედვით სორტირება Sort by Status სტატუსის მიხედვით სორტირება Clear Overrides ცვლილებების გასუფთავება Create New {kind} Style ახალი სტილის შექმნა ({kind}) @@ -2255,6 +2268,7 @@ digits Malayalam მალაიალამური Export Asset რესურსის ექსპორტირება Export to: ექსპორტის ადგილი: Format Settings ფორმატის პარამეტრები + Format Settings… ფორმატის პარამეტრები… Formats: ფორმატები: Full Document მთელი დოკუმენტი Include Bleed ჭრისპირა არის ჩართვა @@ -2342,6 +2356,7 @@ digits Malayalam მალაიალამური e.g. 1-3, 5 მაგ. 1-3, 5 First Page პირველი გვერდი Import PDF PDF-ის იმპორტი + Import PDF pages as links PDF-ის გვერდების იმპორტი ბმულებად Last Page ბოლო გვერდი Next Page შემდეგი გვერდი of {count} / {count} @@ -5681,6 +5696,7 @@ imageTrace Outline კონტური @msg object has no weighted stroke ობიექტს ცვლადი სისქის კონტური არ აქვს @msg objects can't be nested more than 32 deep ობიექტების ჩადგმის სიღრმე 32-ს ვერ გადააჭარბებს @msg the SVG's elements are nested more than {0} deep SVG-ის ელემენტების ჩადგმის სიღრმე {0}-ს აჭარბებს +@msg the SVG's styles expand to more than {0} MB SVG-ის სტილები გაშლისას {0} MB-ს აჭარბებს @msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode უცნობი control `{name}`: fillStroke, coloring, drawMode ან screenMode @plural agrees with {n} default shortcut|agrees with {n} default shortcuts ემთხვევა ნაგულისხმევ მალსახმობებს: {n}|ემთხვევა ნაგულისხმევ მალსახმობებს: {n} @plural {n} part of the file wasn't read|{n} parts of the file weren't read ფაილის წაუკითხავი ნაწილები: {n}|ფაილის წაუკითხავი ნაწილები: {n} @@ -7640,3 +7656,6 @@ font-script Japanese იაპონური Grommets ლუვერები Grommet Inset ლუვერების დაშორება კიდიდან Diameter დიამეტრი + Nest Shapes… ფორმების განლაგება… + Nest Shapes ფორმების განლაგება + Roll რულონი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 04a3234343..4fd8001ea7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -456,6 +456,18 @@ digits Malayalam 말라얄람어 Title Case 제목 대소문자 Sentence case 문장 대소문자 Smart Punctuation… 스마트 문장 부호… + Smart Punctuation 스마트 문장 부호 + ff, fi, ffi Ligatures ff, fi, ffi 합자 + ff, fl, ffl Ligatures ff, fl, ffl 합자 + Smart Quotes 스마트 따옴표 + Smart Spaces 스마트 공백 + En, Em Dashes 엔 대시 및 엠 대시 + Ellipses 줄임표 + Expert Fractions 전문가 분수 + Replace In 바꿀 범위 + Selected Text Only 선택한 텍스트만 + Entire Document 전체 문서 + Report Results 결과 보고 Create Outlines 윤곽선 만들기 Optical Margin Alignment 시각적 여백 정렬 Dynamic Text 동적 텍스트 @@ -1827,6 +1839,7 @@ antiAlias Sharp 날카롭게 Format 형식 Format Options 형식 옵션 Format Settings 형식 설정 + Format Settings… 형식 설정… Format: 형식: Formats: 형식: Fractions 분수 @@ -2064,6 +2077,7 @@ antiAlias Sharp 날카롭게 Images: 이미지: Import Keyboard Shortcuts… 단축키 가져오기… Import PDF PDF 가져오기 + Import PDF pages as links PDF 페이지를 링크로 가져오기 Import PDF Presets PDF 프리셋 가져오기 Import Perspective Grid Presets 원근 격자 프리셋 가져오기 Import Print Presets 인쇄 프리셋 가져오기 @@ -4014,6 +4028,7 @@ file-filter Templates 템플릿 Small Thumbnails 작은 축소판 Smooth Color 부드러운 색상 Social Square Post 1080×1080 소셜 정사각형 게시물 1080×1080 + Sort by Size 크기순 정렬 Sort by Status 상태순 정렬 Specified Distance 지정 거리 Specified Steps 지정 단계 @@ -7104,6 +7119,9 @@ breakText Glyphs 글리프 Grommets 아일렛 Grommet Inset 가장자리에서 아일렛까지 거리 Diameter 지름 + Nest Shapes… 도형 네스팅… + Nest Shapes 도형 네스팅 + Roll 롤 # Messages of the 3D effects, image export, color profiles, swatch exchange files, color books, DXF import, # path operations, libraries, scripts and zip files. @@ -8611,6 +8629,7 @@ breakText Glyphs 글리프 @msg the RTF file is too large to place as type (at most {_1} MB) RTF 파일이 너무 커서 문자로 가져올 수 없습니다(최대 {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG를 확장하면 중첩된 SVG 이미지가 {0}개보다 많아집니다 @msg the SVG expands to more than {0} objects SVG를 확장하면 개체가 {0}개보다 많아집니다 +@msg the SVG's styles expand to more than {0} MB SVG의 스타일을 확장하면 {0}MB를 넘습니다 @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes SVG 파일이 {MAX_IMPORT_BYTES}바이트보다 큽니다 @msg the SVG has no drawable objects SVG에 그릴 수 있는 개체가 없습니다 @msg the SVGZ file unpacks to more than {_1} MB SVGZ 파일의 압축을 풀면 {_1} MB를 넘습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 09459378a0..31872f060e 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -907,6 +907,18 @@ Title Case Koptitel Sentence case Zinsvorm Smart Punctuation… Slimme interpunctie… + Smart Punctuation Slimme interpunctie + ff, fi, ffi Ligatures Ligaturen ff, fi, ffi + ff, fl, ffl Ligatures Ligaturen ff, fl, ffl + Smart Quotes Slimme aanhalingstekens + Smart Spaces Slimme spaties + En, Em Dashes Halve en hele gedachtestreepjes + Ellipses Beletseltekens + Expert Fractions Expertbreuken + Replace In Vervangen in + Selected Text Only Alleen geselecteerde tekst + Entire Document Hele document + Report Results Resultaten rapporteren Create Outlines Omzetten in curven Optical Margin Alignment Optische marge-uitlijning Dynamic Text Dynamische tekst @@ -2598,6 +2610,7 @@ digits Malayalam Malayalam @msg paths entry {i} needs path and ids (object ids no other entry has) item {i} van paths heeft path en ids nodig (object-id's die geen ander item heeft) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder neemt path: in de map van dat bestand wordt naar de andere ontbrekende koppelingen gezocht Show Missing Ontbrekende weergeven + Sort by Size Sorteren op grootte Sort by Status Sorteren op status Clear Overrides Onderdrukkingen wissen Create New {kind} Style Nieuwe {kind}stijl maken @@ -2847,6 +2860,7 @@ digits Malayalam Malayalam Export Asset Asset exporteren Export to: Exporteren naar: Format Settings Indelingsinstellingen + Format Settings… Indelingsinstellingen… Formats: Indelingen: Full Document Volledig document Include Bleed Afrulling opnemen @@ -2936,6 +2950,7 @@ digits Malayalam Malayalam e.g. 1-3, 5 bijv. 1-3, 5 First Page Eerste pagina Import PDF PDF importeren + Import PDF pages as links PDF-pagina's importeren als koppelingen Last Page Laatste pagina Next Page Volgende pagina of {count} van {count} @@ -6960,6 +6975,7 @@ imageTrace Outline Contour @msg the RTF file is too large to place as type (at most {_1} MB) het RTF-bestand is te groot om als tekst te plaatsen (maximaal {_1} MB) @msg the SVG expands to more than {0} nested SVG images de SVG wordt uitgevouwen tot meer dan {0} geneste SVG-afbeeldingen @msg the SVG expands to more than {0} objects de SVG wordt uitgevouwen tot meer dan {0} objecten +@msg the SVG's styles expand to more than {0} MB de stijlen van de SVG worden uitgevouwen tot meer dan {0} MB @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes het SVG-bestand is groter dan {MAX_IMPORT_BYTES} bytes @msg the SVG has no drawable objects de SVG heeft geen tekenbare objecten @msg the SVGZ file unpacks to more than {_1} MB het SVGZ-bestand wordt uitgepakt tot meer dan {_1} MB @@ -9358,6 +9374,9 @@ breakText Glyphs Glyphs Grommets Zeilringen Grommet Inset Afstand van zeilringen tot de rand Diameter Diameter + Nest Shapes… Vormen nesten… + Nest Shapes Vormen nesten + Roll Rol # Status and error messages: 3D effects and Revolve, image export, color profiles, swatch exchange files and # color books, regular expressions in scripts, whole-number parameters, and DXF and DWG files. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 01c8429004..77b1425e5f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -387,6 +387,18 @@ Title Case Jak W Tytule Sentence case Jak w zdaniu Smart Punctuation… Inteligentna interpunkcja… + Smart Punctuation Inteligentna interpunkcja + ff, fi, ffi Ligatures Ligatury ff, fi, ffi + ff, fl, ffl Ligatures Ligatury ff, fl, ffl + Smart Quotes Inteligentne cudzysłowy + Smart Spaces Inteligentne spacje + En, Em Dashes Półpauzy i pauzy + Ellipses Wielokropki + Expert Fractions Ułamki eksperckie + Replace In Zastąp w + Selected Text Only Tylko zaznaczony tekst + Entire Document Cały dokument + Report Results Raportuj wyniki Create Outlines Utwórz kontury Optical Margin Alignment Optyczne wyrównanie marginesów Dynamic Text Tekst dynamiczny @@ -2199,6 +2211,7 @@ digits Malayalam Malajalam @msg paths entry {i} needs path and ids (object ids no other entry has) wpis {i} w paths wymaga path i ids (identyfikatorów obiektów, których nie ma żaden inny wpis) @msg scope missingInFolder takes path: the folder of that file is searched for the other missing links scope missingInFolder przyjmuje path: w folderze tego pliku szukane są pozostałe brakujące łącza Show Missing Pokaż brakujące + Sort by Size Sortuj według rozmiaru Sort by Status Sortuj według stanu Clear Overrides Wyczyść zastąpienia Create New {kind} Style Utwórz nowy styl: {kind} @@ -2451,6 +2464,7 @@ digits Malayalam Malajalam Export Asset Eksportuj zasób Export to: Eksportuj do: Format Settings Ustawienia formatu + Format Settings… Ustawienia formatu… Formats: Formaty: Full Document Cały dokument Include Bleed Uwzględnij spad @@ -2551,6 +2565,7 @@ digits Malayalam Malajalam e.g. 1-3, 5 np. 1-3, 5 First Page Pierwsza strona Import PDF Importuj PDF + Import PDF pages as links Importuj strony PDF jako łącza Last Page Ostatnia strona Next Page Następna strona of {count} z {count} @@ -8868,6 +8883,7 @@ breakText Glyphs Glify @msg the RTF file is too large to place as type (at most {_1} MB) plik RTF jest zbyt duży, aby umieścić go jako tekst (najwyżej {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG rozwija się do ponad {0} zagnieżdżonych obrazów SVG @msg the SVG expands to more than {0} objects SVG rozwija się do ponad {0} obiektów +@msg the SVG's styles expand to more than {0} MB style SVG rozwijają się do ponad {0} MB @msg the SVG has no drawable objects SVG nie zawiera obiektów, które można narysować @msg the SVGZ file unpacks to more than {_1} MB plik SVGZ po rozpakowaniu ma ponad {_1} MB @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place dokument Word ma ponad {MAX_PAGES} stron właściwości, zbyt wiele, aby go umieścić @@ -9180,6 +9196,9 @@ breakText Glyphs Glify @msg {what} can't be intertwined {what} nie można przeplatać @msg {what} doesn't fit the paper with its bleed and marks {what} nie mieści się na papierze wraz ze spadem i znacznikami @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what}: wydruk zająłby ponad {MAX_TILES} kafelków: zmniejsz skalę + Nest Shapes… Rozmieść kształty… + Nest Shapes Rozmieść kształty + Roll Rolka # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Efekty 3D wymagają skończonych współrzędnych w zakresie 100 milionów punktów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 1255008e2b..caed79af2a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1203,6 +1203,7 @@ antiAlias Sharp Nítido Format Formato Format Options Opções de Formato Format Settings Configurações de Formato + Format Settings… Configurações de Formato… Format: Formato: Formats: Formatos: Fractions Frações @@ -1486,6 +1487,7 @@ antiAlias Sharp Nítido Import Keyboard Shortcuts… Importar Atalhos de Teclado… Import Data Sets… Importar Conjuntos de Dados… Import PDF Importar PDF + Import PDF pages as links Importar páginas do PDF como links Import PDF Presets Importar Predefinidos de PDF Import Perspective Grid Presets Importar Predefinidos de Grade de Perspectiva Import Print Presets Importar Predefinidos de Impressão @@ -2912,6 +2914,18 @@ digits Malayalam Malaiala Smart Guides (View → Smart Guides) Guias Inteligentes (Exibir → Guias Inteligentes) Smart Guides (⌘U) Guias Inteligentes (⌘U) Smart Punctuation… Pontuação Inteligente… + Smart Punctuation Pontuação Inteligente + ff, fi, ffi Ligatures Ligações ff, fi, ffi + ff, fl, ffl Ligatures Ligações ff, fl, ffl + Smart Quotes Aspas Inteligentes + Smart Spaces Espaços Inteligentes + En, Em Dashes Travessões En e Em + Ellipses Reticências + Expert Fractions Frações Especiais + Replace In Substituir Em + Selected Text Only Somente Texto Selecionado + Entire Document Documento Inteiro + Report Results Relatar Resultados Smooth Suavizar Smooth Tool Ferramenta Suavizar Snap Curves To Lines Ajustar Curvas às Linhas @@ -5204,6 +5218,7 @@ axis Both Ambos Corner Canto Smooth Color Cor Suave Social Square Post 1080×1080 Post Social Quadrado 1080×1080 + Sort by Size Ordenar por Tamanho Sort by Status Ordenar por Status Source Sans 3 Source Sans 3 Specified Distance Distância Especificada @@ -9080,6 +9095,7 @@ swatch Yellow Green Verde-amarelado @msg the RTF file is too large to place as type (at most {_1} MB) o arquivo RTF é grande demais para ser colocado como texto (no máximo {_1} MB) @msg the SVG expands to more than {0} nested SVG images o SVG se expande em mais de {0} imagens SVG aninhadas @msg the SVG expands to more than {0} objects o SVG se expande em mais de {0} objetos +@msg the SVG's styles expand to more than {0} MB os estilos do SVG se expandem para mais de {0} MB @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes o arquivo SVG tem mais de {MAX_IMPORT_BYTES} bytes @msg the SVG has no drawable objects o SVG não tem objetos desenháveis @msg the SVGZ file unpacks to more than {_1} MB o arquivo SVGZ é descompactado em mais de {_1} MB @@ -9514,3 +9530,6 @@ swatch Yellow Green Verde-amarelado @msg turn on at least one side ative pelo menos um lado @msg with no hem and no grommets there is nothing to mark sem bainha e sem ilhoses não há nada para marcar @msg {saving} failed: {e} {saving} falhou: {e} + Nest Shapes… Aninhar formas… + Nest Shapes Aninhar formas + Roll Rolo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 0cda4fcc05..739aaed4c5 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1351,6 +1351,7 @@ file-filter Templates Шаблоны Format Формат Format Options Параметры формата Format Settings Параметры формата + Format Settings… Параметры формата… Format: Формат: Formats: Форматы: Fractional Widths Дробные ширины @@ -1712,6 +1713,7 @@ file-filter Templates Шаблоны Images: Изображения: Import Keyboard Shortcuts… Импортировать сочетания клавиш… Import PDF Импортировать PDF + Import PDF pages as links Импортировать страницы PDF как связи Import PDF Presets Импортировать наборы PDF Import Perspective Grid Presets Импортировать наборы сетки перспективы Import Print Presets Импортировать наборы печати @@ -3476,6 +3478,18 @@ digits Malayalam Малаялам Smart Guides (View → Smart Guides) Умные направляющие (Просмотр → Умные направляющие) Smart Guides (⌘U) Умные направляющие (⌘U) Smart Punctuation… Умная пунктуация… + Smart Punctuation Умная пунктуация + ff, fi, ffi Ligatures Лигатуры ff, fi, ffi + ff, fl, ffl Ligatures Лигатуры ff, fl, ffl + Smart Quotes Умные кавычки + Smart Spaces Умные пробелы + En, Em Dashes Средние и длинные тире + Ellipses Многоточия + Expert Fractions Экспертные дроби + Replace In Заменить в + Selected Text Only Только выделенный текст + Entire Document Весь документ + Report Results Отчёт о результатах Smooth Сгладить Corner Угол Relative Относительно @@ -3506,6 +3520,7 @@ digits Malayalam Малаялам Solid Сплошной Sort by Kind Сортировать по типу Sort by Name Сортировать по имени + Sort by Size Сортировать по размеру Sort by Status Сортировать по состоянию Source code on GitHub Исходный код на GitHub Source Sans 3 Source Sans 3 @@ -4886,6 +4901,7 @@ axis Both Оба @msg result would exceed the canvas (coordinates out of range) результат превысил бы холст (координаты вне диапазона) @msg objects can't be nested more than 32 deep объекты нельзя вкладывать глубже 32 уровней @msg the SVG's elements are nested more than {0} deep элементы SVG вложены глубже {0} уровней +@msg the SVG's styles expand to more than {0} MB после развёртывания стили SVG занимают более {0} МБ @msg scale must be a number from {_1} to {_2}, not {_3} scale должен быть числом от {_1} до {_2}, а не {_3} @msg scale must be a number from {_1} to {_2}, not {s} scale должен быть числом от {_1} до {_2}, а не {s} @msg select (or target) objects whose appearance isn't basic выделите (или укажите как объект) объекты, оформление которых не является основным @@ -7615,6 +7631,9 @@ shape Open Открытый Grommets Люверсы Grommet Inset Отступ люверсов от края Diameter Диаметр + Nest Shapes… Раскладка фигур… + Nest Shapes Раскладка фигур + Roll Рулон # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points 3D-эффектам нужны конечные координаты в пределах 100 миллионов пунктов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 83c9147590..837fae58b3 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1300,6 +1300,7 @@ font-technology Variable Variabla Format Format Format Options Formatalternativ Format Settings Formatinställningar + Format Settings… Formatinställningar… Format: Format: Formats: Format: Fractional Widths Bråkdelsbredder @@ -1646,6 +1647,7 @@ font-technology Variable Variabla Images: Bilder: Import Keyboard Shortcuts… Importera kortkommandon… Import PDF Importera PDF + Import PDF pages as links Importera PDF-sidor som länkar Import PDF Presets Importera PDF-förinställningar Import Perspective Grid Presets Importera förinställningar för perspektivrutnät Import Print Presets Importera utskriftsförinställningar @@ -3366,6 +3368,18 @@ digits Malayalam Malayalam Smart Guides (View → Smart Guides) Smarta stödlinjer (Visa → Smarta stödlinjer) Smart Guides (⌘U) Smarta stödlinjer (⌘U) Smart Punctuation… Smarta skiljetecken… + Smart Punctuation Smarta skiljetecken + ff, fi, ffi Ligatures Ligaturer ff, fi, ffi + ff, fl, ffl Ligatures Ligaturer ff, fl, ffl + Smart Quotes Smarta citattecken + Smart Spaces Smarta blanksteg + En, Em Dashes Korta och långa tankstreck + Ellipses Ellipser + Expert Fractions Expertbråk + Replace In Ersätt i + Selected Text Only Endast markerad text + Entire Document Hela dokumentet + Report Results Rapportera resultat Smooth Mjuk Corner Hörn Relative Relativ @@ -3396,6 +3410,7 @@ digits Malayalam Malayalam Solid Enfärgad Sort by Kind Sortera efter typ Sort by Name Sortera efter namn + Sort by Size Sortera efter storlek Sort by Status Sortera efter status Source code on GitHub Källkod på GitHub Source Sans 3 Source Sans 3 @@ -8653,6 +8668,7 @@ digits Hindi Hindi @msg the subpath has no ends to extend (it is closed or a single point) delbanan har inga ändar att förlänga (den är stängd eller en enkel punkt) @msg the SVG expands to more than {0} nested SVG images SVG-filen expanderar till fler än {0} kapslade SVG-bilder @msg the SVG expands to more than {0} objects SVG-filen expanderar till fler än {0} objekt +@msg the SVG's styles expand to more than {0} MB SVG-filens stilar expanderar till mer än {0} MB @msg the SVG has no drawable objects SVG-filen har inga ritbara objekt @msg the SVGZ file unpacks to more than {_1} MB SVGZ-filen packas upp till mer än {_1} MB @msg the symbols are nested too deeply to expand their instances symbolerna är kapslade för djupt för att deras instanser ska kunna expanderas @@ -8990,6 +9006,9 @@ digits Hindi Hindi Grommets Öljetter Grommet Inset Öljetternas avstånd från kanten Diameter Diameter + Nest Shapes… Packa former… + Nest Shapes Packa former + Roll Rulle # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points 3D-effekter kräver ändliga koordinater inom 100 miljoner punkter diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index d23eff82c3..73dbe905ff 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1923,6 +1923,43 @@ fn ukrainian_plurals_have_three_forms() { assert!(count >= 13, "Ukrainian plural rows missing"); } +/// Ukrainian shows the image encoders', color profiles', swatch exchange files', Revolve's, DXF +/// import's, the script engine's and the parameter checks' errors in Ukrainian, with their values, +/// backticked names and accepted values kept as the English writes them. +#[test] +fn ukrainian_translates_encoder_profile_swatch_revolve_and_parameter_errors() { + for (english, ukrainian) in [ + ( + "PNG encoding failed: 0 × 0 pixels is not a valid image size", + "Не вдалося закодувати PNG: 0 × 0 пікселів не є допустимим розміром зображення", + ), + ( + "70000 × 10 pixels is too large for GIF (at most 65535 pixels a side): lower the resolution", + "розмір 70000 × 10 пікселів завеликий для GIF (не більше 65535 пікселів на сторону): зменште роздільну здатність", + ), + ("profile colour space XYZ is not RGB, CMYK or Gray", "колірний простір профілю XYZ не є RGB, CMYK чи Gray"), + ( + "color books in color space HSB aren't supported (only RGB, CMYK and Lab)", + "книги кольорів у колірному просторі HSB не підтримуються (лише RGB, CMYK і Lab)", + ), + ("the swatch exchange file holds more than 65536 colors and groups", "файл обміну зразками містить понад 65536 кольорів і груп"), + ( + "Revolve surface is too complex; reduce Segments or simplify the profile", + "Обертання: поверхня надто складна; зменште «Сегменти» або спростіть профіль", + ), + ("regular expression too large", "регулярний вираз завеликий"), + ("this binary DXF file is damaged or cut short", "цей двійковий файл DXF пошкоджено або обрізано"), + ( + "`view` is smallThumb, mediumThumb, largeThumb, smallList or largeList", + "`view` має бути smallThumb, mediumThumb, largeThumb, smallList або largeList", + ), + ("give `fill` or `stroke`, not both", "укажіть `fill` або `stroke`, але не обидва"), + ("stop 2: oops", "точка переходу 2: oops"), + ] { + assert_eq!(message(uk(), english), ukrainian); + } +} + /// Catalogs written with spaces between words keep a fragment's leading and trailing spaces: the /// hint bar and a few labels are joined from pieces (" to finish", "Press "). #[test] @@ -4351,7 +4388,7 @@ fn translated_messages_keep_the_field_names_and_values_their_english_lists() { /// the messages each one lacks. const COMPLETE_MESSAGES: &[&str] = &[ "cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca", - "nl", + "nl", "da", ]; /// Crates whose error and status messages reach the status bar, the crates whose errors the diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 07aff6339a..67a1be74ff 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1293,6 +1293,7 @@ font-technology Variable Değişken Format Biçim Format Options Biçim Seçenekleri Format Settings Biçim Ayarları + Format Settings… Biçim Ayarları… Format: Biçim: Formats: Formatlar: Fractional Widths Kesirli Genişlikler @@ -1524,6 +1525,7 @@ font-technology Variable Değişken Images: Görseller: Import Keyboard Shortcuts… Klavye Kısayollarını İçe Aktar… Import PDF PDF'yi içe aktar + Import PDF pages as links PDF sayfalarını bağlantı olarak içe aktar Import PDF Presets PDF Hazır Ayarlarını İçe Aktar Import Perspective Grid Presets Perspektif Izgarası Ön Ayarlarını İçe Aktar Import Print Presets Yazdırma Ön Ayarlarını İçe Aktar @@ -3242,6 +3244,18 @@ digits Malayalam Malayalam Smart Guides (View → Smart Guides) Akıllı Kılavuzlar (Görünüm → Akıllı Kılavuzlar) Smart Guides (⌘U) Akıllı Kılavuzlar (⌘U) Smart Punctuation… Akıllı Noktalama… + Smart Punctuation Akıllı Noktalama + ff, fi, ffi Ligatures ff, fi, ffi Bitişik Harfleri + ff, fl, ffl Ligatures ff, fl, ffl Bitişik Harfleri + Smart Quotes Akıllı Tırnaklar + Smart Spaces Akıllı Boşluklar + En, Em Dashes En ve Em Tireler + Ellipses Üç Noktalar + Expert Fractions Uzman Kesirleri + Replace In Değiştirilecek Yer + Selected Text Only Yalnızca Seçili Metin + Entire Document Tüm Belge + Report Results Sonuçları Bildir Smooth Pürüzsüz Corner Köşe Relative akraba @@ -3270,6 +3284,7 @@ digits Malayalam Malayalam Solid Katı Sort by Kind Türe göre sırala Sort by Name Ada Göre Sırala + Sort by Size Boyuta göre sırala Sort by Status Duruma göre sırala Source code on GitHub GitHub'daki kaynak kodu Source Sans 3 Kaynak Sans 3 @@ -4619,6 +4634,7 @@ axis Both Her İkisi @msg result would exceed the canvas (coordinates out of range) sonuç tuvali aşacaktır (koordinatlar aralık dışındadır) @msg objects can't be nested more than 32 deep nesneler 32'den fazla derinliğe yerleştirilemez @msg the SVG's elements are nested more than {0} deep SVG'nin öğeleri {0} derinliğinden daha fazla yuvalanmıştır +@msg the SVG's styles expand to more than {0} MB SVG'nin stilleri genişletildiğinde {0} MB'tan fazla yer kaplıyor @msg scale must be a number from {_1} to {_2}, not {_3} scale {_1} ile {_2} arasında bir sayı olmalıdır, {_3} değil @msg scale must be a number from {_1} to {_2}, not {s} scale {_1} ile {_2} arasında bir sayı olmalıdır, {s} değil @msg select (or target) objects whose appearance isn't basic Görünümü temel olmayan nesneleri seçin (veya hedefleyin) @@ -7599,3 +7615,6 @@ breakText Glyphs Glifler Grommets Kuşgözleri Grommet Inset Kuşgözlerinin kenara uzaklığı Diameter Çap + Nest Shapes… Şekilleri yerleştir… + Nest Shapes Şekilleri yerleştir + Roll Rulo diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 31c15f10b5..a74a03529d 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1356,6 +1356,7 @@ file-filter Templates Шаблони Format Формат Format Options Параметри формату Format Settings Параметри формату + Format Settings… Параметри формату… Format: Формат: Formats: Формати: Fractional Widths Дробові ширини @@ -1717,6 +1718,7 @@ file-filter Templates Шаблони Images: Зображення: Import Keyboard Shortcuts… Імпортувати сполучення клавіш… Import PDF Імпортувати PDF + Import PDF pages as links Імпортувати сторінки PDF як зв’язки Import PDF Presets Імпортувати набори PDF Import Perspective Grid Presets Імпортувати набори сітки перспективи Import Print Presets Імпортувати набори друку @@ -3482,6 +3484,18 @@ effect Points Точки Smart Guides (View → Smart Guides) Розумні напрямні (Перегляд → Розумні напрямні) Smart Guides (⌘U) Розумні напрямні (⌘U) Smart Punctuation… Розумна пунктуація… + Smart Punctuation Розумна пунктуація + ff, fi, ffi Ligatures Лігатури ff, fi, ffi + ff, fl, ffl Ligatures Лігатури ff, fl, ffl + Smart Quotes Розумні лапки + Smart Spaces Розумні пробіли + En, Em Dashes Середні й довгі тире + Ellipses Трикрапки + Expert Fractions Експертні дроби + Replace In Замінити в + Selected Text Only Тільки виділений текст + Entire Document Увесь документ + Report Results Звіт про результати Smooth Згладити Corner Кут Relative Відносно @@ -3512,7 +3526,8 @@ effect Points Точки Solid Суцільний Sort by Kind Сортувати за типом Sort by Name Сортувати за назвою - Sort by Status Сортувати за: + Sort by Size Сортувати за розміром + Sort by Status Сортувати за станом Source code on GitHub Вихідний код GitHub Source Sans 3 Source Sans 3 Space After Paragraph Інтервал після абзацу @@ -7001,6 +7016,122 @@ breakText Glyphs Гліфи @msg only an exporter or an importer declares `extensions` `extensions` оголошує лише модуль експорту або імпорту @msg an importer always gets an import's budget: leave `budget` out модуль імпорту завжди отримує бюджет імпорту: не вказуйте `budget` +# Messages of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and parameter checks. +@msg 3D effects require finite coordinates within 100 million points 3D-ефектам потрібні скінченні координати в межах 100 мільйонів пунктів +@msg 3D effects require one to ten lights 3D-ефектам потрібно від одного до десяти джерел світла +@msg BMP depth {_1}: 1, 4, 8, 16, 24 or 32 bits per pixel Глибина BMP {_1}: 1, 4, 8, 16, 24 або 32 біти на піксель +@msg BMP encoding failed: {width} × {height} pixels doesn't fit the format or the pixel buffer Не вдалося закодувати BMP: {width} × {height} пікселів не вміщується у формат або не відповідає буферу пікселів +@msg GIF encoding failed: the palette image is malformed Не вдалося закодувати GIF: зображення з палітрою має неправильну структуру +@msg GIF encoding failed: {e} Не вдалося закодувати GIF: {e} +@msg JPEG colour profile: {e} Профіль кольору JPEG: {e} +@msg JPEG encoding failed: pixel buffer doesn't match the image size Не вдалося закодувати JPEG: буфер пікселів не відповідає розміру зображення +@msg JPEG encoding failed: {e} Не вдалося закодувати JPEG: {e} +@msg PNG encoding failed: pixel buffer doesn't match the image size Не вдалося закодувати PNG: буфер пікселів не відповідає розміру зображення +@msg PNG encoding failed: the palette image is malformed Не вдалося закодувати PNG: зображення з палітрою має неправильну структуру +@msg PNG encoding failed: {e} Не вдалося закодувати PNG: {e} +@msg PNG encoding failed: {width} × {height} pixels is not a valid image size Не вдалося закодувати PNG: {width} × {height} пікселів не є допустимим розміром зображення +@msg PSD colour profile: {e} Профіль кольору PSD: {e} +@msg PSD encoding failed: the pixel buffer doesn't match the image size Не вдалося закодувати PSD: буфер пікселів не відповідає розміру зображення +@msg Revolve profile contains invalid coordinates Обертання: профіль містить неприпустимі координати +@msg Revolve profile is too complex Обертання: профіль надто складний +@msg Revolve projection is not finite Обертання: проєкція не скінченна +@msg Revolve requires finite profile coordinates within 100 million points Обертання: потрібні скінченні координати профілю в межах 100 мільйонів пунктів +@msg Revolve surface is too complex; reduce Segments or simplify the profile Обертання: поверхня надто складна; зменште «Сегменти» або спростіть профіль +@msg Revolve surface is too complex; simplify the profile Обертання: поверхня надто складна; спростіть профіль +@msg Revolve visibility cannot split the projected boundary Обертання: обчислення видимості не може розділити спроєктовану межу +@msg Revolve visibility creates too many fragments Обертання: обчислення видимості створює забагато фрагментів +@msg Revolve visibility creates too many vector anchors Обертання: обчислення видимості створює забагато векторних опорних точок +@msg Revolve visibility exceeds its geometry work limit Обертання: обчислення видимості перевищує межу геометричних обчислень +@msg Revolve visibility exceeds its spatial index limit Обертання: обчислення видимості перевищує межу просторового індексу +@msg Revolve visibility has too many boundary crossings Обертання: обчислення видимості має забагато перетинів меж +@msg Revolve visibility has too many input anchors Обертання: обчислення видимості має забагато вхідних опорних точок +@msg Revolve visibility requires convex cap sectors Обертання: обчисленню видимості потрібні опуклі сектори кришки +@msg Revolve visibility requires finite projected faces Обертання: обчисленню видимості потрібні скінченні спроєктовані грані +@msg SVG options: {e} Параметри SVG: {e} +@msg Save for Web settings: {e} Параметри «Зберегти для Інтернету»: {e} +@msg TIFF colour profile: {e} Профіль кольору TIFF: {e} +@msg TIFF encoding failed: the pixel buffer doesn't match the image size Не вдалося закодувати TIFF: буфер пікселів не відповідає розміру зображення +@msg TIFF encoding failed: {e} Не вдалося закодувати TIFF: {e} +@msg Targa depth {_1}: 16, 24 or 32 bits per pixel Глибина Targa {_1}: 16, 24 або 32 біти на піксель +@msg Targa encoding failed: the pixel buffer doesn't match the image size Не вдалося закодувати Targa: буфер пікселів не відповідає розміру зображення +@msg The 3D projection is not finite 3D-проєкція не скінченна +@msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D-тінь надто складна; вимкніть «Тіні» або спростіть ілюстрацію +@msg The shape contains invalid coordinates Фігура містить неприпустимі координати +@msg Too many Revolve faces for visibility evaluation Забагато граней обертання для обчислення видимості +@msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft читає з файлу обміну зразками не більше {ASE_MAX_ENTRIES} кольорів і груп, а в цій бібліотеці їх {entries} +@msg WebP encoding failed: {e} Не вдалося закодувати WebP: {e} +@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} +@msg `answers[{i}]` {e} `answers[{i}]` {e} +@msg `view` is smallThumb, mediumThumb, largeThumb, smallList or largeList `view` має бути smallThumb, mediumThumb, largeThumb, smallList або largeList +@msg a line can't run from a point to itself лінія не може йти з точки в ту саму точку +@msg a line needs at least two points лінії потрібні щонайменше дві точки +@msg a number cannot be read не вдалося прочитати число +@msg a swatch exchange block is too long блок файлу обміну зразками задовгий +@msg a swatch exchange name is too long назва у файлі обміну зразками задовга +@msg a {sw} × {sh} image can't be resized to {width} × {height} pixels розмір зображення {sw} × {sh} не можна змінити на {width} × {height} пікселів +@msg a {width} × {height} image is too large зображення {width} × {height} завелике +@msg a {width} × {height} image: {e} зображення {width} × {height}: {e} +@msg an image could not be written: {e} не вдалося записати зображення: {e} +@msg an image that couldn't be read was left out зображення, яке не вдалося прочитати, пропущено +@msg can't open “{name}”: {e} не вдалося відкрити «{name}»: {e} +@msg cannot align zip entries to {align} bytes не вдається вирівняти записи архіву zip до {align} байтів +@msg cannot open the automation {kind} root `{_1}`: {e} не вдається відкрити кореневу папку автоматизації ({kind}) `{_1}`: {e} +@msg cannot read profile: {0} не вдалося прочитати профіль: {0} +@msg color book version {version} isn't supported (only 1) версія книги кольорів {version} не підтримується (лише 1) +@msg color books in color space {other} aren't supported (only RGB, CMYK and Lab) книги кольорів у колірному просторі {other} не підтримуються (лише RGB, CMYK і Lab) +@msg file name too long to zip: {_1} назва файлу задовга для архіву zip: {_1} +@msg file name too long to zip: {name} назва файлу задовга для архіву zip: {name} +@msg freeform line {i}: {e} довільна лінія {i}: {e} +@msg freeform point {i}: {e} довільна точка {i}: {e} +@msg give `{key}` or `{other}`, not both укажіть `{key}` або `{other}`, але не обидва +@msg grayscale profiles can't be working spaces yet профілі відтінків сірого поки що не можуть бути робочими просторами +@msg input contains NaN or infinite coordinates вхідні дані містять координати NaN або нескінченні координати +@msg input path could not be closed не вдалося замкнути вхідний контур +@msg invalid ICC profile: {0} неприпустимий профіль ICC: {0} +@msg invalid scale {scale} неприпустимий масштаб {scale} +@msg its localized names take more than {_1} KB його локалізовані назви займають понад {_1} КБ +@msg its objects are nested too deep ({e}) його об’єкти мають завелику вкладеність ({e}) +@msg its tag table lists the `{_1}` tag more than once його таблиця тегів містить тег `{_1}` більше одного разу +@msg not a graphic style library: {e} це не бібліотека графічних стилів: {e} +@msg not a swatch library (.vcswatches or .gpl) це не бібліотека зразків (.vcswatches або .gpl) +@msg not a swatch library (format `{_1}`) це не бібліотека зразків (формат `{_1}`) +@msg not a swatch library: {e} це не бібліотека зразків: {e} +@msg not an action set file ({e}) це не файл набору дій ({e}) +@msg profile colour space {other} is not RGB, CMYK or Gray колірний простір профілю {other} не є RGB, CMYK чи Gray +@msg regular expression too large регулярний вираз завеликий +@msg script file is not UTF-8 text: {value} файл скрипта не є текстом UTF-8: {value} +@msg stop {i}: {e} точка переходу {i}: {e} +@msg swatch exchange version {major}.{minor} isn't supported (only 1.x) версія файлу обміну зразками {major}.{minor} не підтримується (лише 1.x) +@msg the color book holds more than {ASE_MAX_ENTRIES} colors книга кольорів містить понад {ASE_MAX_ENTRIES} кольорів +@msg the color book is cut short книгу кольорів обрізано +@msg the color book's names take more than {_1} MB назви книги кольорів займають понад {_1} МБ +@msg the image would be {w} × {h} pixels; raster exports are limited to {MAX_RASTER_SIDE} pixels per side and {_1} megapixels: lower the scale or resolution зображення мало б розмір {w} × {h} пікселів; растровий експорт обмежено {MAX_RASTER_SIDE} пікселями на сторону та {_1} мегапікселями: зменште масштаб або роздільну здатність +@msg the optimised image can't be read back: {e} оптимізоване зображення не вдається прочитати знову: {e} +@msg the pixel buffer doesn't match the image size буфер пікселів не відповідає розміру зображення +@msg the preview: {e} попередній перегляд: {e} +@msg the request may not read the New Document profiles folder запит не має права читати папку профілів нового документа +@msg the shapes are too degenerate to combine фігури занадто вироджені для об’єднання +@msg the shapes cross themselves and each other too often to combine фігури надто часто перетинають самі себе й одна одну, щоб їх можна було об’єднати +@msg the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups файл обміну зразками містить понад {ASE_MAX_ENTRIES} кольорів і груп +@msg the swatch exchange file is cut short файл обміну зразками обрізано +@msg the {_1} plate can't be read: {e} не вдалося прочитати форму {_1}: {e} +@msg this binary DXF file is damaged or cut short цей двійковий файл DXF пошкоджено або обрізано +@msg this is a DWG drawing, which can't be read: save it from the CAD app as a DXF and open that це креслення DWG, яке неможливо прочитати: збережіть його з CAD як DXF і відкрийте його +@msg too many classes забагато класів +@msg too many groups забагато груп +@msg too many layers for PSD (at most 32767) забагато шарів для PSD (не більше 32767) +@msg too many swatch exchange blocks забагато блоків обміну зразками +@msg unknown colour profile: {0} невідомий профіль кольору: {0} +@msg {_1} clashes with a built-in profile name {_1} збігається з назвою вбудованого профілю +@msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution розмір {_1} × {_2} пікселів завеликий для GIF (не більше 65535 пікселів на сторону): зменште роздільну здатність +@msg {_1}: no usable transform to/from sRGB {_1}: немає придатного перетворення в sRGB або з sRGB +@msg {name} is not a CMYK profile {name} не є профілем CMYK +@msg {name} is not an RGB profile {name} не є профілем RGB +@msg {path}: could not be read {path}: не вдалося прочитати +@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution розмір {width} × {height} пікселів завеликий для JPEG (не більше 65535 пікселів на сторону): зменште роздільну здатність +@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution розмір {width} × {height} пікселів завеликий для Targa (не більше 65535 пікселів на сторону): зменште роздільну здатність +@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution розмір {w} × {h} пікселів завеликий для PSD (не більше {MAX_SIDE} пікселів на сторону): зменште роздільну здатність + # Copy Troubleshooting Info Copy Troubleshooting Info Копіювати відомості для усунення несправностей @msg Copied the troubleshooting info Відомості для усунення несправностей скопійовано @@ -8496,6 +8627,7 @@ breakText Glyphs Гліфи @msg the RTF file is too large to place as type (at most {_1} MB) файл RTF завеликий, щоб помістити його як текст (не більше {_1} МБ) @msg the SVG expands to more than {0} nested SVG images SVG розгортається у понад {0} вкладених зображень SVG @msg the SVG expands to more than {0} objects SVG розгортається у понад {0} об’єктів +@msg the SVG's styles expand to more than {0} MB стилі SVG розгортаються у понад {0} МБ @msg the SVG file is larger than {MAX_IMPORT_BYTES} bytes файл SVG більший за {MAX_IMPORT_BYTES} байтів @msg the SVG has no drawable objects SVG не містить об’єктів, які можна намалювати @msg the SVGZ file unpacks to more than {_1} MB файл SVGZ розпаковується у понад {_1} МБ @@ -8934,3 +9066,6 @@ breakText Glyphs Гліфи @msg turn on at least one side увімкніть принаймні одну сторону @msg with no hem and no grommets there is nothing to mark без підгину й люверсів немає чого розмічати @msg {saving} failed: {e} {saving}: не вдалося: {e} + Nest Shapes… Розкладка фігур… + Nest Shapes Розкладка фігур + Roll Рулон diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b5f29adc72..abed0dc86a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1576,6 +1576,7 @@ file-filter Templates Mẫu Format Định dạng Format Options Tùy chọn định dạng Format Settings Cài đặt định dạng + Format Settings… Cài đặt định dạng… Format: Định dạng: Formats: Các định dạng: Fractional Widths Chiều rộng phân số @@ -1958,6 +1959,7 @@ digits Hindi Hindi Import Library Nhập thư viện Import Library… Nhập thư viện… Import PDF Nhập PDF + Import PDF pages as links Nhập các trang PDF dưới dạng liên kết Import PDF Presets Nhập thiết lập sẵn PDF Import Perspective Grid Presets Nhập thiết lập sẵn lưới phối cảnh Import Print Presets Nhập thiết lập sẵn in @@ -3838,6 +3840,18 @@ mark-style Japanese Kiểu Nhật Smart Guides (View → Smart Guides) Đường căn thông minh (Hiển thị → Đường căn thông minh) Smart Guides (⌘U) Đường căn thông minh (⌘U) Smart Punctuation… Dấu câu thông minh… + Smart Punctuation Dấu câu thông minh + ff, fi, ffi Ligatures Chữ ghép ff, fi, ffi + ff, fl, ffl Ligatures Chữ ghép ff, fl, ffl + Smart Quotes Dấu ngoặc kép thông minh + Smart Spaces Khoảng trắng thông minh + En, Em Dashes Gạch ngang ngắn và dài + Ellipses Dấu chấm lửng + Expert Fractions Phân số chuyên dụng + Replace In Thay thế trong + Selected Text Only Chỉ văn bản đã chọn + Entire Document Toàn bộ tài liệu + Report Results Báo cáo kết quả Smooth Mượt Smooth Color Màu mượt Smooth Tool Công cụ Làm mượt @@ -3860,6 +3874,7 @@ mark-style Japanese Kiểu Nhật Sort Sắp xếp Sort by Kind Sắp xếp theo loại Sort by Name Sắp xếp theo tên + Sort by Size Sắp xếp theo kích thước Sort by Status Sắp xếp theo trạng thái Source code on GitHub Mã nguồn trên GitHub Source Image Ảnh nguồn @@ -5260,6 +5275,7 @@ theme Appearance Giao diện @msg result would exceed the canvas (coordinates out of range) kết quả sẽ vượt quá vùng vẽ (tọa độ ngoài phạm vi) @msg objects can't be nested more than 32 deep không thể lồng các đối tượng sâu quá 32 cấp @msg the SVG's elements are nested more than {0} deep các phần tử SVG lồng nhau sâu quá {0} cấp +@msg the SVG's styles expand to more than {0} MB các kiểu của SVG khi mở rộng chiếm hơn {0} MB @msg Save for Web: the image is empty Lưu cho Web: ảnh trống @msg Save writes {_1}, not {_2}: use document.export for other formats Lưu ghi {_1}, không phải {_2}: dùng document.export cho các định dạng khác @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it Lưu ghi {_1}, không phải {_2}: dùng file.saveAsTemplate để ghi định dạng này @@ -7137,6 +7153,9 @@ breakText Glyphs Glyph Grommets Khoen Grommet Inset Khoảng cách từ mép đến khoen Diameter Đường kính + Nest Shapes… Xếp hình tiết kiệm vật liệu… + Nest Shapes Xếp hình tiết kiệm vật liệu + Roll Cuộn # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9d5fe1c4b6..b83bee650f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1292,6 +1292,7 @@ file-filter Templates 模板 Format 格式 Format Options 格式选项 Format Settings 格式设置 + Format Settings… 格式设置… Format: 格式: Formats: 格式: Fractional Widths 比例宽度 @@ -1642,6 +1643,7 @@ file-filter Templates 模板 Images: 图像: Import Keyboard Shortcuts… 导入键盘快捷键… Import PDF 导入 PDF + Import PDF pages as links 将 PDF 页面导入为链接 Import PDF Presets 导入 PDF 预设 Import Perspective Grid Presets 导入透视网格预设 Import Print Presets 导入打印预设 @@ -3305,6 +3307,18 @@ digits Malayalam 马拉雅拉姆数字 Smart Guides (View → Smart Guides) 智能参考线 (视图 → 智能参考线) Smart Guides (⌘U) 智能参考线 (⌘U) Smart Punctuation… 智能标点… + Smart Punctuation 智能标点 + ff, fi, ffi Ligatures ff、fi、ffi 连字 + ff, fl, ffl Ligatures ff、fl、ffl 连字 + Smart Quotes 智能引号 + Smart Spaces 智能空格 + En, Em Dashes 短破折号和长破折号 + Ellipses 删节号 + Expert Fractions 专家分数字 + Replace In 替换范围 + Selected Text Only 仅所选文本 + Entire Document 整个文档 + Report Results 报告结果 Smooth 平滑 Corner 尖角 Relative 相对 @@ -3335,6 +3349,7 @@ digits Malayalam 马拉雅拉姆数字 Solid 实心 Sort by Kind 按类型排序 Sort by Name 按名称排序 + Sort by Size 依大小排序 Sort by Status 依状态排序 Source code on GitHub GitHub 源代码 Source Sans 3 Source Sans 3 @@ -8854,6 +8869,7 @@ breakText Glyphs 字形 @msg the RTF file is too large to place as type (at most {_1} MB) RTF 文件过大,无法作为文字置入 (最多 {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG 展开后的嵌套 SVG 图像超过 {0} 个 @msg the SVG expands to more than {0} objects SVG 展开后的对象超过 {0} 个 +@msg the SVG's styles expand to more than {0} MB SVG 的样式展开后超过 {0} MB @msg the SVG has no drawable objects SVG 中没有可绘制的对象 @msg the SVGZ file unpacks to more than {_1} MB SVGZ 文件解压后超过 {_1} MB @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word 文档的属性页超过 {MAX_PAGES} 页,过多而无法置入 @@ -9166,6 +9182,9 @@ breakText Glyphs 字形 @msg {what} can't be intertwined {what} 不能交织 @msg {what} doesn't fit the paper with its bleed and marks {what} 连同出血和标记在纸张上放不下 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 会打印成超过 {MAX_TILES} 个拼贴:请将其缩小 + Nest Shapes… 形状排料… + Nest Shapes 形状排料 + Roll 卷材 # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points 3D 效果需要 1 亿点以内的有限坐标 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 528e0a57ca..4637ecb811 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1327,6 +1327,7 @@ file-filter Templates 範本 Format 格式 Format Options 格式選項 Format Settings 格式設定 + Format Settings… 格式設定… Format: 格式: Formats: 格式: Fractional Widths 小數字寬 @@ -1689,6 +1690,7 @@ file-filter Templates 範本 Images: 影像: Import Keyboard Shortcuts… 匯入鍵盤快速鍵… Import PDF 匯入 PDF + Import PDF pages as links 將 PDF 頁面匯入為連結 Import PDF Presets 匯入 PDF 預設集 Import Perspective Grid Presets 匯入透視格點預設集 Import Print Presets 匯入列印預設集 @@ -4562,6 +4564,18 @@ digits Malayalam 馬來亞拉姆數字 Smart Guides (View → Smart Guides) 智慧型參考線 (檢視 → 智慧型參考線) Smart Guides (⌘U) 智慧型參考線 (⌘U) Smart Punctuation… 智慧型標點… + Smart Punctuation 智慧型標點 + ff, fi, ffi Ligatures ff、fi、ffi 連字 + ff, fl, ffl Ligatures ff、fl、ffl 連字 + Smart Quotes 智慧型引號 + Smart Spaces 智慧型空格 + En, Em Dashes 短破折號和長破折號 + Ellipses 刪節號 + Expert Fractions 專家分數 + Replace In 取代範圍 + Selected Text Only 僅限選取的文字 + Entire Document 整份文件 + Report Results 報告結果 Smooth 平滑 Corner 角點 Relative 相對 @@ -4592,6 +4606,7 @@ digits Malayalam 馬來亞拉姆數字 Solid 實心 Sort by Kind 依類型排序 Sort by Name 依名稱排序 + Sort by Size 依大小排序 Sort by Status 依狀態排序 Source code on GitHub GitHub 上的原始碼 Source Sans 3 Source Sans 3 @@ -7160,6 +7175,9 @@ breakText Glyphs 字符 Grommets 扣眼 Grommet Inset 扣眼邊距 Diameter 直徑 + Nest Shapes… 形狀排料… + Nest Shapes 形狀排料 + Roll 捲材 # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points 3D 效果需要位於 1 億點以內的有限座標 @@ -8779,6 +8797,7 @@ breakText Glyphs 字符 @msg the RTF file is too large to place as type (at most {_1} MB) RTF 檔案過大,無法置入為文字 (最多 {_1} MB) @msg the SVG expands to more than {0} nested SVG images SVG 展開後超過 {0} 個巢狀 SVG 影像 @msg the SVG expands to more than {0} objects SVG 展開後超過 {0} 個物件 +@msg the SVG's styles expand to more than {0} MB SVG 的樣式展開後超過 {0} MB @msg the SVG has no drawable objects SVG 中沒有可繪製的物件 @msg the SVGZ file unpacks to more than {_1} MB SVGZ 檔案解壓縮後超過 {_1} MB @msg the Word document has more than {MAX_PAGES} pages of properties, too many to place Word 文件的屬性超過 {MAX_PAGES} 頁,數量過多而無法置入 diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 3aab5e1e44..752d42b9ae 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -83,6 +83,8 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st crate::addons::select::COMMAND => (crate::addons::select::KIND, crate::addons::select::fields(app)), "artboard.rearrange" => (crate::dialogs::rearrange_artboards::KIND, crate::dialogs::rearrange_artboards::open_fields(app)), "artboard.rename" => (crate::dialogs::rename_artboards::KIND, crate::dialogs::rename_artboards::open_fields(app)), + // Smart Punctuation opens on the fields it was last confirmed with. + "type.smartPunctuation" => (crate::dialogs::smart_punctuation::KIND, crate::dialogs::smart_punctuation::fields(app)), _ => return None, }) } diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 4b86b4152d..cc63a489cf 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -436,7 +436,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { cp("Sentence case", "type.changeCase", json!({"case": "sentence"})), ], ), - cp("Smart Punctuation…", "type.smartPunctuation", json!({"quotes": true, "dashes": true, "ellipsis": true, "scope": "selection"})), + c("Smart Punctuation…", "type.smartPunctuation"), sub( "Bullets and Numbering", vec![ diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index ded320a5aa..3e7fb53316 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -379,14 +379,15 @@ mod tests { ) } - /// A pick of a "…" command whose menu bar item gives params opens that item's dialog, and Smooth - /// opens its slider; nothing changes until the dialog is confirmed. + /// A pick of a "…" command whose menu bar item gives params opens that item's dialog, Smart + /// Punctuation opens its dialog and Smooth opens its slider; nothing changes until the dialog + /// is confirmed. #[test] fn a_pick_opens_the_dialog_its_menu_item_opens() { let expected = [ ("object.path.cleanUp", "command"), ("object.mesh.create", "command"), - ("type.smartPunctuation", "command"), + ("type.smartPunctuation", crate::dialogs::smart_punctuation::KIND), ("edit.findReplace", "command"), ("object.path.smooth", crate::dialogs::smooth_slider::KIND), ]; diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 021bc848c9..39b3a0ea85 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -11,6 +11,12 @@ //! marked 3D on their tiles. While the panel's assets include 3D assets, a Format row picks their //! mesh format (USDA, USDZ, glTF or OBJ), and Export writes them as mesh files beside the pictures. //! +//! The panel menu also holds Format Settings… (Export for Screens showing the first row's format +//! settings), and Create Sub-folders and Open Location after Export, the dialog's two checkboxes, +//! which Export follows. Create Sub-folders sorts the pictures into a folder per format row, or per +//! format or item when Export for Screens remembers that choice; 3D assets' mesh files go in the +//! folder itself. +//! //! Everything runs through the `assets.*` commands. use std::cell::RefCell; @@ -26,7 +32,7 @@ use vectorcraft_engine::cmd::fileio::{FORMATS_3D, SCREEN_SETTINGS_KEYS, format_3 use super::{pstate, set_pstate}; use crate::dialogs::{ EXPORT_FOR_SCREENS, ScreenPresetPick, drop_unread_screen_settings, open_export_for_screens_assets, screen_export_preset, screen_formats, - screen_import_presets, screen_preset_list, screen_saved_options, screen_saved_rows, + screen_import_presets, screen_preset_list, screen_saved_options, screen_saved_rows, screen_settings_format, }; use crate::state::Dialog; use crate::theme::Tokens; @@ -229,7 +235,14 @@ fn export_now(app: &mut VectorcraftApp, ids: Vec, files_each: usize) { let (three_d, ids): (Vec, Vec) = ids.into_iter().partition(|id| format(id).is_some()); // An OBJ is two files. let mesh_files: usize = three_d.iter().map(|id| if format(id).as_deref() == Some("obj") { 2 } else { 1 }).sum(); - let mut p = json!({ "assets": ids }); + // Create Sub-folders as the panel menu checks it: on by default, and remembered folders (per + // row, format or item) are used as Export for Screens uses them (a remembered `subfolders` + // false beside them would alone put every file in the folder itself). + let saved = &st.doc.export_settings; + let mut p = keep_subfolders(saved, json!({ "assets": ids })); + if let Some(f) = saved.get("folders").and_then(Value::as_str).filter(|f| !matches!(*f, "none" | "")) { + p["folders"] = json!(f); + } // Match the shared dialog's TIFF defaults, retaining saved choices and other formats. if let Some(st) = app.session.active() && screen_saved_rows(&st.doc.export_settings) @@ -267,7 +280,7 @@ fn export_now(app: &mut VectorcraftApp, ids: Vec, files_each: usize) { } }; p["folder"] = json!(folder); - p["openLocation"] = json!(saved.get("openLocation").and_then(Value::as_bool).unwrap_or(true)); + p["openLocation"] = json!(open_location(&saved)); } let mut meshes = json!({ "assets": three_d }); if io::is_web(app) { @@ -290,6 +303,43 @@ fn export_now(app: &mut VectorcraftApp, ids: Vec, files_each: usize) { } } +/// Create Sub-folders for the remembered settings `saved`, as Export for Screens opens on it: off +/// for remembered folders `none`, on for any other remembered folders (a folder per row, format or +/// item); without them the remembered `subfolders`, else on for a document without settings or +/// with a preset's rows. +fn subfolders_on(saved: &serde_json::Map) -> bool { + match saved.get("folders").and_then(Value::as_str) { + // An export reads empty folders as none. + Some("none" | "") => false, + Some(_) => true, + None => saved.get("subfolders").and_then(Value::as_bool).unwrap_or_else(|| saved.is_empty() || screen_saved_rows(saved).1.is_some()), + } +} + +/// `p` (params of `assets.settings.set` or `assets.export`) with `subfolders: true` when `saved` +/// makes no Create Sub-folders choice and it is on by default: the export would otherwise write +/// into the folder itself, and settings `p` adds would turn the default off. +fn keep_subfolders(saved: &serde_json::Map, mut p: Value) -> Value { + if !saved.contains_key("folders") && !saved.contains_key("subfolders") && subfolders_on(saved) { + p["subfolders"] = json!(true); + } + p +} + +/// Open Location after Export for the remembered settings `saved` (on until it is turned off). +fn open_location(saved: &serde_json::Map) -> bool { + saved.get("openLocation").and_then(Value::as_bool).unwrap_or(true) +} + +/// Open Export for Screens on the Assets tab with assets `ids` checked, showing the Format Settings +/// of format `format`. +fn format_settings(app: &mut VectorcraftApp, ids: &[u64], format: &str) { + open_export_for_screens_assets(app, Some(ids)); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__settings".into(), json!(format)); + } +} + /// What the export settings rows asked for. enum Settings { /// Change the shared settings (`assets.settings.set`). @@ -328,7 +378,7 @@ fn settings(ui: &mut Ui, st: &DocState) -> (Option, usize) { Some(Settings::Set(json!({ "preset": picked, "subfolders": true }))) } else if picked != preset || formats.as_array() != Some(&rows) { // Rows edited, or Custom picked: the rows as they are, without the preset. - Some(Settings::Set(json!({ "formats": formats, "preset": "" }))) + Some(Settings::Set(keep_subfolders(&st.doc.export_settings, json!({ "formats": formats, "preset": "" })))) } else { None }; @@ -432,12 +482,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Some(Settings::Set(p)) => { run(app, "assets.settings.set", p); } - Some(Settings::Format(f)) => { - open_export_for_screens_assets(app, Some(&sel_or_all(&sel, &all))); - if let Some(d) = app.ui.dialog.as_mut() { - d.fields.insert("__settings".into(), json!(f)); - } - } + Some(Settings::Format(f)) => format_settings(app, &sel_or_all(&sel, &all), &f), None => {} } if let Some(pick) = save_pick { @@ -575,6 +620,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let doc = st.uid; let (has_art, sel) = (!st.selection.is_empty(), selected(&ctx, st)); let all: Vec = st.doc.assets.iter().map(|a| a.id).collect(); + let saved = &st.doc.export_settings; + let (subfolders, open_after) = (subfolders_on(saved), open_location(saved)); + let settings_format = screen_settings_format(&screen_saved_rows(saved).0); if menu_item(ui, tl!("Add Selected Artwork as One Asset"), has_art, false) { collect(app, &ctx, None, true); } @@ -599,6 +647,17 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Export for Screens…"), true, false) { open_export_for_screens_assets(app, Some(&sel_or_all(&sel, &all))); } + if menu_item(ui, tl!("Format Settings…"), true, false) { + format_settings(app, &sel_or_all(&sel, &all), settings_format); + } + ui.separator(); + if menu_item(ui, tl!("Create Sub-folders"), true, subfolders) { + run(app, "assets.settings.set", json!({ "subfolders": !subfolders })); + } + // The web downloads the files: there is no location to open. + if !io::is_web(app) && menu_item(ui, tl!("Open Location after Export"), true, open_after) { + run(app, "assets.settings.set", json!({ "openLocation": !open_after })); + } ui.separator(); let (preset_doc, current): (u64, String) = pstate(&ctx, PRESET); let current = if preset_doc == doc { current } else { String::new() }; diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index d003fbcbce..e3c1f68bef 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -143,33 +143,52 @@ fn shared_styles( app: &VectorcraftApp, f: impl Fn(&vectorcraft_doc::TextObject, &vectorcraft_doc::ParaStyle, &CharStyle, bool) -> Option, ) -> Option { - let st = app.session.active()?; + let mut acc = Shared::None; + each_style(app, |t, para, style, inline| acc.add(f(t, para, style, inline))); + acc.value().flatten() +} + +/// Whether `f` holds for any of the character styles [`shared`] reads. +pub(crate) fn any_style(app: &VectorcraftApp, f: impl Fn(&CharStyle) -> bool) -> bool { + let mut any = false; + each_style(app, |_, _, style, _| any = any || f(style)); + any +} + +/// Call `f` with each character style the panels act on, as [`shared_styles`] describes: the +/// caret's style at a Type tool caret, else each piece of the runs the Type tool's selection +/// covers, else of every run of every frame of the selected stories. +fn each_style(app: &VectorcraftApp, mut f: impl FnMut(&vectorcraft_doc::TextObject, &vectorcraft_doc::ParaStyle, &CharStyle, bool)) { + let Some(st) = app.session.active() else { + return; + }; let text = |id: NodeId| match st.doc.node(id).map(|n| &n.kind) { Some(NodeKind::Text(t)) => Some(t), _ => None, }; - let mut acc = Shared::None; if let Some((id, a, b)) = text_editing(app) { - let t = text(id)?; + let Some(t) = text(id) else { + return; + }; if b <= a { let para = t.plain_text().get(..a).map_or(0, |s| s.bytes().filter(|&c| c == b'\n').count()); - return f(t, t.para_at(para), &vectorcraft_text::edit::insertion_style(&t.runs, a, b), false); + f(t, t.para_at(para), &vectorcraft_text::edit::insertion_style(&t.runs, a, b), false); + return; } match text_story(app) { // After Select All in threaded text: all the text of every frame of the story. Some(story) => { for t in story.into_iter().filter_map(text) { - each_paragraph_run(t, None, |para, style, inline| acc.add(f(t, para, style, inline))); + each_paragraph_run(t, None, |para, style, inline| f(t, para, style, inline)); } } - None => each_paragraph_run(t, Some((a, b)), |para, style, inline| acc.add(f(t, para, style, inline))), + None => each_paragraph_run(t, Some((a, b)), |para, style, inline| f(t, para, style, inline)), } } else { for t in selected_story_texts(app) { - each_paragraph_run(t, None, |para, style, inline| acc.add(f(t, para, style, inline))); + each_paragraph_run(t, None, |para, style, inline| f(t, para, style, inline)); } } - acc.value().flatten() } /// `f` of the paragraph and style of each piece of `t`'s runs that lies in one paragraph (a diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index f9d9b524c9..244a67ddb8 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -29,7 +29,7 @@ pub const ID: &str = "links"; /// Seconds between two looks at the linked files (they change outside the app). const RECHECK: f64 = 2.0; const SHOW: [(&str, &str); 4] = [("all", "Show All"), ("missing", "Show Missing"), ("modified", "Show Modified"), ("embedded", "Show Embedded")]; -const SORT: [(&str, &str); 3] = [("name", "Sort by Name"), ("kind", "Sort by Kind"), ("status", "Sort by Status")]; +const SORT: [(&str, &str); 4] = [("name", "Sort by Name"), ("kind", "Sort by Kind"), ("status", "Sort by Status"), ("size", "Sort by Size")]; const THUMBS: [(f32, &str); 4] = [(0.0, "No Thumbnails"), (18.0, "Small Thumbnails"), (28.0, "Medium Thumbnails"), (44.0, "Large Thumbnails")]; /// The panel's options (flyout). diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index 5718aea0ab..2d872872ff 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -7,7 +7,7 @@ use serde_json::json; use vectorcraft_doc::{CharStyle, NodeKind}; use vectorcraft_text::{EXTRA_FEATURES, FontDb, OtFeatures, StylisticSet}; -use super::character::{shared, text_editing, text_style}; +use super::character::{any_style, shared, text_editing, text_style}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; @@ -203,7 +203,6 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { widgets::dim_label(ui, tl!("Select text to set its OpenType features.")); return; }; - let cur = OtFeatures::from_tags(st.features.iter().map(String::as_str)); let mut change = None; let fig = shown_figure(app); ui.horizontal(|ui| { @@ -251,7 +250,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); }); }); - if cur.ligatures && vectorcraft_text::ligatures_suppressed_by(st.tracking) && !vectorcraft_text::explicit_ligatures(&st.features) { + if tracking_drops_ligatures(app) { widgets::dim_label(ui, tl!("Ligatures are off while the text is tracked.")); } if let Some(c) = change { @@ -259,6 +258,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Whether tracking turns off the standard ligatures of any character the panel acts on: one with +/// Standard Ligatures on, tracked past [`vectorcraft_text::ligatures_suppressed_by`]'s limit and +/// without an explicit `liga` or `clig` tag ([`vectorcraft_text::explicit_ligatures`]). +fn tracking_drops_ligatures(app: &VectorcraftApp) -> bool { + any_style(app, |s| { + OtFeatures::from_tags(s.features.iter().map(String::as_str)).ligatures + && vectorcraft_text::ligatures_suppressed_by(s.tracking) + && !vectorcraft_text::explicit_ligatures(&s.features) + }) +} + /// The stylistic sets of the font `st` names. A font that is not available offers none, rather than /// the sets of the face drawn in its place. fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec { @@ -303,6 +313,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { #[cfg(test)] mod tests { use serde_json::Value; + use vectorcraft_doc::NodeId; use super::*; @@ -644,6 +655,45 @@ mod tests { ); } + /// With the Selection tool on the first frame of a threaded story, the tracked-ligatures note + /// reads every frame: it shows when a later, locked frame is tracked with Standard Ligatures + /// on, and not once that frame's ligatures are explicit, off, or its tracking is back within + /// the limit. + #[test] + fn ligature_note_reads_every_frame_of_the_story() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 900, "height": 300})).unwrap(); + let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(6); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 60}}); + let a = app.session.execute("text.create", &area).unwrap()["id"].clone(); + let b = app.session.execute("text.thread.add", &json!({"from": a, "rect": [200, 10, 150, 60]})).unwrap()["id"].clone(); + assert!(!run_features(&mut app, &b, 4).is_empty(), "the second frame holds text"); + app.session.execute("text.setStyle", &json!({"ids": [b], "tracking": 100})).unwrap(); + app.session.execute("select.set", &json!({"ids": [b]})).unwrap(); + app.session.execute("object.lock", &json!({})).unwrap(); + app.session.execute("select.set", &json!({"ids": [a]})).unwrap(); + assert_eq!(text_editing(&app), None); + assert_eq!(text_style(&app).unwrap().0.tracking, 0.0, "the panel reads its first run from the first frame"); + assert!(tracking_drops_ligatures(&app), "the tracked second frame shows the note"); + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); + out.textures_delta.clear(); + // Commands write `liga` as the default and leave it out; an opened file can keep it. + let b_id = NodeId(b.as_u64().unwrap()); + for tags in [&["liga"][..], &["clig"][..], &["-liga"][..]] { + let doc = std::sync::Arc::make_mut(&mut app.session.doc_mut().unwrap().doc); + let Some(NodeKind::Text(t)) = doc.node_mut(b_id).map(|n| &mut n.kind) else { panic!("no second frame") }; + for r in &mut t.runs { + r.style.features = tags.iter().map(|s| s.to_string()).collect(); + } + assert!(!tracking_drops_ligatures(&app), "{tags:?}"); + } + app.session.execute("text.setStyle", &json!({"ids": [b], "features": [], "tracking": 20})).unwrap(); + assert!(!tracking_drops_ligatures(&app), "tracking within the limit"); + app.session.execute("text.setStyle", &json!({"ids": [b], "tracking": -100})).unwrap(); + assert!(tracking_drops_ligatures(&app), "tight tracking shows the note too"); + } + /// At a caret whose insertion style is already a denominator, Denominator still reaches the /// characters the command styles at a caret (all of them) in one undo step; chosen again once /// every character has it, it adds no undo step. diff --git a/crates/ui-egui/src/panels/tests_asset_export.rs b/crates/ui-egui/src/panels/tests_asset_export.rs index 82a6f21245..8b9a9ed884 100644 --- a/crates/ui-egui/src/panels/tests_asset_export.rs +++ b/crates/ui-egui/src/panels/tests_asset_export.rs @@ -514,8 +514,7 @@ fn the_preset_menu_saves_changes_and_opens_import_and_export() { #[cfg(not(target_arch = "wasm32"))] #[test] fn export_writes_into_the_picked_folder() { - let dir = std::env::temp_dir().join(format!("vc-asset-panel-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = vectorcraft_testkit::TempDir::new("asset-panel"); let folder = dir.to_string_lossy().replace('\\', "/"); let (mut app, _, [a, _]) = app(false); let picked = folder.clone(); @@ -526,8 +525,179 @@ fn export_writes_into_the_picked_folder() { frame(&ctx, &mut app, vec![], false); let texts = frame(&ctx, &mut app, vec![], false); frame(&ctx, &mut app, click(at(&texts, "Export")), false); - assert!(dir.join("Badge.png").is_file(), "{:?}", std::fs::read_dir(&dir).map(|d| d.count())); + // Create Sub-folders is on by default: the 1x row's folder. + assert!(dir.join("1x").join("Badge.png").is_file(), "{:?}", std::fs::read_dir(&dir).map(|d| d.count())); +} + +/// The panel menu's Create Sub-folders and Open Location after Export are check items, on by +/// default, that change the settings the panel shares with Export for Screens, and the panel's +/// Export follows them. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_menu_sets_create_subfolders_and_open_location_and_export_follows_them() { + let dir = vectorcraft_testkit::TempDir::new("asset-panel-menu"); + let folder = dir.to_string_lossy().replace('\\', "/"); + let (mut app, _, [a, _]) = app(false); + let picked = folder.clone(); + app.services.pick_folder = Some(Box::new(move || Some(picked.clone()))); + let shown = Rc::new(RefCell::new(Vec::::new())); + let s = shown.clone(); + app.services.reveal = Some(Box::new(move |path: &str| { + s.borrow_mut().push(path.to_string()); + Ok(()) + })); + app.run("assets.add", json!({"ids": [a], "name": "Badge"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + let texts = menu_frame(&ctx, &mut app, vec![]); + for item in ["✓ Create Sub-folders", "✓ Open Location after Export", " Format Settings…"] { + assert!(has(&texts, item), "{item}"); + } + // Both on: the 1x row's folder, and the file manager shows the file. + let export = |app: &mut VectorcraftApp| { + frame(&ctx, app, vec![], false); + let texts = frame(&ctx, app, vec![], false); + frame(&ctx, app, click(at(&texts, "Export")), false); + }; + export(&mut app); + assert!(dir.join("1x").join("Badge.png").is_file()); + assert_eq!(shown.borrow().len(), 1); + // Both turned off (a click lands on the items of the frame before). + menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, "✓ Create Sub-folders"))); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, "✓ Open Location after Export"))); + let settings = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); + assert_eq!((&settings["subfolders"], &settings["openLocation"]), (&json!(false), &json!(false)), "{settings}"); + let texts = menu_frame(&ctx, &mut app, vec![]); + assert!(has(&texts, " Create Sub-folders") && has(&texts, " Open Location after Export")); + // Export for Screens opens on the same choices. + app.run("file.exportForScreens", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["subfolders"], &d.fields["openLocation"]), (&json!(false), &json!(false))); + crate::dialogs::cancel(&mut app); let _ = std::fs::remove_dir_all(&dir); + export(&mut app); + assert!(dir.join("Badge.png").is_file() && !dir.join("1x").exists()); + assert_eq!(shown.borrow().len(), 1, "no file manager after export"); + // Create Sub-folders on again: a folder per row. + menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, " Create Sub-folders"))); + let settings = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); + assert_eq!((&settings["subfolders"], &settings["folders"]), (&json!(true), &json!("rows")), "{settings}"); + // Only true and false are taken. + for bad in [json!({"openLocation": "yes"}), json!({"subfolders": 1})] { + assert!(app.run("assets.settings.set", bad.clone()).is_err(), "{bad}"); + } +} + +/// A folder per format, remembered by Export for Screens or a preset, is used by the panel's Export +/// too. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn export_uses_a_remembered_folder_per_format() { + let dir = vectorcraft_testkit::TempDir::new("asset-panel-format"); + let folder = dir.to_string_lossy().replace('\\', "/"); + let (mut app, _, [a, _]) = app(false); + app.services.pick_folder = Some(Box::new(move || Some(folder.clone()))); + let asset = app.run("assets.add", json!({"ids": [a], "name": "Badge"})).unwrap()["assets"][0].clone(); + // An export as Export for Screens sends it with Create Sub-folders by Format, which the + // document remembers. + let formats = json!([{"format": "png"}, {"format": "svg"}]); + app.run("document.exportForScreens", json!({"assets": [asset], "formats": formats, "folders": "format", "subfolders": false})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + assert!(has(&menu_frame(&ctx, &mut app, vec![]), "✓ Create Sub-folders")); + frame(&ctx, &mut app, vec![], false); + let texts = frame(&ctx, &mut app, vec![], false); + frame(&ctx, &mut app, click(at(&texts, "Export")), false); + assert!(dir.join("png").join("Badge.png").is_file() && dir.join("svg").join("Badge.svg").is_file()); +} + +/// Remembered empty folders are none, as an export reads them: Create Sub-folders is off in the +/// panel menu and in Export for Screens. +#[test] +fn empty_remembered_folders_are_create_subfolders_off() { + let (mut app, _, [a, _]) = app(true); + let asset = app.run("assets.add", json!({"ids": [a]})).unwrap()["assets"][0].clone(); + app.run("document.exportForScreens", json!({"assets": [asset], "formats": [{"format": "svg"}], "folders": "", "subfolders": true})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + assert!(has(&menu_frame(&ctx, &mut app, vec![]), " Create Sub-folders")); + app.run("file.exportForScreens", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["subfolders"], false); +} + +/// Open Location after Export turned off in a document without settings leaves Create Sub-folders +/// on, in the panel menu and in Export for Screens. +#[test] +fn open_location_off_leaves_create_subfolders_on() { + let (mut app, _, _) = app(false); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, "✓ Open Location after Export"))); + let texts = menu_frame(&ctx, &mut app, vec![]); + assert!(has(&texts, "✓ Create Sub-folders") && has(&texts, " Open Location after Export")); + app.run("file.exportForScreens", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((&d.fields["subfolders"], &d.fields["openLocation"]), (&json!(true), &json!(false))); +} + +/// Editing the rows of a document without a Create Sub-folders choice keeps it on, in Export for +/// Screens too; a preset that turns it off shows it off, and the menu turns it on again. +#[test] +fn row_edits_keep_create_subfolders_on_and_a_preset_can_turn_it_off() { + let (mut app, _, [a, _]) = app(true); + app.run("assets.add", json!({"ids": [a]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&ctx, &mut app, vec![], false); + let texts = frame(&ctx, &mut app, vec![], false); + frame(&ctx, &mut app, click(at(&texts, "+ Add Scale")), false); + assert!(has(&menu_frame(&ctx, &mut app, vec![]), "✓ Create Sub-folders")); + app.run("file.exportForScreens", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["subfolders"], true); + crate::dialogs::cancel(&mut app); + // Logo Package sorts by format: checked, as in Export for Screens. Turned off, the sorting + // ends; turned on again, a folder per row. + app.run("assets.settings.set", json!({"exportPreset": "Logo Package"})).unwrap(); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, "✓ Create Sub-folders"))); + let settings = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); + assert_eq!((&settings["subfolders"], &settings["folders"]), (&json!(false), &json!("none")), "{settings}"); + app.run("file.exportForScreens", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["subfolders"], false); + crate::dialogs::cancel(&mut app); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, " Create Sub-folders"))); + let settings = app.run("document.exportSettings", json!({})).unwrap()["settings"].clone(); + assert_eq!((&settings["subfolders"], &settings["folders"]), (&json!(true), &json!("rows")), "{settings}"); + let texts = menu_frame(&ctx, &mut app, vec![]); + assert!(has(&texts, "✓ Create Sub-folders")); + // The web downloads the files: the menu has no Open Location after Export. + assert!(!texts.iter().any(|(t, _)| t.ends_with("Open Location after Export"))); +} + +/// Format Settings… in the panel menu opens Export for Screens on its Assets tab, showing the +/// first row's format settings. +#[test] +fn format_settings_opens_the_first_rows_format_settings() { + let (mut app, _, [a, b]) = app(true); + app.run("assets.add", json!({"ids": [a, b], "multiple": true})).unwrap(); + app.run("assets.settings.set", json!({"formats": [{"format": "jpeg"}, {"format": "svg"}]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + menu_frame(&ctx, &mut app, vec![]); + let texts = menu_frame(&ctx, &mut app, vec![]); + menu_frame(&ctx, &mut app, click(at(&texts, " Format Settings…"))); + let d = app.ui.dialog.as_ref().expect("Export for Screens"); + assert_eq!((d.kind.as_str(), &d.fields["tab"], &d.fields["__settings"]), (crate::dialogs::EXPORT_FOR_SCREENS, &json!("assets"), &json!("jpg"))); + assert_eq!(d.fields["assets"].as_array().map(Vec::len), Some(2)); } #[test] @@ -716,8 +886,7 @@ fn tiff_panel_preserves_shared_antialias_and_explicit_overrides() { #[cfg(not(target_arch = "wasm32"))] #[test] fn tiff_saved_aliases_use_document_defaults_and_explicit_rgb() { - let dir = std::env::temp_dir().join(format!("vc-asset-tiff-aliases-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = vectorcraft_testkit::TempDir::new("asset-tiff-aliases"); // The first case is the historical control: saved tif without an explicit model must be CMYK. // Native picked folders let the mixed-row case inspect each file without introducing a ZIP decoder. for (case, (alias, rgb_override, mixed)) in @@ -764,7 +933,6 @@ fn tiff_saved_aliases_use_document_defaults_and_explicit_rgb() { "direct export preserves saved aliases and explicit options" ); } - let _ = std::fs::remove_dir_all(&dir); } /// Export 3D Object in the panel menu collects the selected 3D object; its tile is marked 3D, the diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 6b773e9d3b..8b3e065a64 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -90,8 +90,16 @@ fn the_panel_lists_the_images_with_link_info_for_the_selected_one() { assert!(text.contains("Linked") && text.contains("300 × 200 px") && text.contains("Location"), "{text}"); // The flyout draws with every item. let menu = painted_text(&mut app, super::links::menu); - for item in ["Relink to Folder…", "Embed Image(s)", "Placement Options…", "Show Missing", "Sort by Status", "Large Thumbnails", "Show in Folder"] - { + for item in [ + "Relink to Folder…", + "Embed Image(s)", + "Placement Options…", + "Show Missing", + "Sort by Status", + "Sort by Size", + "Large Thumbnails", + "Show in Folder", + ] { assert!(menu.contains(item), "{item}: {menu}"); } } diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 92a1ab9768..10ed4efa13 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -297,8 +297,8 @@ fn a_shortcut_runs_what_its_menu_item_runs() { /// Vector Halftone, Rearrange All Artboards, Pathfinder Options, the Object › Plug-ins dialogs /// (Arrange in Grid, Replace with Top Object, the size, opacity and sort dialogs of the Arrange /// add-on, Set Corners…, Divide into Dashes, Find Nearest Swatch, the swatch legend, the type -/// tools, the select add-on and Select by Link Status…), four "…" items whose menu entry gives -/// params, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset +/// tools, the select add-on and Select by Link Status…), three "…" items whose menu entry gives +/// params, Smart Punctuation…, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset /// dialogs and Apply SVG Filter…. const MENU_DIALOG_COMMANDS: [&str; 39] = [ "object.path.smooth", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 80a87b4563..b28e4034a7 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -788,6 +788,9 @@ pub struct UiState { /// dialog opens on them (#1152). #[serde(default)] pub offset_path: Value, + /// The Smart Punctuation fields confirmed last (null: never used): its dialog opens on them. + #[serde(default)] + pub smart_punctuation: Value, /// The Average & Join fields confirmed last (`to`; null: never used): its dialog opens on them. #[serde(default)] pub average_join: Value, @@ -1226,6 +1229,7 @@ impl Default for UiState { dxf_options: Value::Null, eps_options: Value::Null, offset_path: Value::Null, + smart_punctuation: Value::Null, average_join: Value::Null, recolor_preserve: Value::Null, simplify: Value::Null, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cc52d58ed7..f08e3a010d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -122,7 +122,7 @@ the two can still win that race. | Native file dialogs | any command with no `path` that needs one (`file.open`, `file.saveAs`, `file.place`, exports…) | on macOS (a sheet on the window) and Linux the dialog doesn't hold the window: the call returns `"cancelled"` at once, `ui.inspect` reports `fileDialog`, and when the person at the computer picks a file the command runs again on the document it was asked for. While it is open another dialog is refused: that call returns `"cancelled"` too, and the status bar (`ui.inspect` → `ui.status`) says `"A file dialog is open: choose there first"`; on macOS `app.quit`, `file.close` and `file.closeAll` return that message and the menu bar does nothing (#592, #867). On Windows the dialog is shown in line: the call returns once it closes. Pass `path` to skip the dialog | | Background Save / Export | `app.save`, `app.export {path}`, `file.save`, `file.saveAs`, `file.saveCopy`, `file.exportForScreens {folder, …}` | with the `backgroundSave` / `backgroundExport` preferences on (the default) the desktop app writes the file from a snapshot on a worker thread: the call returns `{path, background: true, status}` at once (`file.exportForScreens`: `{background: true, status}`, and the files are written into the folder from a snapshot taken at the call; an `app.export` given an option the format doesn't read: also `warnings`, naming the option), `ui.inspect` lists the jobs still running in `background` (labels such as `"Saving a.vectorcraft"`), and the document counts as saved (as of the snapshot) once its file is written. Quit and Close wait for them. A job that fails reports the error in the status bar only (`ui.inspect` → `ui.status`), a path outside `--automation-write-root` included. With the preferences off (`prefs.set`), saves return once written. `app.save {path?, wait: true}` and `app.export {path, wait: true}` wait for the jobs already running, write the file before they reply whatever the preferences are set to, and return its result or the error. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the preferences. A `wait` that is not `true`, `false` or `null` is refused with "`wait` must be true or false", and nothing is written | | `engine.execute` `file.exportForScreens` | `{}` / `{…document.exportForScreens params}` | without params opens `exportForScreens` on the settings the document last exported with (`document.exportSettings`). While the Artboard tool is in use, the artboards it has selected (its `selected` option, the rows the Artboards panel highlights) are checked instead, and `select` is `range`, or `all` when every artboard is selected. Fields: `tab` (`artboards` \| `assets` \| `layers` \| `selection`; OK reads Export Layer or Export Selection on those), `layers` ([layer id…] checked), `selectionMode` (`one` \| `each`), `name` (the file name pattern of `document.exportForScreens`), `counterStart`, `folders` (`none` \| `rows` \| `format` \| `item` \| `itemFormat`), `exportPreset` (the preset applied last), `__savePreset` (the name typed to save one), `select` (`all` \| `range` \| `full`), `range` ("1-3, 5"), `boards` (a bool per artboard; checking them sets `select` and `range`), `includeBleed`, `folder` (desktop; default the Desktop, else home), `openLocation`, `subfolders`, `prefix`, `preset` (`""` \| `mobile` \| `density`), `formats` (rows `{format, scale: "2x" \| "100w" \| "100h" \| "72ppi", suffix, quality?, folder?}`), `settings` (`{png \| png8 \| jpg \| webp \| gif \| svg \| pdf: {…options}}`, the gear's Format Settings; `__settings` names the format shown). `ui.dialog.confirm` exports (a bad range or no folder keeps it open); on the web OK reads "Download" and the files download (several as one `.zip`). With params it runs `document.exportForScreens`: no `folder` returns the files (or with `zip: true` one zip) as `dataBase64`; with `openLocation` the first file is shown in the file manager. When `warnings` is not empty, an export into a folder or a download shows the first in the status bar as Save As shows a save's notes | -| Export for Screens' Assets tab, Asset Export panel | `ui.dialog.set` `tab: "assets"`, `assets: [asset id…]`; `window.panel {panel: "assetExport"}` | on the Assets tab of `exportForScreens` the `assets` field lists the checked asset ids (all of them when it opens); `ui.dialog.confirm` runs `document.exportForScreens {assets}` (nothing checked keeps it open) and OK reads "Export Asset". The Asset Export panel acts through `assets.*` and shares the format rows with the dialog (`assets.settings.set`). The dialog has the format presets menu (☰). In the dialog, `exportPreset` names the preset applied last (`ui.dialog.set` of it applies the preset it names, as picking it does; a name that is not a preset's is an error and leaves the dialog as it was), `__exportPresets` lists the presets, and `__savePreset` holds the name being typed after Save Preset…. The panel menu applies presets through `assets.settings.set {exportPreset}` and holds Save As Preset…, Save Changes, Delete Preset, Import Preset… and Export Preset…. Import and Export use picked files. | +| Export for Screens' Assets tab, Asset Export panel | `ui.dialog.set` `tab: "assets"`, `assets: [asset id…]`; `window.panel {panel: "assetExport"}` | on the Assets tab of `exportForScreens` the `assets` field lists the checked asset ids (all of them when it opens); `ui.dialog.confirm` runs `document.exportForScreens {assets}` (nothing checked keeps it open) and OK reads "Export Asset". The Asset Export panel acts through `assets.*` and shares the format rows with the dialog (`assets.settings.set`). The dialog has the format presets menu (☰). In the dialog, `exportPreset` names the preset applied last (`ui.dialog.set` of it applies the preset it names, as picking it does; a name that is not a preset's is an error and leaves the dialog as it was), `__exportPresets` lists the presets, and `__savePreset` holds the name being typed after Save Preset…. The panel menu applies presets through `assets.settings.set {exportPreset}` and holds Save As Preset…, Save Changes, Delete Preset, Import Preset… and Export Preset…. Import and Export use picked files. Its Create Sub-folders and Open Location after Export run `assets.settings.set {subfolders}` and `{openLocation}`; its Format Settings… opens the dialog on the Assets tab with `__settings` set to the first row's format. | | `engine.execute` `file.exportSelection` | `{multiple?}` | File › Export Selection…: collects the selected objects as one asset (`assets.add`; one per object with `multiple: true`) and opens `exportForScreens` on its Assets tab with just them checked → `{assets}`. `document.exportSelection` with params still exports the selection in one go, without the dialog; with no params or `{}` the save panel picks the file and its format's options dialog follows, as after Export As, and the call returns `null` while the dialog is open (OK returns what `file.exportAs` returns, without `format` or `bounds`). `file.exportAs {path, exportSelection: true, …options}` writes the selection without a dialog | | CSS Properties panel | `window.panel {panel: "cssProperties"}`; `engine.execute` `css.copy` / `css.exportFile` | the panel shows `css.selection` of the selection (after Generate CSS, while nothing is selected, `css.generate`); its menu holds the options the commands take (`units`, `position`, `dimensions`, `unnamed`, `rasterize`). `css.copy {scope?, …options}` copies the CSS to the clipboard → `{css, rules}`; `css.exportFile {path?, scope?, …options}` writes `css.export` to `path` (else a picked file; the web downloads it) with the pictures of rasterized art next to it → `{path, rules, images, warnings}`, and the status bar shows `warnings` as Export As shows an export's notes | diff --git a/docs/development.md b/docs/development.md index 846d2c02d8..7c22d6ae98 100644 --- a/docs/development.md +++ b/docs/development.md @@ -297,7 +297,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE placeholders are translated in turn (the reason after `: {e}` is often a message too). A literal brace in a row is written `{{` or `}}`, in the English and in the translation: a message made with `format!` keeps the doubled braces of its format string, and a plain string literal has each of its braces doubled, so the row for - `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan and Dutch + `"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch and Danish translate status and error messages (`COMPLETE_MESSAGES` in `i18n::tests`); the untranslated report lists the message literals the scan finds, and the phrases a parameter schema's error builds at run time (`SCHEMA_PHRASES`), that one of them has no row for. The scan covers the crates in `MESSAGE_CRATES`, the diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0e0d2ced4e..bf52925f5c 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -281,7 +281,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | +| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 20311a5182..1fededbc4e 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -15,7 +15,7 @@ translation never fails a test or a build: the interface shows the English text `cargo xtask ci` prints the untranslated report (`cargo xtask i18n-report` alone), which lists per language the strings missing from each catalog with the `complete_menus` flag and the messages missing from each language in the `COMPLETE_MESSAGES` list. Every non-English language marked "full" has the flag, and all of them except -Bosnian, Bulgarian, Danish and Indonesian are in the list. No language has help content: there is no translated (or +Bosnian, Bulgarian and Indonesian are in the list. No language has help content: there is no translated (or English) in-app help, and the docs are English. **Native review:** every catalog was written clean-room from the English meaning, most of it by agents @@ -55,7 +55,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Traditional Chinese (Taiwan) | `zh-hant` | 8,820 rows, 3,438 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 40 missing messages for it; menus, `tl!` literals and messages were complete when counted on 2026-10-21 (80% overall) | partial | | Italian | `it` | 8,924 rows, 3,560 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 54 missing messages for it, which open #7116, #7211, #7378 and #7405 translate | full | | Dutch | `nl` | 3,447 `@msg` and 48 `@msgplural` rows (counted 2026-11-13): in `COMPLETE_MESSAGES`, and the untranslated report lists 41 missing messages for it; one/other plurals | full | -| Danish | `da` | 5,279 rows, 750 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial; one/other plurals | full | +| Danish | `da` | 7,422 rows, 1,636 of them `@msg` and 48 `@msgplural` (counted 2026-11-14 on `main` at `edb228ac3`): in `COMPLETE_MESSAGES`, and the untranslated report lists the same missing messages for it as for Greek, Spanish and Finnish; one/other plurals | full | | Russian | `ru` | 4,009 / 4,020 | full | | Ukrainian | `uk` | 8,802 rows, 3,439 of them `@msg` and 48 `@msgplural` (counted 2026-11-13); one/few/many plurals | full | | Hungarian | `hu` | 9,166 rows, 3,444 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 40 missing messages for it, and lists 47 menu strings, 25 `tl!` strings, 11 undo labels and 45 swatch names without a row; one plural form | full | diff --git a/docs/mcp.md b/docs/mcp.md index cf41f3aaab..f7606a5b11 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # VectorCraft MCP server -> **Last updated:** 2026-11-14 · **Change:** Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. +> **Last updated:** 2026-11-14 · **Change:** Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. `vectorcraft-cli mcp` runs a [Model Context Protocol](https://modelcontextprotocol.io) server on stdio (newline-delimited JSON-RPC 2.0; see [Protocol](#protocol) for version negotiation). Agents use it to @@ -666,7 +666,7 @@ sampler. | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | -| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. | +| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | For example, create editable Japanese area type with the engine's vertical writing mode: @@ -813,10 +813,18 @@ 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. +`transparency.set` and `object.setProps` with an opacity, blend mode, isolation, knockout or knockout shape for the +object, given a series group's id or the selected series group, set them on the group itself, and the graph stores them +for that series. The series group has them again when the graph is drawn again, and they apply to the group as a whole +in addition to each path's own opacity and blend mode. `addon.arrange.randomizeOpacity` and `addon.arrange.sort` with +`apply: "opacity"` given a series group, and Global Edit when a series group takes an edit from another match, store +what they change on the group the same way. Each of the commands above that clears the group's own opacity, blend mode, isolation +and knockout also removes what the graph stores for it. + 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 `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 graph draws the art of a column or marker design in a series again from the design, so the commands that add, change, move or remove fill and stroke rows, effects or graphic styles leave that art out: the `appearance.*` commands @@ -868,6 +876,13 @@ kind takes them when the graph is drawn again. The graph saves the paragraph att `categoriesPara` and `legendPara` in its label styles, and still sets each label's alignment for its place. The legend leaves room for a legend label's stored indents, spacing and leading. +When a graph is drawn again, its plot moves and scales with any move or scale of the graph made since it was last +drawn. The graph saves the bounds of its art other than type as `placedArt` (and the bounds of all of its art as +`placed`), and measures the move or scale on those. Changing the size, indents or spacing of the labels, moving a label +on its own and `type.createOutlines` on labels do not move or scale the plot. A graph opened from a `.ai` file saves +`placedArt` too. A graph saved without `placedArt`, or with a `placedArt` that has no width or height, is measured on +`placed`. + The `appearance.*` commands, `graphicStyle.apply` and `graphicStyle.redefine`, and the paint, stroke, gradient and transparency commands given an `item` (or the Appearance panel's active row) store a graph label's object rows for its kind of label: the paint, weight, opacity and blend mode of its topmost visible fill and stroke row, their order and @@ -1257,6 +1272,15 @@ empty `boxes`, and `thumbnail: 1` shows what that page prints. A page whose `Use opens at its size in points, the file's numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size. +`linkPages: true` (File › Open's Import PDF dialog: Import PDF pages as links) opens each page `pages` picks as a +placed document linked to that page of the file, as `file.place` with `link` places one, instead of as editable art. +Each page gets an artboard of its `cropTo` box (`bounding`: its art's bounds), in a row from the left 36 pt apart, and +a layer named after the page (`Page 2`). The document opens in CMYK when most of those pages are painted mostly in +CMYK, unless `colorMode` names a mode. All the pages' objects share one copy of the file. The Links panel lists each +page, and `links.embed` makes a page editable art. +`document.open` refuses `linkPages` for a file that is not a PDF or a PDF-compatible `.ai`, for a file given as +`dataBase64` without a path, with a `password`, and with `textAs: "outlines"`, and rejects a `linkPages` that is not +true or false. Save then asks for a name. `document.open`, `file.place` and `document.pdfInfo` reject a `cropTo`, `crop`, `password`, `colorMode` or `textAs` that is not a string, and `document.pdfInfo` rejects a `thumbnailSize` that is not a number. The error names the param, and nothing opens or is placed. Leaving a param out or giving null keeps its default. @@ -1272,6 +1296,7 @@ CMYK too. ```json {"name":"run_command","arguments":{"command":"document.pdfInfo","params":{"path":"/tmp/brochure.pdf","thumbnail":2,"cropTo":"trim"}}} {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/brochure.pdf","pages":"2-3","cropTo":"trim"}}} +{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/brochure.pdf","linkPages":true}}} ``` PostScript files (`.eps`, `.epsf`, `.ps`, and `.ai` files saved in older formats or without PDF compatibility) open through the EPS @@ -6310,9 +6335,11 @@ snap the pointer as drawing tools do, so dragging a corner onto another object's ``` Every point a drawing tool places snaps the same way, through one snapper (#506): the Pen's and Curvature tool's -anchors, the Pencil's first and last point, the shape tools' start and dragged corner or radius (`rectangle`, +anchors, the shape tools' start and dragged corner or radius (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, `arc`, `spiral`, `rectangularGrid`, `polarGrid`), the -Type tool's click and frame, and a new artboard's corners. The point lands on another object's anchor, centre or +Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and +shows no Smart Guides: its strokes and straight lines follow the hand (Snap to Grid and Snap to Pixel still move +their ends). The point lands on another object's anchor, centre or path ("anchor", "center", "path"), else lines up with the anchors, edges and centres of the art and the artboards (a line from the target and "align"); the Pen's lands on the path being drawn too, so a click on its first anchor closes it exactly. With `mods.shift` the point keeps to its 45° step from the anchor before it (from `constrainAngle`; a box @@ -7493,8 +7520,10 @@ listed in `warnings`. ASCII and binary DXF files are read; DWG files answer an e ## Links panel -`links.list {show?: all|missing|modified|embedded, sort?: name|kind|status}` lists every image in the layers, top -first, as the Links panel does, then every image and placed document in opacity-mask art and in the art of symbols, +`links.list {show?: all|missing|modified|embedded, sort?: name|kind|status|size}` lists every image in the layers, top +first, as the Links panel does (`sort: "size"`, the panel menu's Sort by Size, puts the smallest file first by the +size Link Info shows; rows without one, embedded images and missing files whose size is not kept, come last, and equal +sizes go by name), then every image and placed document in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes, one row per stored object (never one per symbol instance, pattern tile or brushed stroke): `{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?, page?, preview?, note?, owner?}` (`owner`, for an object outside the layer tree: @@ -8075,7 +8104,12 @@ moving the art moves the crop, and deleting it removes it from its asset (an ass format row of the document's export settings, the ones Export for Screens remembers (`document.exportSettings`); any `formats`, `preset`, `settings`, `prefix` or `subfolders` given win for that export. `assets.settings.set` changes those shared settings (not an undo step); its `subfolders: true` sets Export for Screens' Folders to a folder per row, -and `subfolders: false` sets a folder per row back to All in One Folder. `document.exportForScreens {assets: [id…]}` does the same with its own params +and `subfolders: false` sets a folder per row (without `exportPreset`, also a folder per format or item) back to All +in One Folder. Its `openLocation: true|false` +is Open Location after Export, kept in `document.exportSettings` (not in presets). The panel menu's Create Sub-folders and +Open Location after Export run these two (sub-folders sort the pictures; `assets.export3D` writes mesh files in the +folder itself), and its Format Settings… opens Export for Screens on the first row's format +settings. `document.exportForScreens {assets: [id…]}` does the same with its own params (the dialog's Assets tab). An asset's crop, and the crop of `export` with `selection: true`, is the bounds the renderer measures for what the art draws, its effects included. @@ -8675,6 +8709,34 @@ on again. {"name":"run_command","arguments":{"command":"type.convertToAreaType","params":{"ids":[42]}}} ``` +## Smart Punctuation + +`type.smartPunctuation` replaces keyboard characters in the selected type, or in every text object with `scope: +"document"` or nothing selected, in one undo step. Each option is a switch: + +- `fiLigatures` (default `false`): ff, fi and ffi become the ligature characters U+FB00, U+FB01 and U+FB03. +- `flLigatures` (default `false`): ff, fl and ffl become U+FB00, U+FB02 and U+FB04. The longest match is taken first. +- `quotes` (default `true`): straight quotes become the Document Setup quotes. +- `spaces` (default `false`): two or more spaces after a period become one. +- `dashes` (default `true`): `--` becomes an en dash and `---` an em dash. +- `ellipsis` (default `true`): `...` becomes an ellipsis. +- `fractions` (default `false`): 1/2, 1/4, 3/4 and the other fractions Unicode encodes as one character (thirds, + fifths, sixths, sevenths, eighths, ninths and 1/10) become that character. A fraction with a digit of any script, a + slash or a decimal point next to it, as in 1/25, 1/2/26 or 1/2.5, is left as it is, also when a change of style falls + inside it. An inline graphic separates the text before it from the text after it, for this option and for `spaces`. + +A ligature or a fraction is written only where the run's font has a glyph for it; elsewhere the letters stay. Ruby +stays on the characters it was set on, and no replacement joins characters on both sides of a ruby span's end. A value +other than true, false or null is refused. The reply gives the number of text objects changed and how many of each +replacement were made; with nothing to replace, no undo step is recorded. Type › Smart Punctuation… opens a dialog with +these options, Replace In (Selected Text Only or Entire Document) and Report Results, which lists the count of each +chosen replacement after OK. The dialog opens on the options confirmed last. + +```json +{"name":"run_command","arguments":{"command":"type.smartPunctuation","params":{"fiLigatures":true,"spaces":true,"fractions":true}}} +→ {"changed": 1, "replaced": {"fiLigatures": 2, "flLigatures": 0, "quotes": 1, "spaces": 1, "dashes": 0, "ellipses": 0, "fractions": 2}} +``` + ## Hyphenation options `text.setFormat` sets the Paragraph panel menu's Hyphenation… options of the selected type (or `ids`, or the @@ -9257,9 +9319,8 @@ the type it changed, how many paragraphs were `converted`, and the characters `i Type tool edits, `text.convertListToText` ends its typing first and moves its anchor and caret past the characters inserted at or before them, whether the call comes from the menu, MCP or the control channel. After Select All in a frame of threaded text, a call without `ids`, `id`, `start` or `end` converts every paragraph of -the story's frames that are neither locked nor hidden. While the story is selected, its locked and hidden frames are -not converted, even when `ids` names them, and neither is a paragraph whose text starts in one. When the call converts -all of its other frames, the whole story stays selected. +every frame of the story, locked and hidden frames included. `ids` naming a locked or hidden frame converts its +paragraphs too. When the call converts every frame of the story, the whole story stays selected. In threaded type, when the caret's character moved to another frame, the Type tool edits that frame with the caret next to the same character, and that frame becomes the selection when it was not selected. @@ -10204,7 +10265,8 @@ A canvas-click dialog also has `preview` (initially on): tentative settings draw ``` The Shape Builder tool's options are its Shape Builder Tool Options (dialog `shapeBuilderOptions`): -`openFilledAsClosed` (on: a filled open path bounds a region as if an invisible edge closed it; off: it cuts regions +`openFilledAsClosed` (on: a filled open path bounds a region as if an invisible edge closed it; a path counts as +filled when any of its fill rows is shown, painted and above 0% opacity, whichever row is on top; off: it cuts regions as an unfilled path does), `pickColorFrom` (`artwork`, the default: a merged shape takes the appearance, opacity and blending mode of the front-most selected object under the drag's first point, else of the one under its last point, else of the front-most selected object; `swatches`: the current fill, and the Left and Right arrow keys without @@ -10312,9 +10374,30 @@ or of a plane widget, cancels it and puts the grid back. The Plane Switching Wid of the document window (headless: the first artboard's top-left corner); a press on it picks the plane with any tool while the grid shows (choosing a perspective tool shows it, and `perspective.grid.show` hides it again with the tool still chosen), and the keys 1–4 (`key` with `"1"`…`"4"`) pick the left, horizontal, right and no plane. -`perspective.widget.options {show?, position?}` (Perspective Grid Options, double-click the tool) hides it or moves -it to `topLeft`, `topRight`, `bottomLeft` or `bottomRight`, kept with the preferences (`prefs.get`/`prefs.set` key -`perspectiveWidget`). +`perspective.widget.options {show?, position?, anchorPoint?, gridlineIntersection?}` (Perspective Grid Options, +double-click the tool) hides it or moves it to `topLeft`, `topRight`, `bottomLeft` or `bottomRight`, and turns the +two targets of Automatic Plane Positioning on or off (`anchorPoint`: Anchor Point of Perspective Artwork; +`gridlineIntersection`: Intersection of Gridlines; both on by default). The options are kept with the preferences +(`prefs.get`/`prefs.set` key `perspectiveWidget`), and a value that is not `true` or `false` is an error. + +Automatic Plane Positioning: `perspective.plane.infer {at?: [x, y], tolerance?, clear?}` moves the active plane +through the anchor point of shown art in perspective, or the gridline intersection of a plane that shows, within +`tolerance` points of `at` (6 by default), for now, and hides the other planes. An anchor point within reach wins +over an intersection. With the Perspective Selection tool, `pointer` `move` with Shift over one does the same, +within 6 screen pixels; with a button down, Shift constrains the move as before. `perspective.plane.set` then brings +the plane it makes active through the same point. The plane goes back to its place, and the other planes show +again, when an object is drawn on it or attached to it (`perspective.draw`, `perspective.attach`, or an object +brought into perspective by `perspective.move` or `perspective.transform`; a drag keeps the plane held until it is +committed), when `perspective.plane.matchObject` moves a plane, when the grid hides, when no plane is active, when +the file is opened again, and with `clear` (Escape with the Perspective Selection tool). `perspective.plane.move` +moves the held plane from where it is held and leaves it at its new place, and the other planes show again. +The held point is view state, not an undo step: `perspective.grid.get` reports it as `grid.inferred` (x, y and z +in the grid's frame). `perspective.grid.set`, `perspective.grid.define` and `perspective.grid.preset` keep it +unless the grid they make hides, has no active plane, or would put the plane through the point behind the viewer. +Without params the command reads the state: +`{active, plane, offset, point?, source?: anchor|gridline}`. With `at`, `source` is absent when nothing was within +reach, and the grid stays as it was. It is an error when the grid is hidden, when no plane is active, when both +targets are off, and when `at`, `tolerance` or `clear` is not what the params take. ## Envelopes @@ -10600,9 +10683,9 @@ How blends interpolate: closed shapes start where they twist least unless `start interpolate weight, dashes (a solid stroke counts as the dashed one with its gaps closed), miter limit, arrowhead scale, width profiles and the pen pressure, tilt, bearing and rotation recorded with the Paintbrush (a stroke without a recording counts as half pressure, half tilt and 0°, as brushes read it; angles turn the shorter way round; a key's -profiles, recordings and arrowheads turn with its path when the blend starts it at another anchor), while -caps, joins, alignment, arrowheads and brushes switch halfway; gradients of one kind with -different stop counts resample to a common set of stops. Groups pair their members in stacking order (members only +profiles, recordings, arrowheads, dashes and gradient along or across the stroke turn with its path when the blend +starts it at another anchor), while caps, joins, alignment, arrowheads and brushes switch halfway; gradients of one +kind with different stop counts resample to a common set of stops, keeping each step (two stops at one offset). Groups pair their members in stacking order (members only one group has grow out of the other's centre), compound paths stay compound paths, and type, symbol instances and images interpolate their transforms (type also its colours, stroke weight and size run by run; the words and the symbol switch halfway). New blends are knockout groups (`object.setProps {knockout}` changes it), drawn on the @@ -10981,7 +11064,8 @@ lands where it was drawn. place and paint. Returns `{id, joined, lines}`. - `addon.cleanup.removeBreaks {kind, ids?}` removes the forced line breaks (`kind: "line"`) or paragraph returns (`"paragraph"`) in the characters selected with a Type tool, else in all the text of the selected type. After - Select All in a frame of threaded text, it removes them from the text of every frame of the story, as one undo step. + Select All in a frame of threaded text, it removes them from the text of every frame of the story, locked and hidden + frames included, as one undo step. A break between two words becomes a space; merged paragraphs take the first one's paragraph style. The frames of a threaded story, selected all together or through Select All, are read as one text, so a break at the end of one frame before a word in the next one also becomes a space. @@ -11354,8 +11438,8 @@ A `configure` call that changes no shape records no undo step and returns `{upda ## Cutting Tools add-on Cutting Tools is a built-in add-on that prepares art for cutting. Its commands are `addon.cutting.bridges`, -`addon.cutting.weed` and `addon.cutting.banner`; in the desktop app they are Object › Plug-ins › Cutting Tools › Stencil -Bridges…, Weed Box and Lines… and Banner Hems and Grommets…. +`addon.cutting.weed`, `addon.cutting.banner` and `addon.cutting.nest`; in the desktop app they are Object › Plug-ins › +Cutting Tools › Stencil Bridges…, Weed Box and Lines…, Banner Hems and Grommets… and Nest Shapes…. ### Stencil Bridges @@ -11476,6 +11560,39 @@ Banner Hems and Grommets… opens the command dialog with Preview. {"name":"run_command","arguments":{"command":"addon.cutting.banner","params":{"hem":"1 in","grommetInset":"0.5 in","spacing":"2 ft"}}} ``` +### Nest Shapes + +`addon.cutting.nest {roll?, width?, height?, margin?, spacing?, rotate?, usePreviewBounds?, artboard?, patterns?}` moves +the selected objects close together onto a sheet or a roll of material +([packing problems](https://en.wikipedia.org/wiki/Packing_problems)). The ranges, defaults and rules below are +VectorCraft's own. The sheet starts at the top-left corner of artboard `artboard` (0-based; by default the artboard +under the center of the selection, else the first). It is `width` × `height` points (0 to 1000000 each; 0, the default, +takes the artboard's width or height). With `roll` true it is a roll `width` wide with no end, and `height` is not used. +`margin` (0 to 100000, default 18) is kept clear inside each edge of the sheet; on a roll, inside the sides and the +start. `spacing` (0 to 100000, default 9) is kept between two objects. + +Each selected object is packed by its bounding box: with its strokes and effects, including the reach of shadows, glows +and blurs, when `usePreviewBounds` is true (the default), else by its geometry. A group is one object. The tallest +objects go first, each where its bottom edge is highest and then furthest left. With `rotate` true (false by default), +an object may turn 90° clockwise where that puts its bottom edge higher, or where only the turned object fits; the +longest side then decides the order, and a turned object is measured as it is after the turn. A path of a +pixel-aligned compound path is not turned. Objects are moved, and turned with `rotate`, never resized. An object on the +pixel grid moves by whole points and takes 1 pt more room across and down. Objects that do not fit go in a column to +the right of the sheet, from its top, `spacing` from its edge and from each other, in stacking order (back to front). +Objects without bounds, such as an empty group, are not moved. `patterns` moves pattern fills and strokes with the art +(default: General › Transform Pattern Tiles). + +All of it is one undo step, and nothing changes when no object moves. The command fails when nothing selected can be +measured, when the margin leaves no room on the sheet, when no selected object fits, with more than 10000 objects +selected, and with bad params. Result: `{placed, unplaced, rotated, skipped, length}`: the number of objects placed, +the ids of the objects put beside the sheet, the ids of the objects turned, the ids of the objects without bounds, and +the length of material used in points, from the sheet's top edge to the margin below the lowest object placed. Nest +Shapes… opens the command dialog with Preview. + +```json +{"name":"run_command","arguments":{"command":"addon.cutting.nest","params":{"roll":true,"width":"24 in","margin":"0.25 in","spacing":"0.125 in","rotate":true}}} +``` + ## Color Effects add-on Color Effects is a built-in add-on: its effects are colour adjustments in Effect › Color Effects, its command is @@ -11946,6 +12063,7 @@ the error text. The interactive fallback applies only to ordinary File > Save, n | Date | Change | |---|---| +| 2026-11-13 | The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides; Snap to Grid and Snap to Pixel still move its ends (#7252). | | 2026-11-13 | `path.freehand`: `closed`, when given, decides whether a stroke that continues a path (`extend`) closes it; the Pencil and the Paintbrush send it by Close Paths When Ends Are Within. | | 2026-11-13 | Snap to Point with Smart Guides off draws no Smart Guides labels or lines (#7250). | | 2026-11-13 | Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097). | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d34503fdc5..2d279f9acc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** minor (Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-14 · **Change:** minor (Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -46,6 +46,7 @@ The shared assessment status line and revision history are current upstream; thi - File formats and Type core (#6147): `.ai`/EPS type from the text document keeps its paragraphs' tab stops, and right-aligned area type sets the text before a line's last tab at its stops, from the left edge, and the text after it against the right edge. Evidence: `ate::tests::a_paragraph_keeps_its_tab_stops`, `ate::tests::a_story_s_tab_stops_are_bounded`, `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`, `import_fuzz::text_frames_with_hostile_paragraph_attributes_never_panic`; scores and estimates unchanged - Type core: a right-to-left line with tabs is measured in the order it is drawn, with tab stops still measured from the left edge. Each tab goes to its stop from where the glyphs drawn before it end, and right, center and decimal stops align the text drawn after the tab. Right, Auto and centered lines are aligned by that width, and area type wraps a line that is too wide when drawn. Evidence: `tests::justify::a_right_to_left_line_with_a_tab_is_aligned_as_it_is_drawn`, `tests::justify::a_right_to_left_line_with_a_tab_wraps_when_it_does_not_fit_as_drawn`, `tests::justify::right_to_left_tab_stops_align_the_text_drawn_after_them`, `tests::justify::a_right_to_left_line_with_two_tabs_and_a_latin_run_ends_on_the_right_edge`, `tests::justify::right_aligned_right_to_left_point_type_with_a_tab_ends_at_its_origin`; scores and estimates unchanged +- Type core: a right-to-left line with tabs and negative tracking that is wider than its frame in the order of its text reads at most 1,024 line breaks further and ends at the latest of them that fits as drawn, so a long paragraph is not read to its end to set each line. This is VectorCraft's own limit. Evidence: `layout::wrapping_tests::a_tabbed_line_stepping_back_stops_reading_past_its_overflow`, `layout::wrapping_tests::a_tabbed_line_stepping_back_ends_at_the_latest_break_read_that_fits`; scores and estimates unchanged - File formats and Type core (#6137): `.ai`/EPS type from the text document keeps auto leading at the paragraph's share of each line's largest type, the paragraph's hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them; a line a soft return ends is justified as a wrapped line is. Evidence: `ate::tests::auto_leading_follows_the_size_of_each_line`, `ate::tests::a_paragraph_keeps_its_hyphenation_options`, `ate::tests::the_last_lines_the_file_sets_in_its_frame_show`, `tests::fit_source_lines_keeps_the_last_lines_the_source_sets`, `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`. Limits: frames grow only for area type of one frame, horizontal, by its lines' deepest descent plus 0.05 pt; type in a font that isn't installed, and hyphenation in a language that isn't imported, still lay out differently; scores and estimates unchanged - Current-main conflict reconciliation retains upstream and feature behavior; scores and estimates unchanged - Superseded 2026-10-20 behavior, retained as history: Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting uses the original target artboard and revision-scoped bounds caches (scores/hours unchanged) @@ -61,7 +62,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-14 | minor | G5: Weather Icons joins Basic Shapes, UI Frames, Map Markers, Inventory Icons and Skill Icons as a sixth built-in symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow; original procedural vector symbols generated in code, no default 9-slice); area score and estimate unchanged. | | 2026-11-14 | minor | Pencil and Paintbrush: a closed stroke (Alt at the release, or ending within Close Paths When Ends Are Within of its start) is fitted as the open stroke would be and closed by a straight segment back to its start, instead of curving on past both ends (`pencil_alt_closes_a_stroke_straight_back_to_its_start` in `crates/engine/src/tests/draw2.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release (`a_continued_stroke_shows_where_it_connects_or_closes` in `crates/tools/src/draw2/gesture/tests.rs`, `pencil_extend_closes_as_closed_says` in `crates/engine/src/tests/draw2.rs`). Scores and estimates unchanged. | - +| 2026-11-13 | minor | Pencil: ignores Smart Guides and Snap to Point and shows no Smart Guides, hovering or drawing; a stroke's ends and both ends of its straight lines follow the hand, while Snap to Grid and Snap to Pixel still move them (#7252; `pencil_follows_the_hand_and_shows_no_smart_guides`, `pencil_ends_still_snap_to_the_grid_and_pixels` in `crates/tools/src/draw2/gesture/tests.rs`). Public basis: community experts on the reference app's forum say Smart Guides and the other snapping options don't make the Pencil snap ([Drawing and snapping to path in Illustrator](https://community.adobe.com/questions-652/drawing-and-snapping-to-path-in-illustrator-766887)). Scores and estimates unchanged. | | 2026-11-13 | minor | Snap to Point: with Smart Guides off it still pulls drawn and dragged points onto anchors and ruler guides, but draws none of the Smart Guides labels ("anchor") or lines (#7250; `guides::tests::snap_to_point_without_smart_guides_shows_no_guides`). Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | @@ -583,6 +584,7 @@ since 2026-10-01. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. - 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance. Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. Softness and the shadows of lights after the first are not built. Scores unchanged. +- 3D shadows: with Shadows on, Revolve, Extrude & Bevel, Inflate and Rotate cast the shadow from the faces kept by the build that draws each solid, so drawing an object builds each of its solids once. The art and the shadow are unchanged. Evidence: `crates/three-d/src/shadow/tests.rs` (`a_solid_and_its_shadow_are_built_once` and the tests that compare each solid and its shadow with the two built apart), `solids::tests_shadow::a_shadowed_3d_object_builds_each_solid_once`, `solids::tests_shadow::the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it`, `revolve::tests::the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it`. Scores unchanged. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. - 3D and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. @@ -627,6 +629,7 @@ since 2026-10-01. - **Warp as a Bézier patch per style:** each of the fifteen Warp styles bends the object's bounds as one Bézier patch whose control points the style sets from the bend and the size of the bounds; the horizontal distortion then scales each column of control points about its middle and the vertical distortion scales each row. The Warp effects and warp envelopes share the map, and content with no width or no height takes the middle of the patch along that side. New warps, the built-in graphic styles' Warps and warps opened from `.ai` files carry `version` 1 for it. Warps in `.vectorcraft` documents saved before it read as `version` 0 and keep their earlier look, and edits keep a warp's version; a `version` 0 warp saved to `.ai` opens again with `version` 1, since the file holds only its settings. The patches are VectorCraft's own rules; the styles and ranges are those of the Warp options in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (doc `live::tests::warp_nets_bend_each_style_as_its_own_patch`, `warp_net_arc_edges_are_concentric_circles`, `warp_net_distortion_scales_the_columns_then_the_rows`, `warp_net_takes_any_numbers`, `warp_net_bends_a_huge_box_without_overflowing`, `warp_envelopes_bend_flat_content_as_the_middle_of_the_patch`, `warp_envelopes_write_their_map_version_only_when_it_has_one`, `style_libs::tests::builtin_warp_styles_take_the_nets_map`; effects `tests::a_warp_draws_with_the_map_its_version_names`, `tests::a_warp_bends_a_flat_box_as_the_middle_of_its_patch`, `tests::new_warps_take_the_nets_version`; engine `effectedit::warps_keep_the_map_their_version_names`, `envelope::new_warp_envelopes_take_the_net_and_saved_ones_keep_their_map`; eps `ai_editing::tests::every_effect_a_graphic_style_holds_is_read_back`, `import::ai::tests::a_warp_envelope_opens_live`, `import::ai::tests::warp_envelopes_read_every_style`, `import::ai::style::tests::a_stack_of_fills_with_effects_of_their_own_is_read_as_itself`; ui-egui `dialogs::tests_warp::warp_options_edit_keeps_each_targets_map_version`). Scores and hours unchanged. - **Warp effects bend images:** a Warp effect on an image, or on a group that holds one, bends the image's pixels with its frame, as the Warp effect is documented to distort bitmap images in [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html): after the last effect, the image is cut into 10 × 10 cells of two triangles, each a clipped piece under its own affine map. Effects after the Warp reshape only the frame, a second Warp bends the same pieces, and warps saved without a version bend the pixels with their earlier map, as they bend the frame. A placed gradient on a group that holds the image follows the group's bounds as the pieces draw them. SVG writes the image once for the pieces; PDF, EPS, `.ai` and PNG write the bent pieces. The images stay unbent when their pieces would make the art pass 2 million objects, and so does an image whose frame keeps its shape past the anchor budget. A grayscale image's fill color now colorizes the pieces of a warp or an envelope, and an image under any geometry effect keeps that color and its smoothing setting. Existing documents with a Warp effect on an image, or on a group that holds one, draw differently: before, the image showed unbent, cut by the bent frame. So do existing documents with a colorized image under an envelope or a geometry effect, or an image drawn without smoothing under a geometry effect: before, those lost the color or the setting. The cell count and the limits are VectorCraft's own (effects `tests::warped_images_stay_within_the_object_budget`, `tests::warped_images_keep_document_keys_and_hidden_images_apart`, `tests::an_image_whose_frame_passes_the_budget_stays_whole`, `tests::effects_after_a_warp_reshape_an_images_frame_and_not_its_pieces`, `tests::an_images_pixels_take_the_map_their_warps_version_names`, `tests::an_image_under_a_geometry_effect_keeps_its_color_and_smoothing`, `tests::a_nested_groups_gradient_follows_its_warped_image`; engine `warp_images::an_images_pixels_bend_with_effect_warp`, `a_warped_image_keeps_its_bend_in_svg`, `a_warped_image_keeps_its_bend_in_pdf`, `a_warped_image_keeps_its_bend_in_ai`, `a_warped_image_keeps_its_bend_in_eps`, `a_warped_image_keeps_its_bend_in_png`, `svg_writes_an_image_clipped_twice_in_a_users_group_twice`, `expand_appearance_of_a_warped_image_draws_as_the_canvas_did`, `a_colorized_image_keeps_its_color_when_warped`, `a_warp_on_a_group_bends_the_image_in_it`, `envelope_distort::a_colorized_image_keeps_its_color_in_an_envelope`). Scores and hours unchanged. - **`.ai` files keep an image's Warp live:** an embedded image whose appearance is one Warp effect, with no opacity mask, is saved to the `.ai` editing data with an art style of that Warp: its bent pieces are its drawn look, and the image itself follows on `%_` lines, as for other styled objects. Opening an `.ai` file reads such an image as the image with its Warp live, its pixels, placement, name and opacity kept, when the live warp draws as the file's drawn look and the import has a comparison left; otherwise the drawn look stays, with the drawn-look note. The Warp effect applies to bitmap images ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)), and native files keep live effects ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/supported-file-formats-in-illustrator.html)). Images with an opacity mask, and images with a Warp and another effect or with another geometry effect, are saved and opened as their drawn art. Existing `.ai` files with an embedded image on `%_` lines open differently: before, that image also came in beside its drawn look. Which images keep the Warp and the comparison are VectorCraft's own rules (eps `ai_editing::tests::an_image_with_a_warp_reads_back_with_its_warp_live`, `an_image_whose_warp_draws_otherwise_than_its_look_keeps_its_look`, `an_image_on_hidden_lines_does_not_come_in_beside_its_look`, `other_warped_images_are_written_as_their_drawn_art`, `import::ai::read::ops::tests::an_image_takes_a_style_of_one_warp_alone`). Scores and hours unchanged. +- **`.ai` saves count images with a Warp against the envelope limit:** opening an `.ai` file compares at most 256 envelopes and images with a Warp with their drawn art, and saving the `.ai` editing data now counts both against those 256, in the order they are written. An image with a Warp past them is saved as its drawn look, without its Warp, and an envelope past them as its distorted art, each with a warning on saving. An image with a Warp whose pixels can't be read is saved as its gray outline and is not counted. Before, saving counted only envelopes, so images with a Warp were saved live past the 256 without a warning, and the file opened with the ones past them as their drawn art. The limit of 256 is VectorCraft's own (eps `ai_editing::tests::warped_images_past_the_readers_checks_are_written_as_their_drawn_look`, `envelopes_get_the_checks_warped_images_left`, `a_warped_image_written_as_its_outline_takes_no_check`, `an_unreadable_warped_image_past_the_checks_is_warned_about_its_pixels`). Scores and hours unchanged. - **`.ai` files keep a linked image's Warp live and its link:** a linked image whose appearance is one Warp effect, with no opacity mask, is saved to the `.ai` editing data with an art style of that Warp, as an embedded one is: its bent pieces are its drawn look, and the image itself follows on `%_` lines as a placed file with its path, its folder relative to the document's and its preview. Before, it was saved as its drawn art and its live Warp was lost. Opening the file reads it as the linked image with its Warp live, its link, pixels, placement, name, opacity, hide and lock kept, under the same drawn-look comparison; a hidden image with a Warp, embedded or linked, is now compared with its look drawn shown, and keeps its Warp too. A linked image with a Warp in an opacity mask's art keeps its Warp and is embedded, with the existing warning for linked images in masks. Linked files stay connected to their source and track it by relative path ([the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/manage-linked-and-embedded-files/links-panel-overview.html)); the placed-file form is the one the `.ai` reader reads (`crates/eps/src/import/ai/read/art.rs` `end_place`). eps `ai_editing::tests::a_linked_image_with_a_warp_reads_back_linked_with_its_warp_live`, `a_large_linked_image_with_a_warp_reads_back_from_its_preview`, `a_hidden_or_locked_image_with_a_warp_keeps_its_state`, `a_linked_image_with_a_warp_in_a_mask_is_embedded_with_its_warp_live`. Scores and hours unchanged. - **EPS writes a repeated image's samples once:** an image drawn more than once in an EPS file (the pieces of an envelope or a Warp effect, copies of one image, or one image in a symbol's instances) has its compressed samples written once in the setup, and each placement reads them from there: a reusable stream rewound for each placement at Language Level 3 ([PostScript Language Reference, 3rd ed., §3.13](https://www.adobe.com/jp/print/postscript/pdfs/PLRM.pdf)), and an array of strings of at most 49,152 bytes fed to the image by a procedure at Level 2. An image drawn once is written where it is drawn, as before. The 256 MB limit on the page counts the samples once, so an envelope of a large photo no longer loses pieces to it. A colorized image is reused per ink (eps `tests::an_image_placed_twice_writes_its_samples_once_at_both_levels`, `tests::an_envelopes_image_pieces_draw_one_copy_of_its_samples`, `tests::each_ink_of_a_colorized_image_placed_twice_is_written_once`, `tests::samples_longer_than_a_string_are_reused_at_both_levels`, `tests::the_page_limit_counts_a_repeated_images_samples_once`). Scores and hours unchanged. - **`.ai` files write a warped image's pieces as the parts they show:** in the `.ai` editing data and in legacy `.ai` files, an embedded image cut to a clipping path (in the editing data, also an image under an opacity mask that clips) is written with all of its pixels the first time, and every later copy of the same pixels is written as the rectangle of them that the path or mask shows, 2 pixels more on each side, placed where it lies in the image. The pieces of a Warp effect, an envelope or their expanded art, 200 copies of the image for 10 × 10 cells before, now hold about 7 times the image's pixels in all for a 64 × 64 image. A copy whose opacity mask is left out, nested too deep or past the object limit, keeps all of its pixels. Each image's pixels are read once for the pieces that follow one another. An image cut to a rectangle of half its pixels or more, and the first copy written, keep all of their pixels. The `XI` operator's arguments give an image's location and size ([AI file-format specification, §8.1](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf)); the 2-pixel margin and the half-the-pixels limit are VectorCraft's own rules (eps `ai_editing::tests::the_pieces_of_a_warped_image_are_written_as_the_parts_they_show`, `masked_pieces_of_a_warped_image_are_written_as_the_parts_they_show`, `an_image_with_a_live_warp_writes_its_pixels_whole_once`, `a_clipped_image_written_first_keeps_all_of_its_pixels`, `a_masked_copy_whose_mask_is_left_out_keeps_all_of_its_pixels`, `a_masked_copy_nested_too_deep_for_its_mask_keeps_all_of_its_pixels`, `legacy_ai::tests::the_pieces_of_a_warped_image_are_written_as_the_parts_they_show`). Scores and hours unchanged. @@ -683,6 +686,7 @@ since 2026-10-01. - **COLR colour fonts:** v0 and v1 glyphs draw as vector layers (solid colours, linear and radial gradients, including ones that repeat or reflect, clips, blend modes, the foreground colour from the run's fill) on the canvas, as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as Type 3 text in PDF, and as editable groups with Create Outlines; sweep gradients, Porter-Duff compositing and radial gradients that repeat or reflect and start at a circle draw the glyph as an image. Measured by `tests_colr`, `render::tests_colrglyphs`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colr_glyphs_*`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups`. Scores unchanged (estimated). - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). - **Create Outlines keeps the type object's own appearance:** Type › Create Outlines and Object › Expand put the type object's own fills and strokes (the Appearance panel's items around its Characters row) on paths of the whole outline, below or above the glyph paths as that row places them, with one gradient across every glyph, so the outlines draw what the type drew; `object.expand.info` reports those strokes, pattern fills and gradient fills. Outlined characters keep their stroke and fill (the help page, ); a type object's appearance is separate from its characters' (the help page, ); where the object's items go is VectorCraft's own rule. Measured by `tests::pathops::create_outlines_keeps_the_objects_own_fills_and_strokes`, `tests::objexpand::create_outlines_draws_the_type_objects_own_paint`, `tests::objexpand::type_objects_own_stroke_pattern_and_gradient_are_reported`, `tests::objexpand::type_without_an_outline_reports_no_own_stroke_or_fill`, `tests::objexpand::a_stroke_under_an_unpainted_stroke_is_reported_and_outlined` and `tests::objexpand::expand_keeps_the_type_objects_own_paint`. Scores unchanged (estimated). +- **Create Outlines keeps the characters' gradients across the type:** Type › Create Outlines and Object › Expand give every glyph, ruby glyph and underline or strikethrough bar the gradient its characters drew with: a gradient with no vector of its own stays fitted to the whole layout rather than to each glyph, and one with a vector keeps its place, both moved, scaled and rotated with the type; the characters' stroke keeps the weight it was drawn at on scaled type. `object.expand.info` measures gradient fills on the same paths. Outlined characters keep their stroke and fill (the help page, ); the gradient fitted across the whole layout is VectorCraft's own rule. Measured by `tests::objexpand::create_outlines_keeps_a_character_gradient_across_the_type` and `tests::objexpand::expand_keeps_a_character_gradient_across_the_type`. Scores unchanged (estimated). - **Composite fonts that two documents define differently:** when two open documents each define a composite font (Type › Composite Fonts…) by the same name with different parts, each document draws and exports its type in its own definition: in a tiled or floating window drawn while the front document draws, when it is placed in a document that defines the name differently, and in an export made while another document is in front. Evidence: `tests::composite::nested_loans_of_one_name_use_each_documents_definition` and `threads_lending_one_name_at_once_use_their_own_definitions` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` (`crates/render`). Scores unchanged (estimated). - **Composite fonts only another document defines:** a document draws, measures and exports its type only in the composite fonts it defines itself. Type naming a composite font that only another open document, or the document a placed document sits in, defines is set as in a missing font, also when the document defines no composite font: in a window, a thumbnail or an export of a document in the back, in a file being opened and in a placed document. A temporary document drawn while a document draws keeps that document's composite fonts. Evidence: `tests::composite::a_lent_document_does_not_use_another_documents_composite_font` and `a_document_without_composite_fonts_uses_none_and_a_preview_is_unchanged` (`crates/text`), `tests::fontchange::a_placed_document_draws_its_own_definition_of_a_name_the_page_defines` and `a_document_draws_type_in_another_documents_composite_font_as_missing` (`crates/render`), `a_document_replaced_in_the_back_measures_a_font_it_lacks_as_missing` (`crates/engine`). Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). @@ -802,6 +806,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Unless a recorded Save or Save As step writes a file and makes it the document's own first, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. + - Asset Export panel menu: Create Sub-folders (on by default) and Open Location after Export are check items that set the dialog's two checkboxes (`assets.settings.set {subfolders, openLocation}`), and the panel's Export follows them, including a folder per format or item that Export for Screens remembers (3D assets' mesh files go in the folder itself); Format Settings… opens Export for Screens on the first row's format settings ([Asset Export panel](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/collect-and-export-assets-from-asset-export-panel.html)). Tests: `panels::tests_asset_export`. - Export for Screens is laid out as the reference app's dialog: on the left the Artboards and Assets tabs (thumbnails with their checkboxes, number and name, in a grid or a list), Clear Selection and Prefix; on the right Select (All, Range, Include Bleed, Include Artboard Fill, Full Document), Export to, Open Location after Export, Create Sub-folders by Scale or by Format (on by default), Export PDFs As (Single File writes the chosen artboards as the pages of one PDF named after the document, `pdfs: "single"`), and the format rows with the iOS and Android buttons, the format presets (☰) and Format Settings; under them, how many items are selected and how many files the export writes. File name patterns, the Layers and Selection sources and per-item folders stay available through `document.exportForScreens` (scripts and MCP). Tests: `dialogs::tests_screens` (layout, iOS/Android, Clear Selection, sub-folders, Single File) and `fileio::tests_screens::single_file_pdfs_hold_every_chosen_artboard`. - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). @@ -931,6 +936,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Simplified Chinese catalog (`crates/ui-egui/src/i18n/zh-hans.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,554 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins, including the image export, color profile, color book, swatch exchange file, DXF import and Revolve errors. The report lists 55 Simplified Chinese messages: the composite font, SVG filter, read root, graph design, justification order and Blob Brush connect end errors that open #7211, #7378, #7405, #7116 and #7330 translate. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - Edit › Undo and Edit › Redo, in the in-window and native menus, name the step in the interface language as the History panel lists it (`panels::history::step_name`), so when the catalog has no plain row for a step named after an effect, such as Feather, the menu shows the translation of the effect's menu row without its ellipsis (`undo_and_redo_name_the_step_as_the_history_panel_does`). - The History panel translates the undo step names the engine, the tools and the shell write as literals: the untranslated report (`untranslated_report`) lists any a complete catalog lacks, and a step whose catalog row exists only with an ellipsis (such as an effect's menu name) shows that row without the ellipsis. + - Ukrainian messages (2026-11-13): the Ukrainian catalog (`crates/ui-egui/src/i18n/uk.tsv`) has an `@msg` row for 114 of the 167 status and error messages that the untranslated report (`untranslated_report`) lists as missing in all 23 complete-message languages: the errors of the image encoders, color profiles, swatch exchange files and color books, 3D and Revolve, path operations, DXF import, the script engine and the parameter checks. Open #7211, #7378 and #7405 translate the other 53 (the composite font, SVG filter and read-root errors). The rows keep the placeholders, backticked names, accepted values and limits of their English (`ukrainian_translates_encoder_profile_swatch_revolve_and_parameter_errors`); native review remains; scores and estimates unchanged. - The German catalog (`crates/ui-egui/src/i18n/de.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,563 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins, including the image export, color profile, color book, swatch exchange file, DXF import and Revolve errors that no other catalog translates yet. The report lists 52 German messages: the composite font and SVG filter errors that open #7211 and #7378 translate, and the justification order error that open #7116 translates. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The Korean catalog (`crates/ui-egui/src/i18n/ko.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 39 Korean messages; they are the composite font, select-a-path, justification order and `path.freehand` connect errors that open #7211, #7214, #7116 and #7330 translate. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. - The Vietnamese catalog (`crates/ui-egui/src/i18n/vi.tsv`) has an `@msg` row for 115 of the status and error messages that the untranslated report listed for every complete-message catalog, among them the image export, color profile, color book, swatch exchange file, swatch library, DXF and DWG import, 3D and Revolve errors and the `index` whole-number error, 1,750 `@msg` rows in all. The untranslated report (`untranslated_report`) lists 1,875 Vietnamese messages without a row; open #7211, #7378, #7405 and #7434 translate 53 of them. @@ -1031,7 +1037,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On Windows and Linux, F2, F3 and F4 run Cut, Copy and Paste alongside Ctrl+X, Ctrl+C and Ctrl+V, and in the web build they do so everywhere except macOS. The Edit menu keeps the Ctrl shortcuts, and Keyboard Shortcuts lists both keys of each row. On macOS only Cmd+X, Cmd+C and Cmd+V are the defaults. F2, F3 and F4 do not run these commands in a focused text field or while the Type tool edits text. A saved shortcut set that assigns one of these keys to another command keeps that assignment. Public reference: [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). Not yet: Select All across threaded frames (one frame's text is selected). - Cmd/Ctrl+A follows the keyboard: in a panel, dialog or search field it selects the field's text, while the Type tool edits it selects all of that text (also `select.all` over MCP), and only otherwise every object. On macOS the menu bar's Select All, Cut, Copy and Paste (keys or clicks) act on a focused field too, and elsewhere the in-window menus' do: the field that had the keyboard when the menu opened gets them, with its selection, and the keyboard back (#516). In a frame of threaded text, Select All selects the whole story, highlighted in every frame: Copy and Cut take all of it, typing or Delete replaces it as one undo step, and a fill, a size step or a Character or Paragraph panel change applies to every frame's text (VectorCraft's own behavior; `textedit::select_all_in_a_threaded_frame_selects_the_whole_story`, `textedit::typing_over_the_whole_story_replaces_every_frames_text_in_one_step`). - - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`). + - With the whole story of threaded text selected by Select All, Remove Line Breaks, Remove Paragraph Breaks and Type › Bullets and Numbering › Convert to Text act on the text of every frame as one undo step, locked and hidden frames included, and the story stays selected after Convert to Text; a selection inside one frame changes only that frame (VectorCraft's own behavior; `textedit::remove_breaks_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_takes_the_whole_story_that_select_all_selected`, `textedit::convert_to_text_of_the_whole_story_converts_locked_and_hidden_frames`, `textedit::remove_breaks_of_the_whole_story_takes_locked_and_hidden_frames`). - When only some frames of a threaded story are selected, Remove Line Breaks and Remove Paragraph Breaks go through that story's frames once for all of them, not once per selected frame; each selected frame still loses its own breaks, in the order selected, as one undo step (`addons::cleanup::text::tests::remove_breaks_goes_through_a_partly_named_story_once`). - With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`, `panels::tabs::tests::indent_markers_after_select_all_keep_each_story_paragraphs_indents`, `dialogs::justification::tests::justification_dialog_follows_the_story_thread_at_ok`). - With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`). @@ -1113,7 +1119,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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. While Alt is held during a Paintbrush stroke or before a press with no path selected that the Smooth tool can act on, the Paintbrush shows a closing cursor (a crosshair with a ring), and so does the Pencil with Alt key toggles to Smooth Tool off when Alt is pressed after the drag starts; releasing the mouse button with Alt still held closes the path. Before a Paintbrush press with such a path selected, Alt shows the Smooth cursor, and holding Alt at the press smooths that path with the Smooth tool's radius and Smooth Tool Options' Fidelity. A Pencil drag started with Shift or Alt held draws a straight line instead, which stays open. Smooth Tool Options' Fidelity is in pixels, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=79) gives it: the Smooth tool, and an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush, refits the path at Fidelity divided by the zoom, so a drag smooths a path as much on screen at 25 % as at 800 %. Reading the pixels as screen pixels is VectorCraft's own rule, as for the Pencil and the Paintbrush (#5729); the range (0.05 to 100 px) and the default (2.5 px) are VectorCraft's own values, and a saved Fidelity keeps its number (`crates/tools/src/draw2/gesture/tests.rs` test `smooth_fidelity_is_in_screen_pixels_at_any_zoom`, `crates/engine/src/tests/draw2.rs` test `smooth_region_refits_at_the_tolerance_sent_at_any_zoom`). - With Shift held at the press, the Pencil draws a straight line from the press point to the pointer at 45° steps from the Constrain Angle, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes; pressed on an end of a selected open path, the line continues the path from that end (part of #3799). With Option/Alt held at the press and Alt key toggles to Smooth Tool off, the Pencil draws a straight line at any angle, whose ends snap to Smart Guides, and it stays open when Alt is still held at the release; Shift and Alt together keep the 45° steps (#3799). While Shift or Alt is held before the press, the Pencil shows a straight-line cursor (a crosshair with a short level line), as the page describes. Over an end of a selected open path, where the stroke continues the path, freehand or as a straight line, it shows a path-continuation cursor (a crosshair with a short line rising to the right), as [Extend paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/extend-paths-with-the-pencil-tool.html) describes, and again while a continuing stroke ends near an open end of another selected path, where the release connects the two ([Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html)). A continuing stroke, a straight line too, that ends within Close Paths When Ends Are Within of the path's other end shows the closing cursor, and the release closes the path; Alt held at the release closes a continuing freehand stroke too (a straight line stays open, as above). + With Shift held at the press, the Pencil draws a straight line from the press point to the pointer at 45° steps from the Constrain Angle, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes; pressed on an end of a selected open path, the line continues the path from that end (part of #3799). With Option/Alt held at the press and Alt key toggles to Smooth Tool off, the Pencil draws a straight line at any angle, and it stays open when Alt is still held at the release; Shift and Alt together keep the 45° steps (#3799). While Shift or Alt is held before the press, the Pencil shows a straight-line cursor (a crosshair with a short level line), as the page describes. Over an end of a selected open path, where the stroke continues the path, freehand or as a straight line, it shows a path-continuation cursor (a crosshair with a short line rising to the right), as [Extend paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/extend-paths-with-the-pencil-tool.html) describes, and again while a continuing stroke ends near an open end of another selected path, where the release connects the two ([Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html)). A continuing stroke, a straight line too, that ends within Close Paths When Ends Are Within of the path's other end shows the closing cursor, and the release closes the path; Alt held at the release closes a continuing freehand stroke too (a straight line stays open, as above). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. A shape just drawn stays adjustable with its tool: its Live Shape widgets drag, a press on its centre point (Show Center) moves the selection with the Selection tool's move arrow, snapping and Alt copy, and a press in the rotate zone just outside a bounding-box corner turns it about the centre with the Selection tool's rotate cursor (#5477; tests `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner` and, through the engine, `shapetools.rs`). A drag on one of its eight bounding-box handles scales it as the Selection tool's handles do, with their cursors and snapping, instead of drawing a new shape from the handle. A shape tool takes a press as a handle's only on the drawn handle square (VectorCraft's own rule: 3 screen points from its centre along each axis at the default Anchor Size, a half point more or less per step; the Selection tool takes 5), so a press just beside a handle still draws (tests `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_shape_tool_draws_from_a_press_just_beside_a_handle` and `a_shape_tool_scales_the_shape_just_drawn_by_its_bounding_box_handle`). The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). @@ -1156,10 +1162,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - - **Blend 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`). + - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile, arrowheads, dashes and a gradient along or across the stroke turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`, `stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere`). - **Blend steps of spot gradients with process plates:** when the matching stops of two gradients, or of a gradient and a solid, are tints of one spot swatch, each step's stop stays linked to it at a tint between the two and keeps the process inks printed with it, each of C, M, Y and K between the two stops' amounts; a stop or solid without process inks counts as none of each. Gradients with different stop counts keep the inks at every resampled stop. PDF export writes such a step as one DeviceN shading of the spot and process inks. Tints of one spot color blend into tints of it, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; the process-ink interpolation is VectorCraft's own rule (`crates/doc/src/blend.rs`, `blend_gradient_spot_process_plates_interpolate`, `resampled_gradient_spot_process_plates_interpolate`, `blend_gradient_missing_plates_mean_zero`, `blend_solid_to_spot_gradient_does_not_copy_plates`; `crates/pdf/src/tests/output.rs`, `blend_steps_between_spot_gradients_with_process_plates_print_both_inks`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. - - **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 kept gradient takes the same place on each mark's own box. 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. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. 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. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. 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, a mark's object opacity and blend mode, and the opacity, blend mode, isolation and knockout of a series group picked with Group Selection, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. 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. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. 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. On a pie with Legends in Wedges, the legend labels are drawn black, or white on a dark wedge, until a command sets their fill, which is then drawn on every wedge, black included, and kept through save and open. 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. @@ -1204,6 +1210,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). Double-clicking the Shape Builder tool opens Shape Builder Tool Options ([Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html)): with Consider Open Filled Paths as Closed off, a filled open path cuts regions as an unfilled one does; Pick Color From Color Swatches fills merged shapes with the current fill, the Left and Right arrow keys step it through the document's color swatches, and Cursor Swatch Preview shows the current fill and the swatches before and after it above the pointer; Selection Straight Line merges what the line from a drag's first point to its last crosses ([Setting Illustrator's Shape Builder Options](https://web.archive.org/web/20260615204453/https://creativepro.com/setting-illustrators-shape-builder-options/)); with Highlight Fill off, merge mode shades no regions (`shapeBuilder.merge` `openFilledAsClosed` and `pickColorFrom`). + As VectorCraft's own rule, Consider Open Filled Paths as Closed counts an open path as filled when any of its fill rows draws (shown, painted and above 0% opacity), whichever row is on top, as the canvas paints it: a painted fill under an unpainted top fill closes the path, and a painted fill that is hidden or at 0% opacity does not. The region map, merges, erasing and Clicking Stroke Splits the Path follow that rule, and the Shape Builder takes the faces and edges of a Live Paint group that one of their fill or stroke rows draws and whose own opacity is above 0. Regression tests: `tests::build::shape_builder_closes_open_paths_by_the_fill_rows_that_draw`, `tests::build::shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw` and `tests::build::shape_builder_takes_the_live_paint_faces_and_edges_that_draw`. With In Merge Mode, Clicking Stroke Splits the Path on in the same dialog, a click on a stroke in merge mode splits its path into the run of stroke under the pointer and the rest of the path, as the [Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html) page describes; the run goes from the anchor or crossing point before the pointer to the one after it, and the pointer shows scissors over it. Highlight Stroke When Editable draws that run in the color chosen in its Color list (Red by default), and with Pick Color From Color Swatches the run takes the current fill as its stroke (`shapeBuilder.merge` `splitStroke`). As VectorCraft's own rule, OK in Shape Builder Tool Options gives an error for a highlight Color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. Regression test: `dialogs::shape_builder_options::tests::a_highlight_color_with_an_alpha_part_is_refused`. With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). @@ -1295,6 +1302,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`. - With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`. - When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_draws_its_faces_in_one_order`, `solids::tests::a_depth_cycle_keeps_the_cap_last`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`. + - A graphic mapped onto Extrude & Bevel's cap or onto a Plane is drawn once when the fill is a gradient with transparent stops under a colored light and the object has a stroke (dashed or plain) with the same opacity and blending mode: the fill and stroke share it, as they do without the mask, and it is drawn after the stroke's cap with the mask of the stroke's surface (none for an opaque stroke), instead of once on the fill's cap and again on the stroke's. Members of a 3D group drawn with a mask keep graphics of their own. Unmasked fills and strokes alone draw as before. Tests: `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`, `solids::graphics::tests::a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once`, `solids::graphics::tests::members_in_transparent_gradients_keep_graphics_of_their_own`. - Revolve and Revolve (Classic) draw two overlapping faces of a surface in the order of their depths where they overlap, instead of by the depths of their centers, on one object and across a group's members, so a tilted profile with long edges or a profile of several contours no longer draws a nearer face under a farther one. A surface whose faces were already in the right order keeps it. Tests: `solids::tests_revolve_order::a_revolved_surface_draws_the_nearer_of_two_overlapping_faces_last`, `solids::tests_revolve_order::a_revolved_groups_members_draw_the_nearer_of_two_overlapping_faces_last`, `solids::tests_revolve_order::a_classic_revolved_surface_draws_the_nearer_of_two_overlapping_facets_last`, `solids::tests_revolve_order::a_surface_already_in_order_keeps_it`, `solids::tests_revolve_order::surface_order_puts_the_nearer_face_where_they_overlap_last`, `tests::a_revolved_face_measures_its_depth_on_its_plane`. - Under a colored light, an Inflate fill and strokes in solid colors, opaque with Normal blending, also draw their faces in that one order, inside a group member's own opacity mask too, instead of each solid as one composite with the stroke's faces over every fill face. Each face keeps the composite's paint, light ramps and seam width; a lone solid, the solids of an object with a translucent or blended fill or stroke, and such solids holding more than 30,720 faces together (VectorCraft's own limit) are still drawn as one composite each. Tests: `solids::tests::colored_solid_fills_and_strokes_share_face_depth_order`, `solids::tests::a_colored_solid_face_on_its_own_keeps_the_composites_colors`, `solids::tests::colored_solid_inflate_batches_channels_and_clips_once_per_surface`, `solids::tests::colored_solids_past_the_face_limit_draw_as_composites`. - Without a twist, a tapered Extrude & Bevel wall (and each bevel band) is one flat face; only a twist cuts walls into slices, so no seam between slices paints a light tick or a light line on a tapered, untwisted wall (#7019). Test: `solid::tests::a_tapered_wall_is_one_flat_face_and_a_twisted_one_is_sliced`. @@ -1358,6 +1366,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. When the frame cannot hold all of such a paragraph, the lines it holds are still composed with the whole paragraph, the lines past the frame's end measured as wide as the last line the frame holds (VectorCraft's own rule); they overflow or go on in the next threaded frame, which composes them again. Such a paragraph is broken with the Single-line Composer when the frame has no room for its first line or when the search passes VectorCraft's own limits. The Single-line Composer measures a line's room across the height of its tallest character too: a line that takes in a taller character is placed again and broken again in the room there. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html), and for text that flows on between threaded objects, [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html). A text wrap object's Offset may be negative as well as positive ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=307)). A negative Offset (to -1000 pt) shrinks the wrap object by that distance, measured from each edge itself and from the edges of its holes, so lines beside it, above it and below it run that far into it, and an object narrower than twice the distance no longer moves text aside. With Invert Wrap, a negative Offset keeps the text that far inside the object. These are VectorCraft's own rules for the shape of the shrunk object. Text Wrap Options, `object.textWrap.make` and `object.textWrap.options` and the MCP `text_wrap` tool take the negative value, and layout uses it (`crates/text/src/layout/region.rs` tests, `cmd::textwrap::tests::text_wrap_options_negative_offset_reflows_and_round_trips`). + `object.textWrap.make`, `object.textWrap.options` and the MCP `text_wrap` tool refuse an Offset outside -1000 to 1000 pt, VectorCraft's own range, or one that is not a number, and an Invert Wrap value that is not true or false, with an error and no change or undo step; an omitted or null value takes the default (`cmd::textwrap::tests::text_wrap_commands_refuse_bad_offsets_and_inverts_without_editing`). In area type of a shape other than a rectangle, each line's whole band, ascent to descent, stays inside the frame: where an edge pinches in within the band, the line ends at the narrowest point, and a line runs beside a hole that starts and ends within its band, not across it. In area type of any shape, a line also stays clear of a text wrap object that reaches into any part of its band, and inside an Invert Wrap object over its whole band (`crates/text/src/layout/region.rs` tests). In area type whose frame has several contours, a line runs across an edge two contours share only when their edges lie exactly on one line, so a gap between contours keeps lines from crossing it, even a gap one unit in the last place wide near the edge of the canvas; an edge divided by an anchor exactly on it still lets lines cross (`layout::region::separate_slanted_contours_keep_a_four_ulp_gap_near_canvas_limit`, `shared_slanted_edge_still_joins_near_canvas_limit`, `area_type_sets_no_line_across_a_four_ulp_gap_between_slanted_contours`). With Invert Wrap and a positive Offset, a line uses all the room the wrap shape grown by the Offset (across and along) holds at every height of its band: beside a notch the Offset fills, the line reaches the grown edge, whatever the band's height, the slope of the notch's sides or the number of anchors on the shape (VectorCraft's own measure). Measuring a wrap shape of many parts (a comb of 500 teeth) takes a few dozen steps per part, not one per pair of parts. The measure stops after a fixed number of steps; a shape that needs more, for example one whose edges cross one another tens of thousands of times, has its band cut into at most 64 pieces instead, which keeps the line inside the grown shape but can leave it shorter than the grown shape allows (`crates/text/src/layout/region.rs` tests). @@ -1366,6 +1375,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Character panel's Anti-aliasing Method dropdown, under Character Rotation, sets how the edges of the selected type objects are drawn as pixels (`text.setFormat {antiAlias}`), for the whole object, with each frame of a thread keeping its own method and graph labels keeping it when the graph is drawn again, on the canvas, in raster exports and when the type is rasterized. VectorCraft defines the methods: Sharp, the default, draws edges as before; None paints a pixel only where the type covers at least half of it; Crisp shows a pixel covered by a share c at `2c - 0.5`, and Strong shows it at `2c`, each kept between 0 and 1. SVG, PDF and EPS export are unchanged. Scores and hours unchanged. The OpenType panel's Stylistic Alternates and Titling Alternates checkboxes turn `salt` and `titl` on and off for the selected type, and its Figure menu lists Default Figure, Tabular Lining, Proportional Lining, Proportional Oldstyle and Tabular Oldstyle; Proportional Lining sets `pnum` and `lnum` and turns `tnum` and `onum` off, Tabular Lining turns `pnum` off and keeps `lnum`, Proportional Oldstyle turns `lnum` off and keeps `pnum`, and Default Figure and Tabular Oldstyle turn `pnum` and `lnum` off. Behavior reference: [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) and [Use swashes, titling alternates, or stylistic alternates](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/use-swashes-titling-alternates-or-stylistic-alternates.html) (public documentation). Tests: `panels::opentype::tests`. The OpenType panel's Position menu lists Default Position, Superscript, Subscript, Numerator and Denominator, as [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html) describes; Superscript, Subscript, Numerator and Denominator set `sups`, `subs`, `numr` and `dnom` for the selected type and turn the other three off, and Default Position turns all four off. The menu shows Mixed when the characters it acts on differ, and an entry chosen then applies to all of them. These two rules are VectorCraft's own, as is setting the feature on type whose font lacks the glyphs, which then draws unchanged. The panel's menus and checkboxes change only their own features on each selected character, so characters keep their other OpenType features (`text.setStyle` and `text.setRangeStyle` `{featureChanges}`). Tests: `panels::opentype::tests`, `features::tests::numerators_and_denominators_are_kept_and_shaped`. + The OpenType panel's note that ligatures are off while the text is tracked shows when any character the panel reads has Standard Ligatures on, tracking outside -20 to 55 thousandths of an em, and no explicit `liga` or `clig` tag. With the Selection tool, those characters include every frame of a selected threaded story, locked and hidden frames included; the panel's commands still change only the selected frames. The tracking limits and this rule are VectorCraft's own. Tests: `panels::opentype::tests::ligature_note_reads_every_frame_of_the_story`. The Glyphs panel's Show menu and panel menu have Alternates for Current Selection, 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. The grid lists the selected character's alternate glyphs from `GSUB` single and alternate substitutions of `aalt`, then `salt`, `ss01` to `ss20`, `swsh`, `cv01` to `cv99` and a few other alternate features, each glyph once. A double-click applies the feature that draws the variant, or a glyph choice if no supported feature draws it, as detailed below. The list uses the font of the character's text even when the panel browses another font, and the panel shows a note when the character has no alternates, its font is missing or no character is selected; these rules are VectorCraft's own. Native files keep a glyph choice with the face it was made in; another font or version draws the default glyph. Tests: `panels::glyphs::tests`, `tests::alternates`, `tests::textedit::a_glyph_alternate_replaces_one_character_through_undo_and_reopen`. The Glyphs panel's Alternates for Current Selection (#5514) applies the OpenType feature that draws the glyph to the selected character alone, 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 (Alternates For Current Selection in the Show menu; double-click the glyph to replace the selected character). One deliberate difference from a literal reading: the text keeps the Unicode character and gains a character-style feature with a value (`salt=2`, `ss03`; `text.setRangeStyle {featureChanges}`) instead of taking an unencoded glyph in its place. The grid lists the alternates of the glyph the shaper makes for the character in its word (a medial letter shows its medial variants; the default glyph comes first and the current glyph is highlighted); a variant no supported feature draws there stays enabled as a replacement glyph (`text.setGlyphAlternate`, including positional alternates), and its tooltip says it may not join its neighbors; the default glyph takes the character's alternate features off again. Runs that differ only in their OpenType features are shaped as one piece of text, each run's features over its own characters, so the letters of an Arabic word keep their joining forms. Show › Entire Font also lists the glyphs no character maps, with the font's name for them (or `gid N`) and the feature that gives them. It applies the selected letter's contextual alternates the same way, and applies a glyph no feature reaches whose name does not belong to another letter as a glyph choice; other glyphs are dimmed with the reason. An Arabic presentation form picked there inserts its base letter. These rules are VectorCraft's own. Tests: `tests::glyph_alternates` in the text crate (a fixture font; Kufi Murabba PIIIX when it is installed), `panels::glyphs::tests` (including positional glyph choices, unlisted glyph name ownership, apply and Undo), `tests::textedit::feature_values_are_set_replaced_and_saved`. With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. @@ -1432,7 +1442,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a drag on the Tabs panel's ruler or a value typed in its X field moves a tab stop past another stop, the moved stop stays selected. With the Selection tool, the Tabs panel shows the ruler and stops of the first paragraph of the first selected text object, also when the text is inside a selected group or a shape is selected before it; a selection without text shows "No text selected". A stop set on that ruler is set on every selected text object and the text in selected groups, and other objects are left as they were. This is VectorCraft's own rule. Tests `panels::tabs::tests::the_ruler_shows_text_selected_after_an_object_that_is_not_text`, `the_ruler_shows_text_inside_a_selected_group`, `a_stop_added_on_a_mixed_selection_sets_every_selected_text` and `a_selection_without_text_shows_no_ruler`. The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent (18 pt further in for each list level past the first) when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. -- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan and Dutch also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). +- **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale), Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale), Catalan (every `ca-*` locale) and Polish (every `pl-*` locale; AI-drafted, native review pending) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Finnish, Turkish, Catalan, Dutch and Danish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line; on a vertical path, upright glyphs and tate-chu-yoko blocks face the path's start, and letters on their side are a quarter turn clockwise from them (with Skew, 3D Ribbon and Stair Step only on a path that runs to the right), in one column that Align to Path Baseline or Center centers on the path and that the caret and selection span); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). With Line-end Punctuation Half Width, both composers measure a line with its last character set as narrow as Mojikumi sets it ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-mojikumi-for-japanese-text-composition.html)): a closing bracket, comma or full stop that fits at half width ends the line, and the character before it no longer goes to the next line with it. A mark that already lost its half to the punctuation after it and a line that ends in a hyphen take nothing more off, and the quarter em between Japanese and Latin text counts only where the line ends there. Kinsoku Shori Type and Burasagari Regular measure lines the same way; right-to-left lines and Mojikumi None break as before. In a frame that is not a rectangle, or with text wrap, a line's first word is measured as it is set (an opening bracket at its start flush, its last character narrowed) when layout looks for a line wide enough for it, and it ends only where the line may break, so kinsoku keeps an opening bracket with the character after it and a No Break run counts whole (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/vertical.rs`). Scores and estimates are unchanged. The Paragraph panel's Mojikumi Set lists the five predefined sets the help page names (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku and YakumonoZenkaku), then Line-end Punctuation Half Width, and `text.setFormat {mojikumi}` takes each of them. YakumonoHankaku sets every bracket, comma and full stop half width and takes a quarter em off each side of a middle dot; GyomatsuYakumonoHankaku keeps punctuation full width inside a line, sets an opening bracket flush at a line's start and a closing mark half width at its end, and takes the quarter em after a middle dot off at a line's end; GyomatsuYakumonoZenkaku keeps punctuation full width and adds a quarter em between Japanese and Latin text; YakumonoZenkaku sets characters as None does. These widths are VectorCraft's own rules, from the help page's one-line description of each set. Both composers and vertical type measure each line as it is set, the sets save with the document and paragraph styles, and a `.ai` save reports the new sets as left out (`crates/text/src/tests/vertical.rs`, `crates/ui-egui/src/panels/paragraph/tests.rs`). Scores and estimates are unchanged. Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). @@ -1449,9 +1459,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Linked opacity masks follow geometry effects, the Free Transform distort and envelopes:** when masked art moves, a linked opacity mask moves with it and an unlinked one stays in place ([Transparency and blending modes](https://helpx.adobe.com/illustrator/using/transparency-blending-modes-alt.html)). Applying that rule when art is reshaped, as below, is VectorCraft's own rule. When a group's or layer's geometry effects (Transform, Free Distort, the Warp effects and the others) reshape its members, the linked masks of the paths, compound paths and groups inside it take the same effects, nested and inverted masks included, with the type and live objects in a mask's art outlined first. Each Transform copy of a masked path carries its own mask. An image or symbol instance that a group's Transform effect moves carries its linked mask too, and with Scale Strokes & Effects on, the mask's strokes scale as a path's mask's do. With Transform Objects off, a member's mask takes the effect's stroke and pattern changes as the member does. The linked masks in the art of a symbol instance in perspective are projected with that art. A Free Transform tool distort drag (`object.distort`) warps a linked mask with its object, in a group too, in the same undo step. An envelope bends only a linked mask. When a mask can't take an effect as the art it masks does (a path in either would pass the geometry budget, the mask would get fewer Transform copies, the mask's art holds an image or symbol instance and the effect is not Transform, a Warp effect would bend an image that has a linked mask, or the effect is a live-effect plug-in that paints its pieces), the art and its masks keep their shape under that effect. The copies of a masked path count the art of its mask against the budget. Existing documents draw differently in four cases: a geometry effect on a group whose members have linked masks moves those masks; an envelope no longer bends an unlinked mask; art with linked masks keeps its shape under an effect that its masks can't take; and a Transform effect can make fewer copies of a masked path near the budget (effects `group::tests::a_groups_geometry_effects_reshape_a_members_linked_mask_with_it`, `group::tests::a_groups_geometry_effects_reshape_nested_and_inverted_masks`, `group::tests::a_compound_paths_and_a_layers_members_masks_take_the_effects`, `group::tests::a_groups_effects_reshape_a_live_object_in_a_members_mask`, `group::tests::each_transform_copy_of_a_masked_member_carries_its_mask`, `group::tests::a_groups_transform_moves_an_image_members_linked_mask`, `group::tests::a_groups_transform_moves_a_symbol_instance_members_linked_mask`, `group::tests::a_groups_transform_moves_a_linked_mask_whose_art_is_an_image`, `group::tests::art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp`, `group::tests::art_with_a_masked_image_keeps_its_shape_under_a_warp`, `group::tests::a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike`, `group::tests::a_transform_of_strokes_only_scales_a_members_mask_strokes`, `group::tests::perspective_projects_the_masks_in_a_symbols_art`, `group::tests::a_mask_whose_art_passes_the_budget_stays_whole`, `group::tests::art_whose_mask_would_take_fewer_copies_keeps_its_shape`, `group::tests::transform_copies_count_the_art_of_their_masks`, `group::tests::the_mask_of_a_masks_art_copied_whole_counts_against_the_budget`; engine `xform::distort_command_warps_a_linked_opacity_mask_with_its_object`, `xform::distort_command_warps_the_linked_mask_of_a_path_in_a_group`, `envelope_distort::an_envelope_bends_a_linked_opacity_mask_and_leaves_an_unlinked_one`, `plugins::a_painted_group_effect_leaves_art_with_a_linked_mask_as_it_is`). Scores and hours unchanged. - **Image Trace, thin closed outlines:** generated `fit::snap_area_tests` verify nonzero interiors after straightening, opposite closed-boundary winding and Noise controls; see [quality notes](image-trace-quality.md#thin-closed-outlines-with-snap-curves-to-lines). Scores and hours unchanged; open-piece fitting is unchanged. - **Image Trace, curve fitting tolerance:** the outline fitter keeps cutting a run while a point stays farther than the tolerance from its curve, so a run of fewer than six points or one cut 14 times no longer keeps a piece over the tolerance. Pieces already within the tolerance do not change, and noisy art can get more anchors. Tests: `logo::bezier::tests`, `logo::outline::tests`. Scores and hours unchanged. -- **Image Trace, gray photos:** Color and Grayscale smooth a gray photo within its tones before choosing its colors, as they do a color photo. A picture with at least 95% of its opaque pixels within 8 levels across their channels counts as continuous tone when 8 colors leave an error of more than 6 levels and more than 0.065 of the error of one color, instead of 0.1, unless 16 colors leave at most a fifth of the error of 8 (VectorCraft's own values). That exception keeps gray flat art of up to 16 clean levels on its old route; anti-aliased or noisy gray flat art can now count as continuous tone too. Most gray photos the change reaches, and very noisy gray scans of flat art, trace with fewer specks and fewer staircase edges. Some 16 Colors and High Fidelity Photo palettes of gray photos grow toward the requested count, with more anchors and regions. Some gray illustrations and sketches get more anchors and staircase edges at 16 Colors and High Fidelity Photo, and some 6 Colors traces get more staircase edges. Tests: `tests::a_gray_photo_is_continuous_tone_as_its_color_original_is`, `tests::a_gray_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. -- **Image Trace, tinted photos:** Color and Grayscale smooth a sepia, single-hue or duotone photo within its tones before choosing its colors, as they do a gray photo. A picture with at least 95% of its opaque pixels within 6 levels of its tone curve counts as continuous tone under the same 0.065 rule as a neutral picture. The tone curve runs through the median color of each 8-level stretch along the direction in which the picture's colors spread the most, and a pixel on it must also lie within 6 levels of the plane the colors spread along most, so art in several unrelated colors is not counted (VectorCraft's own rule and values). The neutral rule's exception for 16 colors leaving at most a fifth of the error of 8 applies to it too. Clean tinted bands of 2, 3 and 9 levels and tinted scans of flat art with up to 8 levels of noise stay on the flat-art route. On the synthetic tinted photos the 16 Colors trace keeps 12 to 15 colors instead of 6 to 13, with 525 to 708 anchors instead of up to 1,402. A duotone with strong noise on each channel can still miss the curve and stay unsmoothed. Tests: `tests::a_tinted_photo_is_continuous_tone_as_a_gray_photo_is`, `tests::small_accents_of_other_colors_leave_a_tinted_photo_continuous_tone`, `tests::tinted_flat_art_stays_flat_art`, `tests::pictures_without_tones_are_not_continuous_tone`, `tests::a_tinted_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. -- **Image Trace, flat art of 10 to 16 levels:** the exception for 16 colors leaving at most a fifth of the error of 8 also applies to a neutral or tinted picture whose 8-color error is more than 0.1 of the error of one color (VectorCraft's own values), so Color and Grayscale trace clean gray, sepia, single-hue and duotone art of 10 to 16 evenly spaced levels as flat art, without smoothing it first. At 16 Colors, 16 gray or sepia levels crossed by two 1 px lines trace as the 35 regions the lines cut them into instead of 33, and Automatic traces 16 clean sepia levels in 9 colors instead of 4. Tests: `tests::flat_art_of_up_to_sixteen_clean_levels_stays_flat_art`, `tests::thin_lines_on_flat_art_of_up_to_sixteen_clean_levels_are_traced`. Scores and hours unchanged. +- **Image Trace, gray photos:** Color and Grayscale smooth a gray photo within its tones before choosing its colors, as they do a color photo. A picture with at least 95% of its opaque pixels within 8 levels across their channels counts as continuous tone when 8 colors leave an error of more than 6 levels and more than 0.065 of the error of one color, instead of 0.1, unless 16 colors leave at most a tenth of the error of 8 (VectorCraft's own values). That exception keeps gray flat art of up to 16 clean levels on its old route; anti-aliased or noisy gray flat art can now count as continuous tone too. Most gray photos the change reaches, and very noisy gray scans of flat art, trace with fewer specks and fewer staircase edges. Some 16 Colors and High Fidelity Photo palettes of gray photos grow toward the requested count, with more anchors and regions. Some gray illustrations and sketches get more anchors and staircase edges at 16 Colors and High Fidelity Photo, and some 6 Colors traces get more staircase edges. Tests: `tests::a_gray_photo_is_continuous_tone_as_its_color_original_is`, `tests::a_gray_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. +- **Image Trace, tinted photos:** Color and Grayscale smooth a sepia, single-hue or duotone photo within its tones before choosing its colors, as they do a gray photo. A picture with at least 95% of its opaque pixels within 6 levels of its tone curve counts as continuous tone under the same 0.065 rule as a neutral picture. The tone curve runs through the median color of each 8-level stretch along the direction in which the picture's colors spread the most, and a pixel on it must also lie within 6 levels of the plane the colors spread along most, so art in several unrelated colors is not counted (VectorCraft's own rule and values). The neutral rule's exception for 16 colors leaving at most a tenth of the error of 8 applies to it too. Clean tinted bands of 2, 3 and 9 levels and tinted scans of flat art with up to 8 levels of noise stay on the flat-art route. On the synthetic tinted photos the 16 Colors trace keeps 12 to 15 colors instead of 6 to 13, with 525 to 708 anchors instead of up to 1,402. A duotone with strong noise on each channel can still miss the curve and stay unsmoothed. Tests: `tests::a_tinted_photo_is_continuous_tone_as_a_gray_photo_is`, `tests::small_accents_of_other_colors_leave_a_tinted_photo_continuous_tone`, `tests::tinted_flat_art_stays_flat_art`, `tests::pictures_without_tones_are_not_continuous_tone`, `tests::a_tinted_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. +- **Image Trace, flat art of 10 to 16 levels:** the exception for 16 colors leaving at most a tenth of the error of 8 also applies to a neutral or tinted picture whose 8-color error is more than 0.1 of the error of one color (VectorCraft's own values), so Color and Grayscale trace clean gray, sepia, single-hue and duotone art of 10 to 16 evenly spaced levels as flat art, without smoothing it first. At 16 Colors, 16 gray or sepia levels crossed by two 1 px lines trace as the 35 regions the lines cut them into instead of 33, and Automatic traces 16 clean sepia levels in 9 colors instead of 4. Tests: `tests::flat_art_of_up_to_sixteen_clean_levels_stays_flat_art`, `tests::thin_lines_on_flat_art_of_up_to_sixteen_clean_levels_are_traced`. Scores and hours unchanged. +- **Image Trace, clean gray photos:** the exception for flat art of up to 16 clean levels now applies when 16 colors leave at most a tenth of the error of 8, instead of a fifth (VectorCraft's own values). On the synthetic gray photo with 0 to 2 levels of noise, 16 colors leave 0.19 of the error of 8, so Color and Grayscale now count it as continuous tone and smooth it before tracing, as they do its color original. Clean gray, sepia, single-hue and duotone art of up to 16 levels, where 16 colors leave no error, stays on the flat-art route. Test: `tests::a_clean_gray_photo_is_continuous_tone_as_its_color_original_is`. Scores and hours unchanged. - **Image Trace, JPEG blocks:** Color, Grayscale and Black and White traces smooth the edges of a JPEG's 8 × 8 blocks before tracing, so a dark ground whose tone changes slowly is no longer traced as staircases along the block edges. The block grid is found in the image itself: the mean step between neighboring pixels must peak at one position in eight, across and down. A cropped JPEG and a JPEG saved in another format are smoothed too. A picture of flat 8 × 8 cells is left as it is, and art made of 8 × 8 cells with slight texture inside each cell is smoothed as a JPEG copy would be. A small step at a block edge, with no edge in the eight pixels around it, is spread over those eight pixels, and larger steps are kept, as the deblocking filters of ITU-T H.263 Annex J and MPEG-4 Part 2 Annex F.3.1 do. Black and White smooths only the smallest steps, and traces of more than 16 colors move every row of a stretch of eight by the same amount (VectorCraft's own rule and values). On a 4000 × 3000 photo saved as JPEG, the straight outline segments that lie on the block grid fall from 52% and 51% (across and down) to 24% and 29% at 16 Colors, and from 54% and 51% to 43% and 42% at High Fidelity Photo; staircase runs fall from 83 to 67 (16 Colors), 11 to 1 (6 Colors), 30 to 13 (Black and White Logo) and 428 to 403 (High Fidelity Photo). A 600 px photo saved as a quality-40 JPEG has 4 staircase runs instead of 2 at 16 Colors. Images without a block grid trace as before. Tests: `tests::a_jpegs_blocks_are_not_traced_as_steps`, `deblock::tests`. Scores and hours unchanged. - **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`. @@ -1718,7 +1729,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur SVG import reads each `` and `` as the ellipse VectorCraft draws: four smooth anchors on the axes, starting at the right, with handles of the standard length, so an ellipse exported as `` comes back with the anchors it was written from and draws the same (`circles_and_ellipses_import_as_the_ellipse_drawn` in `crates/svg/tests/it/basic_shapes.rs`, `filled_ellipse_on_the_artboard_edge_survives_visually` in `prop_svg.rs`). SVG import keeps attributes in other applications' XML namespaces (`plotter:pen="2"`) on the objects and layers they belong to, as it keeps their `data-*` attributes: copies, duplicates and `.vectorcraft` files keep them, and SVG export writes them back with each namespace declared once on the root (the rest of #522; `crates/svg/tests/it/foreign_attributes.rs`, `tests/attributes.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps defines every symbol in its editing copy with its art, registration point and place in the Symbols panel's order, and writes its instances as symbol instances, which VectorCraft's `.ai` reader opens as symbols and instances again (`symbols_and_their_instances_are_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the instances written as their art). - A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps envelopes made with a warp, a mesh or a top object editable: its editing copy holds each envelope's contents, shape, Fidelity, Envelope Options and Edit Contents state in the form VectorCraft's `.ai` envelope reader reads, beside its distorted art, so the file opens with the same live envelope, Edit Contents still switching between the contents and the envelope ([Edit the contents of envelopes](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html)). Envelopes of type, envelopes in opacity masks, pattern tiles or another envelope's contents, and envelopes the reader would open with another shape or other settings (a Fidelity that isn't a whole number, bounds margins kept with Distort Appearance off), and envelopes after the first 256 in a file are written as their distorted art, with a warning (`envelopes_are_read_back_live` and `envelopes_the_reader_cannot_open_live_are_written_as_their_art` in `crates/eps/src/ai_editing/tests.rs`). + A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps envelopes made with a warp, a mesh or a top object editable: its editing copy holds each envelope's contents, shape, Fidelity, Envelope Options and Edit Contents state in the form VectorCraft's `.ai` envelope reader reads, beside its distorted art, so the file opens with the same live envelope, Edit Contents still switching between the contents and the envelope ([Edit the contents of envelopes](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/edit-the-contents-of-envelopes.html)). Envelopes of type, envelopes in opacity masks, pattern tiles or another envelope's contents, and envelopes the reader would open with another shape or other settings (a Fidelity that isn't a whole number, bounds margins kept with Distort Appearance off), and envelopes after the first 256 envelopes and images with a Warp in a file are written as their distorted art, with a warning (`envelopes_are_read_back_live` and `envelopes_the_reader_cannot_open_live_are_written_as_their_art` in `crates/eps/src/ai_editing/tests.rs`). A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes eligible paths, compound paths and groups with live effects with an art style when the writer supports their appearance and effects (not a filled path that uses the even-odd rule, and none on a large canvas), which VectorCraft's `.ai` reader opens as the same appearance with its effects live (`objects_with_live_effects_are_read_back` and `every_effect_setting_written_on_an_object_is_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the objects written without one and the effects they lose). The same holds for the objects of an opacity mask's art, a mask inside another mask's art and a hidden art root included, so a mask whose art has Offset Path opens drawing the image it masks as it did, with the effect live; geometry effects that no art style holds on a mask's art, such as Roughen, are written applied to the art, which opens drawing what it drew (`a_masked_image_with_live_offset_path_round_trips`, `hidden_and_nested_mask_art_keep_live_offset_path` and `a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws` in `crates/eps/src/ai_editing/tests.rs`). 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). @@ -1844,8 +1855,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). - An image that Open and Place store again keeps the ICC profile its file embeds and its 16-bit samples. A turned PNG, JPEG, WebP or TIFF stored as PNG, and a TIFF the image decoder reads, keep their gray or RGB samples at 8 or 16 bits with their gray or RGB profile in the PNG's `iCCP` chunk ([PNG specification, iCCP](https://www.w3.org/TR/png-3/#11iCCP)). A CMYK TIFF stored with one plane per ink and a turned CMYK JPEG or TIFF keep their CMYK profile as TIFF tag 34675, a JPEG's put together from all its APP2 segments ([ICC image-format guide](https://github.com/InternationalColorConsortium/iccDEV/blob/master/iccdev-mcp/docs/icc-format-guide.md)). A profile whose color space differs from the stored samples' is left out. The profile is kept in the stored image; how CMYK inks are drawn and exported to PDF does not change (`crates/engine/src/cmd/fileio/tests.rs`). + - PDF export writes a stored gray or RGB TIFF in an `ICCBased` color space that holds the gray or RGB profile of its tag 34675, at 16 bits a sample from PDF 1.5 on and 8 before, with its alpha as a soft mask only when some pixel is not opaque ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)). A gray or RGB image, a PNG included, that the Compression settings resample or compress with JPEG keeps its profile too, and gray pixels in an RGB profile stay RGB. Pixels the Output settings convert, a profile whose color space differs from the samples', and a malformed profile, a PNG's or JPEG's kept as it is included, are written without it; such a JPEG keeps its JPEG data. PDF/X-1a allows no ICC-based color spaces, so there a gray image with a gray profile, kept as it is, resampled or compressed with JPEG, is written in DeviceGray without the profile, a JPEG kept as JPEG with its JPEG data unchanged, and RGB images are converted to CMYK as before. CMYK images are unchanged (`crates/pdf/src/tests/compression.rs`). - 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`). + - SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `` shows (), chains of ``s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `` references that would be copied without end; both limits are VectorCraft's own. An SVG shown as an image counts toward the same 64 MB as the SVG showing it, and one past either limit refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`). - SVG import reads the files that a linked SVG file's own `` elements link to, relative paths from that file's folder (), as it reads the imported SVG's links: a raster stays linked, an SVG file imports as vector art, and one that can't be read gets the placeholder, its link and a warning. SVG 2 tells a viewer not to load these links (); reading them is VectorCraft's own rule. The same href in SVG files of two folders names two files. A link that leads back to an SVG file showing it gets the placeholder and a warning, and reading the links of linked SVG files stops at the nesting depth cap and at 1,024 reads and 512 MB per import, the same limits decoded nested SVG images have, counted separately from them. The text of every linked SVG file read counts, and so does every file read for the links of a linked SVG file, raster or SVG; rasters the imported SVG links to don't. Once either limit is passed, no file linked from a linked SVG file is read and its image is left out with a warning, and an SVG file the imported SVG links to is still shown, without the files its own links name, with a warning. Another href to an SVG file already read, spelled differently or in another SVG file, does not read it again, unless a link back or the depth cap changes what it shows there (`crates/svg/tests/it/import_details.rs`, `crates/svg/src/import/files.rs`). - File › Place and a file dropped on the canvas refuse a PNG, JPEG, GIF or WebP file whose pixels can't be read, such as one cut short by a download or a sync still running, and the status bar shows "Couldn't place : the image's pixels can't be read". Paste and Relink refuse such an image too, and Update Links, or Open when it reads the file again, counts it as missing. A JPEG cut short still places when its pixels can be decoded (`file.place`, `crates/engine/src/tests_place.rs`). - On the desktop, Copy and Cut make the system clipboard's formats (text, SVG, PDF, PNG) from a copy of the clipboard on the thread that writes background saves and exports, and write them when they are ready; while that thread has a save, an export, a print or a recovery copy to finish, they are made and written at once. Until they are written, Paste in VectorCraft takes the internal clipboard, and while a text field or the Type tool has the keyboard the app waits for them. Another Copy or Cut, or a copy of text in VectorCraft, drops them. @@ -1862,6 +1876,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - On Windows, a document opened from a mapped network drive finds its links stored with the share's own path (`\\server\share\…`), as the same document opened from the share does; links on other computers stay missing. - On Windows, a link on a drive mapped to a network share other than the document's (`Y:\…`) is missing, with the reason that the path is on another computer, as a link stored with that share's own path is; links on this computer's drives and on the document's share are followed. - In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one. + - The Links panel menu's Sort by Size ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) lists the links by file size, smallest first (`links.list {sort: "size"}`). VectorCraft's own rules: a file's size is the one Link Info shows, rows without one (embedded images, a missing file whose size the document does not keep) come last, and equal sizes go by name. - When a document opens with notes and with linked files that changed on disk (Update Links: Manually) or, on the web, can't be read, the status bar shows the line about the linked files, then counts the notes and names the first, and hovering it lists the notes. The same holds when the line about modified files follows the Linked File Not Found dialog, and File › New from Template… shows the notes of the file it opens as File › Open does (`an_open_with_modified_links_keeps_link_notice_and_import_notes_reachable`, `new_from_template_preserves_open_warnings`, `an_open_with_unreadable_links_keeps_import_notes_reachable`, `modified_links_after_the_missing_ones_keep_the_open_notes`, `combined_open_and_link_status_lists_notes_on_hover_and_for_accessibility`). - On the web, when a document opens with linked files that can't be read and linked files that changed on disk (Update Links: Manually), the status bar shows the line about the unreadable files, and the line about the changed files is the first of the notes its hover lists, ahead of the open's notes. With Ask When Modified the update question opens and the line about the unreadable files stays (`a_web_open_with_unreadable_and_modified_links_keeps_both_lines`). - Linked images and placed documents kept only in symbols, graph designs, patterns or opacity masks are listed in the Links panel after the layers' own, one row per stored object, with their status in its Missing and Modified filters, in Check Links, in the missing and modified files reported when a document opens, in the link watch and in Find in Folder; Relink, Update, Embed, Placement Options and Link Info act on them, and Go To says they have no place on the canvas. Opening a document gives such an object whose id is 0 or repeats another object's a new id. @@ -1926,6 +1941,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the Perspective Selection tool, Ctrl+Alt-drag (Command+Option-drag on macOS) also copies objects on their perspective plane; Alt/Option-drag continues to do so. With the Perspective Selection tool, holding Shift while moving or copying constrains each object's displacement to the nearest axis or 45° diagonal of its own plane; releasing Shift resumes the raw pointer position, and 5 still moves perpendicular to the plane. Snap to Grid follows the constrained line on the first object's plane and depth. With Snap to Grid on, a move of objects on one perspective plane at different depths moves them all by the same offset on the plane, so they keep their spacing. Without Shift, on each axis, the edge of their joint bounds nearer a gridline lands on it when that edge ends within a quarter cell of the gridline. With Shift, an edge also lands only when it ends within a quarter cell of a gridline: a horizontal or vertical move can land only an edge on its own axis, and a 45° move lands the edge on the axis whose nonzero correction is smaller. When no edge on those axes is that close, the move does not snap. A move perpendicular to the plane does not snap. Regression: `snap_moves_objects_at_different_depths_by_one_plane_offset` in `crates/engine/src/tests/persp_select.rs`. + Perspective Grid Options has Automatic Plane Positioning with its two checkboxes, Anchor Point of Perspective Artwork and Intersection of Gridlines. With the Perspective Selection tool, Shift held over an anchor point of art in perspective, or over a gridline intersection, moves the active plane to that height or depth and hides the other planes; a plane made active then passes through the same point, and the planes are back in place once an object is drawn or placed there (`perspective.plane.infer`). VectorCraft's own rules: both options are on by default and kept with the preferences, the pointer counts as over a target within 6 screen pixels, an anchor point wins over an intersection, and Shift positions the plane only while no button is down. Tests: `crates/engine/src/tests/persp_infer.rs`. When the desktop app opens a document on a thread of its own (#1245), that thread also reads the document's linked files and lays out its type, and the UI thread only adds the finished document: in release builds, the step left on the UI thread takes 0.02 ms instead of 1.04 s for a document with 12 linked 3000 × 2000 TIFFs, and it takes 0.1 ms instead of 0.85 s for one with 300 Auto Size area type objects, every second one in three columns. Laying out type keeps each font face's shaping plans, at most 32 per face, so type objects of the same font, script, direction, language and features share one plan: the layouts of a document of 5,000 short point type objects take 59 ms instead of 73 ms in a release build, and the glyphs, bounds and baselines do not change. Laying out type looks up the font face of each style run once and uses it for the run's glyphs and for the line metrics of a paragraph that starts in that run: the layouts of a document of 5,000 short point type objects take a median of 215 million CPU cycles instead of 236 million in a release build (11 alternating runs of each build on Windows 11, measured while other builds were running), and the glyphs, bounds and baselines do not change. @@ -2324,6 +2340,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Banner Hems and Grommets… (`addon.cutting.banner`) marks where a printed banner is hemmed ([hem](https://en.wikipedia.org/wiki/Hem)) and where its grommets go ([grommet](https://en.wikipedia.org/wiki/Grommet)). The rest is VectorCraft's own: the banner is the selected art's bounds or each artboard; each chosen side gets a hem line at a set depth inside its edge (1 in by default) and grommet marks at a set inset (0.5 in), one at each end of the side and the rest spread evenly at most a set spacing apart (24 in), with one grommet at a shared corner. Each grommet mark is a circle with a cross through its center. The marks are stroked in a chosen swatch ([Registration] by default), in one group named Banner Marks per banner on top of the current layer, added as one undo step. The dialog has Preview. Tests: `cmd::addons::cutting::banner::tests` in `vectorcraft-engine`, `banner_hems_and_grommets_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Banner Hems and Grommets. +## Cutting Tools add-on: Nest Shapes (2026-11-14) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Cutting Tools › Nest Shapes… (`addon.cutting.nest`) moves the selected objects close together onto a sheet or a roll of material ([packing problems](https://en.wikipedia.org/wiki/Packing_problems)). The rest is VectorCraft's own: the sheet is an artboard, or a set width and height from its top-left corner, and a roll is a set width with no end; a margin is kept inside the edges and a spacing between objects. Objects are packed by their bounding boxes, with or without strokes and effects (shadows, glows and blurs included), the tallest first, each where its bottom edge is highest and then furthest left; with Rotate an object may turn 90° where that places it higher or where only the turned object fits. Objects that do not fit go in a column to the right of the sheet, in stacking order. The command is one undo step, and its result gives the length of material used. The dialog has Preview. Tests: `cmd::addons::cutting::nest::tests` in `vectorcraft-engine`, `nest_shapes_previews_cancels_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Cutting Tools add-on › Nest Shapes. + ## Path Precision Tools add-on: Divide into Dashes (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Divide into Dashes… cuts the selected paths into separate open paths along the curve (arc length, not straight distance): each `dash` long (0.01 to 1000000 pt, 10 by default) with `gap` between them (0 by default: the pieces touch); the gap pieces are left out unless Remove Gaps is off. With direct-selected segments (or anchors) only those runs are divided, the pattern running on across segments that follow one another, and the rest of such a path stays as pieces of its own. Fit to Corners and Ends gives every run between corners and ends a whole number of dashes, all stretched or squeezed alike so it starts and ends on a dash (a closed path without corners holds whole periods); otherwise the lengths are exact and each run's last piece is what is left. Every piece keeps the path's appearance and is selected; one undo step; at most 100000 pieces (more is refused). The dialog takes lengths in any unit and previews on the canvas. Tests: `dashes::tests` in `vectorcraft-pathops` (exact and fitted lengths, curves measured along them, picked segments on open and closed paths, the piece cap and bad patterns), `divide_into_dashes_*` in `cmd::addons::pathtools::tests` in `vectorcraft-engine` (gaps removed or kept, fitted lengths, the stroke kept, one undo step, selected segments only, bad params and too many pieces refused), `divide_into_dashes_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. diff --git a/docs/three-d.md b/docs/three-d.md index 37f02f4646..f12ca4675c 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -163,7 +163,8 @@ The rest is our reading: depths where they overlap, with caps on or off. A fill wall in a gap stays in its own depth order. Inflate's curved surfaces follow this only as closely as their flat facets do. A solid painted with a gradient that has transparent stops under a light that is not white is drawn with an opacity mask: its faces keep their places in - this order, in runs that each carry the mask, and so do its graphics. A member of a 3D group with its own opacity + this order, in runs that each carry the mask, and a graphic drawn after one of its faces carries the mask too + ([Graphics](#graphics)). A member of a 3D group with its own opacity mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the lower item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its @@ -389,8 +390,11 @@ These rules are VectorCraft's own: turned, foreshortened by the perspective and twisted and tapered with the face, and clipped to it. It is shaded with the face's light: each color is multiplied by the light that falls on the face, except in pattern tiles, which keep their own colors. It is drawn with the - opacity and blending mode of the fill or stroke the face is painted with. A graphic on a face turned away from - the viewer is not drawn. + opacity and blending mode of the fill or stroke the face is painted with. Solids whose fills and strokes have the + same opacity and blending mode share one graphic on each face, clipped to their faces there and drawn after the + last of them. An object's fill and stroke share it when the fill is drawn with an opacity mask too, and the + graphic takes the mask of the solid it is drawn after; members of a 3D group drawn with a mask keep graphics of + their own. A graphic on a face turned away from the viewer is not drawn. - On the back cap, X runs to the right as the back is seen from behind, so the graphic reads the right way round there. - On Revolve a graphic lies on the swept side, which has one face (Front), unrolled flat. X runs around the axis: diff --git a/docs/type-parity.md b/docs/type-parity.md index 72b8bcfc9d..64c6bcf798 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -51,7 +51,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred lines are still aligned as a whole); in justified area type the text up to a line's last tab keeps its spacing and its tabs their stops, and the text after the last tab takes the line's room to the far edge, VectorCraft's own rule (evidence: `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge` and the other tab tests in `crates/text/src/tests/justify.rs`) | | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | partial | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The Check Spelling dialog remains. Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog). | -| Smart Punctuation, Change Case, Find & Replace | done | | +| Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. |