Merge main into fix/the-liquify-warning-s-tool-name-and-object-kinds

This commit is contained in:
dotCooCoo
2026-11-15 03:43:25 -08:00
101 changed files with 2795 additions and 265 deletions
+31 -3
View File
@@ -281,7 +281,13 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
});
}
b += match &n.kind {
NodeKind::Path { path, live, .. } => path_bytes(path) + boxed(live),
NodeKind::Path { path, live, .. } => {
let was = other.and_then(|o| match &o.kind {
NodeKind::Path { path, .. } => Some(path),
_ => None,
});
path_bytes_besides(path, was) + boxed(live)
}
NodeKind::Layer { children, .. }
| NodeKind::Group { children, .. }
| NodeKind::Compound { children, .. }
@@ -298,8 +304,30 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
}
fn path_bytes(p: &PathData) -> usize {
let anchors: usize =
p.subpaths.iter().map(|s| if s.anchors.capacity() == 0 { 0 } else { ALLOC + s.anchors.capacity() * size_of::<Anchor>() }).sum();
path_bytes_besides(p, None)
}
/// [`path_bytes`] without the anchor chunks that `other` (another version of the path) holds too:
/// a version made by changing one anchor shares every chunk but the one it changed.
fn path_bytes_besides(p: &PathData, other: Option<&PathData>) -> usize {
let mut shared: Vec<usize> =
other.map(|o| o.subpaths.iter().flat_map(|s| s.anchors.chunk_allocations()).map(|(id, _)| id).collect()).unwrap_or_default();
shared.sort_unstable();
let chunk = ALLOC + ARC + size_of::<Vec<Anchor>>() + ALLOC;
let anchors: usize = p
.subpaths
.iter()
.map(|s| {
let table = s.anchors.table_bytes();
let own: usize = s
.anchors
.chunk_allocations()
.filter(|(id, _)| shared.binary_search(id).is_err())
.map(|(_, capacity)| chunk + capacity * size_of::<Anchor>())
.sum();
if table == 0 { own } else { ALLOC + table + own }
})
.sum();
anchors + if p.subpaths.capacity() == 0 { 0 } else { ALLOC + p.subpaths.capacity() * size_of::<SubPath>() }
}
+1 -1
View File
@@ -859,7 +859,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
crate::SVG_FILTER,
"SVG Filter",
&["Effect", "SVG Filters"],
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
"{name: string (the filter's id), xml: string (one SVG <filter> element with an id and 1..64 primitives, at most 64 KB), scale: number 0.001..1000 (1; points per unit of the filter's user space), origin: [x, y] pt ([0, 0]; where the filter's user space starts in the document), axes?: [a, b, c, d] (absent or [1, 0, 0, 1]: the document's axes, and not null; the document directions of one unit along the filter's x axis [a, b] and y axis [c, d] before scale, each -1000..1000, with a·d - b·c at least 0.001 from 0; a turned, skewed or unevenly scaled user space, as SVG import gives a filtered element under a rotate, skew or uneven scale; the filter's offsets, blurs and region run along these axes; moving, turning or skewing the object moves origin and leaves axes)} runs the SVG filter on the object's pixels, its lengths in points times scale, at the Document Raster Effects resolution or finer; svgFilter.apply applies one of the document's filters (svgFilter.list)",
json!({"scale": 1.0, "origin": [0.0, 0.0]}),
));
v
+218 -34
View File
@@ -1,7 +1,8 @@
//! Effect › SVG Filters (`svg.filter`): an SVG `<filter>` element applied as a live raster effect.
//! The filter runs on the object's pixels as SVG 1.1 describes it
//! (<https://www.w3.org/TR/SVG11/filters.html>), drawn by resvg. Its lengths are in points times
//! the effect's `scale`, its user space starts at the effect's `origin`, its object bounding box is the box of the drawn pixels, and it runs at the
//! the effect's `scale`, its user space starts at the effect's `origin`, its axes point as the effect's `axes` say (a turned or
//! skewed user space), its object bounding box is the box of the drawn pixels, and it runs at the
//! Document Raster Effects resolution when the view shows the object at a finer one.
use std::sync::Arc;
@@ -1224,13 +1225,16 @@ fn region_length(v: Option<&str>, default: f64, user: bool) -> Length {
}
/// An SVG filter effect: the filter's XML, how many points one of its units is, where its user
/// space's origin lies in the document, and its region.
/// space's origin lies in the document, which way its axes point, and its region.
#[derive(Clone, Debug, PartialEq)]
pub struct SvgFilterFx {
/// The filter as it is drawn and written ([`rebuilt`]).
xml: Arc<str>,
scale: f64,
origin: Vec2,
/// The directions of the user space's axes in the document, before `scale` ([`axes_param`]):
/// the identity unless the user space is turned, skewed or scaled unevenly.
axes: Affine,
/// Its region (filter effects region): x, y, width, height.
region: [Length; 4],
/// Is the region in user space with a length measured against the object's box? It is then
@@ -1250,11 +1254,92 @@ fn origin_param(p: &Value) -> Vec2 {
Vec2::new(at(0), at(1))
}
/// The largest magnitude of an entry of an SVG filter effect's `axes`.
pub const MAX_AXIS: f64 = 1000.0;
/// The smallest magnitude of the determinant of an SVG filter effect's `axes`.
pub const MIN_AXES_DET: f64 = 0.001;
/// The `axes` of an SVG filter effect's parameters `p`: `[a, b, c, d]`, the document directions
/// of one unit along the filter's x axis (`[a, b]`) and its y axis (`[c, d]`), before `scale`.
/// The identity when absent; `None` when it isn't four numbers from -[`MAX_AXIS`] to [`MAX_AXIS`]
/// whose determinant is at least [`MIN_AXES_DET`] across ([`valid_axes`]).
fn axes_param(p: &Value) -> Option<Affine> {
match p.get("axes") {
None | Some(Value::Null) => Some(Affine::IDENTITY),
Some(v) => valid_axes(v),
}
}
/// `v` as the linear map of an SVG filter effect's `axes` ([`axes_param`]), when it is one.
pub fn valid_axes(v: &Value) -> Option<Affine> {
let n: Vec<f64> = v.as_array()?.iter().map(Value::as_f64).collect::<Option<_>>()?;
axes_of(<[f64; 4]>::try_from(n).ok()?)
}
/// `[a, b, c, d]` as the linear map of an SVG filter effect's `axes`, when the effect takes it ([`valid_axes`]).
fn axes_of([a, b, c, d]: [f64; 4]) -> Option<Affine> {
let det = a * d - b * c;
([a, b, c, d].iter().all(|v| v.is_finite() && v.abs() <= MAX_AXIS) && det.abs() >= MIN_AXES_DET).then(|| Affine::new([a, b, c, d, 0.0, 0.0]))
}
/// A filter's user space as the SVG filter effect stores it ([`user_space`]).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct UserSpace {
/// The effect's `scale`.
pub scale: f64,
/// The effect's `origin`.
pub origin: [f64; 2],
/// The effect's `axes`; `None` when the axes are the document's.
pub axes: Option<[f64; 4]>,
}
/// `ts`, a user space mapped to the document, as the SVG filter effect's `scale` (the square root
/// of its area scale), `origin` and, when it turns, skews or scales unevenly, `axes`. `None` when
/// it can't be stored: not finite, `scale` outside 0.001..1000, or `axes` the effect refuses
/// ([`valid_axes`]).
pub fn user_space(ts: Affine) -> Option<UserSpace> {
let [a, b, c, d, e, f] = ts.as_coeffs();
if ![a, b, c, d, e, f].iter().all(|v| v.is_finite()) {
return None;
}
let scale = ts.determinant().abs().sqrt();
if !(0.001..=1000.0).contains(&scale) {
return None;
}
let even = b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= 1e-9 * a.max(1.0);
if even {
return Some(UserSpace { scale: a, origin: [e, f], axes: None });
}
let axes = [a, b, c, d].map(|v| v / scale);
axes_of(axes)?;
Some(UserSpace { scale, origin: [e, f], axes: Some(axes) })
}
/// The longest a unit vector becomes under the linear part of `a` (its largest singular value).
fn stretch(a: Affine) -> f64 {
let [a, b, c, d, _, _] = a.as_coeffs();
let sum = a * a + b * b + c * c + d * d;
let det = a * d - b * c;
(0.5 * (sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt())).sqrt()
}
/// The share of a raster pixel, `space.px` points wide, that a pixel of the Document Raster Effects
/// resolution is (at most 1).
fn raster_resolution(space: &PixelSpace) -> f64 {
if space.line.is_finite() && space.line > 0.0 && space.px.is_finite() && space.px > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 }
}
/// How many times the raster's pixels a turned filter's canvas may hold ([`SvgFilterFx::turned_canvas`]).
const TURNED_ROOM: f64 = 4.0;
impl SvgFilterFx {
/// The effect's parameters `p` (defaults merged in): `xml`, the `<filter>` element, `scale`
/// and `origin`. `None` when `xml` isn't a filter [`check`] takes, however the effect came to
/// hold it (an opened file, a script): the object is then drawn, printed and exported without it.
/// The effect's parameters `p` (defaults merged in): `xml`, the `<filter>` element, `scale`,
/// `origin` and `axes`. `None` when `xml` isn't a filter [`check`] takes, or `axes` isn't
/// valid ([`axes_param`]), however the effect came to hold it (an opened file, a script): the
/// object is then drawn, printed and exported without it.
pub(crate) fn parse(p: &Value) -> Option<Self> {
let axes = axes_param(p)?;
let xml = checked(text(p, "xml", ""))?;
let (wrapped, _) = wrap(&xml);
let doc = roxmltree::Document::parse(&wrapped).ok()?;
@@ -1273,7 +1358,17 @@ impl SvgFilterFx {
let (window, blur) = (largest(&["radius", "kernelUnitLength"]), largest(&["stdDeviation"]));
let box_units = f.attribute("primitiveUnits").is_some_and(|u| u.trim() == "objectBoundingBox");
let scale = num(p, "scale", 1.0).clamp(1e-3, 1e3);
Some(Self { xml, scale, origin: origin_param(p), region, measured, window, blur, box_units })
Some(Self { xml, scale, origin: origin_param(p), axes, region, measured, window, blur, box_units })
}
/// The filter's user space → the document: moved to `origin`, scaled by `scale`, along `axes`.
pub fn to_doc(&self) -> Affine {
Affine::translate(self.origin) * Affine::scale(self.scale) * self.axes
}
/// The box of `bounds` (document units) in the filter's user space.
fn user_box(&self, bounds: Rect) -> Rect {
self.to_doc().inverse().transform_rect_bbox(bounds)
}
/// The filter's region in its user space for an object whose box there is `b`: lengths in user
@@ -1308,11 +1403,11 @@ impl SvgFilterFx {
with_attributes(xml, &[("x", r.x0), ("y", r.y0), ("width", r.width()), ("height", r.height())])
}
/// The filter as SVG output writes it (one unit a point, [`Self::in_points`]) for an object
/// whose box in the document is `bounds`: in its SVG 1.1 form ([`svg11`]), `None` when SVG 1.1
/// can't hold it ([`Self::writes_as_svg11`]).
pub fn written_xml(&self, bounds: Rect) -> Option<String> {
let out = self.with_region(&self.svg11_form()?, (bounds - self.origin).scale_from_origin(1.0 / self.scale))?;
/// The filter as SVG output writes it, in its user space ([`Self::to_doc`]), for an object
/// whose box in that user space is `user_box`: in its SVG 1.1 form ([`svg11`]), `None` when SVG
/// 1.1 can't hold it ([`Self::writes_as_svg11`]).
pub fn written_xml(&self, user_box: Rect) -> Option<String> {
let out = self.with_region(&self.svg11_form()?, user_box)?;
(written_len(&out) <= MAX_WRITTEN_XML).then_some(out)
}
@@ -1345,10 +1440,11 @@ impl SvgFilterFx {
if !(space.px.is_finite() && space.px > 0.0) {
return 1.0;
}
let mut s: f64 = if space.line.is_finite() && space.line > 0.0 { (space.px / space.line).min(1.0) } else { 1.0 };
// A length spans length × scale / px raster pixels, or a fraction of the box.
let mut s = raster_resolution(space);
// A length spans at most length × scale × the axes' stretch / px raster pixels, or a fraction of the box.
let reach = self.scale * stretch(self.axes);
for (length, most) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] {
let px = if self.box_units { length * box_px.max(0.0) } else { length * self.scale / space.px };
let px = if self.box_units { length * box_px.max(0.0) } else { length * reach / space.px };
if px * s > most {
s = most / px;
}
@@ -1374,15 +1470,21 @@ impl SvgFilterFx {
self.measured
}
/// Does one unit of the filter's user space measure one point (its `scale` is 1)?
pub fn in_points(&self) -> bool {
self.scale == 1.0
/// Is the filter's user space the document's, only moved: one unit a point, its axes the
/// document's (`scale` 1, no `axes`)?
pub fn moves_only(&self) -> bool {
self.scale == 1.0 && self.axes == Affine::IDENTITY
}
/// Can SVG import store the filter's user space ([`Self::to_doc`]) again ([`user_space`])? Its
/// `scale` and `axes` together can scale it past what one of them holds alone.
pub fn opens_again(&self) -> bool {
user_space(self.to_doc()).is_some()
}
/// How far beyond `bounds` (document units) the filter can draw: its region's reach past them.
pub fn outset(&self, bounds: Rect) -> f64 {
let b = (bounds - self.origin).scale_from_origin(1.0 / self.scale);
let region = self.region_in(b).scale_from_origin(self.scale) + self.origin;
let region = self.to_doc().transform_rect_bbox(self.region_in(self.user_box(bounds)));
let reach = [bounds.x0 - region.x0, bounds.y0 - region.y0, region.x1 - bounds.x1, region.y1 - bounds.y1].into_iter().fold(0.0, f64::max);
if reach.is_finite() { reach.min(MAX_OUTSET) } else { 0.0 }
}
@@ -1397,20 +1499,40 @@ impl SvgFilterFx {
}
// Art that draws no pixels still has a box: the whole raster stands for it.
let (x0, y0, x1, y1) = drawn_box(data, w, h).unwrap_or((0, 0, w, h));
let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64);
let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32);
let Some(png) = png_of(data, w, x0, y0, x1, y1).map(Arc::new) else { return };
let k = self.scale;
// Filter user space → the small canvas, and the image's pixels → filter user space.
let outer = Affine::scale(s) * space.to_doc.inverse() * Affine::translate(self.origin) * Affine::scale(k);
let place = Affine::scale(1.0 / k) * Affine::translate(-self.origin) * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64));
let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, (x1 - x0) as f64, (y1 - y0) as f64));
let user = self.to_doc();
// Filter user space → the small canvas, and the small canvas → the raster's pixels.
let (sw, sh, outer, back) = if self.axes == Affine::IDENTITY {
let s = self.resolution(space, (x1 - x0).max(y1 - y0) as f64);
let (sw, sh) = ((w as f64 * s).ceil().max(1.0) as u32, (h as f64 * s).ceil().max(1.0) as u32);
(sw, sh, Affine::scale(s) * space.to_doc.inverse() * user, Affine::scale(1.0 / s))
} else {
// The canvas measures the costly lengths in its own pixels.
let drawn = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64);
let Some(canvas) = self.turned_canvas(w, h, raster_resolution(space), drawn, space) else { return };
canvas
};
// The source as an image, its size, and the map from its pixels to filter user space. The
// object's box in user space is the image's box there, which resvg measures the region and
// a primitive's lengths in the object's box against. In a turned or skewed user space the
// source is first drawn onto the canvas's pixels, whose rows and columns run along the user
// space's axes, and cut to the pixels it draws there: the image then lies along those axes,
// and its box is the box of the art in the user space, not of the raster's box turned into it.
let source = if self.axes == Affine::IDENTITY {
let place = user.inverse() * space.to_doc * Affine::translate(Vec2::new(x0 as f64, y0 as f64));
png_of(data, w, x0, y0, x1, y1).map(|png| (png, x1 - x0, y1 - y0, place))
} else {
on_canvas(data, w, h, sw, sh, outer * user.inverse() * space.to_doc)
.map(|(png, cx, cy, iw, ih)| (png, iw, ih, outer.inverse() * Affine::translate(Vec2::new(cx as f64, cy as f64))))
};
let Some((png, iw, ih, place)) = source else { return };
let png = Arc::new(png);
let b = place.transform_rect_bbox(Rect::new(0.0, 0.0, iw as f64, ih as f64));
let Some(drawn) = self.drawn_xml(b).and_then(|xml| with_id(&xml, DRAWN_ID)) else { return };
let svg = format!(
"<svg xmlns=\"{SVG_NS}\" xmlns:xlink=\"{XLINK_NS}\" width=\"{sw}\" height=\"{sh}\" viewBox=\"0 0 {sw} {sh}\"><defs>{drawn}</defs><g transform=\"{}\"><g filter=\"url(#{DRAWN_ID})\"><image width=\"{}\" height=\"{}\" preserveAspectRatio=\"none\" transform=\"{}\" xlink:href=\"data:image/png;base64,{}\"/></g></g></svg>",
matrix(outer),
x1 - x0,
y1 - y0,
iw,
ih,
matrix(place),
base64(&png)
);
@@ -1420,19 +1542,65 @@ impl SvgFilterFx {
}
let Some(mut small) = tiny_skia::Pixmap::new(sw, sh) else { return };
resvg::render(&tree, tiny_skia::Transform::identity(), &mut small.as_mut());
let out = if s < 1.0 {
let out = if back == Affine::IDENTITY {
small
} else {
let Some(mut full) = tiny_skia::Pixmap::new(w as u32, h as u32) else { return };
let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() };
let up = (1.0 / s) as f32;
full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_scale(up, up), None);
let [a, b, c, d, e, f] = back.as_coeffs().map(|v| v as f32);
full.draw_pixmap(0, 0, small.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None);
full
} else {
small
};
if out.data().len() == data.len() {
data.copy_from_slice(out.data());
}
}
/// The canvas a filter whose user space is turned, skewed or scaled unevenly runs on, for a
/// `w` × `h` raster lying in the document as `space` says, at resolution `s`
/// ([`raster_resolution`]), whose art draws within `drawn` (raster pixels): its axes are the user
/// space's, so the filter's offsets, blurs and other lengths run along them as SVG 1.1 measures
/// them, and it covers what the raster shows. Along each of its axes its pixels are about as
/// large as the raster's at `s`, and coarser when it would hold more than [`TURNED_ROOM`] times
/// as many pixels as the raster does at `s`, and when a morphology radius or kernel unit would
/// span more than 32 of its pixels or a blur's standard deviation more than 512 (a length in the
/// object's box measured against the art's box on the canvas). Returns its size, the map from
/// user space to it, and the map from it to the raster's pixels; `None` when the spaces can't
/// be measured.
fn turned_canvas(&self, w: usize, h: usize, s: f64, drawn: Rect, space: &PixelSpace) -> Option<(u32, u32, Affine, Affine)> {
let to_px = space.to_doc.inverse() * self.to_doc();
let from_px = to_px.inverse();
let ub = from_px.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64));
let most = ((w as f64 * s).ceil().max(1.0) * (h as f64 * s).ceil().max(1.0) * TURNED_ROOM).max(1.0);
// Canvas pixels a unit along each axis of the user space: as many as the raster's at `s`.
let [a, b, c, d, _, _] = to_px.as_coeffs();
let (mut qx, mut qy) = (s * a.hypot(b), s * c.hypot(d));
let pixels = ub.width() * qx * ub.height() * qy;
if pixels > most {
let k = (most / pixels).sqrt();
(qx, qy) = (qx * k, qy * k);
}
// A length along an axis spans length × q canvas pixels, or length × the art's box on the
// canvas along that axis: both shrink with q.
let art = from_px.transform_rect_bbox(drawn);
for (length, cap) in [(self.window, MAX_WINDOW_PX), (self.blur, MAX_BLUR_PX)] {
let px = if self.box_units { length * (art.width() * qx).max(art.height() * qy) } else { length * qx.max(qy) };
if px > cap {
let k = cap / px;
(qx, qy) = (qx * k, qy * k);
}
}
if !(qx.is_finite() && qx > 0.0 && qy.is_finite() && qy > 0.0 && ub.is_finite()) {
return None;
}
let (cw, ch) = ((ub.width() * qx).ceil().max(1.0), (ub.height() * qy).ceil().max(1.0));
// Rounding up adds at most a row and a column.
if cw * ch > most + cw + ch + 1.0 {
return None;
}
let outer = Affine::scale_non_uniform(qx, qy) * Affine::translate(Vec2::new(-ub.x0, -ub.y0));
Some((cw as u32, ch as u32, outer, to_px * outer.inverse()))
}
}
/// The farthest a filter's region reaches beyond the object, in points.
@@ -1450,6 +1618,22 @@ fn drawn_box(data: &[u8], w: usize, h: usize) -> Option<(usize, usize, usize, us
(x1 > x0 && y1 > y0).then_some((x0, y0, x1, y1))
}
/// The pixels of `data` (premultiplied RGBA8, `w` × `h`) drawn onto a `cw` × `ch` canvas through
/// `to_canvas` (the raster's pixels → the canvas's), cut to the box of the canvas pixels that aren't
/// transparent (the whole canvas when all are): a PNG of them, the box's corner on the canvas, and
/// its size.
fn on_canvas(data: &[u8], w: usize, h: usize, cw: u32, ch: u32, to_canvas: Affine) -> Option<(Vec<u8>, usize, usize, usize, usize)> {
let size = tiny_skia::IntSize::from_wh(u32::try_from(w).ok()?, u32::try_from(h).ok()?)?;
let raster = tiny_skia::Pixmap::from_vec(data.to_vec(), size)?;
let mut canvas = tiny_skia::Pixmap::new(cw, ch)?;
let paint = tiny_skia::PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..Default::default() };
let [a, b, c, d, e, f] = to_canvas.as_coeffs().map(|v| v as f32);
canvas.draw_pixmap(0, 0, raster.as_ref(), &paint, tiny_skia::Transform::from_row(a, b, c, d, e, f), None);
let (cw, ch) = (cw as usize, ch as usize);
let (x0, y0, x1, y1) = drawn_box(canvas.data(), cw, ch).unwrap_or((0, 0, cw, ch));
Some((png_of(canvas.data(), cw, x0, y0, x1, y1)?, x0, y0, x1 - x0, y1 - y0))
}
/// The pixels of `data` (premultiplied RGBA8, `w` wide) in columns x0..x1 and rows y0..y1, as a PNG.
fn png_of(data: &[u8], w: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Option<Vec<u8>> {
use image::ImageEncoder;
+150 -1
View File
@@ -222,6 +222,154 @@ fn user_space_starts_at_the_origin() {
assert!((filter(json!({ "xml": half, "origin": [-10.0, 0.0] })).outset(b) - 10.0).abs() < 1e-9);
}
/// The opacity of `data` (`w` wide) after the filter `xml` with `params` runs on a blue square
/// over 10..20 pt of a 40 pt raster one point a pixel, at each of `points`.
fn turned_run(xml: &str, params: serde_json::Value, points: &[(usize, usize)]) -> Vec<u8> {
let w = 40;
let mut data = image(w, w, |x, y| if (10..20).contains(&x) && (10..20).contains(&y) { [0, 0, 255, 255] } else { [0; 4] });
let mut p = params;
p["xml"] = json!(xml);
filter(p).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
points.iter().map(|&(x, y)| at(&data, w, x, y)[3]).collect()
}
const SHIFT_X: &str = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dx="4"/></filter>"#;
/// With `axes`, the filter runs in its turned or skewed user space: an offset along its x axis
/// moves the art along that axis in the document (SVG 1.1 measures a primitive's lengths in the
/// user space of the element the filter is on).
#[test]
fn a_turned_user_space_moves_the_art_along_its_own_axes() {
// The square spans 10..20 pt; moved 4 pt along x it covers 14..24 across.
let points = [(22, 15), (15, 22), (12, 11)];
assert_eq!(turned_run(SHIFT_X, json!({}), &points), [255, 0, 0], "the document's axes: to the right");
// Turned a quarter turn: the filter's x axis points down the page.
let down = turned_run(SHIFT_X, json!({ "axes": [0.0, 1.0, -1.0, 0.0] }), &points);
assert_eq!(down, [0, 255, 0], "moved down, not to the right");
// Skewed: one unit along y is one across and one down, so dy 4 moves the art 4 pt each way.
let shift_y = r#"<filter id="Shift" x="-1" y="-1" width="3" height="3"><feOffset dy="4"/></filter>"#;
let skewed = turned_run(shift_y, json!({ "axes": [1.0, 0.0, 1.0, 1.0] }), &[(22, 22), (11, 22), (11, 11)]);
assert!(skewed[0] > 200 && skewed[1] < 60 && skewed[2] < 60, "moved across and down: {skewed:?}");
}
#[test]
fn axes_the_effect_cannot_measure_are_not_drawn() {
for axes in [json!([0, 0, 0, 0]), json!([1, 2]), json!([1, 0, 0, "1"]), json!([2000, 0, 0, 1]), json!([0.01, 0, 0, 0.01]), json!("turned")] {
let e = Effect { id: SVG_FILTER.into(), params: json!({ "xml": SHIFT_X, "axes": axes }), visible: true };
assert!(raster_effects(&[e]).is_empty(), "{axes}: drawn without it");
assert!(valid_axes(&axes).is_none(), "{axes}");
}
assert_eq!(valid_axes(&json!([0, 1, -1, 0])), Some(Affine::new([0.0, 1.0, -1.0, 0.0, 0.0, 0.0])));
}
/// A region measured against the object's box is measured against its box in the turned user
/// space: a diamond turned an eighth of a turn is a square there, and a flood over 0..100% of it
/// covers the diamond alone.
#[test]
fn a_turned_region_is_measured_against_the_box_in_its_user_space() {
let w = 40;
let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0;
let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] });
let flood = r##"<filter id="F" filterUnits="userSpaceOnUse" x="0%" y="0%" width="100%" height="100%"><feFlood flood-color="#ff0000"/></filter>"##;
let h = std::f64::consts::FRAC_1_SQRT_2;
filter(json!({ "xml": flood, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "inside the diamond");
assert!(at(&data, w, 12, 12)[3] < 40, "outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12));
}
/// In a turned user space, a region in the object's bounding box (the default `filterUnits`) and a
/// primitive's lengths in it (`primitiveUnits="objectBoundingBox"`) are measured against the
/// object's box there: on a diamond turned an eighth of a turn, a flood over 0..100% of the box
/// covers the diamond alone.
#[test]
fn a_turned_filter_measures_box_units_against_the_box_in_its_user_space() {
let w = 40;
let h = std::f64::consts::FRAC_1_SQRT_2;
let region = r##"<filter id="F" x="0" y="0" width="1" height="1"><feFlood flood-color="#ff0000"/></filter>"##;
let primitive = r##"<filter id="F" filterUnits="userSpaceOnUse" x="-1000" y="-1000" width="2000" height="2000" primitiveUnits="objectBoundingBox"><feFlood flood-color="#ff0000" x="0" y="0" width="1" height="1"/></filter>"##;
for xml in [region, primitive] {
let diamond = |x: usize, y: usize| (x as f64 - 19.5).abs() + (y as f64 - 19.5).abs() <= 10.0;
let mut data = image(w, w, |x, y| if diamond(x, y) { [0, 0, 255, 255] } else { [0; 4] });
filter(json!({ "xml": xml, "axes": [h, h, -h, h] })).apply(&mut data, w, w, &space(w, w, 1.0, 1.0));
assert_eq!(at(&data, w, 20, 20), [255, 0, 0, 255], "{xml}: inside the diamond");
assert!(at(&data, w, 12, 12)[3] < 40, "{xml}: outside the diamond, inside its box on the page: {:?}", at(&data, w, 12, 12));
}
}
/// SVG import stores a filter's user space again only when `scale` and `axes` together stay within
/// what it holds: each alone can be valid while their product is not.
#[test]
fn a_user_space_opens_again_only_within_what_import_stores() {
let opens = |scale: f64, axes: serde_json::Value| filter(json!({ "xml": SHIFT_X, "scale": scale, "axes": axes })).opens_again();
assert!(opens(1000.0, json!(null)));
assert!(opens(2.0, json!([0.0, 1.0, -1.0, 0.0])));
assert!(!opens(1000.0, json!([2.0, 0.0, 0.0, 2.0])), "scale 2000 across");
assert!(!opens(0.001, json!([0.5, 0.0, 0.0, 0.5])), "scale 0.0005 across");
let space = user_space(Affine::new([0.0, 2.0, -2.0, 0.0, 5.0, 6.0])).unwrap();
assert_eq!((space.scale, space.origin, space.axes), (2.0, [5.0, 6.0], Some([0.0, 1.0, -1.0, 0.0])));
}
/// The region of a turned filter reaches as far as its turned box does.
#[test]
fn a_turned_region_reaches_along_the_turned_axes() {
let b = Rect::new(0.0, 0.0, 50.0, 50.0);
let user = r#"<filter id="u" filterUnits="userSpaceOnUse" x="-30" y="-5" width="100" height="100"><feOffset/></filter>"#;
assert!((filter(json!({ "xml": user })).outset(b) - 45.0).abs() < 1e-9, "45 pt below the box");
// A quarter turn: user y runs to the left of the page, so -5..95 of it lies 95 pt left of the box.
assert!((filter(json!({ "xml": user, "axes": [0.0, 1.0, -1.0, 0.0] })).outset(b) - 95.0).abs() < 1e-9);
}
/// A filter skewed as far as `axes` allows runs on a canvas no larger than four times the raster's
/// pixels, however far the skew spreads the raster's box in its user space.
#[test]
fn a_skewed_filter_runs_within_its_pixel_budget() {
let (w, h) = (64, 48);
let f = filter(json!({ "xml": SHIFT_X, "axes": [1.0, 0.0, 999.0, 1.0] }));
let all = Rect::new(0.0, 0.0, w as f64, h as f64);
let (cw, ch, ..) = f.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap();
let (cw, ch) = (f64::from(cw), f64::from(ch));
assert!(cw * ch <= TURNED_ROOM * (w * h) as f64 + cw + ch + 1.0, "{cw} × {ch}");
// It still draws.
let mut data = image(w, h, |x, y| if (20..40).contains(&x) && (10..30).contains(&y) { [0, 0, 255, 255] } else { [0; 4] });
f.apply(&mut data, w, h, &space(w, h, 1.0, 1.0));
// A plain quarter turn keeps the raster's own pixel size.
let turned = filter(json!({ "xml": SHIFT_X, "axes": [0.0, 1.0, -1.0, 0.0] }));
let (cw, ch, outer, _) = turned.turned_canvas(w, h, 1.0, all, &space(w, h, 1.0, 1.0)).unwrap();
assert_eq!((cw, ch), (48, 64));
assert!((outer.determinant() - 1.0).abs() < 1e-9);
// Stretched 100 times across and squeezed 100 times down: each canvas axis keeps the raster's
// detail along it, not one column of it.
let stretched = filter(json!({ "xml": SHIFT_X, "axes": [100.0, 0.0, 0.0, 0.01] }));
let (cw, ch, ..) = stretched.turned_canvas(100, 100, 1.0, Rect::new(0.0, 0.0, 100.0, 100.0), &space(100, 100, 1.0, 1.0)).unwrap();
assert_eq!((cw, ch), (100, 100));
}
/// On a far skewed canvas, a radius or a standard deviation in the object's box spans no more
/// canvas pixels than the caps allow: it is measured against the art's box on the canvas, which the
/// skew spreads far wider than the art's box in the raster.
#[test]
fn a_skewed_filter_keeps_box_lengths_within_the_caps_on_its_canvas() {
let (w, h) = (64, 48);
let sp = space(w, h, 1.0, 1.0);
let drawn = Rect::new(20.0, 10.0, 40.0, 30.0);
for (xml, length, cap) in [
("<filter id=\"m\" primitiveUnits=\"objectBoundingBox\"><feMorphology radius=\"1.5\"/></filter>", 1.5, MAX_WINDOW_PX),
("<filter id=\"b\" primitiveUnits=\"objectBoundingBox\"><feGaussianBlur stdDeviation=\"20\"/></filter>", 20.0, MAX_BLUR_PX),
] {
let f = filter(json!({ "xml": xml, "axes": [1.0, 0.0, 999.0, 1.0] }));
let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap();
// The art's box on the canvas: the drawn pixels taken into user space, then onto the canvas.
let art = (outer * f.to_doc().inverse() * sp.to_doc).transform_rect_bbox(drawn);
let px = length * art.width().max(art.height());
assert!(px <= cap + 1e-6, "{xml}: {px} canvas pixels");
}
// A user-space radius spans no more than 32 canvas pixels along either axis.
let f = filter(json!({ "xml": "<filter id=\"u\"><feMorphology radius=\"100\"/></filter>", "scale": 1000.0, "axes": [1.0, 0.0, 999.0, 1.0] }));
let (_, _, outer, _) = f.turned_canvas(w, h, 1.0, drawn, &sp).unwrap();
let [qx, _, _, qy, _, _] = outer.as_coeffs();
assert!(100.0 * qx.max(qy) <= MAX_WINDOW_PX + 1e-6, "{qx} {qy}");
}
#[test]
fn runs_no_finer_than_the_raster_effects_resolution() {
let w = 16;
@@ -448,7 +596,8 @@ fn a_region_measured_against_the_box_is_written_out() {
let far = r#"<filter id="r" filterUnits="userSpaceOnUse" x="-50%" y="0" width="200%" height="10"><feOffset/></filter>"#;
let f = filter(json!({ "xml": far, "origin": [10.0, 0.0] }));
assert_eq!(
f.written_xml(Rect::new(10.0, 0.0, 30.0, 10.0)).as_deref(),
// The object over 10..30 pt of the page: 0..20 of the user space that starts at the origin.
f.written_xml(Rect::new(0.0, 0.0, 20.0, 10.0)).as_deref(),
Some(r#"<filter id="r" filterUnits="userSpaceOnUse" x="-10" y="0" width="40" height="10"><feOffset/></filter>"#)
);
let plain = filter(json!({ "xml": RED_FLOOD }));
+77 -17
View File
@@ -9,8 +9,9 @@
//! text. Each action is an `/action-N` block with a hexadecimal `/name`; each step is an `/event-N`
//! block inside one, with its `/internalName` in parentheses, the `/localizedName` it is shown with
//! as hexadecimal text, and `/isOn` 0 when it is left out of playback; each value a step was
//! recorded with is a `/parameter-N` block inside it, which is counted, and whose hexadecimal
//! `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
//! recorded with is a `/parameter-N` block inside it, which is counted, whose `/key` (a number),
//! `/type` (text in parentheses) and `/value` (a number, text in parentheses or hexadecimal text) are
//! kept, and whose hexadecimal `/value` is checked against its byte count. The set's `/actionCount`, an action's `/eventCount`
//! and a step's `/parameterCount` give how many actions, steps and recorded values follow.
//! The layout follows the README of Inventsable's Redesigning-Illustrator-Actions-in-Scripting
//! (https://github.com/Inventsable/Redesigning-Illustrator-Actions-in-Scripting), the forum post
@@ -40,6 +41,8 @@ const MAX_STEPS: usize = 10_000;
/// The most steps read in the set: a small text can hold hundreds of thousands of empty steps, and
/// the answer holds an object for each.
const MAX_SET_STEPS: usize = 100_000;
/// The most recorded values kept in the set; the others are counted but not kept.
const MAX_VALUES: usize = 100_000;
/// The longest name kept (bytes).
const MAX_NAME: usize = 1024;
/// The most tokens listed as unread.
@@ -56,7 +59,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Read Action Set File",
[],
None,
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
"{path? | data?: the file's text | dataBase64?, name?: the file's name (default: the path's)} read an action set another app saved as text (.aia, starting \"/version\") without changing anything → {set: the set's /name (else the file's name without its extension, else empty), version, actions: [{name, steps: [{name: the step's /internalName, label: its /localizedName, or null when it has none or it is blank, on: false when /isOn is 0, params: how many /parameter blocks it has, values: [{key: the block's /key, or null, type: its /type, or null, value: its /value when it is a number, or text that is UTF-8 (else null), bytes?: the text's length in bytes}] (the first 100,000 recorded values in the set), line}]}], unread: [{line, text}] (tokens that aren't read, at most 1000), truncated: true when a cap stopped the reading (8 MiB, 16 open blocks, 1,000 actions, 10,000 steps in an action, 100,000 steps in the set; names past 1,024 bytes are cut), when the text ends inside a block or a value or after a field's name, when /actionCount, /eventCount or a step's /parameterCount differs from the actions, steps or recorded values read (a negative count, one too large for a number and one that isn't a number always differ), or when a hexadecimal name, label or recorded /value isn't as many bytes as its count says}. Give exactly one of path, data and dataBase64. Text that doesn't start with /version and a number is an error",
always,
read
)]
@@ -73,12 +76,33 @@ pub struct AiaStep {
pub on: Option<i64>,
/// How many `/parameter-N` blocks it has.
pub params: usize,
/// Its `/parameter-N` blocks, in order, while the set keeps at most [`MAX_VALUES`].
pub values: Vec<AiaValue>,
/// Its `/parameterCount`, if it has one.
pub declared: Option<i64>,
/// The line its block opens on (from 1).
pub line: usize,
}
/// A value a step was recorded with: a `/parameter-N` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AiaValue {
/// Its `/key`, if it has one that fits an `i64`.
pub key: Option<i64>,
/// Its `/type`, read as UTF-8 with replacement characters, if it has one.
pub kind: Option<String>,
/// Its `/value`, if it is a number that fits an `i64` or text.
pub value: Option<AiaData>,
}
/// A recorded `/value` that is kept.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AiaData {
Int(i64),
/// The bytes of text in parentheses or of hexadecimal text.
Text(Vec<u8>),
}
/// An action: an `/action-N` block.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AiaAction {
@@ -106,6 +130,8 @@ pub struct AiaSet {
pub truncated: bool,
/// How many steps were read in all the actions.
steps: usize,
/// How many recorded values were kept in all the steps.
values: usize,
}
/// A token of the text.
@@ -252,7 +278,8 @@ fn hex_bytes(digits: &[u8]) -> Option<Vec<u8>> {
enum Kind {
Action,
Step,
Param,
/// A recorded value, and whether it is kept.
Param(bool),
/// A block that isn't read, or one past a cap.
Other,
}
@@ -315,12 +342,18 @@ fn open_block(set: &mut AiaSet, stack: &[Kind], name: &[u8], line: usize) -> Kin
}
},
Some(Kind::Step) if numbered(name, b"parameter-") => {
let mut kept = false;
if let Some(s) = set.actions.last_mut().and_then(|a| a.steps.last_mut()) {
s.params += 1;
if set.values < MAX_VALUES {
s.values.push(AiaValue::default());
set.values += 1;
kept = true;
}
}
Kind::Param
Kind::Param(kept)
}
Some(Kind::Param | Kind::Other) => Kind::Other,
Some(Kind::Param(_) | Kind::Other) => Kind::Other,
_ => {
unread(set, line, format!("/{} {{", String::from_utf8_lossy(name)));
Kind::Other
@@ -355,12 +388,23 @@ fn set_hex(set: &mut AiaSet, kind: Option<&Kind>, name: Option<&[u8]>, bytes: Op
}
}
/// Mark `set` truncated when the hexadecimal `/value` on `line` isn't as many bytes as its count
/// says.
fn check_value(set: &mut AiaSet, bytes: Option<Vec<u8>>, line: usize) {
if bytes.is_none() {
/// Set the field `name` of the recorded value open on `line` to `token`: its `/key`, `/type` or
/// `/value`, when the value is `kept`. A hexadecimal `/value` that isn't as many bytes as its count
/// says marks `set` truncated, kept or not.
fn set_param(set: &mut AiaSet, kept: bool, name: Option<&[u8]>, token: Token, line: usize) {
if name == Some(b"value".as_slice()) && matches!(token, Token::Hex(None)) {
set.truncated = true;
unread(set, line, BAD_HEX);
return;
}
let value = set.actions.last_mut().and_then(|a| a.steps.last_mut()).and_then(|s| s.values.last_mut());
let Some(v) = value.filter(|_| kept) else { return };
match (name, token) {
(Some(b"key"), Token::Int(key)) => v.key = key,
(Some(b"type"), Token::Text(t)) => v.kind = Some(String::from_utf8_lossy(&t).into_owned()),
(Some(b"value"), Token::Int(Some(n))) => v.value = Some(AiaData::Int(n)),
(Some(b"value"), Token::Text(t) | Token::Hex(Some(t))) => v.value = Some(AiaData::Text(t)),
_ => {}
}
}
@@ -448,13 +492,13 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
unread(&mut set, line, "}");
}
}
Token::Hex(bytes) if matches!(stack.last(), Some(Kind::Param)) => {
if field(&mut pending).as_deref() == Some(b"value".as_slice()) {
check_value(&mut set, bytes, line);
}
_ if matches!(stack.last(), Some(Kind::Param(_))) => {
let kept = matches!(stack.last(), Some(Kind::Param(true)));
let name = field(&mut pending);
set_param(&mut set, kept, name.as_deref(), token, line);
}
// The other values inside a recorded value, or a block that isn't read.
_ if matches!(stack.last(), Some(Kind::Param | Kind::Other)) => {
// The values inside a block that isn't read.
_ if matches!(stack.last(), Some(Kind::Other)) => {
pending = None;
}
Token::Hex(bytes) => {
@@ -521,6 +565,21 @@ pub fn read_aia(bytes: &[u8]) -> std::result::Result<AiaSet, String> {
Ok(set)
}
/// A recorded value in `actionSet.read`'s answer: `{key, type, value, bytes?}`, the value a number,
/// text that is UTF-8 (else null) with its length in bytes, or null.
fn value_json(v: &AiaValue) -> Value {
let mut out = json!({ "key": v.key, "type": v.kind, "value": null });
match &v.value {
Some(AiaData::Int(n)) => out["value"] = json!(n),
Some(AiaData::Text(t)) => {
out["value"] = json!(std::str::from_utf8(t).ok());
out["bytes"] = json!(t.len());
}
None => {}
}
out
}
fn read(_: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "actionSet.read";
let (path, data, b64) = (text_param(p, "path", C)?, text_param(p, "data", C)?, text_param(p, "dataBase64", C)?);
@@ -544,7 +603,8 @@ fn read(_: &mut Session, p: &Value) -> Result<Value> {
.iter()
.map(|s| {
let label = s.label.clone().filter(|l| !l.trim().is_empty());
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "line": s.line })
let values: Vec<Value> = s.values.iter().map(value_json).collect();
json!({ "name": s.name, "label": label, "on": s.on != Some(0), "params": s.params, "values": values, "line": s.line })
})
.collect();
json!({ "name": a.name, "steps": steps })
@@ -1225,7 +1225,7 @@ fn expand_dashes_keeps_the_fill_below_and_follows_aligned_corners() {
let mut centred = 0;
for id in ids(&r) {
let sp = path(&s, id).subpaths[0].clone();
if let [a, b, c] = sp.anchors.as_slice()
if let [a, b, c] = &*sp.anchors.to_vec()
&& corners.iter().any(|k| b.p.distance(*k) < 1e-6)
{
assert!((a.p.distance(b.p) - 5.0).abs() < 1e-6 && (c.p.distance(b.p) - 5.0).abs() < 1e-6, "{sp:?}");
+6 -6
View File
@@ -14,8 +14,9 @@ use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_geom::Point;
use super::super::links::{Status, statuses};
use super::super::panelcmds::listed_artboards;
use super::super::select::{is_selectable, on_artboard, selectable};
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, point_indices, switch_or, text_param};
use super::super::{CommandSpec, bad, checked_ids_param, cmd, has_doc, switch_or, text_param};
use crate::{DocState, Result, Session};
/// How Select by Artboards relates an object to the chosen artboards (`relation`).
@@ -33,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select by Artboards",
["Object", "Plug-ins", "Selection Tools"],
None,
"{artboards: [index…] (0-based, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
"{artboards: [index…] (0-based whole numbers, at least one), relation?: \"overlap\" (default: on at least one of them, as select.allOnArtboard takes it: the bounds overlap the artboard or the centre is on it) | \"inside\" (the bounds lie wholly within one of them, edges included) | \"outside\" (on none of them)} select those objects among the ones Select All takes (in isolation mode, the isolated container's); hidden and locked objects, objects on hidden, locked or template layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art → {count}",
has_doc,
by_artboards
),
@@ -58,13 +59,12 @@ fn by_artboards(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`relation` must be overlap, inside or outside"));
}
let listed = p.get("artboards").ok_or_else(|| bad(C, "missing `artboards`"))?;
let indices = point_indices(listed).ok_or_else(|| bad(C, "`artboards` must be a list of artboard indices"))?;
if indices.is_empty() {
if listed.as_array().is_some_and(Vec::is_empty) {
return Err(bad(C, "choose at least one artboard"));
}
let st = s.doc()?;
let rects =
indices.iter().map(|i| st.doc.artboards.get(*i).map(|a| a.rect)).collect::<Option<Vec<_>>>().ok_or_else(|| bad(C, "no such artboard"))?;
let rects: Vec<_> =
listed_artboards(&st.doc, listed, "artboards", C)?.into_iter().filter_map(|i| st.doc.artboards.get(i)).map(|a| a.rect).collect();
let symbols = st.doc.symbol_boxes();
let ids: Vec<NodeId> = selectable(&st.doc, st.isolation)
.into_iter()
@@ -108,6 +108,35 @@ fn bad_params_are_errors_and_leave_the_selection() {
}
}
/// A malformed `artboards` entry is refused as one, naming the parameter, before any entry is
/// looked up; a value that is not a list, an empty list, a left-out list and a whole number past
/// the last artboard each have their own error.
#[test]
fn artboard_errors_say_what_is_wrong() {
let mut s = three_boards();
let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0);
let entries = "invalid parameters for `addon.select.byArtboards`: `artboards` must contain whole numbers";
let not_a_list = "invalid parameters for `addon.select.byArtboards`: `artboards` must be a list of artboard indices";
for (p, want) in [
(json!({"artboards": ["1"]}), entries),
(json!({"artboards": [-1]}), entries),
(json!({"artboards": [1.5]}), entries),
(json!({"artboards": [true]}), entries),
(json!({"artboards": [9, "1"]}), entries),
(json!({"artboards": "0"}), not_a_list),
(json!({"artboards": null}), not_a_list),
(json!({"artboards": []}), "invalid parameters for `addon.select.byArtboards`: choose at least one artboard"),
(json!({}), "invalid parameters for `addon.select.byArtboards`: missing `artboards`"),
(json!({"artboards": [9]}), "no such artboard"),
(json!({"artboards": [0, 9]}), "no such artboard"),
] {
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert_eq!(s.execute(C, &p).unwrap_err().to_string(), want, "{p}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{p}");
}
assert_eq!(pick(&mut s, json!({"artboards": [0, 0]})), vec![a]);
}
#[test]
fn a_symbol_instance_is_measured_by_its_art() {
// The symbol's art, (100, 60) to (140, 80), drawn 50 pt up and left: (50, 10) to (90, 30), on
+30 -7
View File
@@ -12,6 +12,7 @@ use super::{
thread_local! {
static BOX_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static CANDIDATE_VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
static TRACES_ON_THIS_THREAD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
// ---------- Image Trace ----------
@@ -548,15 +549,20 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
Ok(seams.into_iter().chain(groups).collect())
}
/// What a trace depends on: the document it is made in, the object traced (an image, or an Image
/// Trace object traced again), its image, the image's encoded bytes, and the settings it is traced
/// with. The tracer makes the same paths of the same inputs, so a trace made away from the command
/// ([`TraceRun`]) stands in for the command's own in the same document.
/// What a trace depends on: the document it is made in and the content it was reverted to, the
/// object traced (an image, or an Image Trace object traced again), its image, the image's encoded
/// bytes, and the settings it is traced with. The tracer makes the same paths of the same inputs,
/// so a trace made away from the command ([`TraceRun`]) stands in for the command's own in the same
/// document until File › Revert replaces its content.
#[derive(Clone, Debug, PartialEq)]
struct TraceInputs {
/// The [`DocState::uid`](crate::DocState::uid) of the document traced in. A trace made in one
/// document never stands in for one in another, however alike their images and settings.
doc: u64,
/// The document's [`DocState::reverts`](crate::DocState::reverts) when the trace was prepared.
/// A trace prepared before File › Revert never stands in for one after it, even when the
/// restored image, pixels, object and settings are the same.
reverts: u64,
target: NodeId,
image: Box<ImageObject>,
/// The settings traced with, as JSON.
@@ -625,7 +631,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
let bytes = Arc::clone(&blob.bytes);
let library = trace_library(c, s, &mut params)?;
let traced_with = serde_json::to_value(&params).map_err(|e| EngineError::Other(e.to_string()))?;
let inputs = TraceInputs { doc: s.doc()?.uid, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
let st = s.doc()?;
let inputs = TraceInputs { doc: st.uid, reverts: st.reverts, target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
}
@@ -641,7 +648,8 @@ pub struct Traced {
impl Traced {
/// Hand it to the next run of its command with the same inputs ([`TraceRun::params`]) in the
/// document it was made in, which applies it as one undo step instead of tracing again. Any
/// other trace drops it, a trace in another document included.
/// other trace drops it and traces again, a trace in another document included, and so does
/// the command after File › Revert replaced the document's content.
pub fn hand_in(self, s: &mut Session) {
s.trace_hand_off = Some(self);
}
@@ -650,6 +658,8 @@ impl Traced {
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
#[cfg(test)]
TRACES_ON_THIS_THREAD.with(|n| n.set(n.get() + 1));
// An image over the tracer's size is traced scaled down (the paths are scaled back).
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
if !steps(0, 0) {
@@ -725,17 +735,30 @@ impl TraceRun {
}
/// Does it still apply: would the command trace the same object, image, pixels and settings
/// now, in the document it was prepared in?
/// now, in the document it was prepared in, with no File › Revert since?
pub fn current(&self, s: &Session) -> bool {
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
}
/// Has File › Revert replaced the content of the document it was prepared in since then? False
/// when that document is no longer open.
pub fn reverted(&self, s: &Session) -> bool {
let TraceInputs { doc, reverts, .. } = self.prepared.inputs;
s.documents().iter().any(|st| st.uid == doc && st.reverts != reverts)
}
/// Decode and trace the image, telling `steps` how far it has got → what it traced, or why it
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
/// document, so it can run on any thread.
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
}
/// How many images this thread has decoded and traced so far.
#[cfg(test)]
pub(crate) fn traces_on_this_thread() -> usize {
TRACES_ON_THIS_THREAD.with(std::cell::Cell::get)
}
}
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
+2 -1
View File
@@ -356,7 +356,8 @@ fn mirror_open(sp: &SubPath, axis: &Axis, m: Affine) -> Vec<SubPath> {
if !end_on {
run.reverse();
}
let Some((last, body)) = run.anchors.split_last() else { return vec![] };
let run = run.anchors.into_vec();
let Some((last, body)) = run.split_last() else { return vec![] };
let q = axis.project(last.p);
let mut anchors = body.to_vec();
anchors.push(Anchor::with_handles(q, last.h_in, m * last.h_in));
+3 -9
View File
@@ -10,6 +10,7 @@ use vectorcraft_doc::{CharStyle, Guide, Node, NodeId, NodeKind, SavedSelection,
use vectorcraft_geom::Vec2;
use super::edit::selected_roots;
use super::panelcmds::artboard_at;
use super::pathops::Beside;
use super::select::{first_selectable, is_selectable, selectable_ids, walk_selectable};
use super::{
@@ -201,7 +202,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add Guide",
[],
None,
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
"{vertical: bool, pos: pt (x for vertical, y for horizontal), artboard?: index (0-based whole number; an artboard guide: it runs across that artboard only and moves, is copied and is deleted with it; default, or null, a canvas guide, across the whole canvas), layer?: id (the layer it is on, shown, hidden, locked and deleted with it; default the current layer)} → {index}",
has_doc,
guide_add
),
@@ -767,15 +768,8 @@ fn clear_guides(s: &mut Session, _: &Value) -> Result<Value> {
fn guide_add(s: &mut Session, p: &Value) -> Result<Value> {
let pos = f64_req(p, "pos", "guide.add")?;
let vertical = switch_or(p, "vertical", false, "guide.add")?;
let artboard = match p.get("artboard").filter(|v| !v.is_null()) {
Some(v) => {
let boards = &s.doc()?.doc.artboards;
let ab = v.as_u64().and_then(|i| boards.get(usize::try_from(i).ok()?)).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
Some(ab.id)
}
None => None,
};
let st = s.doc()?;
let artboard = artboard_at(&st.doc, p, "artboard", "guide.add")?.and_then(|i| st.doc.artboards.get(i)).map(|a| a.id);
let layer = match id_param(p, "layer") {
Some(l) if st.doc.node(l).is_some_and(Node::is_layer) => Some(l),
Some(_) => return Err(bad("guide.add", "layer must name a layer or sublayer")),
+6 -6
View File
@@ -46,7 +46,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
let sp = vectorcraft_tools::draw2::catmull_rom(&marked, false);
if sp.anchors.len() < 3 {
// Two anchors closed would run back over the line itself.
return SubPath::new(sp.anchors, closed && n > 2);
return SubPath::of(sp.anchors, closed && n > 2);
}
let fitted = po::simplify_with(
&PathData::single(sp.clone()),
@@ -62,7 +62,7 @@ fn fit_freehand(pts: &[Point], tol: f64, closed: bool) -> SubPath {
f.h_in = f.p;
}
}
SubPath::new(anchors, closed)
SubPath::of(anchors, closed)
}
/// The path of a freehand stroke: fitted at `tol` ([`fit_freehand`]), or with no `tol` the points
@@ -133,13 +133,13 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
*s0 = s1.p;
let (Some(e0), Some(e1)) = (stroke.last_mut(), sp.anchors.get(end)) else { return None };
*e0 = e1.p;
let fit = stroke_subpath(&stroke, tol, false).anchors;
let fit = stroke_subpath(&stroke, tol, false).anchors.into_vec();
let (Some(f0), Some(f1)) = (fit.first().copied(), fit.last().copied()) else { return None };
let inner = fit.get(1..fit.len().saturating_sub(1)).unwrap_or_default();
let (before, after): (Vec<Anchor>, Vec<Anchor>) = if sp.closed {
((0..=(start + n - end) % n).filter_map(|k| sp.anchors.get((end + k) % n).copied()).collect(), vec![])
} else {
(sp.anchors.get(..=start)?.to_vec(), sp.anchors.get(end..)?.to_vec())
(sp.anchors.get_range(..=start)?, sp.anchors.get_range(end..)?)
};
let mut anchors = before;
if let Some(a) = anchors.last_mut() {
@@ -316,12 +316,12 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
// outgoing handle.
let mut other_len = 0.0;
if let Some((_, _, y, _)) = &connect
&& let Some((y0, rest)) = y.anchors.split_first()
&& let Some(y0) = y.anchors.first()
{
if let Some(last) = sp.anchors.last_mut() {
*last = Anchor::with_handles(y0.p, last.h_in + (y0.p - last.p), y0.h_out);
}
sp.anchors.extend_from_slice(rest);
sp.anchors.extend(y.anchors.iter().skip(1));
other_len = subpath_len(y);
}
// What the pen recorded along the path (in the direction it is continued in), followed by
+11 -11
View File
@@ -274,7 +274,7 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
for a in &mut out {
*a = Anchor::with_handles(a.p, a.h_in, a.h_out);
}
out
out.into_vec()
}
/// Distance (points) from an anchor within which a smoothed closed path starts at that anchor
@@ -549,7 +549,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
if sp.closed {
let start = sp.anchors[0].p;
let Some(k) = marked.iter().position(|m| !m) else {
let corners = smooth_corners(&sp.anchors, true, radius);
let corners = smooth_corners(&sp.anchors.contiguous(), true, radius);
let Some(c) = corners.iter().position(|c| *c) else {
// Everything is in range and nothing is a corner: smooth the whole closed path,
// across its start too.
@@ -557,7 +557,7 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
return f.subpaths.into_iter().next().map(|r| start_nearest(r, start, sp));
};
// Cut the path open at a corner, which then ends the last part as well as starting the first.
let mut open = sp.anchors.clone();
let mut open = sp.anchors.to_vec();
open.rotate_left(c);
let mut cut = corners;
cut.rotate_left(c);
@@ -576,15 +576,14 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
return Some(start_nearest(SubPath::new(res, true), start, sp));
};
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
let mut open = sp.clone();
open.anchors.rotate_left(k);
let mut open = sp.anchors.to_vec();
open.rotate_left(k);
let mut m = marked.clone();
m.rotate_left(k);
open.anchors.push(open.anchors[0]);
open.push(open[0]);
m.push(false);
open.closed = false;
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma, radius, false);
if same_anchors(&res, &open.anchors) {
let mut res = smooth_open(&open, &m, near, tol, sigma, radius, false);
if same_anchors(&res, &open) {
return None;
}
let l = res.pop()?;
@@ -595,8 +594,9 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f
let res = SubPath::new(res, true);
return Some(if k == 0 { res } else { start_nearest(res, start, sp) });
}
let res = smooth_open(&sp.anchors, &marked, near, tol, sigma, radius, true);
(!same_anchors(&res, &sp.anchors)).then(|| SubPath::new(res, false))
let anchors = sp.anchors.contiguous();
let res = smooth_open(&anchors, &marked, near, tol, sigma, radius, true);
(!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false))
}
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
+40 -5
View File
@@ -10,9 +10,10 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
use vectorcraft_geom::Rect;
use super::panelcmds::listed_artboards;
use super::select::on_artboard;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, index, str_param};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -39,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Text by Font",
[],
None,
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
"{family, style?, scope?: \"document\" (default) | {artboards: [index, …] (0-based whole numbers)} | {layers: [id, …] (layers or sublayers)}} select the text objects using the font, the instances of the symbols whose art uses it, the text whose inline graphics draw such a symbol, the objects painted with a pattern whose art uses it (by a visible fill or stroke whose opacity is above 0, a stroke wider than 0) and the objects whose opacity mask uses it (in type that is not hidden or locked in that art), that are not hidden or locked, in a hidden or locked group or layer, or on a locked artboard; a pattern swatch that nothing paints, or a layer's mask, selects nothing; with scope, only those on one of the artboards (as All on Active Artboard takes them: their bounds overlap it or their center is on it) or in one of the layers → {count}",
has_doc,
select_font
),
@@ -1080,9 +1081,9 @@ impl FontScope {
Some(_) => Err(bad(C, format!("`scope.{key}` must be a non-empty array"))),
}
};
if let Some(a) = list("artboards")? {
let rect = |v: &Value| v.as_u64().and_then(|i| d.artboards.get(index(i))).map(|b| b.rect);
return a.iter().map(|v| rect(v).ok_or_else(|| bad(C, format!("no such artboard {v}")))).collect::<Result<_>>().map(Self::Artboards);
if let (Some(v), Some(_)) = (scope.get("artboards"), list("artboards")?) {
let indices = listed_artboards(d, v, "scope.artboards", C)?;
return Ok(Self::Artboards(indices.into_iter().filter_map(|i| d.artboards.get(i)).map(|b| b.rect).collect()));
}
if let Some(a) = list("layers")? {
let layer = |v: &Value| v.as_u64().map(NodeId).filter(|id| d.node(*id).is_some_and(Node::is_layer));
@@ -1292,6 +1293,40 @@ mod tests {
}
}
/// Select Text by Font refuses a `scope.artboards` entry that is not a whole number, naming the
/// parameter, before it looks at the artboards, and leaves the selection as it was; a whole
/// number past the last artboard is `no such artboard`.
#[test]
fn select_font_refuses_artboards_that_are_not_whole_numbers() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("artboard.new", &json!({"x": 300, "y": 0, "width": 200, "height": 200})).unwrap();
let text = |s: &mut Session, x: i32| {
NodeId(s.execute("text.create", &json!({"x": x, "y": 50, "text": "Serif", "font": "Source Serif 4"})).unwrap()["id"].as_u64().unwrap())
};
let first = text(&mut s, 10);
let second = text(&mut s, 350);
let run =
|s: &mut Session, artboards: Value| s.execute("select.font", &json!({"family": "Source Serif 4", "scope": {"artboards": artboards}}));
let malformed = "invalid parameters for `select.font`: `scope.artboards` must contain whole numbers";
for (artboards, want) in [
(json!(["1"]), malformed),
(json!([-1]), malformed),
(json!([1.5]), malformed),
(json!([true]), malformed),
(json!([null]), malformed),
(json!([9, "1"]), malformed),
(json!([9]), "no such artboard"),
(json!([1, 9]), "no such artboard"),
] {
s.execute("select.set", &json!({"ids": [first.0]})).unwrap();
assert_eq!(run(&mut s, artboards.clone()).unwrap_err().to_string(), want, "{artboards}");
assert_eq!(s.doc().unwrap().selection.objects, [first], "{artboards}");
}
run(&mut s, json!([1, 1])).unwrap();
assert_eq!(s.doc().unwrap().selection.objects, [second]);
}
/// Select Text by Font with a layer scope takes the text in the layers, their sublayers
/// included, and still leaves out hidden and locked text.
#[test]
+1 -1
View File
@@ -255,7 +255,7 @@ pub(crate) fn artboard_indices(d: &vectorcraft_doc::Document, p: &Value, cmd: &s
/// list of artboard indices", and a list with an entry that is not a whole number is "`{key}` must
/// contain whole numbers"; a whole number past the last artboard is `no such artboard`. Every entry
/// is checked for its form before any is checked against the artboards.
fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
pub(crate) fn listed_artboards(d: &vectorcraft_doc::Document, v: &Value, key: &str, cmd: &str) -> Result<Vec<usize>> {
let entries = v.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be a list of artboard indices")))?;
if entries.is_empty() {
return Err(bad(cmd, format!("`{key}` must be a non-empty list of artboard indices")));
+6
View File
@@ -369,6 +369,12 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
{
return Err(bad(id, "`origin` must be [x, y] in points"));
}
if effect == vectorcraft_render::effects::SVG_FILTER
&& let Some(axes) = given.get("axes")
&& vectorcraft_render::effects::svg_filter::valid_axes(axes).is_none()
{
return Err(bad(id, "`axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0"));
}
// Its name is the filter's id.
if effect == vectorcraft_render::effects::SVG_FILTER && given.contains_key("name") && !given.contains_key("xml") {
return Err(bad(id, "an SVG filter is named by its id: give `xml` with `name`"));
+19 -15
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection};
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath, Vec2};
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2};
use super::create::anchor_from_json;
use super::draw2::usize_opt;
@@ -544,10 +544,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
&& before > 2
&& picked(0)
&& picked(before - 1)
&& let [first, .., last] = sp.anchors.as_mut_slice()
&& same(first, last)
&& let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last())
&& same(&first, &last)
{
first.h_in = last.h_in;
if let Some(first) = sp.anchors.first_mut() {
first.h_in = last.h_in;
}
sp.anchors.pop();
if let Some(smooth) = join_kind {
join_point(sp, 0, smooth);
@@ -565,10 +567,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
for i in (1..len).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
&& same(a, b)
&& let (Some(&a), Some(&b)) = (anchors.get(i - 1), anchors.get(i))
&& same(&a, &b)
{
a.h_out = b.h_out;
if let Some(a) = anchors.get_mut(i - 1) {
a.h_out = b.h_out;
}
if let Some(slot) = gone.get_mut(i) {
*slot = true;
}
@@ -603,7 +607,7 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
}
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
fn join_point_between(anchors: &mut Anchors, ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
let (prev, next) = (at(prev), at(next));
if let Some(a) = anchors.get_mut(ai) {
@@ -1565,7 +1569,7 @@ enum Stretch {
/// anchor, so the two handles of a smooth anchor stay in line with it. That share is below 0 or
/// above 1 for a handle long enough beside the span. A closed subpath with no anchor that stays
/// moves whole when it has a focal point.
fn stretch_weights(anchors: &[Anchor], closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
fn stretch_weights(anchors: &Anchors, closed: bool, roles: &[Stretch]) -> Vec<[f64; 3]> {
let n = anchors.len();
let mut shares = vec![[0.0; 3]; n];
let role = |i: usize| match roles.get(i) {
@@ -1891,10 +1895,10 @@ mod tests {
&& before > 2
&& picked(0)
&& picked(before - 1)
&& let [first, .., last] = sp.anchors.as_mut_slice()
&& same(first, last)
&& let (Some(&first), Some(&last)) = (sp.anchors.first(), sp.anchors.last())
&& same(&first, &last)
{
first.h_in = last.h_in;
sp.anchors[0].h_in = last.h_in;
sp.anchors.pop();
if let Some(smooth) = join_kind {
join_point(sp, 0, smooth);
@@ -1903,10 +1907,10 @@ mod tests {
for i in (1..sp.anchors.len()).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
&& same(a, b)
&& let (Some(&a), Some(&b)) = (sp.anchors.get(i - 1), sp.anchors.get(i))
&& same(&a, &b)
{
a.h_out = b.h_out;
sp.anchors[i - 1].h_out = b.h_out;
sp.anchors.remove(i);
if let Some(smooth) = join_kind {
join_point(sp, i - 1, smooth);
+3 -1
View File
@@ -486,7 +486,9 @@ fn imaged(n: &Node, which: Which) -> bool {
let live = filters
&& pixels == 1
&& effects::svg_filter::writes_live(&n.appearance.effects)
&& fx.iter().any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if s.in_points() && (!s.measured() || fx.len() == 1) && s.writes_as_svg11()));
&& fx
.iter()
.any(|f| matches!(f, RasterFx::Pixel(effects::PixelFx::Svg(s)) if (!s.measured() || fx.len() == 1) && s.writes_as_svg11() && s.opens_again()));
(pixels > 0 && !live)
|| (fx.iter().any(|f| matches!(f, RasterFx::DropShadow { darkness: Some(_), .. })) && (cmyk || !simple_rgb_shadow_source(n, &fx)))
}
+6 -5
View File
@@ -8,9 +8,10 @@ use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
use vectorcraft_tools::builder::is_live_paint;
use super::object::can_align;
use super::panelcmds::artboard_at;
use super::wand::{fill_of, stroke_of};
use super::{
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param,
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param,
switch_or, text_param,
};
use crate::DocState;
@@ -31,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"All on Active Artboard",
["Select"],
Some("Cmd+Alt+A"),
"{artboard?: index (0-based; the app passes the active one; default: the first)}",
"{artboard?: index (0-based whole number; the app passes the active one; default, or null: the first)}",
has_doc,
all_on_artboard
),
@@ -229,7 +230,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Appearance Attribute",
["Select", "Same"],
None,
"{item?: appearance item index} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)",
"{item?: appearance item index (0-based whole number; default, or null: the Appearance panel's active item)} the objects sharing an appearance attribute of the first selected object: its fill or stroke `item` (default: the Appearance panel's active item), else its first effect, else its topmost fill (compound paths as select.same.fillColor)",
has_selection,
same_attribute
),
@@ -428,7 +429,7 @@ fn all(s: &mut Session, _: &Value) -> Result<Value> {
fn all_on_artboard(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let i = p.get("artboard").and_then(Value::as_u64).map_or(0, index);
let i = artboard_at(&st.doc, p, "artboard", "select.allOnArtboard")?.unwrap_or(0);
let r = st.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| bad("select.allOnArtboard", "no such artboard"))?;
let symbols = st.doc.symbol_boxes();
let ids: Vec<NodeId> =
@@ -1217,10 +1218,10 @@ enum Attribute {
fn same_attribute(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "select.same.appearanceAttribute";
let item = index_opt(p, "item", cmd)?.or(s.appearance_item());
let st = s.doc()?;
let (refn, _) = same_reference(st, cmd)?;
let ap = &refn.appearance;
let item = p.get("item").and_then(Value::as_u64).map(index).or(s.appearance_item());
let attr = match (item.and_then(|i| ap.items.get(i)), ap.effects.first()) {
(Some(it), _) => Attribute::Item(it.clone()),
(None, Some(e)) => Attribute::Effect(e.clone()),
+28 -3
View File
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Merge Swatches",
["Window", "Swatches"],
None,
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), as one undo step → {name, merged: [deleted names], relinked}",
"{names: [two or more solid-colour swatches], name?: the merged swatch's name (one swatch kept)} keep the first (its name and colour) and delete the others; paints linked to them take its colour and link to it (or unlink when it isn't global), and gradient stops linked to them drop their process plates, as one undo step → {name, merged: [deleted names], relinked}",
has_doc,
swatch_merge
),
@@ -688,6 +688,11 @@ impl Relink {
/// batch, and a canceled batch preview, put back the paints the batch started with. A change is
/// recorded with the step just made, so Undo and Redo put these paints back with the document.
pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()> {
map_default_paints_by(s, &mut |p| p.map_links(f))
}
/// [`map_default_paints`] with `f` applied to each whole paint; `f` returns true when it changed it.
fn map_default_paints_by(s: &mut Session, f: &mut dyn FnMut(&mut Paint) -> bool) -> Result<()> {
if s.in_interaction() && s.batch_stash.is_none() {
return Ok(());
}
@@ -699,7 +704,7 @@ pub(super) fn map_default_paints(s: &mut Session, f: &mut LinkFn) -> Result<()>
});
let mut changed = false;
for p in [&mut pd.fill, &mut pd.stroke].into_iter().chain(template) {
changed |= p.map_links(f);
changed |= f(p);
}
if changed {
super::colormgmt::record_new_art_colors(s, start)?;
@@ -1124,17 +1129,37 @@ fn swatch_merge(s: &mut Session, p: &Value) -> Result<Value> {
*l = link.clone();
true
};
// A stop linked to a merged swatch loses its process plates, which printed with that ink.
let mut unplate = |p: &Paint| {
let mut q = p.clone();
drop_stop_plates(&mut q, &merged_names).then_some(q)
};
let colorized_ok = super::paint::check_colorized(d).is_ok();
let relinked = s.edit("Merge Swatches", |d, _| {
take_swatches(d, merged, |_| true);
map_all_paints(d, &mut unplate);
let relinked = map_swatch_links(d, &mut relink);
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?;
Ok(relinked)
})?;
map_default_paints(s, &mut relink)?;
map_default_paints_by(s, &mut |p| {
let unplated = drop_stop_plates(p, &merged_names);
p.map_links(&mut relink) | unplated
})?;
Ok(json!({"name": keep, "merged": merged, "relinked": relinked}))
}
/// Clear the process plates of `p`'s gradient stops linked to a swatch in `names`. True when any
/// stop had plates.
fn drop_stop_plates(p: &mut Paint, names: &HashSet<&str>) -> bool {
let Paint::Gradient(g) = p else { return false };
g.gradient
.stops
.iter_mut()
.filter(|st| st.swatch.as_deref().is_some_and(|l| names.contains(l)))
.fold(false, |ch, st| st.plates.take().is_some() | ch)
}
fn swatch_ungroup(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.ungroup";
let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?.to_string();
+1 -1
View File
@@ -384,7 +384,7 @@ fn weather_icons() -> SymbolLibrary {
Anchor { p: Point::new(5.0, 16.0), h_in: Point::new(-6.0, 16.0), h_out: Point::new(0.0, 8.0), kind: AnchorKind::Corner },
Anchor { p: Point::new(-4.0, -1.0), h_in: Point::new(-4.0, 6.0), h_out: Point::new(-4.0, -8.0), kind: AnchorKind::Smooth },
];
let moon = PathData::single(SubPath { anchors: moon_anchors, closed: true });
let moon = PathData::single(SubPath::new(moon_anchors, true));
// Helper for cloud contour
let cloud_subpath = |offset_y: f64, scale: f64| -> SubPath {
+4 -4
View File
@@ -2133,7 +2133,7 @@ mod pen_interactions {
gesture(&mut s, &[(400.0, 500.0)], Mods::default(), v);
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], reversed.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], reversed.subpaths[0].anchors);
assert!(!s.in_interaction() && !s.tool_busy());
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
@@ -2168,7 +2168,7 @@ mod pen_interactions {
gesture(&mut s, &[(300.0, 400.0)], Mods::default(), v);
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], converted.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], converted.subpaths[0].anchors);
assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
@@ -2227,7 +2227,7 @@ mod pen_interactions {
}
let extended = path(&s, id);
assert_eq!(extended.anchor_count(), 3);
assert_eq!(extended.subpaths[0].anchors[..2], before.subpaths[0].anchors);
assert_eq!(extended.subpaths[0].anchors.to_vec()[..2], before.subpaths[0].anchors);
let a = extended.subpaths[0].anchors[2];
assert_eq!(a.p, Point::new(320.0, 450.0));
assert_eq!(a.h_in, Point::new(290.0, 430.0), "Alt freezes the incoming handle and Space translates it");
@@ -3381,7 +3381,7 @@ fn reshape_open_path(s: &mut Session, anchors: Value) -> NodeId {
/// The anchors of the path's first subpath.
fn reshape_anchors(s: &Session, id: NodeId) -> Vec<vectorcraft_geom::Anchor> {
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.clone()
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.to_vec()
}
/// The share of the drag an anchor takes at `u` of the way from an end to the grabbed point.
+57 -3
View File
@@ -3,7 +3,7 @@
use serde_json::json;
use crate::cmd::actionset::{AiaStep, read_aia};
use crate::cmd::actionset::{AiaData, AiaStep, AiaValue, read_aia};
use crate::*;
/// `text` as a bracketed hexadecimal value.
@@ -37,7 +37,12 @@ fn a_set_reads_its_actions_and_steps() {
let names: Vec<&str> = set.actions.iter().map(|a| a.name.as_str()).collect();
assert_eq!(names, ["First", "二番目"]);
let step = |a: usize, s: usize| set.actions[a].steps[s].clone();
let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, declared: Some(3), line: 9 };
let values = vec![
AiaValue { key: Some(1), kind: Some("unit real".into()), value: None },
AiaValue { key: None, kind: Some("ustring".into()), value: Some(AiaData::Text(b"a } brace".to_vec())) },
AiaValue { key: None, kind: Some("raw".into()), value: None },
];
let join = AiaStep { name: "sample_join".into(), label: Some("Join".into()), on: Some(1), params: 3, values, declared: Some(3), line: 9 };
assert_eq!(step(0, 0), join);
assert_eq!((step(1, 0).name.as_str(), step(1, 0).label.clone(), step(1, 0).on), ("sample)one", None, Some(0)));
assert_eq!((step(1, 1).label.as_deref(), step(1, 1).on, step(1, 1).line), (Some("Second Step"), None, 39));
@@ -60,6 +65,55 @@ fn recorded_values_are_counted_and_checked() {
assert!(set(&[value("one"), "/value [ 1 zz ]".to_string()]).truncated, "a second value that isn't hexadecimal");
}
/// `actionSet.read` answers with each recorded value's key, type and value: a number, text in
/// parentheses or hexadecimal text that is UTF-8 with its length in bytes, and null for text that
/// isn't UTF-8 and for other values. Fields may come in any order, and a value with the wrong byte
/// count still marks the set truncated.
#[test]
fn recorded_values_come_back_with_their_keys_and_types() {
let mut s = Session::new();
let text = format!(
"/version 3 /action-1 {{ /event-1 {{ /internalName (sample_values) /parameterCount 6 \
/parameter-1 {{ /key 1952807028 /type (ustring) /value {note} }} \
/parameter-2 {{ /value 1 /type (boolean) /key 2003792484 }} \
/parameter-3 {{ /type (ustring) /value [ 2 c328 ] /key 7 }} \
/parameter-4 {{ /key 99999999999999999999 /type (real) /value 4.5 }} \
/parameter-5 {{ /key 3 /type (text) /value (plain) }} \
/parameter-6 {{ }} }} }}",
note = hex("Größe ✓")
);
let r = s.execute("actionSet.read", &json!({ "data": text })).unwrap();
assert_eq!(r["truncated"], false);
assert_eq!(
r["actions"][0]["steps"][0]["values"],
json!([
{"key": 1952807028, "type": "ustring", "value": "Größe ✓", "bytes": 11},
{"key": 2003792484, "type": "boolean", "value": 1},
{"key": 7, "type": "ustring", "value": null, "bytes": 2},
{"key": null, "type": "real", "value": null},
{"key": 3, "type": "text", "value": "plain", "bytes": 5},
{"key": null, "type": null, "value": null},
])
);
let bad = "/version 3 /action-1 { /event-1 { /parameter-1 { /key 1 /type (ustring) /value [ 3 4142 ] } } }";
assert_eq!(s.execute("actionSet.read", &json!({ "data": bad })).unwrap()["truncated"], true);
}
/// At most 100,000 recorded values are kept in a set: the others are still counted, so a step's
/// `values` can be shorter than its `params`.
#[test]
fn recorded_values_past_the_cap_are_counted_but_not_kept() {
let step = format!("/event-1 {{ {} }} ", "/parameter-1 { /key 1 /value 0 } ".repeat(1000));
let action = format!("/action-1 {{ {} }} ", step.repeat(50));
let set = read_aia(format!("/version 3 {}", action.repeat(3)).as_bytes()).unwrap();
assert!(!set.truncated);
let steps = || set.actions.iter().flat_map(|a| &a.steps);
assert_eq!(steps().map(|s| s.params).sum::<usize>(), 150_000);
assert_eq!(steps().map(|s| s.values.len()).sum::<usize>(), 100_000);
assert_eq!(set.actions[2].steps[0].values.len(), 0);
assert_eq!(set.actions[1].steps[49].values[999], AiaValue { key: Some(1), kind: None, value: Some(AiaData::Int(0)) });
}
/// `actionSet.read` takes exactly one of `path`, `data` and `dataBase64`, and text for the text
/// params; any other value is an error.
#[test]
@@ -97,7 +151,7 @@ fn read_command_answers_with_the_set() {
let text = sample().replacen(&format!("/name {}", hex("Prep Sätze")), "", 1);
let r = s.execute("actionSet.read", &json!({ "data": text, "name": "/sets/Mine.aia" })).unwrap();
assert_eq!(r["set"], "Mine");
assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "line": 34}));
assert_eq!(r["actions"][1]["steps"][0], json!({"name": "sample)one", "label": null, "on": false, "params": 0, "values": [], "line": 34}));
assert_eq!(r["actions"][0]["steps"][0]["on"], true);
assert_eq!(r["actions"][0]["steps"][0]["label"], "Join");
let blank = format!("/version 3 /action-1 {{ /event-1 {{ /internalName (x) /localizedName {} }} }}", hex(" "));
+43 -2
View File
@@ -1,6 +1,7 @@
//! An edit of one anchor of a long selected path does not measure the path's segments
//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, and
//! an edit that leaves the anchor as it was records no undo step.
//! ([`vectorcraft_geom::path::measured_segments`]) to check that it stays within the canvas, its
//! undo step keeps the chunk of anchors it changed rather than a copy of every anchor, and an edit
//! that leaves the anchor as it was records no undo step.
use std::collections::BTreeSet;
use std::sync::Arc;
@@ -74,6 +75,46 @@ fn one_anchor_edit_of_a_long_path_measures_few_segments() {
}
}
/// Most bytes the undo step of one anchor edit may keep, however many anchors the path has: about
/// one chunk of anchors and the node, with room for the chunk tables of 200,000 anchors.
const MOST_STEP_BYTES: usize = 48 * 1024;
#[test]
fn one_anchor_edit_of_a_long_path_keeps_one_chunk_in_its_undo_step() {
for n in [10_000, 200_000] {
let (mut s, id) = long_path(n);
let original = s.doc().unwrap().doc.clone();
let edits = [
("path.moveAnchor", json!({"id": id.0, "anchor": 5, "x": 3, "y": 50})),
("path.setHandle", json!({"id": id.0, "anchor": 5, "which": "out", "x": 4, "y": 40})),
("path.moveAnchors", json!({"dx": 1, "dy": 0})),
("object.nudge", json!({"dx": 1, "dy": 0})),
];
let mut docs = vec![];
for (cmd, p) in &edits {
s.execute(cmd, p).unwrap();
let step = s.doc().unwrap().history.undo.last().unwrap().bytes;
assert!(step <= MOST_STEP_BYTES, "{cmd} on {n} anchors kept {step} bytes in its undo step");
docs.push(s.doc().unwrap().doc.clone());
}
assert_eq!(anchor(&s, id, 5).p, Point::new(5.0, 50.0));
assert_eq!(anchor(&s, id, 5).h_out, Point::new(6.0, 40.0));
assert_eq!(anchor(&s, id, n - 1), original.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[n - 1]);
// Undo gives back each version exactly, and redo the edits, each step as small.
for k in (0..edits.len()).rev() {
s.execute("edit.undo", &json!({})).unwrap();
let expected = if k == 0 { &original } else { &docs[k - 1] };
assert!(s.doc().unwrap().doc == *expected, "undo of {} on {n} anchors", edits[k].0);
let redo = s.doc().unwrap().history.redo.last().unwrap().bytes;
assert!(redo <= MOST_STEP_BYTES, "redo of {} on {n} anchors keeps {redo} bytes", edits[k].0);
}
for (k, doc) in docs.iter().enumerate() {
s.execute("edit.redo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == *doc, "redo of {} on {n} anchors", edits[k].0);
}
}
}
/// A handle past the canvas is measured: the edit stands while the curve stays within the canvas,
/// and is refused once the curve leaves it.
#[test]
+51
View File
@@ -5688,6 +5688,57 @@ fn a_trace_run_applies_only_in_its_own_document() {
}
}
/// A trace prepared before File › Revert doesn't apply after it, even when the document keeps its
/// uid and the restored image, object and settings are the same: both trace commands drop the
/// trace handed in and trace the restored image again, as one undo step. Reverting another
/// document, or a revert that fails, leaves the run current, and a trace prepared after the revert
/// applies as usual.
#[test]
fn a_trace_run_prepared_before_a_revert_does_not_apply_after_it() {
let p = json!({"params": {"ignoreWhite": true}});
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
let mut direct = session();
image_doc(&mut direct);
let want = direct.execute(command, &p).unwrap();
let mut s = session();
let img = image_doc(&mut s);
let a = s.active_index().unwrap();
let copy = (*s.doc().unwrap().doc).clone();
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
let traced = run.run(&|_, _| true).unwrap();
let b = s.add_document(copy.clone(), None);
assert!(s.replace_document(b, copy.clone()));
assert!(s.set_active(a));
assert!(run.current(&s) && !run.reverted(&s), "{command}: another document reverted");
assert!(!s.replace_document(s.documents().len(), copy.clone()));
assert!(run.current(&s) && !run.reverted(&s), "{command}: a revert that failed");
let (uid, reverts) = (s.doc().unwrap().uid, s.doc().unwrap().reverts);
assert!(s.replace_document(a, copy));
assert_eq!(s.doc().unwrap().uid, uid, "{command}: the tab keeps its uid");
assert_eq!(s.doc().unwrap().reverts, reverts + 1, "{command}");
assert!(!run.current(&s), "{command}: reverted");
assert!(run.reverted(&s), "{command}");
traced.hand_in(&mut s);
let traces = cmd::TraceRun::traces_on_this_thread();
let got = s.execute(run.command(), run.params()).unwrap();
assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces + 1, "{command}: traced again");
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
assert_eq!(got, want, "{command}");
let g = NodeId(got["id"].as_u64().unwrap());
assert_eq!(node(&s, g), node(&direct, g), "{command}");
s.execute("edit.undo", &json!({})).unwrap();
assert!(matches!(node(&s, img).kind, NodeKind::Image(_)), "{command}: one undo step");
// A trace prepared after the revert is handed in and applied without tracing again.
let after = cmd::TraceRun::prepare(&s, command, run.params()).unwrap();
let traced = after.run(&|_, _| true).unwrap();
assert!(after.current(&s) && !after.reverted(&s), "{command}: prepared after the revert");
traced.hand_in(&mut s);
let traces = cmd::TraceRun::traces_on_this_thread();
s.execute(after.command(), after.params()).unwrap();
assert_eq!(cmd::TraceRun::traces_on_this_thread(), traces, "{command}: the trace handed in applied");
}
}
/// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in
/// place, as it leaves the document.
#[test]
+1 -1
View File
@@ -40,7 +40,7 @@ fn close(a: f64, b: f64) -> bool {
fn segment_angles(p: &PathData) -> Vec<f64> {
p.subpaths
.iter()
.flat_map(|sp| sp.anchors.windows(2).map(|w| w[1].p - w[0].p))
.flat_map(|sp| sp.anchors.iter().zip(sp.anchors.iter().skip(1)).map(|(a, b)| b.p - a.p))
.filter(|v| v.hypot() > 1e-9)
.map(|v| (-v.y).atan2(v.x).to_degrees().rem_euclid(90.0))
.collect()
+5 -5
View File
@@ -890,7 +890,7 @@ fn curvature_rubber_band_is_the_path_the_click_makes() {
s.pointer(&PointerEvent::new(PointerKind::Up, 450.0, 400.0), v).unwrap();
let made = path(&s, id).subpaths[0].clone();
assert_eq!(made.anchors.len(), 4);
let tail = vectorcraft_geom::SubPath::new(made.anchors[1..].to_vec(), false);
let tail = vectorcraft_geom::SubPath::new(made.anchors.to_vec()[1..].to_vec(), false);
assert_eq!(preview, bez(&tail));
}
@@ -1218,7 +1218,7 @@ fn scissors_cut_ellipse_end_drags_alone() {
s.pointer(&PointerEvent::new(PointerKind::Up, cut.x + 8.0, cut.y + 8.0).with_mods(m), v).unwrap();
assert_eq!(undo_steps(&s), undo + 1);
let after = path(&s, id);
let (old, new) = (&sp.anchors, &after.subpaths[0].anchors);
let (old, new) = (&sp.anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert_eq!(new.len(), old.len());
assert_eq!(new[1..], old[1..], "only the dragged end moves (at anchor: {at_anchor}, {m:?})");
let d = Point::new(cut.x + 8.0, cut.y + 8.0) - cut;
@@ -1572,7 +1572,7 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() {
drag(&mut s, "smooth", &[(195.0, 194.0), (205.0, 194.0)], Mods::default());
let p = path(&s, id);
assert_ne!(p, before, "the bump is smoothed");
let a = &p.subpaths[0].anchors;
let a = &p.subpaths[0].anchors.to_vec();
let (first, second, last) = (a[0], a[1], a[a.len() - 1]);
assert!(first.p == Point::new(50.0, 200.0) && !first.has_out() && !second.has_in(), "the left side is a line still: {first:?} {second:?}");
assert!(last.p == Point::new(350.0, 200.0) && !last.has_in() && !a[a.len() - 2].has_out(), "and the right one: {last:?}");
@@ -1783,7 +1783,7 @@ fn smoothing_over_a_closed_paths_first_anchor_keeps_its_start() {
assert_ne!(after, before, "the bump is smoothed");
assert_starts_nearest(&after, old, 12.0);
let kept = &after.subpaths[0].anchors;
for a in &before.subpaths[0].anchors[2..=10] {
for a in &before.subpaths[0].anchors.to_vec()[2..=10] {
assert!(kept.iter().any(|k| k.p == a.p), "{:?} is out of reach and stays: {kept:?}", a.p);
}
s.execute("edit.undo", &json!({})).unwrap();
@@ -3885,7 +3885,7 @@ fn pen_cmd_selected_anchors_are_what_copy_and_cut_take() {
assert!(left.is_empty());
assert!(s.doc().unwrap().selection.objects.is_empty());
assert_eq!(s.clipboard.nodes.len(), 1);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors[1..3]);
assert_eq!(s.clipboard.nodes[0].path_data().unwrap().subpaths[0].anchors, original.subpaths[0].anchors.to_vec()[1..3]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(paths(&s), vec![(id, original.clone())]);
assert_eq!(s.doc().unwrap().selection, picked);
+69
View File
@@ -231,6 +231,75 @@ fn deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks() {
assert_eq!(gradient(&s, id).gradient.stops[1], linked, "undo brings back the link and the plates");
}
/// The stops of the gradients the merge test puts in place: the art's fill, gradient swatch "Glow",
/// graphic style "Style", the art of brush "Brush" and the fill new art takes.
fn merge_test_stops(s: &Session, id: NodeId) -> Vec<(&'static str, Vec<GradientStop>)> {
let d = doc(s);
let stops = |p: Paint| match p {
Paint::Gradient(g) => g.gradient.stops,
p => panic!("not a gradient: {p:?}"),
};
let style = d.graphic_style("Style").unwrap().appearance.items.iter().find_map(|it| match it {
vectorcraft_doc::AppearanceItem::Fill(f) => Some(f.paint.clone()),
vectorcraft_doc::AppearanceItem::Stroke(_) => None,
});
let mut brush = None;
for n in vectorcraft_brush::find(d, "Brush").unwrap().art() {
n.walk(&mut |m| {
if brush.is_none() && matches!(m.appearance.fill_paint(), Paint::Gradient(_)) {
brush = Some(m.appearance.fill_paint());
}
});
}
vec![
("art", stops(d.node(id).unwrap().appearance.fill_paint())),
("gradient swatch", stops(d.swatch("Glow").unwrap().paint.clone())),
("graphic style", stops(style.unwrap())),
("brush art", stops(brush.unwrap())),
("new art", stops(s.paint.fill.clone())),
]
}
#[test]
fn merging_swatches_takes_the_process_plates_of_the_stops_it_relinks() {
// Kept swatch "Keep": spot, global process, and process that isn't global.
for (spot, global) in [(true, true), (false, true), (false, false)] {
let (mut s, id) = setup();
run(&mut s, "swatch.new", json!({"name": "Keep", "color": "#00ff00", "spot": spot, "global": global}));
run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 1, "m": 0, "y": 0, "k": 0}, "spot": true}));
// Ink at 50 % over a 30 % cyan plate, and Other over its own 20 % magenta plate, which the
// merge leaves alone.
let plated = json!({"stops": [
{"offset": 0, "swatch": "Ink", "tint": 50, "plates": [0.3, 0, 0, 0]},
{"offset": 1, "swatch": "Other", "plates": [0, 0.2, 0, 0]},
]});
run(&mut s, "paint.editGradient", plated.clone());
run(&mut s, "swatch.new", json!({"name": "Glow", "gradient": plated}));
run(&mut s, "graphicStyle.new", json!({"name": "Style"}));
run(&mut s, "brush.new", json!({"type": "art", "name": "Brush"}));
s.paint.fill = doc(&s).node(id).unwrap().appearance.fill_paint();
let before = merge_test_stops(&s, id);
let kept = doc(&s).linked_color(doc(&s).swatch("Keep").unwrap().paint.color().unwrap(), spot);
assert!(before.iter().all(|(_, st)| st[0].plates == Some([0.3, 0.0, 0.0, 0.0])), "{before:?}");
run(&mut s, "swatch.merge", json!({"names": ["Keep", "Ink"]}));
let after = merge_test_stops(&s, id);
// The stop shows its tint of the kept color, unlinked when the kept swatch isn't global.
let (link, tint, color) = if global { (Some("Keep"), 0.5, kept.tinted(0.5)) } else { (None, 1.0, kept.tinted(0.5)) };
for (place, st) in &after {
let what = format!("spot {spot}, global {global}, {place}: {st:?}");
assert_eq!((st[0].swatch.as_deref(), st[0].tint, st[0].plates), (link, tint, None), "{what}");
assert_eq!(st[0].color, color, "{what}");
assert_eq!((st[1].swatch.as_deref(), st[1].plates), (Some("Other"), Some([0.0, 0.2, 0.0, 0.0])), "{what}");
}
run(&mut s, "edit.undo", json!({}));
assert_eq!(merge_test_stops(&s, id), before, "undo brings back the links and the plates");
run(&mut s, "edit.redo", json!({}));
assert_eq!(merge_test_stops(&s, id), after, "redo merges again");
}
}
#[test]
fn radial_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings() {
let (mut s, _) = setup();
+47
View File
@@ -3299,6 +3299,32 @@ fn select_all_on_artboard_refuses_an_artboard_past_u32() {
assert!(selected(&s).is_empty());
}
/// All on Active Artboard refuses an `artboard` that is not a whole number, naming the parameter,
/// and leaves the selection as it was; a whole number past the last artboard is `no such
/// artboard`. Left out or null, it takes the first artboard.
#[test]
fn select_all_on_artboard_refuses_an_artboard_that_is_not_a_whole_number() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "artboardLayout": {"layout": "row", "spacing": 0}})).unwrap();
let (first, second) = (rect(&mut s, 10.0, 10.0, 20.0, 20.0), rect(&mut s, 110.0, 10.0, 20.0, 20.0));
for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {
s.execute("select.none", &json!({})).unwrap();
let err = s.execute("select.allOnArtboard", &json!({"artboard": bad})).unwrap_err().to_string();
assert_eq!(err, "invalid parameters for `select.allOnArtboard`: `artboard` must be a whole number", "{bad}");
assert!(selected(&s).is_empty(), "{bad}");
}
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.execute("select.allOnArtboard", &json!({"artboard": 9})).unwrap_err().to_string(), "no such artboard");
assert!(selected(&s).is_empty());
for p in [json!({}), json!({"artboard": null}), json!({"artboard": 0})] {
s.execute("select.none", &json!({})).unwrap();
s.execute("select.allOnArtboard", &p).unwrap();
assert_eq!(selected(&s), vec![first], "{p}");
}
s.execute("select.allOnArtboard", &json!({"artboard": 1})).unwrap();
assert_eq!(selected(&s), vec![second]);
}
#[test]
fn save_and_recall_selection() {
let mut s = session();
@@ -4605,6 +4631,27 @@ fn artboard_guides_go_with_their_artboard() {
assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1]));
}
/// `guide.add` refuses an `artboard` that is not a whole number, naming the parameter, and adds no
/// guide; a whole number past the last artboard is `no such artboard`. Null makes a canvas guide,
/// and a whole number an artboard guide.
#[test]
fn guide_add_refuses_an_artboard_that_is_not_a_whole_number() {
let mut s = session();
s.execute("artboard.new", &json!({"x": 900, "y": 0, "width": 400, "height": 300})).unwrap();
let add = |s: &mut Session, artboard: Value| s.execute("guide.add", &json!({"vertical": true, "pos": 10, "artboard": artboard}));
for bad in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {
let err = add(&mut s, bad.clone()).unwrap_err().to_string();
assert_eq!(err, "invalid parameters for `guide.add`: `artboard` must be a whole number", "{bad}");
}
assert_eq!(add(&mut s, json!(9)).unwrap_err().to_string(), "no such artboard");
assert!(s.doc().unwrap().doc.ruler_guides().is_empty());
add(&mut s, Value::Null).unwrap();
add(&mut s, json!(1)).unwrap();
let d = &s.doc().unwrap().doc;
let boards: Vec<_> = d.ruler_guides().iter().map(|g| g.artboard).collect();
assert_eq!(boards, [None, Some(d.artboards[1].id)]);
}
/// #451: a guide dragged out of a ruler snaps (to the art's corners, side midpoints and anchors,
/// the artboards' edges and centres) and is made in one undo step where it is released over the
/// canvas; with the Artboard tool it is an artboard guide of the active artboard.
+2 -1
View File
@@ -704,10 +704,11 @@ fn effect_params_are_the_effects_own() {
fn an_effect_parameter_without_a_default_is_held_to_its_type() {
use crate::cmd::params::undefaulted_type;
use vectorcraft_render::effects::effect_catalog;
// Read by checks of their own: a stored texture or a texture to load, an SVG filter, a Warp's
// Read by checks of their own: a stored texture or a texture to load, an SVG filter and its axes, a Warp's
// map and the style of Crop Marks.
let own_check = |effect: &str, key: &str| match key {
"textureImage" | "name" | "xml" => true,
"axes" => effect == "svg.filter",
"version" => effect.starts_with("warp."),
"style" => effect == "cropMarks",
_ => false,
+10 -10
View File
@@ -73,8 +73,8 @@ fn simplify_refits_only_the_run_between_direct_selected_anchors() {
assert_eq!(out["after"].as_u64(), Some(len as u64));
assert!(len < 101 - 30, "{len}");
let end = len - 41;
assert_eq!(sp.anchors[..20], original.anchors[..20], "the anchors before the run");
assert_eq!(sp.anchors[end + 1..], original.anchors[61..], "the anchors after the run");
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "the anchors before the run");
assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..], "the anchors after the run");
assert_eq!((sp.anchors[20].p, sp.anchors[20].h_in), (original.anchors[20].p, original.anchors[20].h_in));
assert_eq!((sp.anchors[end].p, sp.anchors[end].h_out), (original.anchors[60].p, original.anchors[60].h_out));
for i in 0..20 {
@@ -100,7 +100,7 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
let id = wave(&mut s);
select_anchors(&mut s, id, ranges);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
path_of(&s, id).subpaths[0].anchors.clone()
path_of(&s, id).subpaths[0].anchors.to_vec()
};
let (first, second) = (alone(&[(10, 30)]), alone(&[(60, 80)]));
let mut s = session();
@@ -110,13 +110,13 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() {
let undo = undo_len(&s);
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
assert_eq!(undo_len(&s), undo + 1, "one undo step");
let both = path_of(&s, id).subpaths[0].anchors.clone();
let both = path_of(&s, id).subpaths[0].anchors.to_vec();
// Where old anchor 30 is in the first result, and old anchor 80 in the second.
let (a30, a80) = (first.len() - 71, second.len() - 21);
assert!(a30 < 30 && a80 < 80, "both runs lose anchors");
let mid = a30 + 30;
assert_eq!(both[..=a30], first[..=a30]);
assert_eq!(both[a30 + 1..mid], original.anchors[31..60], "the anchors between the runs");
assert_eq!(both[a30 + 1..mid], original.anchors.to_vec()[31..60], "the anchors between the runs");
assert_eq!(both[mid..], second[60..]);
let sel: BTreeSet<_> = (10..=a30).chain(mid..=mid + a80 - 60).map(|i| (0, i)).collect();
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel));
@@ -138,7 +138,7 @@ fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() {
assert!(sp.closed);
assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len());
assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run");
assert_eq!(sp.anchors[1..60], original.anchors[11..70]);
assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]);
assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out));
assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in));
for i in 0..60 {
@@ -162,8 +162,8 @@ fn picked_segments_simplify_and_stay_picked() {
s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap();
let sp = path_of(&s, id).subpaths[0].clone();
let end = sp.anchors.len() - 41;
assert_eq!(sp.anchors[..20], original.anchors[..20]);
assert_eq!(sp.anchors[end + 1..], original.anchors[61..]);
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20]);
assert_eq!(sp.anchors.to_vec()[end + 1..], original.anchors.to_vec()[61..]);
let sel = &s.doc().unwrap().selection;
assert_eq!(sel.segments.get(&id), Some(&(20..end).map(|i| (0, i)).collect()));
assert_eq!(sel.anchors.get(&id), Some(&(20..=end).map(|i| (0, i)).collect()));
@@ -200,8 +200,8 @@ fn slider_preview_and_auto_simplify_only_the_run() {
let previewed = path_of(&s, id);
let sp = &previewed.subpaths[0];
assert!(sp.anchors.len() < 101, "{p}");
assert_eq!(sp.anchors[..20], original.anchors[..20], "{p}");
assert_eq!(sp.anchors[sp.anchors.len() - 40..], original.anchors[61..], "{p}");
assert_eq!(sp.anchors.to_vec()[..20], original.anchors.to_vec()[..20], "{p}");
assert_eq!(sp.anchors.to_vec()[sp.anchors.len() - 40..], original.anchors.to_vec()[61..], "{p}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.path.simplify", &p).unwrap();
assert_eq!(path_of(&s, id), previewed, "{p}");
+2 -2
View File
@@ -93,7 +93,7 @@ fn more_smoothing_removes_the_jags_and_keeps_the_shape() {
// Within the tolerance (2.5 % of 300 pt at most) plus the jag the refit smooths away.
assert!(farthest(&before, &after) <= 7.5 + 1.5, "level {level}: {}", farthest(&before, &after));
// The end points of an open path stay put.
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert_eq!((a[0].p, a[a.len() - 1].p), (b[0].p, b[b.len() - 1].p));
assert!(!after.subpaths[0].closed);
s.execute("edit.undo", &json!({})).unwrap();
@@ -206,7 +206,7 @@ fn direct_selected_anchors_smooth_only_their_section() {
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors})).unwrap();
s.execute("object.path.smooth", &json!({"level": 100})).unwrap();
let after = path_of(&s, id);
let (a, b) = (&before.subpaths[0].anchors, &after.subpaths[0].anchors);
let (a, b) = (&before.subpaths[0].anchors.to_vec(), &after.subpaths[0].anchors.to_vec());
assert!(b.len() < a.len(), "{} → {}", a.len(), b.len());
// Anchors 0..=10 and 30..=40 are untouched, the section between them refitted.
assert_eq!(a[..=10].iter().map(|x| x.p).collect::<Vec<_>>(), b[..=10].iter().map(|x| x.p).collect::<Vec<_>>());
+20
View File
@@ -325,6 +325,26 @@ fn select_same_appearance_attribute() {
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "select.same.appearanceAttribute", json!({"item": (1u64 << 32) + 1}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]);
// Null is the default: the shared effect.
run(&mut s, "select.set", json!({"ids": [a.0]}));
run(&mut s, "select.same.appearanceAttribute", json!({"item": null}));
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]);
}
/// Select > Same > Appearance Attribute refuses an `item` that is not a whole number and leaves
/// the selection as it was.
#[test]
fn select_same_appearance_attribute_refuses_an_item_that_is_not_a_whole_number() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "distort.roughen"}));
rect(&mut s, 100.0);
run(&mut s, "select.set", json!({"ids": [a.0]}));
for item in [json!("1"), json!(-1), json!(1.5), json!(true), json!([1])] {
let e = s.execute("select.same.appearanceAttribute", &json!({"item": item})).unwrap_err().to_string();
assert_eq!(e, "invalid parameters for `select.same.appearanceAttribute`: `item` must be a whole number", "{item}");
assert_eq!(s.doc().unwrap().selection.objects, vec![a], "{item}");
}
}
/// With a member path of a compound path selected first, Select > Same > Graphic Style and
+37
View File
@@ -551,6 +551,26 @@ fn svg_export_keeps_a_measured_region_only_on_the_object_alone() {
assert!(after.contains("<image") && !after.contains("<feOffset dx=\"3\""), "{after}");
}
/// SVG export keeps a filter live only in a user space SVG import stores again: `scale` 1000 with
/// `axes` that double it scales the user space 2000 times, past what import holds, so the object is
/// written as an image instead of a filter that would be left out when the file is opened.
#[test]
fn svg_export_writes_an_image_for_a_user_space_import_cannot_store() {
let hue = r#"<filter id="Hue"><feColorMatrix type="hueRotate" values="90"/></filter>"#;
for (scale, axes, live) in [(2.0, json!([2, 0, 0, 2]), true), (1000.0, json!([2, 0, 0, 2]), false)] {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": hue, "scale": scale, "axes": axes}}));
let out = svg(&mut s);
assert_eq!((out.contains("<feColorMatrix"), out.contains("<image")), (live, !live), "scale {scale}: {out}");
let (back, warnings) = vectorcraft_svg::import_with_report(&out).unwrap();
assert!(warnings.is_empty(), "scale {scale}: {warnings:?}");
let mut kept = 0;
back.walk(|n| kept += n.appearance.effects.iter().filter(|e| e.id == "svg.filter").count());
assert_eq!(kept, usize::from(live), "scale {scale}: {out}");
}
}
/// SVG export writes a filter rebuilt from its filter elements and filter attributes, not the XML
/// the effect holds.
#[test]
@@ -575,6 +595,23 @@ fn moving_the_object_moves_the_filters_origin() {
assert_eq!(p["origin"], json!([8.0, 2.0]));
}
/// `axes` turns or skews the filter's user space; a move moves only its origin. Axes the effect
/// can't measure are refused.
#[test]
fn axes_turn_the_filters_user_space_and_bad_axes_are_refused() {
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": SHIFT, "axes": [0, 1, -1, 0]}}));
run(&mut s, "object.move", json!({"ids": [a.0], "dx": 5, "dy": -2}));
let p = &s.doc().unwrap().doc.node(a).unwrap().appearance.effects[0].params;
assert_eq!((&p["axes"], &p["origin"]), (&json!([0, 1, -1, 0]), &json!([5.0, -2.0])));
for axes in [json!([0, 0, 0, 0]), json!([1, 0, 0]), json!([1, 0, 0, "1"]), json!([1001, 0, 0, 1]), json!(null), json!("x")] {
let e = err(&mut s, "effect.apply", json!({"effect": "svg.filter", "ids": [a.0], "params": {"xml": SHIFT, "axes": axes}}));
assert!(e.contains("`axes` must be [a, b, c, d]"), "{axes}: {e}");
}
assert!(err(&mut s, "effect.setParams", json!({"ids": [a.0], "index": 0, "params": {"axes": [0.01, 0, 0, 0.01]}})).contains("`axes` must be"));
}
#[test]
fn filters_survive_a_native_round_trip() {
let mut s = session();
+1 -1
View File
@@ -286,7 +286,7 @@ fn legacy_spiral_decay_preferences_report_the_ratio_drawn_after_reopening() {
assert_eq!(d.selection.objects.len(), 1);
let id = d.selection.objects[0];
let path = d.doc.node(id).unwrap().path_data().unwrap().clone();
let anchors = &path.subpaths[0].anchors;
let anchors = &path.subpaths[0].anchors.to_vec();
assert_eq!(anchors.len(), 5);
assert!(!path.is_closed());
let center = Point::new(200.0, 200.0);
+6
View File
@@ -1672,6 +1672,9 @@ fn action_set(bytes: &[u8]) -> Result<(), TestCaseError> {
prop_assert!(actions.iter().all(|a| a["steps"].as_array().map_or(0, Vec::len) <= 10_000));
prop_assert!(actions.iter().map(|a| a["steps"].as_array().map_or(0, Vec::len)).sum::<usize>() <= 100_000);
prop_assert!(r["unread"].as_array().map_or(0, Vec::len) <= 1000);
let steps = || actions.iter().flat_map(|a| a["steps"].as_array().cloned().unwrap_or_default());
prop_assert!(steps().all(|s| s["values"].as_array().map_or(0, Vec::len) as u64 <= s["params"].as_u64().unwrap_or(0)));
prop_assert!(steps().map(|s| s["values"].as_array().map_or(0, Vec::len)).sum::<usize>() <= 100_000);
}
Ok(())
}
@@ -1690,6 +1693,8 @@ fn arb_aia_token() -> impl Strategy<Value = Vec<u8>> {
"/localizedName",
"/isOn",
"/value",
"/key",
"/type",
"/x",
"/version",
])
@@ -1699,6 +1704,7 @@ fn arb_aia_token() -> impl Strategy<Value = Vec<u8>> {
"[a-z ()\\\\]{0,12}".prop_map(|t| format!("({t})").into_bytes()),
prop::sample::select(vec!["(", ")", "\\", "[ 2 4142 ]", "[ 3 41 4", "[ 1 zz ]", "[", "]", "< 2 0a0b >", "<", ">", "2.5"])
.prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec!["[ 2 c328 ]", "(ustring)", "(boolean)"]).prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec!["{", "}", "\r\n", "\r", "\n"]).prop_map(|t| t.as_bytes().to_vec()),
prop::sample::select(vec![vec![0u8], vec![0xFF, 0xFE], vec![0xC3]]),
]
+2 -4
View File
@@ -36,10 +36,8 @@ pub(crate) fn subpath(s: &mut String, xf: Affine, sp: &SubPath) {
s.push_str(if smooth { "c\n" } else { "C\n" });
}
};
for pair in sp.anchors.windows(2) {
if let [a, b] = pair {
segment(s, a, b);
}
for (a, b) in sp.anchors.iter().zip(sp.anchors.iter().skip(1)) {
segment(s, a, b);
}
if sp.closed
&& sp.anchors.len() > 1
+790
View File
@@ -0,0 +1,790 @@
//! The anchors of a subpath, held in shared chunks.
//!
//! [`Anchors`] keeps its anchors in chunks of at most [`CHUNK`] anchors, each behind an `Arc`.
//! Copying the list copies the table of chunks and shares the chunks themselves; changing an
//! anchor copies only the chunk that holds it when another copy still shares that chunk. An undo
//! step that keeps the version of a path before a one-anchor edit then keeps one chunk of its
//! own, however many anchors the path has. Inserting or removing an anchor copies the chunk it is
//! in and rebuilds the table, which has one entry per chunk.
//!
//! The list reads and writes as one flat sequence of anchors, as a `Vec<Anchor>` does.
use std::borrow::Cow;
use std::fmt;
use std::ops::{Index, IndexMut, RangeBounds};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use crate::path::Anchor;
/// An [`Anchors`] list of the anchors given, as `vec!` makes a `Vec`.
#[macro_export]
macro_rules! anchors {
($($t:tt)*) => {
$crate::Anchors::from(vec![$($t)*])
};
}
/// Most anchors one chunk holds.
pub const CHUNK: usize = 256;
/// The anchors of a subpath: a sequence with the reads of a slice and the edits of a `Vec`, whose
/// copies share the chunks they have not changed.
#[derive(Clone, Default)]
pub struct Anchors {
/// The chunks in order, none of them empty.
chunks: Vec<Arc<Vec<Anchor>>>,
/// Empty while every chunk but the last holds [`CHUNK`] anchors (anchor `i` is then in chunk
/// `i / CHUNK`). Otherwise `ends[c]` is the number of anchors in chunks `0..=c`.
ends: Vec<usize>,
/// The number of anchors.
len: usize,
}
impl Anchors {
/// An empty list.
pub const fn new() -> Self {
Self { chunks: Vec::new(), ends: Vec::new(), len: 0 }
}
/// The number of anchors.
pub fn len(&self) -> usize {
self.len
}
/// Whether the list has no anchors.
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// The chunk that holds anchor `i` and its place in that chunk. For `i` at or past the end the
/// chunk or the place is out of range.
fn locate(&self, i: usize) -> (usize, usize) {
if self.ends.is_empty() {
(i / CHUNK, i % CHUNK)
} else {
let c = self.ends.partition_point(|&e| e <= i);
let start = c.checked_sub(1).and_then(|p| self.ends.get(p)).copied().unwrap_or(0);
(c, i.saturating_sub(start))
}
}
/// Anchor `i`, or `None` past the end.
pub fn get(&self, i: usize) -> Option<&Anchor> {
if i >= self.len {
return None;
}
let (c, o) = self.locate(i);
self.chunks.get(c)?.get(o)
}
/// Anchor `i` to change, or `None` past the end. Copies the chunk that holds it when another
/// list shares that chunk.
pub fn get_mut(&mut self, i: usize) -> Option<&mut Anchor> {
if i >= self.len {
return None;
}
let (c, o) = self.locate(i);
Arc::make_mut(self.chunks.get_mut(c)?).get_mut(o)
}
/// The first anchor.
pub fn first(&self) -> Option<&Anchor> {
self.chunks.first()?.first()
}
/// The last anchor.
pub fn last(&self) -> Option<&Anchor> {
self.chunks.last()?.last()
}
/// The first anchor to change.
pub fn first_mut(&mut self) -> Option<&mut Anchor> {
Arc::make_mut(self.chunks.first_mut()?).first_mut()
}
/// The last anchor to change.
pub fn last_mut(&mut self) -> Option<&mut Anchor> {
Arc::make_mut(self.chunks.last_mut()?).last_mut()
}
/// The anchors in order.
pub fn iter(&self) -> Iter<'_> {
let (front, back): (&[Anchor], &[Anchor]) = (&[], &[]);
Iter { chunks: self.chunks.iter(), front: front.iter(), back: back.iter(), left: self.len }
}
/// The anchors in order, to change. Each chunk is copied, when another list shares it, as the
/// iterator reaches it.
pub fn iter_mut(&mut self) -> IterMut<'_> {
let chunk: fn(&mut Arc<Vec<Anchor>>) -> std::slice::IterMut<'_, Anchor> = |c| Arc::make_mut(c).iter_mut();
self.chunks.iter_mut().flat_map(chunk)
}
/// The anchors as one slice: borrowed when they are in one chunk, copied otherwise.
pub fn contiguous(&self) -> Cow<'_, [Anchor]> {
match self.chunks.as_slice() {
[] => Cow::Borrowed(&[]),
[one] => Cow::Borrowed(one.as_slice()),
_ => Cow::Owned(self.to_vec()),
}
}
/// The anchors in `range` copied into a `Vec`, or `None` when the range is out of bounds or
/// starts after it ends (as `slice::get` with a range).
pub fn get_range(&self, range: impl RangeBounds<usize>) -> Option<Vec<Anchor>> {
use std::ops::Bound;
let start = match range.start_bound() {
Bound::Included(&s) => s,
Bound::Excluded(&s) => s.checked_add(1)?,
Bound::Unbounded => 0,
};
let end = match range.end_bound() {
Bound::Included(&e) => e.checked_add(1)?,
Bound::Excluded(&e) => e,
Bound::Unbounded => self.len,
};
(start <= end && end <= self.len).then(|| self.iter().skip(start).take(end - start).copied().collect())
}
/// The anchors copied into a `Vec`.
pub fn to_vec(&self) -> Vec<Anchor> {
let mut v = Vec::with_capacity(self.len);
for c in &self.chunks {
v.extend_from_slice(c);
}
v
}
/// The anchors as a `Vec`, without a copy when they are in one chunk no other list shares.
pub fn into_vec(mut self) -> Vec<Anchor> {
if self.chunks.len() == 1
&& let Some(one) = self.chunks.pop()
{
return Arc::try_unwrap(one).unwrap_or_else(|shared| (*shared).clone());
}
self.to_vec()
}
/// Change the anchors as a `Vec` (for edits that move many of them, such as reversing).
pub fn with_vec<R>(&mut self, f: impl FnOnce(&mut Vec<Anchor>) -> R) -> R {
let mut v = std::mem::take(self).into_vec();
let r = f(&mut v);
*self = Self::from(v);
r
}
/// Rebuild `ends` and `len` after the chunks changed, dropping empty chunks.
fn reindex(&mut self) {
self.chunks.retain(|c| !c.is_empty());
self.len = self.chunks.iter().map(|c| c.len()).sum();
let n = self.chunks.len();
let uniform = self.chunks.iter().enumerate().all(|(k, c)| if k + 1 == n { c.len() <= CHUNK } else { c.len() == CHUNK });
self.ends.clear();
if !uniform {
let mut total = 0;
self.ends.extend(self.chunks.iter().map(|c| {
total += c.len();
total
}));
}
}
/// Add `a` at the end.
pub fn push(&mut self, a: Anchor) {
match self.chunks.last_mut() {
Some(last) if last.len() < CHUNK => Arc::make_mut(last).push(a),
_ => {
self.chunks.push(Arc::new(vec![a]));
if !self.ends.is_empty() {
self.ends.push(self.len);
}
}
}
self.len += 1;
if let Some(end) = self.ends.last_mut() {
*end = self.len;
}
}
/// Remove the last anchor.
pub fn pop(&mut self) -> Option<Anchor> {
let last = self.chunks.last_mut()?;
let a = Arc::make_mut(last).pop();
if last.is_empty() {
self.chunks.pop();
self.ends.pop();
}
self.len = self.len.saturating_sub(1);
if let Some(end) = self.ends.last_mut() {
*end = self.len;
}
a
}
/// Insert `a` before anchor `i`, or at the end when `i` is the length or more.
pub fn insert(&mut self, i: usize, a: Anchor) {
if i >= self.len {
self.push(a);
return;
}
let (c, o) = self.locate(i);
let Some(chunk) = self.chunks.get_mut(c) else { return };
let chunk = Arc::make_mut(chunk);
chunk.insert(o.min(chunk.len()), a);
if chunk.len() > CHUNK {
let tail = chunk.split_off(chunk.len() / 2);
self.chunks.insert(c + 1, Arc::new(tail));
}
self.reindex();
}
/// Remove anchor `i`, or `None` past the end.
pub fn try_remove(&mut self, i: usize) -> Option<Anchor> {
if i >= self.len {
return None;
}
let (c, o) = self.locate(i);
let chunk = Arc::make_mut(self.chunks.get_mut(c)?);
let a = (o < chunk.len()).then(|| chunk.remove(o));
// A chunk left small joins the next one when the two fit in one chunk.
if chunk.len() < CHUNK / 4
&& let Some(next) = self.chunks.get(c + 1)
&& self.chunks.get(c).map_or(0, |c| c.len()) + next.len() <= CHUNK
{
let next = self.chunks.remove(c + 1);
if let Some(chunk) = self.chunks.get_mut(c) {
Arc::make_mut(chunk).extend_from_slice(&next);
}
}
self.reindex();
a
}
/// Remove anchor `i`. Panics past the end, as `Vec::remove` does.
pub fn remove(&mut self, i: usize) -> Anchor {
match self.try_remove(i) {
Some(a) => a,
None => {
let none: &[Anchor] = &[];
none[i]
}
}
}
/// Keep the first `n` anchors.
pub fn truncate(&mut self, n: usize) {
if n >= self.len {
return;
}
let (c, o) = self.locate(n);
self.chunks.truncate(c + 1);
if let Some(last) = self.chunks.last_mut() {
Arc::make_mut(last).truncate(o);
}
self.reindex();
}
/// Remove every anchor.
pub fn clear(&mut self) {
*self = Self::new();
}
/// Add the anchors of `s` at the end.
pub fn extend_from_slice(&mut self, s: &[Anchor]) {
self.extend(s.iter().copied());
}
/// Keep the anchors for which `f` is true.
pub fn retain(&mut self, f: impl FnMut(&Anchor) -> bool) {
self.with_vec(|v| v.retain(f));
}
/// Keep the anchors for which `f` is true, letting `f` change them.
pub fn retain_mut(&mut self, f: impl FnMut(&mut Anchor) -> bool) {
self.with_vec(|v| v.retain_mut(f));
}
/// Reverse the order of the anchors.
pub fn reverse(&mut self) {
self.with_vec(|v| v.reverse());
}
/// Rotate the anchors `k` places towards the start.
pub fn rotate_left(&mut self, k: usize) {
self.with_vec(|v| v.rotate_left(k));
}
/// Rotate the anchors `k` places towards the end.
pub fn rotate_right(&mut self, k: usize) {
self.with_vec(|v| v.rotate_right(k));
}
/// Remove the anchors in `range` and return them.
pub fn drain(&mut self, range: impl RangeBounds<usize>) -> std::vec::IntoIter<Anchor> {
self.with_vec(|v| v.drain(range).collect::<Vec<_>>()).into_iter()
}
/// Replace the anchors in `range` with those of `with`, and return the anchors replaced.
pub fn splice(&mut self, range: impl RangeBounds<usize>, with: impl IntoIterator<Item = Anchor>) -> std::vec::IntoIter<Anchor> {
self.with_vec(|v| v.splice(range, with).collect::<Vec<_>>()).into_iter()
}
/// The pairs of anchors in the same place in `self` and `other`, with that place, in order.
/// When the two are chunked alike, the chunks they share in the same place are skipped (their
/// anchors are the same); otherwise every pair is visited. Stops at the end of the shorter list.
pub fn pairs_not_shared<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = (usize, &'a Anchor, &'a Anchor)> + 'a {
let alike = self.len == other.len && self.chunks.len() == other.chunks.len() && self.ends == other.ends;
let chunked = alike.then(|| {
let starts = self.chunks.iter().scan(0, |start, c| {
let at = *start;
*start += c.len();
Some(at)
});
starts
.zip(self.chunks.iter().zip(&other.chunks))
.filter(|(_, (a, b))| !Arc::ptr_eq(a, b))
.flat_map(|(at, (a, b))| a.iter().zip(b.iter()).enumerate().map(move |(o, (x, y))| (at + o, x, y)))
});
let flat = (!alike).then(|| self.iter().zip(other.iter()).enumerate().map(|(i, (a, b))| (i, a, b)));
chunked.into_iter().flatten().chain(flat.into_iter().flatten())
}
/// Each chunk's address and capacity (in anchors): two lists hold a chunk in common when they
/// give the same address. For memory estimates.
pub fn chunk_allocations(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
self.chunks.iter().map(|c| (Arc::as_ptr(c) as usize, c.capacity()))
}
/// The bytes the list's own tables hold on the heap (the chunk table and the running totals),
/// without the chunks.
pub fn table_bytes(&self) -> usize {
self.chunks.capacity() * size_of::<Arc<Vec<Anchor>>>() + self.ends.capacity() * size_of::<usize>()
}
}
/// [`Anchors::iter_mut`]'s iterator.
pub type IterMut<'a> = std::iter::FlatMap<
std::slice::IterMut<'a, Arc<Vec<Anchor>>>,
std::slice::IterMut<'a, Anchor>,
fn(&mut Arc<Vec<Anchor>>) -> std::slice::IterMut<'_, Anchor>,
>;
/// [`Anchors::iter`]'s iterator.
#[derive(Clone)]
pub struct Iter<'a> {
/// The chunks neither end has reached.
chunks: std::slice::Iter<'a, Arc<Vec<Anchor>>>,
/// What is left of the chunk the front is in.
front: std::slice::Iter<'a, Anchor>,
/// What is left of the chunk the back is in.
back: std::slice::Iter<'a, Anchor>,
/// The anchors left.
left: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a Anchor;
fn next(&mut self) -> Option<&'a Anchor> {
loop {
if let Some(a) = self.front.next() {
self.left -= 1;
return Some(a);
}
match self.chunks.next() {
Some(c) => self.front = c.iter(),
None => {
let a = self.back.next()?;
self.left -= 1;
return Some(a);
}
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.left, Some(self.left))
}
fn nth(&mut self, mut n: usize) -> Option<&'a Anchor> {
// Whole chunks are skipped without visiting their anchors.
loop {
let f = self.front.len();
if n < f {
self.left -= n + 1;
return self.front.nth(n);
}
n -= f;
self.left -= f;
self.front = Default::default();
match self.chunks.as_slice().first() {
Some(c) if c.len() <= n => {
n -= c.len();
self.left -= c.len();
self.chunks.next();
}
Some(_) => {
if let Some(c) = self.chunks.next() {
self.front = c.iter();
}
}
None => {
let b = self.back.len();
if n < b {
self.left -= n + 1;
return self.back.nth(n);
}
self.left -= b;
self.back = Default::default();
return None;
}
}
}
}
fn count(self) -> usize {
self.left
}
fn last(mut self) -> Option<&'a Anchor> {
self.next_back()
}
}
impl<'a> DoubleEndedIterator for Iter<'a> {
fn next_back(&mut self) -> Option<&'a Anchor> {
loop {
if let Some(a) = self.back.next_back() {
self.left -= 1;
return Some(a);
}
match self.chunks.next_back() {
Some(c) => self.back = c.iter(),
None => {
let a = self.front.next_back()?;
self.left -= 1;
return Some(a);
}
}
}
}
}
impl ExactSizeIterator for Iter<'_> {}
impl std::iter::FusedIterator for Iter<'_> {}
impl Index<usize> for Anchors {
type Output = Anchor;
/// Anchor `i`. Panics past the end, as indexing a slice does.
fn index(&self, i: usize) -> &Anchor {
let (c, o) = self.locate(i);
&self.chunks[c][o]
}
}
impl IndexMut<usize> for Anchors {
/// Anchor `i` to change ([`Anchors::get_mut`]). Panics past the end, as indexing a slice does.
fn index_mut(&mut self, i: usize) -> &mut Anchor {
let (c, o) = self.locate(i);
&mut Arc::make_mut(&mut self.chunks[c])[o]
}
}
impl From<Vec<Anchor>> for Anchors {
fn from(v: Vec<Anchor>) -> Self {
if v.is_empty() {
return Self::new();
}
let len = v.len();
let chunks = if len <= CHUNK { vec![Arc::new(v)] } else { v.chunks(CHUNK).map(|c| Arc::new(c.to_vec())).collect() };
Self { chunks, ends: Vec::new(), len }
}
}
impl From<&[Anchor]> for Anchors {
fn from(s: &[Anchor]) -> Self {
Self::from(s.to_vec())
}
}
impl<const N: usize> From<[Anchor; N]> for Anchors {
fn from(s: [Anchor; N]) -> Self {
Self::from(Vec::from(s))
}
}
impl From<Anchors> for Vec<Anchor> {
fn from(a: Anchors) -> Self {
a.into_vec()
}
}
impl FromIterator<Anchor> for Anchors {
fn from_iter<I: IntoIterator<Item = Anchor>>(it: I) -> Self {
Self::from(it.into_iter().collect::<Vec<_>>())
}
}
impl Extend<Anchor> for Anchors {
fn extend<I: IntoIterator<Item = Anchor>>(&mut self, it: I) {
for a in it {
self.push(a);
}
}
}
impl<'a> Extend<&'a Anchor> for Anchors {
fn extend<I: IntoIterator<Item = &'a Anchor>>(&mut self, it: I) {
self.extend(it.into_iter().copied());
}
}
impl<'a> IntoIterator for &'a Anchors {
type Item = &'a Anchor;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
impl<'a> IntoIterator for &'a mut Anchors {
type Item = &'a mut Anchor;
type IntoIter = IterMut<'a>;
fn into_iter(self) -> IterMut<'a> {
self.iter_mut()
}
}
impl IntoIterator for Anchors {
type Item = Anchor;
type IntoIter = std::vec::IntoIter<Anchor>;
fn into_iter(self) -> std::vec::IntoIter<Anchor> {
self.into_vec().into_iter()
}
}
impl PartialEq for Anchors {
fn eq(&self, other: &Self) -> bool {
self.len == other.len && self.iter().eq(other.iter())
}
}
impl PartialEq<[Anchor]> for Anchors {
fn eq(&self, other: &[Anchor]) -> bool {
self.len == other.len() && self.iter().eq(other.iter())
}
}
impl PartialEq<&[Anchor]> for Anchors {
fn eq(&self, other: &&[Anchor]) -> bool {
*self == **other
}
}
impl PartialEq<Vec<Anchor>> for Anchors {
fn eq(&self, other: &Vec<Anchor>) -> bool {
*self == **other
}
}
impl<const N: usize> PartialEq<[Anchor; N]> for Anchors {
fn eq(&self, other: &[Anchor; N]) -> bool {
*self == other[..]
}
}
impl PartialEq<Anchors> for [Anchor] {
fn eq(&self, other: &Anchors) -> bool {
*other == *self
}
}
impl PartialEq<Anchors> for Vec<Anchor> {
fn eq(&self, other: &Anchors) -> bool {
*other == **self
}
}
impl fmt::Debug for Anchors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl Serialize for Anchors {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.collect_seq(self.iter())
}
}
impl<'de> Deserialize<'de> for Anchors {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Vec::<Anchor>::deserialize(d).map(Self::from)
}
}
#[cfg(test)]
mod tests {
use kurbo::Point;
use super::*;
fn line(n: usize) -> Vec<Anchor> {
(0..n).map(|i| Anchor::corner(Point::new(i as f64, (i % 7) as f64))).collect()
}
/// Chunks of `a` that `b` does not hold, with their capacity in anchors.
fn own_chunks(a: &Anchors, b: &Anchors) -> Vec<usize> {
let theirs: Vec<usize> = b.chunk_allocations().map(|(id, _)| id).collect();
a.chunk_allocations().filter(|(id, _)| !theirs.contains(id)).map(|(_, cap)| cap).collect()
}
#[test]
fn editing_one_anchor_copies_one_chunk_whatever_the_length() {
for n in [10_000, 200_000] {
let before = Anchors::from(line(n));
let mut after = before.clone();
after[n / 2].p = Point::new(-1.0, -1.0);
if let Some(a) = after.get_mut(n / 2 + 1) {
a.h_out = Point::new(-2.0, -2.0);
}
let copied = own_chunks(&after, &before);
assert_eq!(copied.len(), 1, "{n} anchors: one chunk copied");
assert!(copied.iter().all(|&cap| cap <= CHUNK), "{n} anchors: {copied:?}");
assert_eq!(own_chunks(&before, &after).len(), 1, "{n} anchors: the old version keeps one chunk of its own");
// The old version is as it was; the new one differs only at the two anchors.
assert_eq!(before, line(n));
let mut expected = line(n);
expected[n / 2].p = Point::new(-1.0, -1.0);
expected[n / 2 + 1].h_out = Point::new(-2.0, -2.0);
assert_eq!(after, expected);
}
}
#[test]
fn inserting_and_removing_copy_only_the_chunk_touched() {
let n = 200_000;
let before = Anchors::from(line(n));
let mut after = before.clone();
let extra = Anchor::corner(Point::new(0.5, 0.5));
after.insert(n / 2, extra);
assert!(own_chunks(&after, &before).len() <= 2, "the chunk split in two");
assert_eq!(after.len(), n + 1);
assert_eq!(after[n / 2], extra);
assert_eq!(after[n / 2 + 1], line(n)[n / 2]);
assert_eq!(after.remove(n / 2), extra);
assert_eq!(after, line(n));
assert!(own_chunks(&after, &before).len() <= 2);
assert_eq!(before, line(n));
}
#[test]
fn acts_as_a_vec_through_edits() {
// A run of edits applied to an `Anchors` and to a `Vec` leaves the two the same, across
// chunk splits, joins and the uniform and non-uniform layouts.
let mut v = line(700);
let mut a = Anchors::from(v.clone());
let mut seed = 7u64;
let mut next = |m: usize| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 33) as usize % m.max(1)
};
for step in 0..3000 {
let x = Anchor::corner(Point::new(step as f64, 0.25));
match next(8) {
0 | 1 => {
let i = next(v.len() + 1);
v.insert(i, x);
a.insert(i, x);
}
2 | 3 if !v.is_empty() => {
let i = next(v.len());
assert_eq!(v.remove(i), a.remove(i));
}
4 => {
v.push(x);
a.push(x);
}
5 => assert_eq!(v.pop(), a.pop()),
6 if !v.is_empty() => {
let i = next(v.len());
v[i].h_in = x.p;
a[i].h_in = x.p;
}
_ => {
let keep = v.len().saturating_sub(next(3));
v.truncate(keep);
a.truncate(keep);
}
}
assert_eq!(a.len(), v.len(), "step {step}");
if step % 50 == 0 {
assert_eq!(a, v, "step {step}");
for i in 0..v.len() {
assert_eq!(a.get(i), v.get(i), "step {step}, anchor {i}");
}
}
}
assert_eq!(a, v);
assert_eq!(a.iter().rev().copied().collect::<Vec<_>>(), v.iter().rev().copied().collect::<Vec<_>>());
assert_eq!(a.get(v.len()), None);
}
#[test]
fn iterators_skip_and_count_as_a_slice_does() {
let v = line(1000);
let a = Anchors::from(v.clone());
for skip in [0, 1, 255, 256, 257, 999, 1000, 1001] {
assert_eq!(a.iter().nth(skip), v.get(skip), "nth {skip}");
assert_eq!(a.iter().skip(skip).count(), v.iter().skip(skip).count(), "skip {skip}");
assert_eq!(a.iter().skip(skip).len(), v.iter().skip(skip).len(), "len after {skip}");
}
let mut both = a.iter();
let mut vs = v.iter();
for k in 0..1000 {
let (x, y) = if k % 3 == 0 { (both.next_back(), vs.next_back()) } else { (both.next(), vs.next()) };
assert_eq!(x, y, "step {k}");
assert_eq!(both.len(), vs.len());
}
assert_eq!(both.next(), None);
assert_eq!(a.iter().last(), v.last());
let mut m = a.clone();
m.iter_mut().for_each(|x| x.p.x += 1.0);
assert!(m.iter().zip(&v).all(|(x, y)| x.p.x == y.p.x + 1.0));
assert_eq!(a, v, "changing a copy left the original alone");
}
#[test]
fn reads_and_writes_as_a_flat_list() {
let v = line(600);
let a = Anchors::from(v.clone());
assert_eq!(serde_json::to_string(&a).ok(), serde_json::to_string(&v).ok());
let back: Anchors = serde_json::from_str(&serde_json::to_string(&v).unwrap_or_default()).unwrap_or_default();
assert_eq!(back, v);
assert_eq!(format!("{a:?}"), format!("{v:?}"));
}
#[test]
fn pairs_not_shared_skip_the_chunks_both_hold() {
let before = Anchors::from(line(10_000));
let mut after = before.clone();
after[5000].p = Point::new(-3.0, 0.0);
let pairs: Vec<_> = before.pairs_not_shared(&after).collect();
assert!(pairs.len() <= CHUNK);
let changed: Vec<usize> = pairs.iter().filter(|(_, a, b)| a != b).map(|(i, _, _)| *i).collect();
assert_eq!(changed, [5000]);
assert!(pairs.iter().all(|&(i, a, b)| *a == before[i] && *b == after[i]));
// Chunked differently: every pair.
let mut moved = before.clone();
moved.insert(0, Anchor::corner(Point::ZERO));
moved.remove(0);
assert_eq!(before.pairs_not_shared(&moved).count(), 10_000);
}
}
+2
View File
@@ -7,6 +7,7 @@
//! Coordinates are document points (1/72 in), y pointing down.
#![forbid(unsafe_code)]
pub mod anchors;
pub mod arc;
pub mod bez;
pub mod corners;
@@ -17,6 +18,7 @@ pub mod recognize;
pub mod shapes;
pub mod snap;
pub use anchors::Anchors;
pub use arc::ArcPath;
pub use kurbo;
pub use kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, Rect, Shape, Size, Vec2};
+14 -9
View File
@@ -6,6 +6,7 @@ use kurbo::{Affine, BezPath, CubicBez, ParamCurve, ParamCurveExtrema, ParamCurve
use serde::{Deserialize, Serialize};
use crate::EPS;
use crate::anchors::Anchors;
/// Fill rule for paths and compound paths.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -224,15 +225,15 @@ pub fn with_anchor_budget<T>(max: usize, f: impl FnOnce() -> T) -> T {
}
/// A subpath's anchors read within [`with_anchor_budget`].
fn anchors_within<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<Anchor>, D::Error> {
fn anchors_within<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Anchors, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = Vec<Anchor>;
type Value = Anchors;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of anchors")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<Vec<Anchor>, A::Error> {
let mut out = Vec::new();
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut a: A) -> Result<Anchors, A::Error> {
let mut out = Anchors::new();
while let Some(anchor) = a.next_element::<Anchor>()? {
if let Some(left) = ANCHORS_LEFT.get() {
let left = left
@@ -262,13 +263,17 @@ pub fn measured_segments() -> u64 {
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SubPath {
#[serde(deserialize_with = "anchors_within")]
pub anchors: Vec<Anchor>,
pub anchors: Anchors,
#[serde(default)]
pub closed: bool,
}
impl SubPath {
pub fn new(anchors: Vec<Anchor>, closed: bool) -> Self {
Self { anchors: anchors.into(), closed }
}
/// A subpath of `anchors`, sharing their chunks.
pub fn of(anchors: Anchors, closed: bool) -> Self {
Self { anchors, closed }
}
/// Polyline from points.
@@ -442,7 +447,7 @@ impl SubPath {
let (run, cuts): (Vec<Anchor>, BTreeSet<usize>) = if self.closed {
(self.anchors.iter().cycle().skip(first).take(n + 1).copied().collect(), cuts.map(|c| (c + n - first) % n).chain([n]).collect())
} else {
(self.anchors.clone(), cuts.collect())
(self.anchors.to_vec(), cuts.collect())
};
let mut pieces = vec![];
let mut cur: Vec<Anchor> = vec![];
@@ -511,11 +516,11 @@ impl PathData {
{
subpaths.push(sp);
}
cur = Some(SubPath { anchors: vec![Anchor::corner(p)], closed: false });
cur = Some(SubPath::new(vec![Anchor::corner(p)], false));
last = p;
}
PathEl::LineTo(p) => {
let sp = cur.get_or_insert_with(|| SubPath { anchors: vec![Anchor::corner(last)], closed: false });
let sp = cur.get_or_insert_with(|| SubPath::new(vec![Anchor::corner(last)], false));
sp.anchors.push(Anchor::corner(p));
last = p;
}
@@ -752,7 +757,7 @@ pub fn segment_bounds(seg: PathSeg) -> Rect {
}
fn push_curve(cur: &mut Option<SubPath>, last: Point, c1: Point, c2: Point, p: Point) {
let sp = cur.get_or_insert_with(|| SubPath { anchors: vec![Anchor::corner(last)], closed: false });
let sp = cur.get_or_insert_with(|| SubPath::new(vec![Anchor::corner(last)], false));
if let Some(a) = sp.anchors.last_mut() {
a.h_out = c1;
}
+1 -1
View File
@@ -814,7 +814,7 @@ mod tests {
for decay in [20.0, 30.0, 50.0, 80.0, 95.0] {
for clockwise in [true, false] {
let p = spiral(center, 100.0, decay, 8, clockwise);
let anchors = &p.subpaths[0].anchors;
let anchors = &p.subpaths[0].anchors.to_vec();
let k = (decay / 100.0_f64).ln() / TAU;
let mut worst = 0.0_f64;
for pair in anchors.windows(2) {
+1 -1
View File
@@ -1615,7 +1615,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.actionSet.load",
"Load Actions…",
"",
"{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file; the other steps, every step with no label and every step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"",
"{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"",
),
(
"ui.actionSet.delete",
+1 -1
View File
@@ -104,7 +104,7 @@ pub fn merge_duplicate_anchors(sp: &mut SubPath, distance: f64) -> usize {
{
*f = Anchor::with_handles(f.p, moved(f.p, last.p, last.h_in), f.h_out);
}
sp.anchors = out;
sp.anchors = out.into();
before - sp.anchors.len()
}
+1 -1
View File
@@ -27,7 +27,7 @@ const ACCURACY: f64 = 1e-6;
fn merged(prev: &Anchor, cur: &Anchor, next: &Anchor) -> CubicBez {
let mut run = SubPath::new(vec![*prev, *cur, *next], false);
remove_anchor(&mut run, 1);
match run.anchors.as_slice() {
match &*run.anchors.contiguous() {
[a, b] => CubicBez::new(prev.p, a.h_out, b.h_in, next.p),
_ => CubicBez::new(prev.p, prev.h_out, next.h_in, next.p),
}
@@ -377,7 +377,7 @@ fn splice(sp: &SubPath, st: Stretch, chain: &[CubicBez]) -> Option<SubPath> {
let own = backward(chain);
let chain = if st.reversed { own.as_slice() } else { chain };
let (first, last) = (chain.first()?, chain.last()?);
let mut out = sp.anchors.clone();
let mut out = sp.anchors.to_vec();
let start = st.start.min(out.len());
out.rotate_left(start);
let settle = |a: &mut Anchor| {
+3 -3
View File
@@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2};
use vectorcraft_geom::path::measured_arclen;
use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath};
use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, SubPath};
use crate::boolean::{Seg, segs_to_subpath};
use crate::fit::{end_tangent, fit_cubics, fit_single, fit_single_from, is_straight, largest_second_difference, sample, start_tangent, unit};
@@ -1091,7 +1091,7 @@ pub fn remove_anchor(sp: &mut SubPath, index: usize) -> bool {
/// Refit the facing handles of anchors `pi` and `ni` so one cubic follows the two segments that
/// meet at anchor `index` between them ([`remove_anchor`]). Two straight segments are left as
/// they are, and so are the handles when the fit is not finite.
fn refit_across(anchors: &mut [Anchor], pi: usize, index: usize, ni: usize) {
fn refit_across(anchors: &mut Anchors, pi: usize, index: usize, ni: usize) {
let (Some(&a), Some(&b), Some(&c)) = (anchors.get(pi), anchors.get(index), anchors.get(ni)) else { return };
let line = |a: &Anchor, b: &Anchor| !a.has_out() && !b.has_in();
if line(&a, &b) && line(&b, &c) {
@@ -1233,7 +1233,7 @@ pub fn add_anchor_points(path: &PathData) -> PathData {
v[2 * seg + 1] = Anchor { p: l.p3, h_in: l.p2, h_out: r.p1, kind: AnchorKind::Smooth };
}
}
sp.anchors = v;
sp.anchors = v.into();
}
out
}
+1 -1
View File
@@ -769,7 +769,7 @@ fn add_anchor_points_doubles() {
/// The one-pass build gives what inserting a midpoint into each segment (last first) gives, open or closed.
#[test]
fn add_anchor_points_matches_inserting() {
let open = PathData::single(SubPath::new(circle(0.0, 0.0, 10.0).subpaths[0].anchors.clone(), false));
let open = PathData::single(SubPath::new(circle(0.0, 0.0, 10.0).subpaths[0].anchors.to_vec(), false));
for src in [circle(0.0, 0.0, 10.0), rect(0.0, 0.0, 10.0, 10.0), open] {
let mut want = src.clone();
for sp in &mut want.subpaths {
+2 -2
View File
@@ -290,7 +290,7 @@ impl Sub {
/// them.
fn moved(&mut self, was: &SubPath, now: &SubPath, els: &mut [PathEl], st: Option<&StrokeLayer>) {
let (mut first, mut segs) = (false, vec![]);
for (k, (a, b)) in was.anchors.iter().zip(&now.anchors).enumerate() {
for (k, a, b) in was.anchors.pairs_not_shared(&now.anchors) {
if same(a, b) {
continue;
}
@@ -489,7 +489,7 @@ fn differs(was: &PathData, now: &PathData) -> bool {
!std::ptr::eq(was, now)
&& (was.subpaths.len() != now.subpaths.len()
|| was.subpaths.iter().zip(&now.subpaths).any(|(w, p)| {
w.closed != p.closed || w.anchors.len() != p.anchors.len() || w.anchors.iter().zip(&p.anchors).any(|(a, b)| !same(a, b))
w.closed != p.closed || w.anchors.len() != p.anchors.len() || w.anchors.pairs_not_shared(&p.anchors).any(|(_, a, b)| !same(a, b))
}))
}
+4 -4
View File
@@ -140,7 +140,7 @@ fn a_long_path_draws_and_culls_after_each_edit_as_when_its_path_is_made_again()
}),
("that anchor moved off it", |p| moved(&mut p.subpaths[0].anchors[1535], Vec2::new(5.0, 5.0))),
("a doubled anchor moved off its twin", |p| moved(&mut p.subpaths[0].anchors[1536], Vec2::new(0.0, -12.0))),
("1,200 anchors moved", |p| p.subpaths[0].anchors[..1200].iter_mut().for_each(|a| moved(a, Vec2::new(2.0, 1.0)))),
("1,200 anchors moved", |p| p.subpaths[0].anchors.iter_mut().take(1200).for_each(|a| moved(a, Vec2::new(2.0, 1.0)))),
("an anchor added", |p| _ = p.subpaths[0].insert_anchor(1520, 0.5)),
("an anchor deleted", |p| _ = p.subpaths[0].anchors.remove(1521)),
("the subpath closed", |p| p.subpaths[0].closed = true),
@@ -454,7 +454,7 @@ fn random_edit(g: &mut Seeded, p: &mut PathData) -> String {
match g.below(3) {
0 => moved(&mut sp.anchors[at], Vec2::new(g.offset(30), g.offset(30))),
1 => sp.anchors[at].h_out = sp.anchors[at].p + Vec2::new(g.offset(10), g.offset(10)),
_ => sp.anchors[at..].iter_mut().take(n / 10).for_each(|a| moved(a, Vec2::new(1.0, -1.0))),
_ => sp.anchors.iter_mut().skip(at).take(n / 10).for_each(|a| moved(a, Vec2::new(1.0, -1.0))),
}
format!("anchors moved at {at} of subpath {s} of {n}")
}
@@ -486,7 +486,7 @@ fn same_as_made_again(k: &mut crate::kept_paths::KeptPath, n: &Arc<Node>, st: &S
fn random_edits_of_a_long_path_keep_what_making_its_path_again_makes() {
let st = stroke(6.0, LineJoin::Miter, LineCap::Butt);
let mut g = Seeded(5744);
let closed = |sp: SubPath| SubPath::new(sp.anchors, true);
let closed = |sp: SubPath| SubPath::of(sp.anchors, true);
let path = PathData::new(vec![
zigzag(2, 11_990.0),
closed(zigzag(3, 12_000.0)),
@@ -517,7 +517,7 @@ fn random_edits_of_a_long_compound_path_keep_what_making_its_path_again_makes()
Arc::new(Node::path(NodeId(ids.get()), p, Appearance::default()))
};
let children = vec![
member(PathData::new(vec![SubPath::new(zigzag(3, 11_990.0).anchors, true), zigzag(5, 12_010.0)])),
member(PathData::new(vec![SubPath::of(zigzag(3, 11_990.0).anchors, true), zigzag(5, 12_010.0)])),
member(PathData::single(zigzag(3000, 0.0))),
member(PathData::single(ring(40, Point::new(12_000.0, 15.0), 30.0))),
member(PathData::single(zigzag(2, 12_020.0))),
+2 -2
View File
@@ -500,8 +500,8 @@ impl Writer<'_> {
/// `<circle>` when its radii are written the same, else `<ellipse>`.
fn ellipse_shape(&self, sp: &SubPath, m: Affine) -> Option<(&'static str, String)> {
let tol = 10f64.powi(-i32::from(self.opts.decimals));
let (anchors, closed) = (sp.anchors.as_slice(), sp.closed);
let [a0, a1, a2, a3] = anchors else { return None };
let (anchors, closed) = (sp.anchors.contiguous(), sp.closed);
let [a0, a1, a2, a3] = &*anchors else { return None };
let [p0, p1, p2, p3] = [a0.p, a1.p, a2.p, a3.p].map(|p| m * p);
let c = p0.midpoint(p2);
let near = |a: f64, b: f64| (a - b).abs() <= tol;
+63 -8
View File
@@ -604,25 +604,41 @@ impl Writer<'_> {
let mut inner = n.clone();
inner.appearance.effects.retain(|e| !vectorcraft_effects::is_raster(&e.id));
// An SVG filter's user-space coordinates are the document's from the effect's origin: the
// object is written in them, in a group that moves it where the rest of the art goes.
// object is written in them, in a group that moves it where the rest of the art goes. A
// user space that is scaled or turned ([`turned_filter_space`]) is the group's own: the
// object is written as it is in a group inside the filter that maps it back
// ([`Self::open_filters`]), so its strokes keep their widths.
let xf = self.xf;
let origin = live_svg_filter(&n.appearance.effects).map(|f| Affine::translate(f.origin()));
let live = live_svg_filter(&n.appearance.effects);
let turned = self.turned_filter_space(live.as_ref());
let origin = live.filter(|_| turned.is_none()).map(|f| Affine::translate(f.origin()));
let moved = origin.is_some_and(|o| xf * o != Affine::IDENTITY);
if let Some(o) = origin.filter(|_| moved) {
self.line(&format!("<g transform=\"{}\">", self.matrix(xf * o)));
self.depth += 1;
self.xf = o.inverse();
}
if let Some(space) = turned {
self.line(&format!("<g transform=\"{}\">", exact_matrix(space)));
self.depth += 1;
}
let opened = self.open_filters(n, &n.appearance.effects);
self.node_body(&inner);
self.close_filters(opened);
if moved {
if moved || turned.is_some() {
self.xf = xf;
self.depth -= 1;
self.line("</g>");
}
}
/// The group transform that holds a live SVG filter `live` ([`live_svg_filter`]) whose user
/// space is scaled or turned (not only moved, [`vectorcraft_effects::svg_filter::SvgFilterFx::moves_only`]): the filter's user
/// space in the output's. `None` for other filters and in SVG Tiny, which writes no filters.
fn turned_filter_space(&self, live: Option<&vectorcraft_effects::svg_filter::SvgFilterFx>) -> Option<Affine> {
live.filter(|f| !f.moves_only() && !self.tiny()).map(|f| self.xf * f.to_doc())
}
/// Open one `<g filter>` per visible raster effect of `effects` (an object's, or one fill or
/// stroke's) on `n`, outermost last effect; returns how many to close.
pub(super) fn open_filters(&mut self, n: &Node, effects: &[vectorcraft_doc::Effect]) -> usize {
@@ -644,6 +660,7 @@ impl Writer<'_> {
let mut opened = 0;
// An SVG filter that is the object's last effect is written as it is ([`Self::filtered`]).
let live = if std::ptr::eq(effects, n.appearance.effects.as_slice()) { live_svg_filter(effects) } else { None };
let turned = self.turned_filter_space(live.as_ref());
for (k, f) in fx.iter().enumerate().rev() {
if let RasterFx::Pixel(vectorcraft_effects::PixelFx::Svg(sf)) = f
&& live.is_some()
@@ -654,12 +671,40 @@ impl Writer<'_> {
// against the object alone, which is all it runs on ([`live_svg_filter`]).
let mut input = n.clone();
input.appearance.effects.clear();
let input_bounds = input.visual_bounds_with(&self.doc.symbol_boxes()).unwrap_or_default();
if let Some(def) = sf.written_xml(input_bounds).and_then(|xml| vectorcraft_effects::svg_filter::with_id(&xml, &fid)) {
self.def(1, &def);
// Its box in the filter's user space: in a turned or skewed one, the box of the
// object's geometry turned into it, grown by what its strokes and other paint add
// around it in the document: a square that far to each side, as it measures in
// user space along each axis (a miter corner reaches that far along both).
let symbols = self.doc.symbol_boxes();
let visual = input.visual_bounds_with(&symbols).unwrap_or_default();
let user_box = if sf.moves_only() {
visual - sf.origin()
} else {
let geometric = input.geometric_bounds_with(&symbols).unwrap_or(visual);
let margin = [geometric.x0 - visual.x0, geometric.y0 - visual.y0, visual.x1 - geometric.x1, visual.y1 - geometric.y1]
.into_iter()
.fold(0.0, f64::max);
let to_user = sf.to_doc().inverse();
input.transform(to_user, false);
let [a, b, c, d, _, _] = to_user.as_coeffs();
let turned = input.geometric_bounds_with(&symbols).unwrap_or_default();
turned.inflate(margin * (a.abs() + c.abs()), margin * (b.abs() + d.abs()))
};
let def = sf.written_xml(user_box).and_then(|xml| vectorcraft_effects::svg_filter::with_id(&xml, &fid));
if let Some(def) = &def {
self.def(1, def);
self.line(&format!("<g filter=\"url(#{fid})\">"));
self.depth += 1;
opened += 1;
}
// Inside the group of a turned user space ([`Self::filtered`]), the object and its
// other effects are written as they are, in a group that maps them back to it.
if let Some(space) = turned {
self.line(&format!("<g transform=\"{}\">", exact_matrix(space.inverse())));
self.depth += 1;
opened += 1;
}
if def.is_some() {
continue;
}
}
@@ -786,8 +831,18 @@ pub(super) fn pixel_gradient(p: &Paint, fill: bool) -> Option<&GradientPaint> {
}
}
/// `a` as an SVG `matrix(…)` with every digit its numbers need to read back the same, whatever
/// the export's decimals: the transforms around a turned SVG filter ([`Writer::turned_filter_space`])
/// and their inverses still undo each other when one holds very small numbers.
fn exact_matrix(a: Affine) -> String {
// (Without negative zeros.)
let [a, b, c, d, e, f] = a.as_coeffs().map(|v| v + 0.0);
format!("matrix({a} {b} {c} {d} {e} {f})")
}
/// The SVG filter (Effect › SVG Filters) of an object's `effects` that SVG keeps as a `<filter>`:
/// its last visible effect, measured in points.
/// its last visible effect, in any user space the effect gives it ([`Writer::turned_filter_space`])
/// that SVG import can store again.
fn live_svg_filter(effects: &[vectorcraft_doc::Effect]) -> Option<vectorcraft_effects::svg_filter::SvgFilterFx> {
if !vectorcraft_effects::svg_filter::writes_live(effects) {
return None;
@@ -797,7 +852,7 @@ fn live_svg_filter(effects: &[vectorcraft_doc::Effect]) -> Option<vectorcraft_ef
let alone = fx.len() == 1;
match fx.pop() {
Some(vectorcraft_effects::RasterFx::Pixel(vectorcraft_effects::PixelFx::Svg(f)))
if f.in_points() && (alone || !f.measured()) && f.writes_as_svg11() =>
if (alone || !f.measured()) && f.writes_as_svg11() && f.opens_again() =>
{
Some(f)
}
+10 -7
View File
@@ -142,19 +142,22 @@ fn source_of<'a>(filter: &Filter, sources: &'a HashMap<String, Source>) -> Optio
/// XML from `sources` ([`sources`]), in user space mapped to the document by `ts`. `None` when one
/// isn't there, looks different outside the document, or isn't a filter the effect draws
/// ([`vectorcraft_effects::svg_filter::check`]), or
/// when `ts` turns or skews the user space or scales it past what the effect measures (0.001 to
/// 1000 points to a unit). Where `ts` moves the user space is the effect's `origin`.
/// when `ts` scales the user space past what the effect measures (0.001 to 1000 points to a unit,
/// as the square root of its area scale) or stretches its axes past what the effect's `axes` hold.
/// Where `ts` moves the user space is the effect's `origin`; a user space that `ts` turns, skews
/// or scales unevenly keeps those directions in the effect's `axes`, so the filter runs in the
/// element's own user space as SVG 1.1 defines it (<https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion>).
pub(super) fn kept(filters: &[Arc<Filter>], ts: Affine, sources: &HashMap<String, Source>) -> Option<Vec<Effect>> {
let [a, b, c, d, e, f] = ts.as_coeffs();
if b != 0.0 || c != 0.0 || !(0.001..=1000.0).contains(&a) || (a - d).abs() > 1e-9 * a.abs().max(1.0) || !e.is_finite() || !f.is_finite() {
return None;
}
let space = vectorcraft_effects::svg_filter::user_space(ts)?;
filters
.iter()
.map(|filter| {
// A filter styled by the document is left out rather than drawn differently.
let source = source_of(filter, sources).filter(|s| !s.styled)?;
let params = json!({ "name": source.name()?, "xml": source.xml, "scale": a, "origin": [e, f] });
let mut params = json!({ "name": source.name()?, "xml": source.xml, "scale": space.scale, "origin": space.origin });
if let Some(axes) = space.axes {
params["axes"] = json!(axes);
}
Some(Effect { id: vectorcraft_effects::SVG_FILTER.into(), params, visible: true })
})
.collect()
+6 -5
View File
@@ -763,14 +763,15 @@ fn percentages_in_a_symbol_are_of_its_view_box() {
}
/// #1598: the warning for a filter that neither the live effects nor an SVG filter effect can hold
/// (here, on turned objects) names the filter, its primitives and the object, and says it is drawn
/// without it (not "a group": usvg wraps the element in one). Such a filter on an object that
/// isn't turned comes in as an SVG filter effect holding the filter's XML.
/// (here, on objects skewed past what the effect measures) names the filter, its primitives and the
/// object, and says it is drawn without it (not "a group": usvg wraps the element in one). Such a
/// filter on an object that isn't skewed that far comes in as an SVG filter effect holding the
/// filter's XML.
#[test]
fn unsupported_filters_are_named_in_the_warning() {
let body = r#"<filter id="f"><feColorMatrix type="saturate" values="0"/></filter><filter id="t"><feTurbulence baseFrequency="0.05"/></filter>
<rect x="20" y="20" width="60" height="60" fill="red" transform="rotate(10 50 50)" filter="url(#f)"/>
<rect id="r" x="100" y="20" width="60" height="60" fill="blue" transform="rotate(10 130 50)" filter="url(#t)"/>
<rect x="0.02" y="0.02" width="0.06" height="0.06" fill="red" transform="skewX(89.95)" filter="url(#f)"/>
<rect id="r" x="0.1" y="0.02" width="0.06" height="0.06" fill="blue" transform="skewX(89.95)" filter="url(#t)"/>
<rect x="20" y="90" width="20" height="20" fill="red" filter="url(#f)"/>"#;
let (d, w) = import_with_report(&svg(body)).unwrap();
assert!(w.iter().any(|w| w == "filter 'f' (feColorMatrix) on an object isn't supported; drawn without it"), "{w:?}");
+124 -2
View File
@@ -522,7 +522,8 @@ fn a_filter_used_twice_among_many_is_kept_twice() {
assert_eq!(filters, vec![vec![json!("g")], vec![json!("g")]], "{:?}", art(&d));
}
/// Other filters come in as SVG filters; one on a turned object is reported and left out.
/// Other filters come in as SVG filters, on a turned or skewed object too, with the object's user
/// space in `scale`, `origin` and `axes`; one past what the effect measures is reported and left out.
#[test]
fn other_filters_are_kept_or_reported() {
let (d, w) =
@@ -530,8 +531,32 @@ fn other_filters_are_kept_or_reported() {
assert!(w.is_empty(), "{w:?}");
let fx = effects(&d);
assert_eq!((fx.len(), fx[0].id.as_str(), &fx[0].params["name"]), (1, "svg.filter", &json!("t")));
assert!(fx[0].params.get("axes").is_none(), "the document's axes: {:?}", fx[0].params);
let (d, w) = open(
r##"<defs><filter id="t"><feTurbulence baseFrequency="0.05"/></filter></defs><rect width="60" height="40" transform="rotate(30)" filter="url(#t)"/>"##,
r##"<defs><filter id="t"><feTurbulence baseFrequency="0.05"/></filter></defs><rect width="60" height="40" transform="translate(10 20) scale(2) rotate(30)" filter="url(#t)"/>"##,
);
assert!(w.is_empty(), "{w:?}");
let fx = effects(&d);
assert_eq!(fx.len(), 1);
let p = &fx[0].params;
let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
let num = |v: &serde_json::Value| v.as_f64().unwrap();
assert!((num(&p["scale"]) - 2.0).abs() < 1e-6 && p["origin"] == json!([10.0, 20.0]), "{p}");
let axes: Vec<f64> = p["axes"].as_array().unwrap().iter().map(num).collect();
assert!(axes.iter().zip([c, s, -s, c]).all(|(a, b)| (a - b).abs() < 1e-6), "{axes:?}");
// Skewed, and scaled unevenly: the axes keep both.
let (d, w) = open(
r##"<defs><filter id="t"><feTurbulence baseFrequency="0.05"/></filter></defs><rect width="60" height="40" transform="skewX(45)" filter="url(#t)"/><rect width="60" height="40" transform="scale(1 4)" filter="url(#t)"/>"##,
);
assert!(w.is_empty(), "{w:?}");
let all: Vec<Vec<f64>> =
art(&d).iter().flat_map(|n| &n.appearance.effects).map(|e| e.params["axes"].as_array().unwrap().iter().map(num).collect()).collect();
assert_eq!(all.len(), 2);
assert!(all.iter().any(|a| a.iter().zip([1.0, 0.0, 1.0, 1.0]).all(|(a, b)| (a - b).abs() < 1e-6)), "{all:?}");
assert!(all.iter().any(|a| a.iter().zip([0.5, 0.0, 0.0, 2.0]).all(|(a, b)| (a - b).abs() < 1e-6)), "{all:?}");
// Skewed so far that an axis would stretch past 1000 times: reported and left out.
let (d, w) = open(
r##"<defs><filter id="t"><feTurbulence baseFrequency="0.05"/></filter></defs><rect width="0.01" height="0.01" transform="skewX(89.95)" filter="url(#t)"/>"##,
);
assert!(w.iter().any(|w| w.contains("filter")), "{w:?}");
assert!(effects(&d).is_empty());
@@ -543,6 +568,40 @@ fn other_filters_are_kept_or_reported() {
assert!(effects(&d).is_empty());
}
/// A filter on a turned object runs in the object's user space (SVG 1.1 measures its lengths
/// there): opened, it draws as the same filter does on the same art drawn unturned with its offset
/// turned by hand.
#[test]
fn a_filter_on_a_turned_object_draws_in_its_user_space() {
let filter = |dx: f64, dy: f64| {
format!(
r#"<filter id="m" x="-1" y="-1" width="3" height="3"><feOffset dx="{dx}" dy="{dy}"/><feColorMatrix type="hueRotate" values="90"/></filter>"#
)
};
let turned = format!(
r##"<defs>{}</defs><rect x="60" y="30" width="40" height="40" fill="#08f" transform="rotate(30 80 50)" filter="url(#m)"/>"##,
filter(24.0, 0.0)
);
let (d, w) = open(&turned);
assert!(w.is_empty(), "{w:?}");
assert_eq!(effects(&d).iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["svg.filter"]);
// The same square, its corners turned by hand, with the offset 24 along the turned x axis.
let (c, s) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
let corner = |x: f64, y: f64| format!("{},{}", 80.0 + c * (x - 80.0) - s * (y - 50.0), 50.0 + s * (x - 80.0) + c * (y - 50.0));
let reference = format!(
r##"<defs>{}</defs><polygon points="{} {} {} {}" fill="#08f" filter="url(#m)"/>"##,
filter(24.0 * c, 24.0 * s),
corner(60.0, 30.0),
corner(100.0, 30.0),
corner(100.0, 70.0),
corner(60.0, 70.0)
);
let canvas = render_artboard(&d);
// The moved square lies beyond where it was: its center, turned and moved, is near (100.8, 62).
assert!(canvas.over_white(101, 62) != [255, 255, 255], "drawn where the offset puts it");
assert_similar(&canvas, &resvg_render(&svg(&reference), 200, 120), 40.0, 0.02);
}
#[test]
fn a_filter_and_a_clip_on_one_object_filter_first() {
let body = r##"<defs><filter id="b"><feGaussianBlur stdDeviation="4"/></filter><clipPath id="c"><rect x="60" y="40" width="40" height="40"/></clipPath></defs>
@@ -638,6 +697,69 @@ fn filtered_rect(xml: &str) -> Document {
d
}
/// An SVG filter in a scaled, turned or skewed user space is written live: the filter's user space
/// is a group's transform, and the art is written in document coordinates in a group inside the
/// filter that maps it back, so its stroke keeps its width. Opened again, it is the same effect
/// and draws as the canvas drew it.
#[test]
fn an_exported_turned_filter_opens_as_the_same_effect() {
let xml = r#"<filter id="m" x="-1" y="-1" width="3" height="3"><feOffset dx="10"/><feColorMatrix type="hueRotate" values="90"/></filter>"#;
for (scale, axes) in [(2.0, json!([0.8, 0.6, -0.6, 0.8])), (1.0, json!([1.0, 0.0, 0.5, 1.0])), (0.5, serde_json::Value::Null)] {
let mut d = Document::new(200.0, 120.0);
let mut n = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(40.0, 20.0, 100.0, 70.0)),
Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::solid(Color::BLACK), 4.0),
);
let mut params = json!({ "xml": xml, "scale": scale, "origin": [30.0, 10.0] });
if !axes.is_null() {
params["axes"] = axes.clone();
}
n.appearance.effects = vec![Effect { id: "svg.filter".into(), params, visible: true }];
let l = d.layers[0].id;
d.insert(Some(l), 0, n).unwrap();
let out = export(&d, &ExportOptions::default());
assert!(out.contains("<g filter=\"url(#") && !out.contains("<image"), "{out}");
assert!(out.contains("stroke-width=\"4\""), "the stroke keeps its width: {out}");
let (back, w) = import_with_report(&out).unwrap();
assert!(w.is_empty(), "{w:?}");
let fx = effects(&back);
assert_eq!(fx.len(), 1, "{out}");
let num = |v: &serde_json::Value| v.as_f64().unwrap();
assert!((num(&fx[0].params["scale"]) - scale).abs() < 1e-6, "{:?}", fx[0].params);
let origin: Vec<f64> = fx[0].params["origin"].as_array().unwrap().iter().map(num).collect();
assert!((origin[0] - 30.0).abs() < 1e-6 && (origin[1] - 10.0).abs() < 1e-6, "{origin:?}");
match fx[0].params.get("axes") {
Some(got) => {
let got: Vec<f64> = got.as_array().unwrap().iter().map(num).collect();
let want: Vec<f64> = axes.as_array().unwrap().iter().map(num).collect();
assert!(got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6), "{got:?}");
}
None => assert!(axes.is_null(), "{:?}", fx[0].params),
}
assert_similar(&render_artboard(&d), &render_artboard(&back), 40.0, 0.02);
}
// A user space stretched 10,000 times along x: the inverse transform holds 0.0001, which the
// export's three decimals would round to 0, and the art still opens at its place.
let mut d = Document::new(200.0, 120.0);
let mut n = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(40.0, 20.0, 100.0, 70.0)),
Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::None, 0.0),
);
let xml = r#"<filter id="k"><feColorMatrix type="hueRotate" values="90"/></filter>"#;
let params = json!({ "xml": xml, "scale": 10.0, "axes": [1000.0, 0.0, 0.0, 1.0] });
n.appearance.effects = vec![Effect { id: "svg.filter".into(), params, visible: true }];
let l = d.layers[0].id;
d.insert(Some(l), 0, n).unwrap();
let out = export(&d, &ExportOptions::default());
let (back, w) = import_with_report(&out).unwrap();
assert!(w.is_empty(), "{w:?}");
let bounds = |d: &Document| art(d).iter().find_map(|n| n.path_data().and_then(|p| p.bounds())).unwrap();
let (a, b) = (bounds(&d), bounds(&back));
assert!((a.x0 - b.x0).abs() < 1e-3 && (a.x1 - b.x1).abs() < 1e-3 && (a.y1 - b.y1).abs() < 1e-3, "{a:?} {b:?}: {out}");
}
/// SVG 1.1 export writes an SVG filter's image reference as `xlink:href`, and it imports back.
#[test]
fn an_exported_filter_image_has_an_xlink_reference() {
+43 -4
View File
@@ -395,8 +395,29 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins
if end >= g.len() { set(w, trailing, ink) } else { w }
}
/// Whether the cluster `j..end` is drawn last, at the right end, of the left-to-right line of
/// glyphs `i..end`: the line's glyphs are reordered by their levels (UAX #9 L2), with each tab and
/// the spaces before it at the paragraph's level (L1).
fn drawn_last(g: &[SGlyph], i: usize, j: usize, end: usize) -> bool {
let line = g.get(i..end).unwrap_or_default();
let mut levels: Vec<unicode_bidi::Level> = line.iter().map(|h| h.level).collect();
let mut before_tab = false;
for (level, h) in levels.iter_mut().zip(line).rev() {
if h.ch == '\t' && h.len > 0 {
before_tab = true;
} else if !h.is_space() {
before_tab = false;
}
if before_tab {
*level = unicode_bidi::Level::ltr();
}
}
unicode_bidi::BidiInfo::reorder_visual(&levels).last().is_some_and(|&k| i + k >= j)
}
/// Greedy break: returns (end glyph index, hyphenated) for a line starting at `i` of `width`.
/// With burasagari, a comma or full stop that doesn't fit ends the line, hanging outside it.
/// With burasagari, a comma or full stop that doesn't fit ends the line, hanging outside it,
/// unless No Break or Bunri-Kinshi keeps characters after it on its line.
/// `hyphenate` holds the paragraph's Hyphenation options and the Hyphenation Zone in force when
/// the line may hyphenate a word; a line whose text before the overflowing word already ends
/// within the zone breaks before that word. A tab is as wide as it is set: up to its next stop
@@ -416,7 +437,9 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins
/// 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.
/// drawn. Such a line with a tab hangs a burasagari mark only when the mark is drawn at its right
/// end in the visual order of the line's levels ([`drawn_last`]) and the line before the mark fits
/// as drawn.
#[allow(clippy::too_many_arguments)]
pub(super) fn break_line(
text: &str,
@@ -543,8 +566,24 @@ pub(super) fn break_line(
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) {
// It ends the line with the spaces after it, when the mark is all the characters kept
// together (the line's last character is the mark, which is what hangs). Once the line
// holds a tab and is measured as drawn, the mark hangs only where it is drawn at the
// line's right end (its cluster is last in the line's visual order, [`drawn_last`]) and
// the line before it fits as drawn with no line-end trim on its last glyph; otherwise the
// line ends at a legal break that fits as drawn.
let alone = g[j..cluster_end].iter().all(|h| h.byte == gl.byte);
let hangs_as_drawn = || match fits.filter(|_| tabbed) {
None => true,
Some(fits) => {
let mut body = j;
while body > i && g[body - 1].is_space() {
body -= 1;
}
drawn_last(g, i, j, cluster_end) && line_end_credit(g, line_end, body) == 0.0 && fits(j, false)
}
};
if burasagari != Burasagari::None && hangs(gl) && alone && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() {
let mut end = cluster_end;
while g.get(end).is_some_and(SGlyph::is_space) {
end += 1;
+3 -1
View File
@@ -474,7 +474,9 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
&para.tabs,
ind_l,
hyphenate,
para.burasagari,
// A right-to-left paragraph draws a burasagari mark inside its line
// ([`prepare_line_geometry`]): the line ends where it fits with the mark.
if *rtl { Burasagari::None } else { para.burasagari },
para.kinsoku,
ty,
*hanging,
+89
View File
@@ -477,6 +477,95 @@ fn a_tabbed_line_ends_at_the_latest_break_that_fits_as_drawn() {
assert_eq!(ended, (8, false));
}
/// A tabbed line measured as drawn hangs a burasagari full stop that overflows only when the stop
/// is drawn at the line's right end (last in the visual order of the line's levels, whatever its
/// own level) and the line before it fits as drawn with no line-end trim on its last glyph;
/// otherwise it ends at the latest legal break that fits as drawn.
#[test]
fn a_tabbed_burasagari_mark_hangs_only_at_the_drawn_end_of_a_fitting_line() {
let text = "a \t\u{05D0} 漢。";
let specs: Vec<_> = text.char_indices().map(|(byte, ch)| (byte, ch.len_utf8(), 10.0, ch)).collect();
let mut glyphs = synthetic_glyphs(&specs);
glyphs[3].level = unicode_bidi::Level::rtl();
// The text without its tab is 60 pt wide at 。 (glyph 6), past 55 pt; kinsoku keeps 。 off a line
// start, so the latest legal break before it ends the line before 漢 (glyph 5).
let end = |glyphs: &[SGlyph], line_end: &[f64], fits: Option<&dyn Fn(usize, bool) -> bool>| {
break_line(
text,
glyphs,
0,
55.0,
&[],
0.0,
None,
Burasagari::Standard,
Kinsoku::Hard,
KinsokuShoriType::PushOutOnly,
false,
false,
line_end,
fits,
)
};
let all_fit = |_end: usize, _hyphenated: bool| true;
assert_eq!(end(&glyphs, &[], Some(&all_fit)), (7, false), "drawn at the right end of a line that fits: 。 hangs");
let body_too_wide = |end: usize, _hyphenated: bool| end <= 5;
assert_eq!(end(&glyphs, &[], Some(&body_too_wide)), (5, false), "the line before 。 is too wide as drawn");
let mut trimmed = vec![0.0; glyphs.len()];
trimmed[5] = 2.0;
assert_eq!(end(&glyphs, &trimmed, Some(&all_fit)), (5, false), "the line before 。 fits only with 漢 trimmed");
let level = |n: u8| unicode_bidi::Level::new(n).unwrap_or_else(|_| panic!("level {n}"));
glyphs[6].level = level(2);
assert_eq!(end(&glyphs, &[], Some(&all_fit)), (7, false), "。 set left to right in right-to-left text is drawn at the right end");
glyphs[6].level = level(1);
assert_eq!(end(&glyphs, &[], Some(&all_fit)), (7, false), "。 alone right to left after 漢 is drawn at the right end");
glyphs[5].level = level(1);
assert_eq!(end(&glyphs, &[], Some(&all_fit)), (5, false), "。 right to left after 漢 in the same run is drawn inside the line");
glyphs[6].level = level(2);
assert_eq!(end(&glyphs, &[], Some(&all_fit)), (5, false), "。 left to right inside the right-to-left run of 漢 is drawn inside the line");
}
/// A burasagari full stop that No Break keeps with the character after it does not hang: the line
/// would end with that character, which is drawn inside the line, so it ends at an earlier break.
#[test]
fn a_burasagari_mark_kept_with_the_next_character_does_not_hang() {
let text = "漢漢。漢";
let specs: Vec<_> = text.char_indices().map(|(byte, ch)| (byte, ch.len_utf8(), 10.0, ch)).collect();
let mut glyphs = synthetic_glyphs(&specs);
let end = |glyphs: &[SGlyph]| {
break_line(text, glyphs, 0, 25.0, &[], 0.0, None, Burasagari::Standard, Kinsoku::Hard, KinsokuShoriType::PushOutOnly, false, false, &[], None)
};
assert_eq!(end(&glyphs), (3, false), "alone, 。 overflows by 5 pt and hangs");
glyphs[2].no_break = true;
glyphs[3].no_break = true;
assert_eq!(end(&glyphs), (1, false), "kept with the 漢 after it, 。 does not end the line");
}
/// A line with a tab and right-to-left text pushes a closing bracket out with every Kinsoku Shori
/// Type, where the same widths without them push it in.
#[test]
fn push_in_leaves_a_tabbed_right_to_left_line_to_push_out() {
use vectorcraft_doc::{TabAlign, TabStop};
let tabbed = "\u{05D0}\t一二三四五」六";
let mut glyphs = full_width(tabbed);
glyphs[0].level = unicode_bidi::Level::rtl();
glyphs[1].adv = 2.0;
let tabs = [TabStop { position: 12.0, align: TabAlign::Left, leader: String::new(), align_on: '.' }];
let all_fit = |_end: usize, _hyphenated: bool| true;
let fits: Option<&dyn Fn(usize, bool) -> bool> = Some(&all_fit);
// 」 (glyph 7) ends 72 pt along, 5 pt past the measure: five gaps close by 1 pt each.
let end = |ty| break_line(tabbed, &glyphs, 0, 67.0, &tabs, 0.0, None, Burasagari::None, Kinsoku::Hard, ty, false, false, &[], fits);
for ty in [KinsokuShoriType::PushInFirst, KinsokuShoriType::PushOutFirst, KinsokuShoriType::PushOutOnly] {
assert_eq!(end(ty), (6, false), "{ty:?}: 五 is pushed out with 」");
}
let plain = "ax一二三四五」六";
let mut glyphs = full_width(plain);
glyphs[1].adv = 2.0;
let pushed =
break_line(plain, &glyphs, 0, 67.0, &[], 0.0, None, Burasagari::None, Kinsoku::Hard, KinsokuShoriType::PushInFirst, false, false, &[], None);
assert_eq!(pushed, (8, false), "without the tab and right-to-left text, 」 is pushed in");
}
/// Past the breaks a tabbed line measures one by one, it ends at the latest break without a hyphen
/// that fits as drawn, whatever the breaks with a hyphen between them measure.
#[test]
+35
View File
@@ -293,3 +293,38 @@ fn burasagari_counts_the_hung_start() {
assert!((quote.origin.x + quote.advance).abs() < EPS, "the quote hangs: {:?}", quote.origin);
assert!((comma.origin.x + comma.advance - 100.0).abs() < EPS, "、 inside, on the edge: {:?} {}", comma.origin, comma.advance);
}
/// A right-to-left paragraph draws a burasagari full stop inside its line, so the line breaks where
/// it fits with the stop: in a frame too narrow for the whole line by half the stop, the line ends
/// after the first word and nothing is drawn past the frame.
#[test]
fn right_to_left_burasagari_keeps_the_line_inside_the_frame() {
use vectorcraft_doc::{Burasagari, Kinsoku, ParaDirection};
const EPS: f64 = 1e-6;
let text = "\u{05D0}\u{05D1} \u{05D2}\u{05D3}\u{3002}";
let lay = |width: f64| {
let mut t = area(text, 20.0, Rect::new(0.0, 0.0, width, 400.0), Justify::Auto);
t.para.direction = Some(ParaDirection::RightToLeft);
t.para.burasagari = Burasagari::Standard;
t.para.kinsoku = Kinsoku::Hard;
let l = layout(db(), &t);
(t, l)
};
let (_, wide) = lay(1000.0);
assert_eq!(wide.lines.len(), 1);
let full: f64 = wide.glyphs.iter().map(|g| g.advance).sum();
let Some(stop) = wide.glyphs.iter().find(|g| g.byte == text.len() - '\u{3002}'.len_utf8()) else {
panic!("。 is set as a glyph of its own");
};
let (t, l) = lay(full - stop.advance / 2.0);
assert!(!l.overflow);
assert_eq!(l.lines.len(), 2, "the line ends after the first word");
for (li, gs) in inked(&t, &l) {
// A right-to-left line's trailing space is set at its left, outside the aligned text.
for g in gs.into_iter().filter(|g| !is_space(ch(&t, g))) {
let c = ch(&t, g);
assert!(g.origin.x >= li.avail.0 - EPS, "{c:?} starts at {} before {}", g.origin.x, li.avail.0);
assert!(g.origin.x + g.advance <= li.avail.1 + EPS, "{c:?} ends at {} past {}", g.origin.x + g.advance, li.avail.1);
}
}
}
+6 -5
View File
@@ -1457,7 +1457,7 @@ fn touching_contours_keep_their_parts_and_holes() {
#[test]
fn an_open_subpath_closes_straight_whether_or_not_contours_meet() {
let open = vectorcraft_geom::SubPath {
anchors: vec![
anchors: vectorcraft_geom::anchors![
vectorcraft_geom::Anchor {
p: Point::new(0.0, 0.0),
h_in: Point::new(0.0, -50.0),
@@ -1505,7 +1505,7 @@ fn flat_far_and_too_large_merges() {
assert!(close(area(&cap), 200.0, 1e-3), "joined, not lost");
// Handles count too: a lobe whose handles reach 1.3e8 widens the boolean's snapping to 1.85e-6.
let lobe = vectorcraft_geom::SubPath {
anchors: vec![
anchors: vectorcraft_geom::anchors![
vectorcraft_geom::Anchor {
p: Point::new(0.0, 1000.0),
h_in: Point::new(0.0, 1000.0),
@@ -1604,7 +1604,7 @@ fn meets_within_twice_the_boolean_tolerance() {
// What the boolean is given decides the tolerance: an open subpath's end handles (closed
// straight) and a one-anchor subpath (skipped) don't widen it.
let ends = vectorcraft_geom::SubPath {
anchors: vec![
anchors: vectorcraft_geom::anchors![
vectorcraft_geom::Anchor {
p: Point::new(0.0, 0.0),
h_in: Point::new(1e9, 0.0),
@@ -1620,7 +1620,8 @@ fn meets_within_twice_the_boolean_tolerance() {
],
closed: false,
};
let speck = vectorcraft_geom::SubPath { anchors: vec![vectorcraft_geom::Anchor::corner(Point::new(1e9, 1e9))], closed: true };
let speck =
vectorcraft_geom::SubPath { anchors: vectorcraft_geom::anchors![vectorcraft_geom::Anchor::corner(Point::new(1e9, 1e9))], closed: true };
let quiet = PathData::new(vec![ends, speck]);
assert_eq!(rings::touch(&rings::closed_straight(&quiet)), 1e-6);
// A closing-side handle at either end alone is enough to close the subpath straight.
@@ -1653,7 +1654,7 @@ fn the_merged_rings_are_turned_as_a_whole() {
#[test]
fn a_one_anchor_subpath_builds_nothing() {
let loop_ = vectorcraft_geom::SubPath {
anchors: vec![vectorcraft_geom::Anchor {
anchors: vectorcraft_geom::anchors![vectorcraft_geom::Anchor {
p: Point::new(0.0, 0.0),
h_in: Point::new(-20.0, 30.0),
h_out: Point::new(20.0, 30.0),
+2 -2
View File
@@ -178,10 +178,10 @@ impl Tool for ExtendPathTool {
let (k, n) = (end.sp.anchors.len(), ext.anchors.len());
// From the old end on; a stretched last curve (no anchor added) shows whole.
let from = if n > k { k - 1 } else { n.saturating_sub(2) };
let tail = if end.start { ext.anchors.get(..n - from) } else { ext.anchors.get(from..) };
let tail = if end.start { ext.anchors.get_range(..n - from) } else { ext.anchors.get_range(from..) };
if let Some(tail) = tail {
let mut bp = vectorcraft_geom::BezPath::new();
SubPath::new(tail.to_vec(), false).to_bezpath_into(&mut bp);
SubPath::new(tail, false).to_bezpath_into(&mut bp);
out.push(Overlay::Path { path: bp, color: GREY, width: 1.0, dashed: true });
}
}
+2 -2
View File
@@ -478,9 +478,9 @@ impl SmartPenTool {
} else {
straighten_segment(&mut sp, prev);
}
let tail = sp.anchors.get(prev..)?;
let tail = sp.anchors.get_range(prev..)?;
let mut bp = BezPath::new();
SubPath::new(tail.to_vec(), false).to_bezpath_into(&mut bp);
SubPath::new(tail, false).to_bezpath_into(&mut bp);
Some(bp)
}
}
+1 -1
View File
@@ -547,7 +547,7 @@ fn simplify(sp: &mut SubPath, tol: f64, region: Rect) {
None => out[0].h_in = h_in,
}
}
sp.anchors = out;
sp.anchors = out.into();
}
/// Apply a liquify stroke (its dabs, at the brush's intensity) to `path`. `salt` decorrelates
+2 -2
View File
@@ -607,7 +607,7 @@ fn a_drag_from_the_first_anchor_always_closes() {
fn alt_mid_close_keeps_the_turned_outgoing_handle() {
use vectorcraft_geom::{Anchor, SubPath};
let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))];
let (mut d, id, s) = drawing(SubPath { anchors, closed: false });
let (mut d, id, s) = drawing(SubPath::new(anchors, false));
let p = paint();
let mut t = PenTool { drawing: true, ..PenTool::default() };
assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0)));
@@ -634,7 +634,7 @@ fn alt_mid_close_keeps_the_turned_outgoing_handle() {
fn space_moves_the_closing_anchor() {
use vectorcraft_geom::{Anchor, SubPath};
let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))];
let (mut d, id, s) = drawing(SubPath { anchors, closed: false });
let (mut d, id, s) = drawing(SubPath::new(anchors, false));
let p = paint();
let mut t = PenTool { drawing: true, ..PenTool::default() };
assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0)));
+1 -1
View File
@@ -172,7 +172,7 @@ fn live_curve_fitting_off_shows_the_points_until_the_release_fits_them() {
let pointer = |kind, (x, y)| vectorcraft_tools::PointerEvent::new(kind, x, y);
let newest = |app: &VectorcraftApp| {
let doc = &app.session.doc().unwrap().doc;
doc.layers[0].children().unwrap().last().unwrap().path_data().unwrap().subpaths[0].anchors.clone()
doc.layers[0].children().unwrap().last().unwrap().path_data().unwrap().subpaths[0].anchors.to_vec()
};
crate::canvas::dispatch(app, &pointer(vectorcraft_tools::PointerKind::Down, pts[0]), view);
for p in &pts[1..] {
+1 -1
View File
@@ -532,7 +532,7 @@ fn simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path()
let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 20 + i * 8, "y": 150.0 + 60.0 * (f64::from(i) / 6.0).sin()})).collect();
let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap();
let path = |app: &VectorcraftApp| {
app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).and_then(|n| n.path_data()).expect("a path").subpaths[0].anchors.clone()
app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).and_then(|n| n.path_data()).expect("a path").subpaths[0].anchors.to_vec()
};
let original = path(&app);
let run: Vec<_> = (10..=30).map(|i| json!([0, i])).collect();
+12
View File
@@ -5730,6 +5730,17 @@ liquify-list-end {0}, {1} {0} i {1}
@msg `name` must be the name of a script engine `name` ha de ser el nom d'un motor d'scripts
@msg the main script engine is new for each run and is never kept, so it cannot be dropped el motor d'scripts principal és nou a cada execució i no es conserva mai, per tant no es pot descartar
@msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name}
@msg `answers` must be a list of answers `answers` ha de ser una llista de respostes
@msg `answers` has more than {MAX_ANSWERS} answers `answers` té més de {MAX_ANSWERS} respostes
@msg `answers` is larger than 1 MiB `answers` ocupa més d'1 MiB
@msg must be an object with `kind` and `value` ha de ser un objecte amb `kind` i `value`
@msg must have exactly `kind` and `value` ha de tenir exactament `kind` i `value`
@msg is an alert's answer, whose `value` must be "ok" és la resposta d'un alert, i el seu `value` ha de ser "ok"
@msg is a confirm's answer, whose `value` must be true or false és la resposta d'un confirm, i el seu `value` ha de ser true o false
@msg is longer than 16 KiB ocupa més de 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null
@msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg
@msg Running a script S'està executant un script
@msg Copied the script report S’ha copiat l’informe de l’script
@msg Copied the link info S’ha copiat la informació de l’enllaç
@@ -6691,6 +6702,7 @@ liquify-list-end {0}, {1} {0} i {1}
@msg {what} points outside memory {what} apunta fora de la memòria
@msg `angle` must be a number `angle` ha de ser un nombre
@msg `aspect` must be from 0.01 to 100 `aspect` ha d’estar entre 0.01 i 100
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` ha de ser [a, b, c, d], cadascun entre -1000 i 1000, amb a·d - b·c com a mínim a 0.001 de 0
@msg `cap` must be "butt", "round" or "square" `cap` ha de ser "butt", "round" o "square"
@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` ha de ser "nonzero" o "evenodd"
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` ha de ser una adreça https:// de {MAX_HELP_URL} bytes com a màxim
Can't render this file because it contains an unexpected character in line 2 and column 73.
+7 -2
View File
@@ -219,8 +219,13 @@ impl Catalog {
}
// Templates that start with text before those that start with a placeholder, so
// `plug-in manifest: {0}` wins over `{_1} is {_2} bytes (limit {_3})` for a message it
// wraps; then most literal text first, so `Couldn't open {name}: {e}` wins over `{path}: {e}`.
c.templates.sort_by_key(|t| (matches!(t.pieces.first(), Some(Piece::Hole(_))), std::cmp::Reverse(t.literal)));
// wraps; then the longest text before the first placeholder, so `` `answers[{i}]` {e} `` wins
// over `` `{key}` must be true or false `` for a message it wraps; then most literal text
// first, so `Couldn't open {name}: {e}` wins over `{path}: {e}`.
c.templates.sort_by_key(|t| {
let lead = if let Some(Piece::Text(text)) = t.pieces.first() { text.len() } else { 0 };
(matches!(t.pieces.first(), Some(Piece::Hole(_))), std::cmp::Reverse(lead), std::cmp::Reverse(t.literal))
});
c
}
+3
View File
@@ -4819,6 +4819,7 @@ liquify-list-end {0}, {1} {0} a {1}
@msg `name` must be the name of a script engine `name` musí být název skriptovacího jádra
@msg the main script engine is new for each run and is never kept, so it cannot be dropped hlavní skriptovací jádro je pro každý běh nové a nikdy se neuchovává, proto je nelze zahodit
@msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` je jen pro běh, kde se nemá koho zeptat: v aplikaci odpovídá na každý dialog uživatel
@msg Running a script Běží skript
@msg Copied the script report Zpráva o skriptu zkopírována
@msg Copied the link info Informace o propojení zkopírovány
@@ -7825,6 +7826,7 @@ breakText Glyphs Glyfy
@msg Image Trace failed: {e} Vektorizace obrazu selhala: {e}
@msg Image Trace finished, but its document was closed Vektorizace obrazu skončila, ale její dokument byl zavřen
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Vektorizace obrazu skončila, ale obraz nebo jeho nastavení se mezitím změnily: vektorizujte ho znovu
@msg Image Trace finished, but its document was reverted: trace it again Vektorizace obrazu skončila, ale její dokument byl vrácen k uložené verzi: vektorizujte ho znovu
@msg Import SVG Filter reads SVG files, not SVGZ Importovat filtr SVG čte soubory SVG, ne SVGZ
@msg Invalid dimension offset Neplatné odsazení kóty
@msg Invalid point Neplatný bod
@@ -7998,6 +8000,7 @@ breakText Glyphs Glyfy
@msg `names` must be an array of style names `names` musí být pole názvů stylů
@msg `new` is a design name, or true `new` je název návrhu, nebo true
@msg `origin` must be [x, y] in points `origin` musí být [x, y] v bodech
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` musí být [a, b, c, d], každé od -1000 do 1000, a a·d - b·c se musí od 0 lišit alespoň o 0.001
@msg `path` must be a folder `path` musí být složka
@msg `path` must be a path object `path` musí být objekt cesty
@msg `picks` must be an array (got {v}) `picks` musí být pole (zadáno {v})
Can't render this file because it is too large.
+13
View File
@@ -166,6 +166,18 @@ liquify-list-end {0}, {1} {0} og {1}
@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 `answers` must be a list of answers `answers` skal være en liste med svar
@msg `answers` has more than {MAX_ANSWERS} answers `answers` har flere end {MAX_ANSWERS} svar
@msg `answers` is larger than 1 MiB `answers` er større end 1 MiB
@msg `answers[{i}]` {e} `answers[{i}]` {e}
@msg must be an object with `kind` and `value` skal være et objekt med `kind` og `value`
@msg must have exactly `kind` and `value` skal have præcis `kind` og `value`
@msg is an alert's answer, whose `value` must be "ok" er svaret på en alert, hvis `value` skal være "ok"
@msg is a confirm's answer, whose `value` must be true or false er svaret på en confirm, hvis `value` skal være true eller false
@msg is longer than 16 KiB er længere end 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null
@msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog
@msg 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}
@@ -448,6 +460,7 @@ liquify-list-end {0}, {1} {0} og {1}
@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 `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` skal være [a, b, c, d], hver fra -1000 til 1000, med a·d - b·c mindst 0,001 fra 0
@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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -7282,6 +7282,7 @@ breakText Glyphs Glyphen
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` für dieses {kind}-Dialogfeld muss eines der folgenden sein: {_1}
@msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten
@msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog
@msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein
@msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein
@msg `artboardsAt` must be [x, y] `artboardsAt` muss [x, y] sein
@@ -7313,6 +7314,7 @@ breakText Glyphs Glyphen
@msg `name` must be a name that is not empty `name` muss ein nicht leerer Name sein
@msg `name` must not be empty `name` darf nicht leer sein
@msg `origin` must be [x, y] in points `origin` muss [x, y] in Punkt sein
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` muss [a, b, c, d] sein, jeweils von -1000 bis 1000, mit a·d - b·c mindestens 0,001 von 0 entfernt
@msg `picks` must be an array (got {v}) `picks` muss ein Array sein (erhalten: {v})
@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` muss 1 bis {MAX_PICKS} Auswahlen enthalten (erhalten: {_1})
@msg `radius` must be 0 or more `radius` muss 0 oder größer sein
@@ -7670,6 +7672,7 @@ breakText Glyphs Glyphen
@msg Image Trace failed: {e} Bildnachzeichner fehlgeschlagen: {e}
@msg Image Trace finished, but its document was closed Bildnachzeichner abgeschlossen, aber sein Dokument wurde geschlossen
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildnachzeichner abgeschlossen, aber das Bild oder seine Einstellungen haben sich inzwischen geändert: Zeichnen Sie es erneut nach
@msg Image Trace finished, but its document was reverted: trace it again Bildnachzeichner abgeschlossen, aber sein Dokument wurde auf die letzte Version zurückgesetzt: Zeichnen Sie es erneut nach
@msg Invalid dimension offset Ungültiger Bemaßungsversatz
@msg Invalid point Ungültiger Punkt
@msg Join: a subpath went missing Zusammenfügen: Ein Teilpfad ist verloren gegangen
Can't render this file because it is too large.
+13
View File
@@ -2506,6 +2506,18 @@ liquify-list-end {0}, {1} {0} και {1}
@msg `name` must be the name of a script engine το `name` πρέπει να είναι το όνομα μιας μηχανής σεναρίων
@msg the main script engine is new for each run and is never kept, so it cannot be dropped η κύρια μηχανή σεναρίων είναι νέα σε κάθε εκτέλεση και δεν διατηρείται ποτέ, οπότε δεν μπορεί να απορριφθεί
@msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name}
@msg `answers` must be a list of answers το `answers` πρέπει να είναι λίστα απαντήσεων
@msg `answers` has more than {MAX_ANSWERS} answers το `answers` έχει περισσότερες από {MAX_ANSWERS} απαντήσεις
@msg `answers` is larger than 1 MiB το `answers` είναι μεγαλύτερο από 1 MiB
@msg `answers[{i}]` {e} το `answers[{i}]` {e}
@msg must be an object with `kind` and `value` πρέπει να είναι αντικείμενο με `kind` και `value`
@msg must have exactly `kind` and `value` πρέπει να έχει ακριβώς `kind` και `value`
@msg is an alert's answer, whose `value` must be "ok" είναι απάντηση σε alert, οπότε το `value` πρέπει να είναι "ok"
@msg is a confirm's answer, whose `value` must be true or false είναι απάντηση σε confirm, οπότε το `value` πρέπει να είναι true ή false
@msg is longer than 16 KiB είναι μεγαλύτερο από 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null
@msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου
@msg Running a script Εκτελείται σενάριο
@msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε
@msg Copied the link info Οι πληροφορίες συνδέσμου αντιγράφηκαν
@@ -6529,6 +6541,7 @@ axis Y Axis Άξονας Y
@msg {what} points outside memory το {what} δείχνει εκτός μνήμης
@msg `angle` must be a number το `angle` πρέπει να είναι αριθμός
@msg `aspect` must be from 0.01 to 100 το `aspect` πρέπει να είναι από 0.01 έως 100
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 το `axes` πρέπει να είναι [a, b, c, d], καθένα από -1000 έως 1000, με το a·d - b·c να απέχει τουλάχιστον 0.001 από το 0
@msg `cap` must be "butt", "round" or "square" το `cap` πρέπει να είναι "butt", "round" ή "square"
@msg `fillRule` must be "nonzero" or "evenodd" το `fillRule` πρέπει να είναι "nonzero" ή "evenodd"
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes το `helpUrl` πρέπει να είναι διεύθυνση https:// έως {MAX_HELP_URL} byte
Can't render this file because it is too large.
+12
View File
@@ -4503,6 +4503,17 @@ liquify-list-end {0}, {1} {0}, {1}
@msg `name` must be the name of a script engine `name` debe ser el nombre de un motor de scripts
@msg the main script engine is new for each run and is never kept, so it cannot be dropped el motor de scripts principal es nuevo en cada ejecución y nunca se conserva, por lo que no se puede descartar
@msg there is no script engine named {name} no hay ningún motor de scripts llamado {name}
@msg `answers` must be a list of answers `answers` debe ser una lista de respuestas
@msg `answers` has more than {MAX_ANSWERS} answers `answers` tiene más de {MAX_ANSWERS} respuestas
@msg `answers` is larger than 1 MiB `answers` ocupa más de 1 MiB
@msg must be an object with `kind` and `value` debe ser un objeto con `kind` y `value`
@msg must have exactly `kind` and `value` debe tener exactamente `kind` y `value`
@msg is an alert's answer, whose `value` must be "ok" es la respuesta de un alert, cuyo `value` debe ser "ok"
@msg is a confirm's answer, whose `value` must be true or false es la respuesta de un confirm, cuyo `value` debe ser true o false
@msg is longer than 16 KiB ocupa más de 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null
@msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo
@msg Running a script Ejecutando un script
@msg Copied the script report Se copió el informe del script
@msg Copied the link info Se copió la información del vínculo
@@ -6518,6 +6529,7 @@ axis Y Axis Eje Y
@msg {what} points outside memory {what} apunta fuera de la memoria
@msg `angle` must be a number `angle` debe ser un número
@msg `aspect` must be from 0.01 to 100 `aspect` debe estar entre 0.01 y 100
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` debe ser [a, b, c, d], cada uno entre -1000 y 1000, con a·d - b·c a al menos 0.001 de 0
@msg `cap` must be "butt", "round" or "square" `cap` debe ser "butt", "round" o "square"
@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` debe ser "nonzero" o "evenodd"
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` debe ser una dirección https:// de {MAX_HELP_URL} bytes como máximo
Can't render this file because it contains an unexpected character in line 2 and column 73.
+12
View File
@@ -4733,6 +4733,17 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg `name` must be the name of a script engine `name` on oltava skriptimoottorin nimi
@msg the main script engine is new for each run and is never kept, so it cannot be dropped pääskriptimoottori on uusi jokaisella ajolla eikä sitä koskaan säilytetä, joten sitä ei voi poistaa
@msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole
@msg `answers` must be a list of answers `answers` on oltava vastausten luettelo
@msg `answers` has more than {MAX_ANSWERS} answers kohteessa `answers` on yli {MAX_ANSWERS} vastausta
@msg `answers` is larger than 1 MiB `answers` on suurempi kuin 1 MiB
@msg must be an object with `kind` and `value` on oltava objekti, jossa on `kind` ja `value`
@msg must have exactly `kind` and `value` siinä on oltava täsmälleen `kind` ja `value`
@msg is an alert's answer, whose `value` must be "ok" on alert-vastaus, joten sen `value`-arvon on oltava "ok"
@msg is a confirm's answer, whose `value` must be true or false on confirm-vastaus, joten sen `value`-arvon on oltava true tai false
@msg is longer than 16 KiB on pidempi kuin 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null
@msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan
@msg Running a script Suoritetaan komentosarjaa
@msg Copied the script report Komentosarjan raportti kopioitiin
@msg Copied the link info Linkin tiedot kopioitiin
@@ -6607,6 +6618,7 @@ axis Y Axis Y-akseli
@msg {what} points outside memory {what} osoittaa muistin ulkopuolelle
@msg `angle` must be a number `angle` on oltava luku
@msg `aspect` must be from 0.01 to 100 `aspect` on oltava 0.01 ja 100 välillä
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` on oltava [a, b, c, d], kukin -1000 ja 1000 välillä, ja a·d - b·c:n on oltava vähintään 0.001:n päässä 0:sta
@msg `cap` must be "butt", "round" or "square" `cap` on oltava "butt", "round" tai "square"
@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` on oltava "nonzero" tai "evenodd"
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` on oltava enintään {MAX_HELP_URL} tavun https://-osoite
Can't render this file because it contains an unexpected character in line 2 and column 73.
+3
View File
@@ -4492,6 +4492,7 @@ liquify-list-end {0}, {1} {0} et {1}
@msg `name` must be the name of a script engine `name` doit être le nom d'un moteur de script
@msg the main script engine is new for each run and is never kept, so it cannot be dropped le moteur de script principal est nouveau à chaque exécution et n'est jamais conservé, il ne peut donc pas être supprimé
@msg there is no script engine named {name} il n'y a aucun moteur de script nommé {name}
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l'application, la personne répond à chaque boîte de dialogue
@msg Running a script Exécution d’un script
@msg Copied the script report Rapport du script copié
@msg Copied the link info Informations sur le lien copiées
@@ -7693,6 +7694,7 @@ breakText Glyphs Glyphes
@msg Image Trace failed: internal error: its thread stopped (please report this bug) Échec de la vectorisation de l’image : erreur interne : son thread s’est arrêté (merci de signaler ce bogue)
@msg Image Trace failed: {e} Échec de la vectorisation de l’image : {e}
@msg Image Trace finished, but its document was closed La vectorisation de l’image est terminée, mais son document a été fermé
@msg Image Trace finished, but its document was reverted: trace it again La vectorisation de l’image est terminée, mais son document a été rétabli à la version précédente : vectorisez-la à nouveau
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again La vectorisation de l’image est terminée, mais l’image ou ses réglages ont changé entre-temps : vectorisez-la à nouveau
@msg Import SVG Filter reads SVG files, not SVGZ Importer un filtre SVG lit les fichiers SVG, pas SVGZ
@msg Invalid dimension offset Décalage de cote non valide
@@ -7865,6 +7867,7 @@ breakText Glyphs Glyphes
@msg `names` must be an array of style names `names` doit être une liste de noms de styles
@msg `new` is a design name, or true `new` est un nom de motif, ou true
@msg `origin` must be [x, y] in points `origin` doit être [x, y] en points
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` doit être [a, b, c, d], chacun compris entre -1000 et 1000, avec a·d - b·c à au moins 0.001 de 0
@msg `path` must be a folder `path` doit être un dossier
@msg `path` must be a path object `path` doit être un objet tracé
@msg `picks` must be an array (got {v}) `picks` doit être une liste (reçu : {v})
Can't render this file because it is too large.
+14
View File
@@ -5711,6 +5711,7 @@ antiAlias Sharp शार्प
@msg needs approval: it asks for {0}, which the user grants when installing it on its own स्वीकृति आवश्यक: यह {0} माँगता है, जिसे उपयोगकर्ता इसे अलग से स्थापित करते समय देता है
@msg `angle` must be a number `angle` एक संख्या होना चाहिए
@msg `aspect` must be from 0.01 to 100 `aspect` 0.01 से 100 तक होना चाहिए
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` [a, b, c, d] होना चाहिए, हर मान -1000 से 1000 तक, और a·d - b·c का 0 से अंतर कम से कम 0.001 होना चाहिए
@msg `cap` must be "butt", "round" or "square" `cap` "butt", "round" या "square" होना चाहिए
@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` "nonzero" या "evenodd" होना चाहिए
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` अधिकतम {MAX_HELP_URL} बाइट का https:// पता होना चाहिए
@@ -6842,6 +6843,18 @@ liquify-list-end {0}, {1} {0} और {1}
@msg `name` must be the name of a script engine `name` किसी स्क्रिप्ट इंजन का नाम होना चाहिए
@msg the main script engine is new for each run and is never kept, so it cannot be dropped मुख्य स्क्रिप्ट इंजन हर रन के लिए नया होता है और कभी रखा नहीं जाता, इसलिए इसे हटाया नहीं जा सकता
@msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है
@msg `answers` must be a list of answers `answers` उत्तरों की सूची होनी चाहिए
@msg `answers` has more than {MAX_ANSWERS} answers `answers` में {MAX_ANSWERS} से अधिक उत्तर हैं
@msg `answers` is larger than 1 MiB `answers` 1 MiB से बड़ा है
@msg `answers[{i}]` {e} `answers[{i}]`: {e}
@msg must be an object with `kind` and `value` `kind` और `value` वाला ऑब्जेक्ट होना चाहिए
@msg must have exactly `kind` and `value` इसमें ठीक-ठीक `kind` और `value` होने चाहिए
@msg is an alert's answer, whose `value` must be "ok" यह alert का उत्तर है, इसलिए इसका `value` "ok" होना चाहिए
@msg is a confirm's answer, whose `value` must be true or false यह confirm का उत्तर है, इसलिए इसका `value` true या false होना चाहिए
@msg is longer than 16 KiB 16 KiB से लंबा है
@msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए
@msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है
@msg Running a script स्क्रिप्ट चल रही है
@msg Copied the script report Copied स्क्रिप्ट रिपोर्ट
@msg Copied the link info लिंक जानकारी कॉपी की गई
@@ -7137,6 +7150,7 @@ liquify-list-end {0}, {1} {0} और {1}
@msg Image Trace failed: internal error: its thread stopped (please report this bug) इमेज ट्रेस विफल: आंतरिक त्रुटि: इसके धागे को बंद कर दिया (कृपया इस बग की रिपोर्ट करें)
@msg Image Trace finished, but its document was closed इमेज ट्रेस समाप्त हो गया, लेकिन इसका डॉक्यूमेंट बंद हो गया।
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इस बीच इमेज या इसकी सेटिंग्स बदल गई: इसे फिर से ट्रेस करें
@msg Image Trace finished, but its document was reverted: trace it again इमेज ट्रेस समाप्त हो गया, लेकिन इसके डॉक्यूमेंट को मूल स्थिति में लाया गया: इसे फिर से ट्रेस करें
@msg Image Trace: the traced image is missing इमेज ट्रेस: ज्ञात इमेज गायब है
@msg image would be too large; lower the resolution इमेज बहुत बड़ी होगी; रिज़ॉल्यूशन कम करें
@msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client या server
Can't render this file because it is too large.
+4
View File
@@ -5321,6 +5321,8 @@ liquify-list-end {0}, {1} {0} és {1}
@msg `name` must be the name of a script engine a `name` értékének egy parancsfájlmotor nevének kell lennie
@msg the main script engine is new for each run and is never kept, so it cannot be dropped a fő parancsfájlmotor minden futáshoz új, és sosem marad meg, ezért nem dobható el
@msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor
@msg `answers[{i}]` {e} `answers[{i}]`: {e}
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog az `answers` csak olyan futtatáshoz való, ahol nincs kit megkérdezni: az alkalmazásban minden párbeszédpanelre a felhasználó válaszol
@msg Running a script Parancsfájl futtatása
@msg Copied the script report Szkriptjelentés másolva
@msg Copied the link info Csatolás adatai másolva
@@ -7695,6 +7697,7 @@ breakText Glyphs Glifák
@msg Image Trace failed: {e} A képvektorizálás nem sikerült: {e}
@msg Image Trace finished, but its document was closed A képvektorizálás elkészült, de a dokumentumát bezárták
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again A képvektorizálás elkészült, de a kép vagy a beállításai közben megváltoztak: vektorizáld újra
@msg Image Trace finished, but its document was reverted: trace it again A képvektorizálás elkészült, de a dokumentumát visszaállították a mentett változatra: vektorizáld újra
@msg Import SVG Filter reads SVG files, not SVGZ Az SVG-szűrő importálása SVG-fájlokat olvas, SVGZ-fájlokat nem
@msg Invalid dimension offset Érvénytelen méretvonal-eltolás
@msg Invalid point Érvénytelen pont
@@ -7868,6 +7871,7 @@ breakText Glyphs Glifák
@msg `names` must be an array of style names `names`: stílusnevek tömbje kell
@msg `new` is a design name, or true `new`: diagramminta neve vagy true
@msg `origin` must be [x, y] in points `origin`: [x, y] kell pontban megadva
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes`: [a, b, c, d] kell, mindegyik -1000 és 1000 között, és a·d - b·c legalább 0.001-gyel térjen el 0-tól
@msg `path` must be a folder `path`: mappa kell
@msg `path` must be a path object `path`: útvonalobjektum kell
@msg `picks` must be an array (got {v}) `picks`: tömb kell (kapott érték: {v})
Can't render this file because it is too large.
+3
View File
@@ -7321,6 +7321,7 @@ breakText Glyphs Glifi
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` per questa finestra di dialogo {kind} deve essere uno tra: {_1}
@msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte
@msg `answers` is larger than 1 MiB `answers` supera 1 MiB
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo
@msg `answers` must be a list of answers `answers` deve essere un elenco di risposte
@msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento
@msg `artboardsAt` must be [x, y] `artboardsAt` deve essere [x, y]
@@ -7353,6 +7354,7 @@ breakText Glyphs Glifi
@msg `name` must be a name that is not empty `name` deve essere un nome non vuoto
@msg `name` must not be empty `name` non deve essere vuoto
@msg `origin` must be [x, y] in points `origin` deve essere [x, y] in punti
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` deve essere [a, b, c, d], ciascuno compreso tra -1000 e 1000, con a·d - b·c distante almeno 0.001 da 0
@msg `picks` must be an array (got {v}) `picks` deve essere un array (ricevuto {v})
@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` deve contenere da 1 a {MAX_PICKS} scelte (ricevute {_1})
@msg `points` must hold from 2 to 100000 points `points` deve contenere da 2 a 100000 punti
@@ -7720,6 +7722,7 @@ breakText Glyphs Glifi
@msg Image Trace failed: {e} Ricalco immagine non riuscito: {e}
@msg Image Trace finished, but its document was closed Ricalco immagine terminato, ma il suo documento è stato chiuso
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Ricalco immagine terminato, ma nel frattempo l'immagine o le sue impostazioni sono cambiate: ricalcala di nuovo
@msg Image Trace finished, but its document was reverted: trace it again Ricalco immagine terminato, ma il suo documento è stato ripristinato: ricalcala di nuovo
@msg Invalid dimension offset Distanza della quota non valida
@msg Invalid point Punto non valido
@msg Join: a subpath went missing Unisci: un sottotracciato è andato perso
Can't render this file because it is too large.
+3
View File
@@ -5320,6 +5320,7 @@ liquify-list-end {0}, {1} {0}、{1}
@msg `name` must be the name of a script engine `name` はスクリプトエンジンの名前にしてください
@msg the main script engine is new for each run and is never kept, so it cannot be dropped メインのスクリプトエンジンは実行ごとに新しく作られ、保持されないため、破棄できません
@msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` は尋ねる相手がいない実行専用です。アプリでは、各ダイアログに本人が回答します
@msg Running a script スクリプトを実行中
@msg Copied the script report スクリプトのレポートをコピーしました
@msg Copied the link info リンク情報をコピーしました
@@ -6553,6 +6554,7 @@ axis Y Axis Y 軸
@msg `name` must be a name that is not empty `name` には空でない名前を指定してください
@msg `name` must not be empty `name` を空にすることはできません
@msg `origin` must be [x, y] in points `origin` にはポイント単位の [x, y] を指定してください
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` には [a, b, c, d] を指定してください (各値は -1000 から 1000、a·d - b·c は 0 から 0.001 以上離れた値)
@msg `picks` must be an array (got {v}) `picks` には配列を指定してください (指定値: {v})
@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` には 1~{MAX_PICKS} 個の指定が必要です (指定数: {_1})
@msg `points` must hold from 2 to 100000 points `points` には 2~100000 個の点が必要です
@@ -6921,6 +6923,7 @@ axis Y Axis Y 軸
@msg Image Trace failed: {e} 画像トレースに失敗しました: {e}
@msg Image Trace finished, but its document was closed 画像トレースは完了しましたが、ドキュメントが閉じられています
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 画像トレースは完了しましたが、その間に画像または設定が変更されました: もう一度トレースしてください
@msg Image Trace finished, but its document was reverted: trace it again 画像トレースは完了しましたが、ドキュメントは保存済みの状態に戻されました: もう一度トレースしてください
@msg Invalid dimension offset 寸法のオフセットが無効です
@msg Invalid point 点が無効です
@msg Join: a subpath went missing 連結: サブパスが見つからなくなりました
Can't render this file because it is too large.
+13
View File
@@ -5737,6 +5737,18 @@ liquify-list-end {0}, {1} {0} და {1}
@msg `name` must be the name of a script engine `name` უნდა იყოს სკრიპტის ძრავის სახელი
@msg the main script engine is new for each run and is never kept, so it cannot be dropped მთავარი სკრიპტის ძრავა ყოველი გაშვებისთვის ახალია და არასოდეს ინახება, ამიტომ მისი მოცილება შეუძლებელია
@msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს
@msg `answers` must be a list of answers `answers` უნდა იყოს პასუხების სია
@msg `answers` has more than {MAX_ANSWERS} answers `answers`-ში {MAX_ANSWERS}-ზე მეტი პასუხია
@msg `answers` is larger than 1 MiB `answers` 1 MiB-ზე დიდია
@msg `answers[{i}]` {e} `answers[{i}]`: {e}
@msg must be an object with `kind` and `value` უნდა იყოს ობიექტი `kind`-ითა და `value`-ით
@msg must have exactly `kind` and `value` უნდა ჰქონდეს ზუსტად `kind` და `value`
@msg is an alert's answer, whose `value` must be "ok" alert-ის პასუხია, ამიტომ მისი `value` უნდა იყოს "ok"
@msg is a confirm's answer, whose `value` must be true or false confirm-ის პასუხია, ამიტომ მისი `value` უნდა იყოს true ან false
@msg is longer than 16 KiB 16 KiB-ზე გრძელია
@msg is a prompt's answer, whose `value` must be a string or null prompt-ის პასუხია, ამიტომ მისი `value` უნდა იყოს სტრიქონი ან null
@msg must have `kind` alert, confirm or prompt `kind` უნდა იყოს alert, confirm ან prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` მხოლოდ ისეთი გაშვებისთვისაა, სადაც შესაკითხი არავინაა: აპში თითოეულ დიალოგს ადამიანი პასუხობს
@msg Running a script სკრიპტი მუშაობს
@msg Copied the script report კოპირებულია სკრიპტის ანგარიში
@msg Copied the link info კოპირებულია ბმულის ინფორმაცია
@@ -6528,6 +6540,7 @@ axis Y Axis Y ღერძი
@msg {what} points outside memory {what} მეხსიერების გარეთ მიუთითებს
@msg `angle` must be a number `angle` უნდა იყოს რიცხვი
@msg `aspect` must be from 0.01 to 100 `aspect` უნდა იყოს 0.01-დან 100-მდე
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` უნდა იყოს [a, b, c, d], თითოეული -1000-დან 1000-მდე, ხოლო a·d - b·c უნდა განსხვავდებოდეს 0-ისგან მინიმუმ 0.001-ით
@msg `cap` must be "butt", "round" or "square" `cap` უნდა იყოს "butt", "round" ან "square"
@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` უნდა იყოს "nonzero" ან "evenodd"
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` უნდა იყოს https:// მისამართი, არაუმეტეს {MAX_HELP_URL} ბაიტისა
Can't render this file because it is too large.
+3
View File
@@ -5247,6 +5247,7 @@ liquify-list-end {0}, {1} {0} 및 {1}
@msg `name` must be the name of a script engine `name`은(는) 스크립트 엔진의 이름이어야 합니다
@msg the main script engine is new for each run and is never kept, so it cannot be dropped 기본 스크립트 엔진은 실행마다 새로 만들어지고 유지되지 않으므로 삭제할 수 없습니다
@msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers`는 물어볼 사람이 없는 실행에만 쓰입니다. 앱에서는 사람이 각 대화 상자에 답합니다
@msg Running a script 스크립트 실행 중
@msg Copied the script report 스크립트 보고서를 복사했습니다
@msg Copied the link info 링크 정보를 복사했습니다
@@ -7420,6 +7421,7 @@ breakText Glyphs 글리프
@msg Image Trace failed: {e} 이미지 추적 실패: {e}
@msg Image Trace finished, but its document was closed 이미지 추적이 끝났지만 문서가 닫혔습니다
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 이미지 추적이 끝났지만 그 사이에 이미지나 설정이 바뀌었습니다: 다시 추적하세요
@msg Image Trace finished, but its document was reverted: trace it again 이미지 추적이 끝났지만 문서가 되돌려졌습니다: 다시 추적하세요
@msg Import SVG Filter reads SVG files, not SVGZ SVG 필터 가져오기는 SVGZ가 아닌 SVG 파일을 읽습니다
@msg Invalid dimension offset 잘못된 치수 오프셋
@msg Invalid point 잘못된 점
@@ -7593,6 +7595,7 @@ breakText Glyphs 글리프
@msg `names` must be an array of style names `names`은(는) 스타일 이름의 배열이어야 합니다
@msg `new` is a design name, or true `new`은(는) 디자인 이름 또는 true입니다
@msg `origin` must be [x, y] in points `origin`은(는) 포인트 단위의 [x, y]여야 합니다
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes`은(는) [a, b, c, d]여야 하며, 각 값은 -1000에서 1000 사이이고 a·d - b·c는 0에서 0.001 이상 떨어져야 합니다
@msg `path` must be a folder `path`은(는) 폴더여야 합니다
@msg `path` must be a path object `path`은(는) 패스 개체여야 합니다
@msg `picks` must be an array (got {v}) `picks`은(는) 배열이어야 합니다({v} 입력됨)
Can't render this file because it is too large.
+3
View File
@@ -166,6 +166,7 @@ liquify-list-end {0}, {1} {0} en {1}
@msg `name` must be the name of a script engine `name` moet de naam van een scriptengine zijn
@msg the main script engine is new for each run and is never kept, so it cannot be dropped de hoofdscriptengine is bij elke uitvoering nieuw en wordt nooit bewaard, dus kan hij niet worden verwijderd
@msg there is no script engine named {name} er is geen scriptengine met de naam {name}
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` is alleen voor een uitvoering zonder iemand om te vragen: in de app beantwoordt de persoon elk dialoogvenster
@msg Running a script Er wordt een script uitgevoerd
@msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e}
@msg Plug-ins can't be loaded from {path}: {e} Plug-ins kunnen niet worden geladen uit {path}: {e}
@@ -5747,6 +5748,7 @@ imageTrace Outline Contour
@msg Image Trace failed: {e} Afbeelding traceren is mislukt: {e}
@msg Image Trace finished, but its document was closed Afbeelding traceren is voltooid, maar het document ervan is gesloten
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Afbeelding traceren is voltooid, maar de afbeelding of de instellingen ervan zijn intussen gewijzigd: traceer de afbeelding opnieuw
@msg Image Trace finished, but its document was reverted: trace it again Afbeelding traceren is voltooid, maar het document ervan is teruggezet: traceer de afbeelding opnieuw
@msg Import SVG Filter reads SVG files, not SVGZ SVG-filter importeren leest SVG-bestanden, geen SVGZ
@msg Invalid dimension offset Ongeldige verschuiving van de maatlijn
@msg Invalid point Ongeldig punt
@@ -5921,6 +5923,7 @@ imageTrace Outline Contour
@msg `names` must be an array of style names `names` moet een array van stijlnamen zijn
@msg `new` is a design name, or true `new` is de naam van een ontwerp, of true
@msg `origin` must be [x, y] in points `origin` moet [x, y] in punten zijn
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` moet [a, b, c, d] zijn, elk van -1000 tot 1000, met a·d - b·c minstens 0,001 van 0 af
@msg `path` must be a folder `path` moet een map zijn
@msg `path` must be a path object `path` moet een padobject zijn
@msg `picks` must be an array (got {v}) `picks` moet een array zijn (kreeg {v})
Can't render this file because it is too large.
+3
View File
@@ -7556,6 +7556,7 @@ breakText Glyphs Glify
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` dla tego okna dialogowego {kind} musi mieć jedną z wartości: {_1}
@msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi
@msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik
@msg `answers` must be a list of answers `answers` musi być listą odpowiedzi
@msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu
@msg `artboardsAt` must be [x, y] `artboardsAt` musi mieć postać [x, y]
@@ -7588,6 +7589,7 @@ breakText Glyphs Glify
@msg `name` must be a name that is not empty `name` musi być niepustą nazwą
@msg `name` must not be empty `name` nie może być puste
@msg `origin` must be [x, y] in points `origin` musi mieć postać [x, y] w punktach
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` musi mieć postać [a, b, c, d], każda wartość od -1000 do 1000, a a·d - b·c musi różnić się od 0 o co najmniej 0,001
@msg `picks` must be an array (got {v}) `picks` musi być tablicą (podano {v})
@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` musi zawierać od 1 do {MAX_PICKS} wskazań (podano {_1})
@msg `points` must hold from 2 to 100000 points `points` musi zawierać od 2 do 100000 punktów
@@ -7963,6 +7965,7 @@ breakText Glyphs Glify
@msg Image Trace failed: {e} Obrys obrazu nie powiódł się: {e}
@msg Image Trace finished, but its document was closed Obrys obrazu został ukończony, ale jego dokument został zamknięty
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Obrys obrazu został ukończony, ale obraz lub jego ustawienia zmieniły się w międzyczasie: obrysuj go ponownie
@msg Image Trace finished, but its document was reverted: trace it again Obrys obrazu został ukończony, ale jego dokument został przywrócony: obrysuj go ponownie
@msg Join: a subpath went missing Połącz: brakuje ścieżki podrzędnej
@msg Lock Workspace is not available in VectorCraft Polecenie Zablokuj obszar roboczy nie jest dostępne w programie VectorCraft
@msg Move Panel to New Window is not available: floating panels stay in the main window Polecenie Przenieś panel do nowego okna nie jest dostępne: panele pływające pozostają w oknie głównym
Can't render this file because it is too large.
+3
View File
@@ -7887,6 +7887,7 @@ swatch Yellow Green Verde-amarelado
@msg Image Trace failed: {e} O Rastreamento de Imagem falhou: {e}
@msg Image Trace finished, but its document was closed O Rastreamento de Imagem terminou, mas o documento dele foi fechado
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again O Rastreamento de Imagem terminou, mas a imagem ou as configurações dela mudaram nesse meio-tempo: rastreie-a novamente
@msg Image Trace finished, but its document was reverted: trace it again O Rastreamento de Imagem terminou, mas o documento dele foi revertido: rastreie-a novamente
@msg Import SVG Filter reads SVG files, not SVGZ Importar Filtro SVG lê arquivos SVG, não SVGZ
@msg Invalid dimension offset Deslocamento de cota inválido
@msg Invalid point Ponto inválido
@@ -7934,6 +7935,7 @@ swatch Yellow Green Verde-amarelado
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` para esta caixa de diálogo {kind} deve ser um de: {_1}
@msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas
@msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo
@msg `answers` must be a list of answers `answers` deve ser uma lista de respostas
@msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento
@msg `artboardsAt` must be [x, y] `artboardsAt` deve ser [x, y]
@@ -8060,6 +8062,7 @@ swatch Yellow Green Verde-amarelado
@msg `names` must be an array of style names `names` deve ser uma matriz de nomes de estilos
@msg `new` is a design name, or true `new` é o nome de um projeto, ou true
@msg `origin` must be [x, y] in points `origin` deve ser [x, y] em pontos
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` deve ser [a, b, c, d], cada um de -1000 a 1000, com a·d - b·c a pelo menos 0.001 de 0
@msg `path` must be a folder `path` deve ser uma pasta
@msg `path` must be a path object `path` deve ser um objeto de caminho
@msg `picks` must be an array (got {v}) `picks` deve ser uma matriz (recebido {v})
Can't render this file because it is too large.
+12
View File
@@ -4540,6 +4540,17 @@ liquify-list-end {0}, {1} {0} и {1}
@msg `name` must be the name of a script engine `name` должно быть именем движка скриптов
@msg the main script engine is new for each run and is never kept, so it cannot be dropped основной движок скриптов создаётся заново для каждого запуска и никогда не сохраняется, поэтому его нельзя удалить
@msg there is no script engine named {name} движка скриптов с именем {name} нет
@msg `answers` must be a list of answers `answers` должен быть списком ответов
@msg `answers` has more than {MAX_ANSWERS} answers в `answers` больше {MAX_ANSWERS} ответов
@msg `answers` is larger than 1 MiB `answers` больше 1 МиБ
@msg must be an object with `kind` and `value` должен быть объектом с `kind` и `value`
@msg must have exactly `kind` and `value` должен содержать ровно `kind` и `value`
@msg is an alert's answer, whose `value` must be "ok" является ответом на alert, поэтому его `value` должно быть "ok"
@msg is a confirm's answer, whose `value` must be true or false является ответом на confirm, поэтому его `value` должно быть true или false
@msg is longer than 16 KiB длиннее 16 КиБ
@msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null
@msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно
@msg Running a script Выполняется скрипт
@msg Copied the script report Отчёт о сценарии скопирован
@msg Copied the link info Сведения о связи скопированы
@@ -6186,6 +6197,7 @@ axis Y Axis Ось Y
@msg {what} points outside memory {what} указывает за пределы памяти
@msg `angle` must be a number `angle` должно быть числом
@msg `aspect` must be from 0.01 to 100 `aspect` должно быть от 0.01 до 100
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` должно быть [a, b, c, d], каждое от -1000 до 1000, а a·d - b·c должно отличаться от 0 не менее чем на 0.001
@msg `cap` must be "butt", "round" or "square" `cap` должно быть "butt", "round" или "square"
@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` должно быть "nonzero" или "evenodd"
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` должно быть адресом https:// длиной не более {MAX_HELP_URL} байт
Can't render this file because it is too large.
+14
View File
@@ -4413,6 +4413,18 @@ liquify-list-end {0}, {1} {0} och {1}
@msg `name` must be the name of a script engine `name` måste vara namnet på en skriptmotor
@msg the main script engine is new for each run and is never kept, so it cannot be dropped huvudskriptmotorn är ny för varje körning och sparas aldrig, så den kan inte tas bort
@msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name}
@msg `answers` must be a list of answers `answers` måste vara en lista med svar
@msg `answers` has more than {MAX_ANSWERS} answers `answers` har fler än {MAX_ANSWERS} svar
@msg `answers` is larger than 1 MiB `answers` är större än 1 MiB
@msg `answers[{i}]` {e} `answers[{i}]` {e}
@msg must be an object with `kind` and `value` måste vara ett objekt med `kind` och `value`
@msg must have exactly `kind` and `value` måste ha exakt `kind` och `value`
@msg is an alert's answer, whose `value` must be "ok" är svaret på en alert, vars `value` måste vara "ok"
@msg is a confirm's answer, whose `value` must be true or false är svaret på en confirm, vars `value` måste vara true eller false
@msg is longer than 16 KiB är längre än 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null
@msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta
@msg Running a script Kör ett skript
@msg Copied the script report Kopierade skriptrapporten
@msg Copied the link info Kopierade länkinfo
@@ -6554,6 +6566,7 @@ axis Y Axis Y-axel
@msg needs approval: it asks for {0}, which the user grants when installing it on its own kräver godkännande: det begär {0}, som användaren beviljar när pluginet installeras för sig
@msg `angle` must be a number `angle` måste vara ett tal
@msg `aspect` must be from 0.01 to 100 `aspect` måste vara från 0.01 till 100
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` måste vara [a, b, c, d], vart och ett från -1000 till 1000, med a·d - b·c minst 0.001 från 0
@msg `cap` must be "butt", "round" or "square" `cap` måste vara "butt", "round" eller "square"
@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` måste vara "nonzero" eller "evenodd"
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` måste vara en https://-adress på högst {MAX_HELP_URL} byte
@@ -8225,6 +8238,7 @@ digits Hindi Hindi
@msg Image Trace failed: internal error: its thread stopped (please report this bug) Bildkalkering misslyckades: internt fel: dess tråd stoppades (rapportera gärna felet)
@msg Image Trace finished, but its document was closed Bildkalkeringen är klar, men dess dokument har stängts
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Bildkalkeringen är klar, men bilden eller dess inställningar ändrades under tiden: vektorisera den igen
@msg Image Trace finished, but its document was reverted: trace it again Bildkalkeringen är klar, men dess dokument har återgått till sparad version: vektorisera den igen
@msg imageMap `{m}`: none, client or server imageMap `{m}`: none, client eller server
@msg index out of range index utanför intervallet
@msg instances must be 1..1000 instances måste vara 1..1000
Can't render this file because it is too large.
+119 -3
View File
@@ -2499,6 +2499,26 @@ fn a_repeated_placeholder_matches_the_same_text() {
assert!(c.message("alert: the next answer is for prompt, not confirm").is_none());
}
/// Of two templates that start with text, the one with the longer text before its first
/// placeholder matches first, so a row that wraps a message takes it before a row with more text
/// in all whose placeholder would take part of it; a quoted name may still hold a backtick.
#[test]
fn the_longer_leading_text_matches_first() {
let c = Catalog::parse(concat!(
"@msg\t`{key}` must be true or false\tkey {key}\n",
"@msg\t`answers[{i}]` {e}\tanswer {i} {e}\n",
"@msg\tno brush named `{name}`\tbrush {name}\n",
));
let (form, caps) = c.message("`select` must be true or false").expect("matches");
assert_eq!((form, caps), ("key {key}", vec![("key", "select")]));
let (form, caps) = c.message("`answers[3]` is a confirm's answer, whose `value` must be true or false").expect("matches");
assert_eq!((form, caps), ("answer {i} {e}", vec![("i", "3"), ("e", "is a confirm's answer, whose `value` must be true or false")]));
let (form, caps) = c.message("`a`b` must be true or false").expect("matches");
assert_eq!((form, caps), ("key {key}", vec![("key", "a`b")]));
let (form, caps) = c.message("no brush named `a`b`").expect("matches");
assert_eq!((form, caps), ("brush {name}", vec![("name", "a`b")]));
}
/// A template that starts with text matches a message it wraps before a template that starts
/// with a placeholder, even one with more literal text, so the wrapped reason is translated by
/// its own row.
@@ -3845,6 +3865,96 @@ fn dataset_import_repeated_column_error_is_translated() {
}
}
/// The scan reads the refusals `script.run`'s `param(msg)` gives, and not the arguments of a type's
/// own function of that name.
#[test]
fn message_scan_reads_script_run_param_refusals() {
let code = r#"
fn f(p: &Value) -> Result<()> {
let grays = Grays::param(C, p)?;
let pick = Pick::param(p, C)?;
let _ = cmd::bad(C, "the name is too long");
Err(param("`path` is empty"))
}
"#;
let engine: Vec<_> = ERROR_HELPERS.iter().filter(|(c, _, _)| *c == "engine").map(|&(_, call, before)| (call, before)).collect();
let consts = [("C".to_string(), vec!["view.proofSetup".to_string()])].into();
assert_eq!(source_messages(code, &engine, &consts), ["the name is too long", "`path` is empty"]);
}
/// `script.run`'s refusals of `answers`, the list's own, an answer's at its index and the refusal
/// of `answers` in the app, are translated in every language that translates every message, with
/// the index, the counts and the code names kept. The command's error stays in English.
#[test]
fn script_answers_errors_are_translated() {
use serde_json::{Value, json};
use vectorcraft_engine::{EngineError, Session};
let reasons = [
"must be an object with `kind` and `value`",
"must have exactly `kind` and `value`",
"is an alert's answer, whose `value` must be \"ok\"",
"is a confirm's answer, whose `value` must be true or false",
"is longer than 16 KiB",
"is a prompt's answer, whose `value` must be a string or null",
"must have `kind` alert, confirm or prompt",
];
let in_app = "`answers` is only for a run with nobody to ask: in the app, the person answers each dialog";
let lists = ["`answers` must be a list of answers", "`answers` has more than {MAX_ANSWERS} answers", "`answers` is larger than 1 MiB"];
let scanned = message_literals();
for template in reasons.into_iter().chain(lists).chain(["`answers[{i}]` {e}", in_app]) {
assert!(scanned.contains(template), "{template}");
}
let ok = json!({"kind": "alert", "value": "ok"});
let wrong = [
json!(1),
json!({"kind": "alert"}),
json!({"kind": "alert", "value": "yes"}),
json!({"kind": "confirm", "value": "yes"}),
json!({"kind": "prompt", "value": "x".repeat(16 * 1024 + 1)}),
json!({"kind": "prompt", "value": 1}),
json!({"kind": "beep", "value": 1}),
];
let run = |s: &mut Session, answers: Value| s.execute("script.run", &json!({"source": "1", "answers": answers})).unwrap_err();
let mut s = Session::new();
// Each error, with the English message the command gives and the reason an answer's holds.
let mut errors = vec![];
for (reason, answer) in reasons.into_iter().zip(wrong) {
for at in [3, 9_999] {
let mut list = vec![ok.clone(); at];
list.push(answer.clone());
errors.push((run(&mut s, json!(list)), format!("`answers[{at}]` {reason}"), Some(reason)));
}
}
errors.push((run(&mut s, json!("ok")), lists[0].to_string(), None));
errors.push((run(&mut s, json!(vec![ok.clone(); 10_001])), "`answers` has more than 10000 answers".to_string(), None));
let long = json!({"kind": "prompt", "value": "x".repeat(16 * 1024)});
errors.push((run(&mut s, json!(vec![long; 70])), lists[2].to_string(), None));
s.script_frames = true;
errors.push((run(&mut s, json!([ok])), in_app.to_string(), None));
for (e, want, reason) in &errors {
assert!(matches!(e, EngineError::BadParams { cmd, msg } if cmd == "script.run" && msg == want), "{e}");
let line = e.to_string();
for code in COMPLETE_MESSAGES {
let lang = Lang::from_code(code).expect("registered");
let shown = message(lang, &line);
let inner = message(lang, want);
assert_ne!(inner, *want, "{code}");
assert!(shown.contains(&inner) && !shown.contains("invalid parameters"), "{code}: {shown}");
if let Some(reason) = reason {
let translated = message(lang, reason);
assert_ne!(translated, *reason, "{code}");
assert!(inner.contains(&translated), "{code}: {inner}");
}
let numbers: Vec<&str> = want.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect();
let names = ["`answers", "`kind`", "`value`", "true", "false", "null"];
assert!(numbers.iter().chain(&names).all(|n| !want.contains(n) || shown.contains(n)), "{code}: {shown}");
if want.ends_with("alert, confirm or prompt") {
assert!(["alert", "confirm", "prompt"].iter().all(|k| shown.contains(k)), "{code}: {shown}");
}
}
}
}
/// The errors of a command's parameter schema are translated in every language that translates
/// every message, with the parameter's path and the refused value kept.
#[test]
@@ -4711,14 +4821,15 @@ const MESSAGE_MARKERS: &[&str] = &[".status(", "ui.status = ", "status = ", "Oth
/// message: the engine's `bad(cmd, msg)` (`EngineError::BadParams`), `err(msg)` (`cmd/fileio`)
/// and `error(msg)` (`cmd/dimension.rs`), the script host's `fail(msg)` (`script/files.rs`,
/// `script/dollar.rs`) and `value(msg)`, which gives the messages the script `File` object's own
/// code throws (`script/files.rs`), and `.over(limit)` for a limit a run passes (`script/mod.rs`),
/// the PDF writer's `bad(why)` (`forms.rs`) and `failed(why)` (`encrypt.rs`, `linearize.rs`), the
/// code throws (`script/files.rs`), `.over(limit)` for a limit a run passes (`script/mod.rs`) and
/// `param(msg)` for `script.run`'s parameters (`cmd/scripts.rs`), the PDF writer's `bad(why)` (`forms.rs`) and `failed(why)` (`encrypt.rs`, `linearize.rs`), the
/// plug-in host's `bad(what)` (a parameter's spec and dialog keys), `wrong(what)` (a parameter's
/// value), `out_err(at, msg)` (plug-in output), `in_range(x, lo, hi, at, what)` and
/// `unit(x, at, what)` (a painted effect's numbers) and `.read_packed(packed, what, max)` (the block
/// a plug-in returned), and the script interpreter's methods that throw an error at a script:
/// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`. A helper that
/// starts with `.` is a method of any receiver.
/// starts with `.` is a method of any receiver; any other is a function, not a type's own function
/// of the same name (`Grays::param(C, p)`).
const ERROR_HELPERS: &[(&str, &str, usize)] = &[
("engine", "bad(", 1),
("engine", "err(", 0),
@@ -4726,6 +4837,7 @@ const ERROR_HELPERS: &[(&str, &str, usize)] = &[
("engine", "fail(", 0),
("engine", "value(", 0),
("engine", ".over(", 0),
("engine", "param(", 0),
("pdf", "bad(", 0),
("pdf", "failed(", 0),
("plugins", "bad(", 0),
@@ -4908,6 +5020,10 @@ fn source_messages(code: &str, helpers: &[(&str, usize)], consts: &std::collecti
let in_helpers = helpers.iter().flat_map(|&(call, before)| {
code.match_indices(call)
.filter(|&(at, _)| call.starts_with('.') || !code[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_' || c == '.'))
.filter(|&(at, _)| {
let owner = code[..at].strip_suffix("::").map(|p| p.rsplit(|c: char| !c.is_alphanumeric() && c != '_').next().unwrap_or(""));
!owner.is_some_and(|o| o.starts_with(|c: char| c.is_ascii_uppercase()))
})
// `format!(` given as a helper, and an `error(` helper that is an `#[error(…)]` attribute, take a format string.
.filter_map(move |(at, _)| {
skip_args(&code[at + call.len()..], before).map(|rest| (rest, call == "format!(" || code[..at].ends_with("#[")))
+3
View File
@@ -4276,6 +4276,7 @@ liquify-list-end {0}, {1} {0} ve {1}
@msg `name` must be the name of a script engine `name` bir betik motorunun adı olmalıdır
@msg the main script engine is new for each run and is never kept, so it cannot be dropped ana betik motoru her çalıştırmada yenidir ve hiç saklanmaz, bu yüzden bırakılamaz
@msg there is no script engine named {name} {name} adlı bir betik motoru yok
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` yalnızca sorulacak kimsenin olmadığı bir çalıştırma içindir: uygulamada her iletişim kutusunu kişi yanıtlar
@msg Running a script Betik çalıştırılıyor
@msg Copied the script report Komut dosyası raporu kopyalandı
@msg Copied the link info Bağlantı bilgisi kopyalandı
@@ -6936,6 +6937,7 @@ axis Y Axis Y ekseni
@msg `name` must be a name that is not empty `name` boş olmayan bir ad olmalıdır
@msg `name` must not be empty `name` boş olmamalıdır
@msg `origin` must be [x, y] in points `origin` punto cinsinden [x, y] olmalıdır
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` [a, b, c, d] olmalıdır; her biri -1000 ile 1000 arasında, a·d - b·c ise 0'dan en az 0.001 uzakta olmalıdır
@msg `picks` must be an array (got {v}) `picks` bir dizi olmalıdır (verilen: {v})
@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` 1 ile {MAX_PICKS} arasında seçim içermelidir (verilen: {_1})
@msg `points` must hold from 2 to 100000 points `points` 2 ile 100000 arasında nokta içermelidir
@@ -7304,6 +7306,7 @@ axis Y Axis Y ekseni
@msg Image Trace failed: {e} Görüntü İzleme başarısız oldu: {e}
@msg Image Trace finished, but its document was closed Görüntü İzleme tamamlandı, ancak belgesi kapatılmıştı
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Görüntü İzleme tamamlandı, ancak bu sırada görüntü veya ayarları değişti: yeniden izleyin
@msg Image Trace finished, but its document was reverted: trace it again Görüntü İzleme tamamlandı, ancak belgesi geri döndürüldü: yeniden izleyin
@msg Invalid dimension offset Geçersiz boyut ofseti
@msg Invalid point Geçersiz nokta
@msg Join: a subpath went missing Birleştir: bir alt yol kayboldu
Can't render this file because it is too large.
+3
View File
@@ -7431,6 +7431,7 @@ breakText Glyphs Гліфи
@msg Image Trace failed: {e} Трасування зображення не вдалося: {e}
@msg Image Trace finished, but its document was closed Трасування зображення завершено, але його документ закрито
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again Трасування зображення завершено, але зображення або його параметри тим часом змінилися: виконайте трасування ще раз
@msg Image Trace finished, but its document was reverted: trace it again Трасування зображення завершено, але його документ було повернуто до збереженої версії: виконайте трасування ще раз
@msg Import SVG Filter reads SVG files, not SVGZ Імпорт фільтра SVG читає файли SVG, а не SVGZ
@msg Invalid dimension offset Неприпустиме зміщення розміру
@msg Invalid point Неприпустима точка
@@ -7477,6 +7478,7 @@ breakText Glyphs Гліфи
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` для цього діалогового вікна ({kind}) має бути одним з: {_1}
@msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей
@msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` призначений лише для запуску, у якому немає кого запитати: у застосунку людина сама відповідає на кожне діалогове вікно
@msg `answers` must be a list of answers `answers` має бути списком відповідей
@msg `artboard` must be the index of an artboard of the document `artboard` має бути індексом монтажної області документа
@msg `artboardsAt` must be [x, y] `artboardsAt` має бути [x, y]
@@ -7602,6 +7604,7 @@ breakText Glyphs Гліфи
@msg `names` must be an array of style names `names` має бути масивом імен стилів
@msg `new` is a design name, or true `new` — це назва дизайну або true
@msg `origin` must be [x, y] in points `origin` має бути [x, y] у пунктах
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` має бути [a, b, c, d], кожне від -1000 до 1000, а a·d - b·c має відрізнятися від 0 щонайменше на 0.001
@msg `path` must be a folder `path` має бути папкою
@msg `path` must be a path object `path` має бути об’єктом-контуром
@msg `picks` must be an array (got {v}) `picks` має бути масивом (отримано {v})
Can't render this file because it is too large.
+12
View File
@@ -4977,6 +4977,17 @@ liquify-list-end {0}, {1} {0} và {1}
@msg `name` must be the name of a script engine `name` phải là tên của một bộ máy tập lệnh
@msg the main script engine is new for each run and is never kept, so it cannot be dropped bộ máy tập lệnh chính được tạo mới cho mỗi lần chạy và không bao giờ được giữ lại, nên không thể loại bỏ nó
@msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name}
@msg `answers` must be a list of answers `answers` phải là một danh sách câu trả lời
@msg `answers` has more than {MAX_ANSWERS} answers `answers` có hơn {MAX_ANSWERS} câu trả lời
@msg `answers` is larger than 1 MiB `answers` lớn hơn 1 MiB
@msg must be an object with `kind` and `value` phải là một đối tượng có `kind` và `value`
@msg must have exactly `kind` and `value` phải có đúng `kind` và `value`
@msg is an alert's answer, whose `value` must be "ok" là câu trả lời cho alert, nên `value` phải là "ok"
@msg is a confirm's answer, whose `value` must be true or false là câu trả lời cho confirm, nên `value` phải là true hoặc false
@msg is longer than 16 KiB dài hơn 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null
@msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại
@msg Running a script Đang chạy tập lệnh
@msg Copied the script report Đã sao chép báo cáo script
@msg Copied the link info Đã sao chép thông tin liên kết
@@ -6184,6 +6195,7 @@ axis Y Axis Trục Y
@msg {what} points outside memory {what} trỏ ra ngoài bộ nhớ
@msg `angle` must be a number `angle` phải là một số
@msg `aspect` must be from 0.01 to 100 `aspect` phải từ 0.01 đến 100
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` phải là [a, b, c, d], mỗi số từ -1000 đến 1000, và a·d - b·c phải cách 0 ít nhất 0.001
@msg `cap` must be "butt", "round" or "square" `cap` phải là "butt", "round" hoặc "square"
@msg `fillRule` must be "nonzero" or "evenodd" `fillRule` phải là "nonzero" hoặc "evenodd"
@msg `helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes `helpUrl` phải là một địa chỉ https:// dài tối đa {MAX_HELP_URL} byte
Can't render this file because it contains an unexpected character in line 205 and column 5.
+3
View File
@@ -7537,6 +7537,7 @@ breakText Glyphs 字形
@msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 对话框的 `answer` 必须是以下之一:{_1}
@msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个
@msg `answers` is larger than 1 MiB `answers` 大于 1 MiB
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 仅用于无人可问的运行:在应用中,由用户回答每个对话框
@msg `answers` must be a list of answers `answers` 必须是回答的列表
@msg `artboard` must be the index of an artboard of the document `artboard` 必须是文档中某个画板的索引
@msg `artboardsAt` must be [x, y] `artboardsAt` 必须是 [x, y]
@@ -7569,6 +7570,7 @@ breakText Glyphs 字形
@msg `name` must be a name that is not empty `name` 必须是非空的名称
@msg `name` must not be empty `name` 不能为空
@msg `origin` must be [x, y] in points `origin` 必须是以点为单位的 [x, y]
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` 必须是 [a, b, c, d],每个值在 -1000 到 1000 之间,且 a·d - b·c 与 0 的差至少为 0.001
@msg `picks` must be an array (got {v}) `picks` 必须是数组 (实际为 {v})
@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` 必须包含 1 到 {MAX_PICKS} 个拾取项 (实际为 {_1})
@msg `points` must hold from 2 to 100000 points `points` 必须包含 2 到 100000 个点
@@ -7947,6 +7949,7 @@ breakText Glyphs 字形
@msg Image Trace failed: {e} 图像描摹失败:{e}
@msg Image Trace finished, but its document was closed 图像描摹已完成,但其文档已关闭
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 图像描摹已完成,但图像或其设置在此期间发生了更改:请重新描摹
@msg Image Trace finished, but its document was reverted: trace it again 图像描摹已完成,但其文档已恢复:请重新描摹
@msg Invalid dimension offset 尺寸标注的偏移无效
@msg Invalid point 点无效
@msg Join: a subpath went missing 连接:有一条子路径丢失
Can't render this file because it is too large.
+3
View File
@@ -2647,6 +2647,7 @@ liquify-list-end {0}, {1} {0}和{1}
@msg `name` must be the name of a script engine `name` 必須是指令碼引擎的名稱
@msg the main script engine is new for each run and is never kept, so it cannot be dropped 主指令碼引擎在每次執行時都是新的,從不保留,因此無法捨棄
@msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 僅適用於沒有人可詢問的執行:在應用程式中,由使用者回答每個對話框
@msg Running a script 正在執行指令碼
@msg Copied the script report 已複製指令碼報告
@msg Copied the link info 已複製連結資訊
@@ -7497,6 +7498,7 @@ breakText Glyphs 字符
@msg `name` must be a name that is not empty `name` 必須是不為空的名稱
@msg `name` must not be empty `name` 不能為空
@msg `origin` must be [x, y] in points `origin` 必須是以點為單位的 [x, y]
@msg `axes` must be [a, b, c, d], each from -1000 to 1000, with a·d - b·c at least 0.001 from 0 `axes` 必須是 [a, b, c, d],每個值介於 -1000 到 1000 之間,且 a·d - b·c 與 0 的差至少為 0.001
@msg `picks` must be an array (got {v}) `picks` 必須是陣列 (收到 {v})
@msg `picks` must hold 1 to {MAX_PICKS} picks (got {_1}) `picks` 必須包含 1 到 {MAX_PICKS} 個選擇 (收到 {_1})
@msg `points` must hold from 2 to 100000 points `points` 必須包含 2 到 100000 個點
@@ -7875,6 +7877,7 @@ breakText Glyphs 字符
@msg Image Trace failed: {e} 影像描圖失敗:{e}
@msg Image Trace finished, but its document was closed 影像描圖已完成,但其文件已關閉
@msg Image Trace finished, but the image or its settings changed meanwhile: trace it again 影像描圖已完成,但影像或其設定在此期間已變更:請重新描圖
@msg Image Trace finished, but its document was reverted: trace it again 影像描圖已完成,但其文件已回復:請重新描圖
@msg Invalid dimension offset 尺寸標註位移無效
@msg Invalid point 點無效
@msg Join: a subpath went missing 連接:有一條子路徑不見了
Can't render this file because it is too large.
+1 -1
View File
@@ -1616,7 +1616,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
crate::panels::actions::LOAD_SET,
"Load Actions…",
"",
"{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file; the other steps, every step with no label and every step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"",
"{path? | data?: the file's text} read an action set file (.vcactions) at path, else a picked one, and add its set after the Actions panel's sets; a set named like one in the panel gets the next free number (Print 2), and the other sets stay. Files of another version, over 8 MiB, with more than 1,000 actions or with an action of more than 10,000 steps are refused, and so is any set, .aia ones too, that Save Actions… would write larger than 8 MiB (a file with less white space, or a name that gets a number); the panel menu's Load Actions… (disabled where there is no open dialog, the web) → {set: index, name, actions: n}. An action set another app saved as text (.aia, starting /version; read with actionSet.read) comes in with its actions. A step with a label and no recorded values comes in when exactly one menu command has that label (in English or the interface language, any case, no final …), and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with no values and opens no dialog (never a submenu's item, a file or document command, Paste, Undo, Redo or an add-on's command), with no params and excluded from playback when it is off in the file. A Set Selection step (found by its internal name, whatever its label) comes in as select.byNote {note, caseSensitive, wholeWord} when it has exactly three recorded values: text (ustring, UTF-8; 1 to 1,024 bytes once trimmed), word and case (boolean, 0 or 1); with any other values it is left out. The other steps, every other step with no label and every other step recorded with values (a recorded menu item too) among them, are left out → {set, name, actions, skipped: [{action, step: its label, else its name}] (the first 1,000), leftOut: n}, and the status bar says how many were left out; a set with no name takes the file's name, else Actions; a file actionSet.read marks truncated is refused, and text that starts /version and isn't an action set gives \"not an action set file\"",
),
(
crate::panels::actions::DELETE_SETS,
+119
View File
@@ -4237,6 +4237,125 @@ mod tests {
assert_eq!(r["skipped"], json!([{"action": "A", "step": "group"}, {"action": "A", "step": "Ungroup"}]));
assert_eq!(r["leftOut"], 2);
}
/// A Set Selection step written from scratch, as `/event-N` text: its label (none when empty),
/// whether it is on, and its recorded values, each the text inside a `/parameter-N` block.
fn set_selection_event(n: usize, label: &str, on: bool, values: &[String]) -> String {
let hex = |t: &[u8]| format!("[ {} {} ]", t.len(), t.iter().map(|b| format!("{b:02x}")).collect::<String>());
let label = if label.is_empty() { String::new() } else { format!("/localizedName {} ", hex(label.as_bytes())) };
let params: String = values.iter().enumerate().map(|(i, v)| format!("/parameter-{} {{ {v} }} ", i + 1)).collect();
format!(
"/event-{n} {{ /useRulersIn1stQuadrant 0 /internalName (adobe_setSelection) {label}/isOn {} /isOff 0 /parameterCount {} {params}}} ",
u8::from(on),
values.len()
)
}
/// The recorded values of a Set Selection step: the note's bytes, then Whole Word and Case
/// Sensitive.
fn set_selection_values(note: &[u8], whole_word: u8, case_sensitive: u8) -> Vec<String> {
let hex = |t: &[u8]| format!("[ {} {} ]", t.len(), t.iter().map(|b| format!("{b:02x}")).collect::<String>());
vec![
format!("/key 1952807028 /showInPalette 4294967295 /type (ustring) /value {}", hex(note)),
format!("/key 2003792484 /showInPalette 4294967295 /type (boolean) /value {whole_word}"),
format!("/key 1667330917 /showInPalette 4294967295 /type (boolean) /value {case_sensitive}"),
]
}
/// Load Actions… reads an `.aia` Set Selection step, found by its internal name whatever its
/// label, as a Select Object step with its note (trimmed), Case Sensitive and Whole Word, in any
/// order; a step that is off stays excluded. The set saves to VectorCraft's own file and loads
/// back the same, and playing it selects the objects with that note.
#[test]
fn load_actions_reads_set_selection_steps_as_select_object() {
let mut reordered = set_selection_values("Größe ✓".as_bytes(), 1, 0);
reordered.reverse();
let events = [
set_selection_event(1, "Set Selection", true, &set_selection_values(b" Badge front ", 0, 1)),
set_selection_event(2, "Auswahl festlegen", true, &reordered),
set_selection_event(3, "", false, &set_selection_values(b"Off", 1, 1)),
]
.concat();
let text = format!("/version 3 /name [ 5 4e6f746573 ] /actionCount 1 /action-1 {{ /name [ 1 41 ] /eventCount 3 {events}}}");
let mut app = app_with_sets();
let r = app.run(LOAD_SET, json!({ "data": text })).unwrap();
assert_eq!((r["leftOut"].clone(), r["skipped"].clone()), (json!(0), json!([])));
let step = |note: &str, case_sensitive: bool, whole_word: bool| {
(SELECT_OBJECT_STEP.to_string(), json!({"note": note, "caseSensitive": case_sensitive, "wholeWord": whole_word}))
};
let expected = [step("Badge front", true, false), step("Größe ✓", false, true), step("Off", true, true)];
assert_eq!(app.ui.action_sets[3].actions[0].steps, expected);
assert_eq!(app.ui.action_sets[3].actions[0].excluded_steps, [2].into());
let saved = files::write_set(&app.ui.action_sets[3]);
assert!(saved.contains("\"version\": 4"), "{saved}");
app.run(LOAD_SET, json!({ "data": saved })).unwrap();
assert_eq!(app.ui.action_sets[4].actions[0].steps, expected);
assert_eq!(app.ui.action_sets[4].actions[0].excluded_steps, [2].into());
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let mut ids = vec![];
for x in [0, 50] {
ids.push(app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap());
}
app.run("attributes.set", json!({"ids": [ids[1]], "note": "Badge front"})).unwrap();
app.run("select.all", json!({})).unwrap();
app.ui.action_sets[3].actions[0].excluded_steps = [1, 2].into();
play(&mut app, 3, 0).unwrap();
let selected: Vec<u64> = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect();
assert_eq!(selected, [ids[1]], "the step selected the object with the note");
}
/// A Set Selection step whose recorded values are not exactly the note (UTF-8 text, not empty
/// once trimmed, at most 1,024 bytes) and the two options (each 0 or 1), with the right types and
/// no other value, is left out, listed by its label (else its internal name) and counted; no step
/// comes in with a missing option filled in. A value whose byte count is wrong refuses the file.
#[test]
fn set_selection_steps_with_bad_values_are_left_out() {
let good = || set_selection_values(b"Badge", 0, 0);
let with = |i: usize, value: &str| {
let mut v = good();
v[i] = value.to_string();
v
};
let mut extra = good();
extra.push("/key 1 /type (boolean) /value 0".into());
let mut duplicate = good();
duplicate[0] = good()[2].clone();
let bad: Vec<Vec<String>> = vec![
good()[1..].to_vec(),
vec![good()[0].clone(), good()[1].clone()],
extra,
duplicate,
with(0, "/key 1952807028 /type (ustring) /value [ 2 c328 ]"),
with(0, "/key 1952807028 /type (ustring) /value [ 3 202020 ]"),
with(0, &format!("/key 1952807028 /type (ustring) /value [ 1025 {} ]", "61".repeat(1025))),
with(0, "/key 1952807028 /type (text) /value [ 5 4261646765 ]"),
with(0, "/key 1952807028 /type (ustring) /value 5"),
with(1, "/key 2003792484 /type (boolean) /value 2"),
with(1, "/key 2003792484 /type (integer) /value 1"),
with(2, "/key 1667330917 /type (boolean) /value 1.0"),
with(2, "/key 1667330917 /type (boolean)"),
with(2, "/key 1 /type (boolean) /value 1"),
];
let events: String = bad.iter().enumerate().map(|(i, values)| set_selection_event(i + 1, "Set Selection", true, values)).collect();
let events = events + &set_selection_event(bad.len() + 1, "", true, &[]);
let text = format!("/version 3 /name [ 3 426164 ] /action-1 {{ /name [ 1 41 ] {events}}}");
let mut app = app_with_sets();
let r = app.run(LOAD_SET, json!({ "data": text })).unwrap();
assert!(app.ui.action_sets[3].actions[0].steps.is_empty(), "{:?}", app.ui.action_sets[3].actions[0].steps);
assert_eq!(r["leftOut"], bad.len() + 1);
let names: Vec<&str> = r["skipped"].as_array().unwrap().iter().map(|s| s["step"].as_str().unwrap()).collect();
let mut expected = vec!["Set Selection"; bad.len()];
expected.push("adobe_setSelection");
assert_eq!(names, expected);
assert_eq!(app.ui.status, format!("Loaded “Bad”: {} steps were left out", bad.len() + 1));
let wrong_count = set_selection_event(1, "Set Selection", true, &with(0, "/key 1952807028 /type (ustring) /value [ 6 4261646765 ]"));
let text = format!("/version 3 /action-1 {{ {wrong_count}}}");
assert_eq!(app.run(LOAD_SET, json!({ "data": text })).unwrap_err(), "the action set file can't be read in full");
assert_eq!(app.ui.action_sets.len(), 4, "no set added");
}
/// Load Actions… picks action set files of both kinds, and a set another app saved without a
/// name takes the file's name, or `Actions` when there is no file; one named like a set in the
/// panel gets the next free number. A file that isn't UTF-8 still reads. A set past the reader's
+52 -6
View File
@@ -15,7 +15,7 @@
//! version 6 so older builds refuse them rather than fail at that step. Other sets use version 1, and
//! earlier version 1 to 5 files still work.
//! Load Actions… also reads the action sets another app saves as text (`.aia`, through
//! `actionSet.read`).
//! `actionSet.read`), a Set Selection step as a Select Object step.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -398,6 +398,45 @@ fn step_commands() -> std::collections::HashMap<String, Option<&'static str>> {
by_label
}
/// The `/internalName` of a step of another app's action set that selects objects by their note: the
/// Set Selection step.
const SET_SELECTION: &str = "adobe_setSelection"; // brand-ok: the step's internal name in the file format
/// The `/key` of a Set Selection step's note (`text`), of its Whole Word option (`word`) and of its
/// Case Sensitive option (`case`): four characters read as a big-endian number.
const NOTE_KEY: i64 = 0x7465_7874;
const WHOLE_WORD_KEY: i64 = 0x776f_7264;
const CASE_SENSITIVE_KEY: i64 = 0x6361_7365;
/// The Select Object step ([`super::SELECT_OBJECT_STEP`]) a Set Selection step of `actionSet.read`'s
/// answer stands for. The step must have exactly three recorded values, all kept: the note, of type
/// `ustring` and UTF-8, and Whole Word and Case Sensitive, each of type `boolean` and 0 or 1. The note
/// is as [`super::select_object_params`] takes it (trimmed, not empty, at most 1,024 bytes). Anything
/// else stands for nothing.
fn select_object_step(step: &Value) -> Option<(String, Value)> {
let values = step.get("values").and_then(Value::as_array)?;
if values.len() != 3 || step.get("params").and_then(Value::as_u64) != Some(3) {
return None;
}
let value = |key: i64, kind: &str| {
let mut found = values.iter().filter(|v| v.get("key").and_then(Value::as_i64) == Some(key));
let v = found.next().filter(|v| v.get("type").and_then(Value::as_str) == Some(kind))?;
if found.next().is_some() {
return None;
}
v.get("value")
};
let flag = |key: i64| match value(key, "boolean")?.as_i64()? {
0 => Some(false),
1 => Some(true),
_ => None,
};
let note = value(NOTE_KEY, "ustring")?.as_str()?;
let params = json!({"note": note, "caseSensitive": flag(CASE_SENSITIVE_KEY)?, "wholeWord": flag(WHOLE_WORD_KEY)?});
let (note, case_sensitive, whole_word) = super::select_object_params(&params).ok()?;
Some((super::SELECT_OBJECT_STEP.to_string(), json!({"note": note, "caseSensitive": case_sensitive, "wholeWord": whole_word})))
}
/// The command a step of another app's action set stands for ([`step_commands`]).
#[cfg(test)]
pub(super) fn step_command(label: &str) -> Option<&'static str> {
@@ -414,8 +453,9 @@ struct AiaLoad {
}
/// The set of `read`, `actionSet.read`'s answer, named `name` when the file gives none. A step comes
/// in as the command it stands for ([`step_name`], [`step_commands`]), with no params, and excluded
/// from playback when it is off in the file. An action with no name is called `Action N`.
/// in as the command it stands for ([`step_name`], [`step_commands`]), with no params, or a Set
/// Selection step as a Select Object step ([`select_object_step`]), and excluded from playback when
/// it is off in the file. An action with no name is called `Action N`.
fn aia_set(read: &Value, name: &str) -> AiaLoad {
let (mut skipped, mut left_out) = (vec![], 0usize);
let commands = step_commands();
@@ -432,7 +472,12 @@ fn aia_set(read: &Value, name: &str) -> AiaLoad {
let (mut steps, mut excluded_steps) = (vec![], std::collections::BTreeSet::new());
for s in a.get("steps").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default() {
let (name, can_stand) = step_name(s);
let Some(id) = commands.get(&bare_label(&name)).copied().flatten().filter(|_| can_stand) else {
let step = if s.get("name").and_then(Value::as_str) == Some(SET_SELECTION) {
select_object_step(s)
} else {
commands.get(&bare_label(&name)).copied().flatten().filter(|_| can_stand).map(|id| (id.to_string(), json!({})))
};
let Some(step) = step else {
left_out += 1;
if skipped.len() < MAX_SKIPPED {
skipped.push(json!({ "action": action, "step": name }));
@@ -442,7 +487,7 @@ fn aia_set(read: &Value, name: &str) -> AiaLoad {
if s.get("on").and_then(Value::as_bool) == Some(false) {
excluded_steps.insert(steps.len());
}
steps.push((id.to_string(), json!({})));
steps.push(step);
}
Action { excluded_steps, ..Action::new(action, steps) }
})
@@ -496,7 +541,8 @@ fn load_aia(app: &mut VectorcraftApp, params: Value) -> Result<Value, String> {
///
/// An action set another app saved as text (`.aia`, read with `actionSet.read`) comes in with its
/// actions and the steps that stand for a VectorCraft command ([`step_name`], [`step_commands`]),
/// with no params; a step that is off in the file is excluded from playback. A set with no name is
/// with no params, and its Set Selection steps as Select Object steps ([`select_object_step`]); a
/// step that is off in the file is excluded from playback. A set with no name is
/// called after the file, else `Actions`. The other steps are left out and listed, and the status
/// bar says how many → `{set, name, actions, skipped: [{action, step}] (at most 1,000), leftOut: n}`.
/// Such a file that `actionSet.read` marks `truncated` is refused, and so is one whose set Save
+1 -1
View File
@@ -315,7 +315,7 @@ fn point_type_offers_dynamic_text() {
/// The path's anchors (its first subpath).
fn anchors(app: &VectorcraftApp, id: u64) -> Vec<vectorcraft_geom::Anchor> {
match kind(app, id) {
NodeKind::Path { path, .. } => path.subpaths[0].anchors.clone(),
NodeKind::Path { path, .. } => path.subpaths[0].anchors.to_vec(),
k => panic!("not a path: {k:?}"),
}
}
+17
View File
@@ -162,6 +162,23 @@ fn a_trace_needs_its_image_as_it_was() {
assert!(app.ui.status.contains("changed meanwhile: trace it again"), "{}", app.ui.status);
}
/// A trace started before File › Revert doesn't apply after it, even when the document was
/// reverted to the same image: nothing changes, and the status bar says why.
#[test]
fn a_trace_started_before_a_revert_does_not_apply() {
let mut app = app();
let i = app.session.active_index().unwrap();
let copy = (*app.session.doc().unwrap().doc).clone();
let [img] = app.session.doc().unwrap().selection.objects[..] else { panic!("the image is selected") };
crate::menus::invoke(&mut app, "imageTrace.make", json!({"preset": "Default"}));
assert!(app.session.replace_document(i, copy));
wait(&mut app);
assert_eq!(undos(&app), 0, "nothing changes");
let st = app.session.doc().unwrap();
assert!(matches!(st.doc.node(img).unwrap().kind, vectorcraft_doc::NodeKind::Image(_)), "the image is not traced");
assert_eq!(app.ui.status, "Image Trace finished, but its document was reverted: trace it again");
}
/// The progress window opens after its delay with Cancel and Continue in Background; Continue in
/// Background closes it and the trace goes on.
#[test]
+8 -3
View File
@@ -8,7 +8,8 @@
//!
//! When it is done, what it traced is handed to its command with the same parameters
//! ([`Traced::hand_in`]), so the edit is one undo step like any trace, unless the image or the
//! settings changed meanwhile: then nothing changes and the status bar says to trace it again. The
//! settings changed meanwhile or File › Revert replaced the document's content: then nothing
//! changes and the status bar says to trace it again. The
//! control channel, MCP and scripts run the commands at once, and so does every trace on the web,
//! in unit tests that don't set `off_the_ui_thread`, and with `VECTORCRAFT_SYNC_OPEN` set
//! ([`available`]).
@@ -158,8 +159,8 @@ pub fn poll(app: &mut VectorcraftApp) {
}
/// Applies trace `r`'s result in its document, which becomes the active one again, as its command
/// would while the object, its image and the settings are as they were; else why it has none, in
/// the status bar.
/// would while the object, its image and the settings are as they were and the document was not
/// reverted; else why it has none, in the status bar.
fn finish(app: &mut VectorcraftApp, r: Running, done: Option<Done>) {
// Cancel changes nothing, even when the trace ended just before it.
if r.token.is_cancelled() {
@@ -184,6 +185,10 @@ fn finish(app: &mut VectorcraftApp, r: Running, done: Option<Done>) {
return;
};
app.session.set_active(i);
if run.reverted(&app.session) {
app.status("Image Trace finished, but its document was reverted: trace it again");
return;
}
if !run.current(&app.session) {
app.status("Image Trace finished, but the image or its settings changed meanwhile: trace it again");
return;
+1 -1
View File
@@ -27,7 +27,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md](
| Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own |
| Rasterize | Rasterize… (as a live effect) | 1/1 | — |
| Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets |
| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `<filter>` element; otherwise SVG export draws the object as an image. A filter on a turned or skewed object in an imported SVG is left out with a warning |
| SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `<filter>` element; otherwise SVG export draws the object as an image. A filter on a turned, skewed or unevenly scaled object in an imported SVG is kept and runs in that object's user space, and SVG export writes it back under the same transform |
| Warp | Arc, Arc Lower, Arc Upper, Arch, Bulge, Shell Lower, Shell Upper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist | 15/15 | warp point editing in envelopes; each style bends the bounds as one Bézier patch (`version` 1), so Arc's edges are cubic curves close to concentric arcs; warps saved without a version keep the earlier map, where Arc is a circular arc in the object's own proportions (#1578) |
Document Raster Effects Settings exists. When the 64 million pixel cap on an effect image lowers
+54 -18
View File
@@ -964,7 +964,8 @@ them in the Swatches panel does); give colour group names instead to reorder the
in the app runs `paint.setFill` (or `paint.setStroke`, the active proxy) with `ids: [the object under the pointer]`.
The Swatches panel menu's commands: `swatch.addUsedColors {selection?, global?}`, `swatch.unused` (a query: the
names Select All Unused selects; a spot swatch counts as used while an image placed from a DCS file has a plate of
its ink), `swatch.merge {names}` (the first is kept), `swatch.ungroup {name}` and
its ink), `swatch.merge {names}` (the first is kept; gradient stops linked to the others drop their process
plates), `swatch.ungroup {name}` and
`swatch.sortByKind`.
`brush.move {name | names, to?, type?}` reorders brushes among the brushes of their type, as dragging one onto
another of its type in the Brushes panel does. `to` is an index among the brushes of that type in `brush.list`
@@ -2860,7 +2861,10 @@ group selected on its own, or, for `symbolInstance`, an object that is not a sym
leaves the selection empty. A selected object that is hidden or locked, inside a hidden or locked group or layer, on a
template layer, on a locked artboard while nothing is isolated, or outside the isolated group is passed over. New art,
such as a symbol instance just placed, is not passed over for being on a locked artboard while it stays selected. When
the selection holds no other object, they return the error "nothing selected".
the selection holds no other object, they return the error "nothing selected". `appearanceAttribute {item?}` takes
the fill or stroke at appearance item `item`, or the Appearance panel's active item when the call gives none or null; a
value that is not a whole number of 0 or more fails with "`item` must be a whole number" and leaves the selection as it
was.
`select.similar {by?}` is the Control bar's Select Similar Objects button and the Select Similar Options menu beside it
([help](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=165)). It selects the
@@ -3200,7 +3204,9 @@ number. `guide.add {vertical, pos, artboard?}` makes one (the x of a
vertical guide, the y of a horizontal one, in points) → `{index}`. With `artboard` (an artboard's index) it is an
artboard guide: it runs across that artboard only, moves with it (`artboard.move`, a pure move in
`artboard.setProps`, `artboard.rearrange`), scales with it (`artboard.setProps {scaleArt}`), is copied with it (`artboard.duplicate`, `artboard.move {copy}`) and is
deleted with it (`artboard.delete`); without, a canvas guide runs across the whole canvas. `guide.list` →
deleted with it (`artboard.delete`); without, or with null, a canvas guide runs across the whole canvas. An `artboard`
that is not a whole number of 0 or more fails with "`artboard` must be a whole number", and an index past the last
artboard with `no such artboard`; neither adds a guide. `guide.list` →
`[{index, id, vertical, pos, selected, artboard?, layer?, hidden, locked, shown, editable}…]` (`artboard` only for
artboard guides; `id` is the guide's node and `layer` the layer it is on; `hidden` and `locked` are its own state,
`shown` and `editable` also take its layer into account). `layer.setProps {ids: [id…], visible?, locked?}` hides or
@@ -5565,17 +5571,30 @@ SVG Filter (New, Edit, Delete, Import…), and from the Appearance panel it edit
The canvas, raster export, printing and PDF draw the filter with the object as its source graphic, its user space
starting at `origin` (`[x, y]` in points, `[0, 0]` by default) with its units `scale` points (1 by default), its
object bounding box the drawn object's, and at the Document Raster Effects resolution when the view is finer. The
axes along `axes` (`[a, b, c, d]`: one unit along the filter's x axis points `[a, b]` in the document and one along
its y axis `[c, d]`, before `scale`; absent or `[1, 0, 0, 1]`, the document's axes, and `effect.setParams` sets them
back with `[1, 0, 0, 1]`, since the commands refuse `null`; each number -1000 to 1000 and `a·d - b·c` at least
0.001 from 0, or the command refuses it), its object bounding box the drawn object's, and at the Document Raster Effects resolution when the view is finer. The
filter runs on coarser pixels when a morphology radius or kernel unit would span more than 32 of them, or a standard
deviation more than 512. An effect whose XML these rules refuse (from a file or a script) is not drawn or exported. The
deviation more than 512. With `axes`, the filter runs on pixels lined up with its own axes, so offsets, blurs and the
region run along them, and the result is drawn onto the object's pixels through `axes`; those pixels are about as fine
along each axis as the object's and coarser when there would be more than 4 times as many, or when a radius, kernel
unit or standard deviation would span more than 32 or 512 of them. The object's box is then
its box in that user space: a region measured against it, and a region or primitive lengths in `objectBoundingBox`
units, are measured against that box. Moving, turning, scaling or skewing the object moves `origin` with it and
leaves `axes` as they are, and `scale` too unless Scale Strokes & Effects scales it. An effect whose XML or `axes` these rules refuse (from a file or a script) is not drawn or exported. The
filter is drawn and written rebuilt from its filter elements and their filter attributes alone, without comments,
text, descriptions or other attributes. An image in a filter is drawn only when its bytes are a PNG, JPEG, GIF or WebP
within the pixel limit. A filter region in user space given in percentages is measured against the object's box (x
and y from its top-left corner), and one in em or ex or left out takes the default region of that box (10% beyond
each side); these are VectorCraft's own rules. Scale Strokes & Effects scales
`scale`. SVG export writes the filter as a `<filter>` element when it is the object's last effect, its only pixel
effect and `scale` is 1 (with a region measured against the object's box, its only raster effect), with the object in a
group that places the filter's user space and such a region written in user units. The filter is written in SVG 1.1
`scale`. SVG export writes the filter as a `<filter>` element when it is the object's last effect and its only pixel
effect (with a region measured against the object's box, its only raster effect) and SVG import can store its user
space again (`scale` and `axes` together within the import limits below), with the object in a
group that places the filter's user space and such a region written in user units. When `scale` isn't 1 or the effect
has `axes`, that group's transform is the filter's user space and the object is written in document coordinates in a
group inside the filter whose transform is the inverse, so its strokes keep their widths; SVG import reads that back
as the same `scale`, `origin` and `axes`. The filter is written in SVG 1.1
terms: `feImage`'s reference as `xlink:href`; each `feDropShadow` as the blur, offset, flood, composite and merge that
[Filter Effects](https://www.w3.org/TR/filter-effects-1/#feDropShadowElement) gives as its equivalent; colors as
`#rrggbb` with a flood color's alpha in `flood-opacity`; `image-rendering` as `optimizeSpeed` or `optimizeQuality`;
@@ -5587,9 +5606,12 @@ whose `flood-color` is `currentColor` or with `primitiveUnits="objectBoundingBox
its shadows are expanded, has no SVG 1.1 form. Neither does a filter whose written form, with its region and id, is
one SVG import would not read, such as one longer than 64 KB. In that case, otherwise, and with the SVG Tiny 1.2 profile, the object
becomes an image. SVG import keeps a filter that the live effects (Drop Shadow, the
glows, Gaussian Blur, Feather) can't express as an `svg.filter` effect holding the filter's XML, with `scale` and
`origin` from the object's user space, unless that user space is turned, skewed or scaled past 0.001 to 1000 points
to a unit, or the filter is styled by the document's style sheets: such a filter is left out with a warning. The native format keeps the document's filters and the effects.
glows, Gaussian Blur, Feather) can't express as an `svg.filter` effect holding the filter's XML, with `scale`,
`origin` and, when the object's user space is turned, skewed or scaled unevenly (a `rotate`, `skewX`, `skewY`, uneven
`scale` or `matrix` transform), `axes` from that user space, so the filter runs in the element's user space as
[SVG 1.1](https://www.w3.org/TR/SVG11/filters.html#FilterEffectsRegion) defines it. A filter is left out with a
warning when that user space is scaled past 0.001 to 1000 points to a unit (the square root of its area scale), its
`axes` would pass the limits above, or the filter is styled by the document's style sheets. The native format keeps the document's filters and the effects.
```json
{"name":"run_command","arguments":{"command":"svgFilter.define","params":{"xml":"<filter id=\"Soft\"><feGaussianBlur stdDeviation=\"2\"/></filter>"}}}
@@ -6118,8 +6140,12 @@ below 3 or above 1000 counts as 3 or 1000, and a fractional or negative `sides`
Without `artboard`, or with an index the document doesn't have, it aligns them to the artboard under the center of the
selection, or to the first artboard when no artboard is under the center. With `to: "selection"` or `"key"`,
`object.align` does not use `artboard`. `select.allOnArtboard {artboard?}` (Select › All on Active Artboard) selects
the objects on artboard `artboard`, or on the first artboard when the call gives none; an index the document doesn't
have is an error.
the objects on artboard `artboard`, or on the first artboard when the call gives none or null. A value that is not a
whole number of 0 or more fails with "`artboard` must be a whole number", and an index the document doesn't have with
`no such artboard`; either leaves the selection as it was. `select.font {family, style?, scope?}` (Select Text
by Font) takes `scope: {artboards: [index…]}` the same way: an entry that is not a whole number fails with
"`scope.artboards` must contain whole numbers" before any entry is looked up, and an index the document doesn't have
fails with `no such artboard`.
`object.distribute {to: "artboard", artboard?}` and `object.distributeSpacing {to: "artboard", artboard?}` (the
Distribute Objects and Distribute Spacing buttons with Align to Artboard) use the same artboard as `object.align`.
@@ -11455,7 +11481,11 @@ that starts with `/version`) without changing anything. Give exactly one of `pat
the set's name (`set`, else the file's name, else empty), its `version`, and its `actions`, each with its `name` and
`steps`. A step lists its `name` (the file's `/internalName`), its `label` (the `/localizedName` it is shown with, or
null when it has none or it is blank), `on` (false when the file sets `/isOn 0`), `params` (how many recorded values it
has) and its `line`. `unread` lists the tokens the reader skipped, with their lines. The reader stops at 8 MiB, 16 open
has), `values` and its `line`. `values` lists the step's recorded values in order, each as `{key, type, value, bytes?}`:
the block's `/key` and `/type` (null when it has none), and its `/value` when that is a whole number, or text in
parentheses or hexadecimal text that is UTF-8, with `bytes` giving the text's length in bytes; any other value, and text
that is not UTF-8, is null. Only the first 100,000 recorded values in the set are listed, so a step's `values` can be
shorter than its `params`. `unread` lists the tokens the reader skipped, with their lines. The reader stops at 8 MiB, 16 open
blocks, 1,000 actions, 10,000 steps in an action and 100,000 steps in the set, and cuts names at 1,024 bytes. It sets
`truncated` when it reaches one of these limits, when the text ends inside a block or a value or after a field's name,
when `/actionCount`, `/eventCount` or a step's `/parameterCount` differs from the actions, steps or recorded values read
@@ -11470,8 +11500,12 @@ label, in English or in the interface language, in any case and without a final
that label and that command is directly in a top menu, can be recorded in actions, is what its menu bar item runs with
no values and opens no dialog (Group, Ungroup). A submenu's items, file and document commands, Paste, Undo, Redo and
add-on commands are never matched. The step runs with no params, and a step that is off in the file is excluded from
playback. Other steps are left out, including every step with no label and every step recorded with values (recorded
menu items too). The reply lists the first 1,000 in `skipped` (`{action, step}`, the step by its label, else its name),
playback. A Set Selection step, found by its `/internalName` whatever its label, comes in as a Select Object step
(`select.byNote` with `{note, caseSensitive, wholeWord}`) when it has exactly three recorded values: the note (key
`text`, 1952807028, of type `ustring`, UTF-8), Whole Word (key `word`, 2003792484) and Case Sensitive (key `case`,
1667330917), each of type `boolean` and 0 or 1. The note loses its leading and trailing spaces and must then be 1 to
1,024 bytes long. A Set Selection step with any other values is left out; no option is filled in. Other steps are left
out, including every other step with no label and every other step recorded with values (recorded menu items too). The reply lists the first 1,000 in `skipped` (`{action, step}`, the step by its label, else its name),
`leftOut` counts them, and the status bar says how many were left out. An action with no name is called `Action N`, by
its place in the file. Function keys and colors are not read. A file marked `truncated` is refused, and no set is added.
Text that starts `/version` and is not an action set gives "not an action set file". Tokens in `unread` do not stop a
@@ -12153,8 +12187,10 @@ overlapping the artboard or the centre on it), `inside` (the bounds wholly withi
straddling two touching artboards is inside neither) or `outside` (on none of them). It looks at the objects Select All
takes, or the isolated container's in isolation mode, so hidden and locked objects, objects on hidden, locked or template
layers and art held by a locked artboard are left out. Bounds are geometric, a symbol instance's measured by its art. It
returns the `count` selected. An empty list, an index with no artboard, a value that isn't an index, or another
relation is an error, and the selection is left as it was.
returns the `count` selected. An empty list, an index with no artboard (`no such artboard`), a value that isn't a list
("`artboards` must be a list of artboard indices"), an entry that isn't a whole number of 0 or more ("`artboards` must
contain whole numbers", checked before any entry is looked up), or another relation is an error, and the selection is
left as it was.
```json
{"name":"run_command","arguments":{"command":"addon.select.byArtboards","params":{"artboards":[2,6,11],"relation":"inside"}}}
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More