mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge main into fix/brush-options-unchanged-approval-b-verify
This commit is contained in:
commit
055b0e786f
95 files changed
+4960
-374
No files matched your search
@@ -1780,6 +1780,44 @@ fn perspective_projects_the_masks_in_a_symbols_art() {
|
||||
assert_eq!(mask, path, "and so is its mask");
|
||||
}
|
||||
|
||||
/// The images in the art of a symbol instance drawn through a projection have their corners where
|
||||
/// the projection takes them, beside a path, in a group and in the art of a linked mask, and an
|
||||
/// image's own linked mask is projected with it.
|
||||
#[test]
|
||||
fn a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them() {
|
||||
let masked = masked_by(white_square(22), image_node(23), true);
|
||||
let art = Node::group(NodeId(20), vec![Arc::new(image_node(21)), Arc::new(Node::group(NodeId(24), vec![Arc::new(masked)]))]);
|
||||
// An image with a linked mask of its own, whose path has a linked mask too.
|
||||
let inner = masked_by(white_square(32), white_square(33), true);
|
||||
let own = Node::group(NodeId(30), vec![Arc::new(masked_by(image_node(31), inner, true))]);
|
||||
let at = vectorcraft_doc::PerspectiveAttachment { projection: Some([1.0, 0.2, 3.0, 0.1, 1.0, 2.0, 0.01, 0.02, 1.0]), ..Default::default() };
|
||||
let h = at.homography().unwrap();
|
||||
let mut instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "t".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
instance.extras_mut().perspective = Some(Box::new(at.clone()));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&own)).unwrap();
|
||||
let mut masks = vec![];
|
||||
out.walk(&mut |c| masks.extend(c.image_corners().and(c.extras().mask.as_deref()).map(|m| m.art.clone())));
|
||||
let [mask] = masks.as_slice() else { panic!("one masked image: {out:?}") };
|
||||
assert!(mask.path_data() != white_square(32).path_data(), "the image's mask is projected");
|
||||
let inner = mask.extras().mask.as_deref().map(|m| m.art.path_data().cloned());
|
||||
assert_eq!(inner, Some(mask.path_data().cloned()), "and so is the mask on that mask's path");
|
||||
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
|
||||
instance.extras_mut().perspective = Some(Box::new(at));
|
||||
let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap();
|
||||
let want = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| h.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
|
||||
let mut images = vec![];
|
||||
out.walk(&mut |c| {
|
||||
images.extend(c.image_corners());
|
||||
images.extend(c.extras().mask.as_deref().and_then(|m| m.art.image_corners()));
|
||||
});
|
||||
assert_eq!(images.len(), 2, "{out:?}");
|
||||
for q in images {
|
||||
for (got, want) in q.iter().zip(want) {
|
||||
assert!(got.distance(want) < 1e-9, "{q:?} against {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit
|
||||
/// pitch, each crossing every bar of the other direction: n² crossings.
|
||||
fn crossing_bars(n: usize, effect: &str) -> Node {
|
||||
|
||||
@@ -1544,11 +1544,40 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
|
||||
/// follow it. The type and live objects in the art of those masks are outlined and evaluated
|
||||
/// first ([`outlined_members`], with the symbols of `doc`).
|
||||
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
|
||||
project_art(art, h, doc, false);
|
||||
}
|
||||
|
||||
/// [`project_leaves`], the linked opacity mask of `art` itself included when `own`.
|
||||
fn project_art(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>, own: bool) {
|
||||
project_paths(art, h);
|
||||
each_linked_mask_mut(art, false, 0, &mut |m| {
|
||||
each_linked_mask_mut(art, own, 0, &mut |m| {
|
||||
*m = outlined_mask_art(doc, m);
|
||||
project_paths(m, h);
|
||||
project_image_masks(m, h, doc);
|
||||
});
|
||||
project_image_masks(art, h, doc);
|
||||
}
|
||||
|
||||
/// The art of the linked opacity masks of the images under `art` (`art` itself, and in groups and
|
||||
/// layers, as [`project_images`] reaches them) projected through `h` as [`project_leaves`]
|
||||
/// projects art, the linked mask of that art's own root included, so that each mask stays on the
|
||||
/// object it masks. Unlinked masks stay where they are.
|
||||
fn project_image_masks(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
|
||||
match &mut art.kind {
|
||||
NodeKind::Image(_) => {
|
||||
if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) {
|
||||
let a = Arc::make_mut(&mut m.art);
|
||||
*a = outlined_mask_art(doc, a);
|
||||
project_art(a, h, doc, true);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter_mut() {
|
||||
project_image_masks(Arc::make_mut(c), h, doc);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated
|
||||
@@ -1584,6 +1613,27 @@ fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
project_images(art, h);
|
||||
}
|
||||
|
||||
/// Place the corners of every image under `art` (in groups and layers, as [`for_each_leaf`] reaches
|
||||
/// paths) where the projective map `h` takes them, so that its pixels are drawn in perspective
|
||||
/// between them ([`Node::set_image_corners`]). An image with a corner that `h` sends past its
|
||||
/// horizon keeps its place, as the points of a path there do.
|
||||
fn project_images(n: &mut Node, h: &vectorcraft_geom::Homography) {
|
||||
match &mut n.kind {
|
||||
NodeKind::Image(_) => {
|
||||
if let Some([Some(a), Some(b), Some(c), Some(d)]) = n.image_corners().map(|q| q.map(|p| h.apply(p))) {
|
||||
let _ = n.set_image_corners([a, b, c, d]);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
|
||||
for c in children.iter_mut() {
|
||||
project_images(Arc::make_mut(c), h);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The visible geometry effects of `n`'s own effect list, in order.
|
||||
|
||||
+324
-25
@@ -1180,8 +1180,11 @@ impl Placed {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares;
|
||||
/// the pairs they have not reached by then keep the order of their depths.
|
||||
/// The most pairs of faces [`local_order`] compares, together with the steps it takes to break
|
||||
/// rings of them ([`drawn_in_pairs_order`]), and the most pairs [`cut_stroke_faces`] compares. A
|
||||
/// pair not compared by then adds no constraint on the order (the pairs that were compared can
|
||||
/// still move its faces), and once the steps run out the first face left by depth goes next only
|
||||
/// when no face can.
|
||||
const MAX_LOCAL_CHECKS: usize = 4_000_000;
|
||||
|
||||
/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other
|
||||
@@ -1412,11 +1415,11 @@ fn half(p: &[Point], values: &[f64], sign: f64) -> Vec<Point> {
|
||||
/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill
|
||||
/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each
|
||||
/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays
|
||||
/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`.
|
||||
/// where its depth puts it. A cycle of such pairs is broken at one of its own faces
|
||||
/// ([`drawn_in_pairs_order`]).
|
||||
/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place:
|
||||
/// no face moves across it. Otherwise `order` as it is.
|
||||
fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
use std::cmp::Reverse;
|
||||
// The faces of each shape that take part, from left to right for a sweep along x.
|
||||
let mut shapes: Vec<Vec<usize>> = vec![];
|
||||
for (k, f) in faces.iter().enumerate() {
|
||||
@@ -1428,7 +1431,7 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
}
|
||||
shapes[f.member].push(k);
|
||||
}
|
||||
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) {
|
||||
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) || u32::try_from(faces.len()).is_err() {
|
||||
return order;
|
||||
}
|
||||
for list in &mut shapes {
|
||||
@@ -1471,9 +1474,9 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
// faces with a polygon and a plane that overlap goes in the order of their depths there.
|
||||
let mut sweep: Vec<usize> = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect();
|
||||
sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
|
||||
// For each face, the faces drawn after it, and for each, how many go before it.
|
||||
let mut after: Vec<Vec<usize>> = vec![vec![]; faces.len()];
|
||||
let mut waits = vec![0usize; faces.len()];
|
||||
// Each pair in its order: a face, and a face drawn after it (as `u32`: there are fewer faces
|
||||
// than that, which is checked above).
|
||||
let mut pairs: Vec<(u32, u32)> = vec![];
|
||||
'pairs: for (i, &k) in sweep.iter().enumerate() {
|
||||
let a = &faces[k];
|
||||
for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) {
|
||||
@@ -1491,38 +1494,117 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue };
|
||||
a_nearer
|
||||
};
|
||||
let (back, front) = if a_later { (j, k) } else { (k, j) };
|
||||
after[back].push(front);
|
||||
waits[front] += 1;
|
||||
pairs.push(if a_later { (j as u32, k as u32) } else { (k as u32, j as u32) });
|
||||
}
|
||||
}
|
||||
// Each step draws the face that comes first in `order` of those whose faces before are drawn.
|
||||
// Breaking rings has what is left of the limit.
|
||||
let last: Vec<bool> = faces.iter().map(|f| f.depth >= f64::MAX).collect();
|
||||
let mut room = MAX_LOCAL_CHECKS.saturating_sub(checks);
|
||||
drawn_in_pairs_order(order, &position, &last, pairs, &mut room)
|
||||
}
|
||||
|
||||
/// `order` with each face after the faces that go before it: each of `pairs` is a face and a face
|
||||
/// drawn after it, `position` is each face's place in `order`, and `last` says of each face
|
||||
/// whether it is drawn last. Each step draws the face that comes first in `order` of those whose
|
||||
/// faces before are drawn. A face drawn last goes only after every face before it in `order`, so
|
||||
/// a face before it never waits for it or for a face after it: those pairs, with the face drawn
|
||||
/// last itself or with a face that follows it, are drawn the wrong way round.
|
||||
///
|
||||
/// When no face can go next, some of the faces left go before each other in a ring, or wait for a
|
||||
/// face drawn last or one that follows it. The faces that go before the first face left in `order`
|
||||
/// are followed back, among the faces that come before the next face drawn last, to the first
|
||||
/// group found that waits for no other of them ([`RingFinder::behind`]): a ring, or one face. That
|
||||
/// group gives up its face that comes first in `order`. So when the first face left is in the
|
||||
/// group, it goes next, as it would with no ring looked for; when it only waits for the group, a
|
||||
/// face of the group goes instead, and the only other pairs drawn the wrong way round are pairs of
|
||||
/// a ring.
|
||||
///
|
||||
/// Every face and pair looked at takes one from `room`. The search is kept from one stop to the
|
||||
/// next and goes on from where it stopped, and a face that is drawn is dropped from a list the
|
||||
/// next time the list is looked at, so rings of a few faces take a few steps a face whether they
|
||||
/// stand apart, all lie behind one face or lie one behind the other. Two costs are not in
|
||||
/// proportion to the faces. A ring that is still a ring after it gives up a face is walked again
|
||||
/// from the face the search reached it by, so a large ring can cost about its pairs for each face
|
||||
/// it gives up: the square of its faces, even when each waits for few others (3,200 faces with
|
||||
/// four pairs each at random take about 3,000,000 steps). And a face at or
|
||||
/// after the next face drawn last is passed over again each time a face that waits for it is
|
||||
/// looked at. Once `room` runs out the first face left in `order` goes next, ring or not.
|
||||
/// A first face left that waits only for the next face drawn last or faces after it goes next
|
||||
/// with no search, at no cost.
|
||||
///
|
||||
/// An `order` and `position` that do not agree, or a pair of a face that is not in them, give
|
||||
/// `order` back.
|
||||
///
|
||||
/// The pairs come at 8 bytes each and are dropped once the lists of the faces after each face
|
||||
/// are made, 4 bytes a pair; the lists of the faces before each face, as many again, are made
|
||||
/// when a ring is first looked for, a step a pair not taken from `room`, and only when the room
|
||||
/// left is at least a quarter of the pairs: with less, no ring is looked for and the first face
|
||||
/// left goes next. So a solid whose comparing of pairs leaves less than a quarter of its pairs
|
||||
/// of the limit breaks its rings as before rings were looked for.
|
||||
fn drawn_in_pairs_order(order: Vec<usize>, position: &[usize], last: &[bool], pairs: Vec<(u32, u32)>, room: &mut usize) -> Vec<usize> {
|
||||
use std::cmp::Reverse;
|
||||
let n = order.len();
|
||||
// `order` holds each face once when each face's place in it is the place `position` gives.
|
||||
let agree = position.len() == n && last.len() == n && order.iter().enumerate().all(|(at, &k)| position.get(k) == Some(&at));
|
||||
if !agree || u32::try_from(pairs.len()).is_err() || pairs.iter().any(|&(back, front)| back as usize >= n || front as usize >= n) {
|
||||
return order;
|
||||
}
|
||||
// For each face, how many faces not drawn yet go before it, and the faces drawn after it.
|
||||
let mut waits = vec![0usize; n];
|
||||
for &(_, front) in &pairs {
|
||||
waits[front as usize] += 1;
|
||||
}
|
||||
let after = Lists::from_pairs(n, pairs.iter().map(|&(back, front)| (back as usize, front as usize)));
|
||||
drop(pairs);
|
||||
let mut ready: std::collections::BinaryHeap<Reverse<(usize, usize)>> =
|
||||
(0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
|
||||
(0..n).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
|
||||
// The faces drawn last, in `order`: each goes only after every face before it in `order`.
|
||||
let last: Vec<usize> = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect();
|
||||
let lasts: Vec<usize> = order.iter().copied().filter(|&k| last[k]).collect();
|
||||
let mut next_last = 0usize;
|
||||
let mut drawn = vec![false; faces.len()];
|
||||
let mut out = Vec::with_capacity(order.len());
|
||||
let mut drawn = vec![false; n];
|
||||
let mut out = Vec::with_capacity(n);
|
||||
let mut first = 0usize;
|
||||
while out.len() < order.len() {
|
||||
while last.get(next_last).is_some_and(|&k| drawn[k]) {
|
||||
let mut rings: Option<RingFinder> = None;
|
||||
// For each face, how many faces not drawn yet go before it among the first `counted` of
|
||||
// `order`, which keeps up with the next face drawn last.
|
||||
let mut early = vec![0u32; n];
|
||||
let mut counted = 0usize;
|
||||
while out.len() < n {
|
||||
while lasts.get(next_last).is_some_and(|&k| drawn[k]) {
|
||||
next_last += 1;
|
||||
}
|
||||
let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]);
|
||||
let limit = lasts.get(next_last).map_or(usize::MAX, |&k| position[k]);
|
||||
while counted < limit.min(n) {
|
||||
if let Some(&back) = order.get(counted).filter(|&&back| !drawn[back]) {
|
||||
for &j in after.list(back) {
|
||||
early[j as usize] += 1;
|
||||
}
|
||||
}
|
||||
counted += 1;
|
||||
}
|
||||
let k = match ready.peek() {
|
||||
Some(&Reverse((at, k))) if at < limit => {
|
||||
ready.pop();
|
||||
k
|
||||
}
|
||||
_ => {
|
||||
// A cycle, or the faces left to draw before a face drawn last wait for faces after
|
||||
// it: the first face in `order` not drawn yet goes next.
|
||||
while order.get(first).is_some_and(|&k| drawn[k]) {
|
||||
first += 1;
|
||||
}
|
||||
let Some(&k) = order.get(first) else { break };
|
||||
k
|
||||
let Some(&next) = order.get(first) else { break };
|
||||
// The face drawn last goes in its turn, and so does a face that waits only for it or
|
||||
// faces after it: no face it waits for can go first. Any other face waits for a
|
||||
// face before the face drawn last: the group behind it gives up a face, while there
|
||||
// is room to look for one. The lists of the faces before each face take a step a
|
||||
// pair to make, which is not taken from `room`: they are made only when the room
|
||||
// left is at least a quarter of the pairs, so making them costs no more than four
|
||||
// times the room left.
|
||||
let mut released = None;
|
||||
let room_for_lists = rings.is_some() || room.saturating_mul(4) >= after.faces.len();
|
||||
if *room > 0 && position[next] < limit && early[next] > 0 && room_for_lists {
|
||||
released = rings.get_or_insert_with(|| RingFinder::new(&after)).behind(next, &drawn, position, limit, room);
|
||||
}
|
||||
released.unwrap_or(next)
|
||||
}
|
||||
};
|
||||
if drawn[k] {
|
||||
@@ -1530,8 +1612,13 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
}
|
||||
drawn[k] = true;
|
||||
out.push(k);
|
||||
for &j in &after[k] {
|
||||
let was_counted = position[k] < counted;
|
||||
for &j in after.list(k) {
|
||||
let j = j as usize;
|
||||
waits[j] = waits[j].saturating_sub(1);
|
||||
if was_counted {
|
||||
early[j] = early[j].saturating_sub(1);
|
||||
}
|
||||
if waits[j] == 0 && !drawn[j] {
|
||||
ready.push(Reverse((position[j], j)));
|
||||
}
|
||||
@@ -1540,6 +1627,217 @@ fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A list of faces for each of some faces, all in one array: the faces after each face, or the
|
||||
/// faces before it.
|
||||
struct Lists {
|
||||
/// The list of face `k` is `faces[starts[k]..starts[k + 1]]`.
|
||||
starts: Vec<u32>,
|
||||
faces: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Lists {
|
||||
/// For each of `n` faces, the second faces of the `pairs` it is first in, in the order of
|
||||
/// `pairs`. There are fewer than 2^32 faces and pairs ([`drawn_in_pairs_order`] checks this);
|
||||
/// a pair with a face that is not one of the `n` is left out.
|
||||
fn from_pairs(n: usize, pairs: impl Iterator<Item = (usize, usize)> + Clone) -> Self {
|
||||
let pairs = pairs.filter(move |&(first, second)| first < n && second < n);
|
||||
let mut starts = vec![0u32; n + 1];
|
||||
for (first, _) in pairs.clone() {
|
||||
if let Some(count) = starts.get_mut(first + 1) {
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
for k in 1..starts.len() {
|
||||
starts[k] += starts[k - 1];
|
||||
}
|
||||
let mut filled = starts.clone();
|
||||
let mut faces = vec![0u32; starts.last().map_or(0, |&end| end as usize)];
|
||||
for (first, second) in pairs {
|
||||
if let Some(at) = filled.get_mut(first) {
|
||||
if let Some(slot) = faces.get_mut(*at as usize) {
|
||||
*slot = second as u32;
|
||||
}
|
||||
*at += 1;
|
||||
}
|
||||
}
|
||||
Lists { starts, faces }
|
||||
}
|
||||
|
||||
/// The list of face `k`; none for a face that is not one of them.
|
||||
fn list(&self, k: usize) -> &[u32] {
|
||||
let (Some(&start), Some(&end)) = (self.starts.get(k), self.starts.get(k + 1)) else { return &[] };
|
||||
self.faces.get(start as usize..end as usize).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Each list's faces and the face it is the list of, as pairs.
|
||||
fn pairs(&self) -> impl Iterator<Item = (usize, usize)> + Clone + '_ {
|
||||
(0..self.starts.len().saturating_sub(1)).flat_map(move |k| self.list(k).iter().map(move |&j| (k, j as usize)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The entries of the lists of faces before each face that [`RingFinder`] has read, counted
|
||||
/// where they are read, for tests to hold the reading to the room.
|
||||
pub(super) static LIST_ENTRIES_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// No place among the faces reached, in [`RingFinder`].
|
||||
const NONE: usize = usize::MAX;
|
||||
|
||||
/// Finds the ring behind a face for [`drawn_in_pairs_order`], and keeps its search from one stop to
|
||||
/// the next.
|
||||
///
|
||||
/// Every index it holds is in range: the faces of its lists are faces of the pairs
|
||||
/// [`drawn_in_pairs_order`] checked against the number of faces, which is the length of the
|
||||
/// `drawn` and `position` it is given, and the places it keeps are places in its own lists.
|
||||
struct RingFinder {
|
||||
/// For each face, the faces that go before it, lowest first.
|
||||
before: Lists,
|
||||
/// For each face, where its list in `before` now ends: the faces found drawn are dropped
|
||||
/// from it, and those left moved up.
|
||||
ends: Vec<u32>,
|
||||
/// For each face, its place in `reached`; [`NONE`] for a face not reached.
|
||||
marks: Vec<usize>,
|
||||
/// The faces reached, in the order reached. Every one is in a group not completed yet.
|
||||
reached: Vec<usize>,
|
||||
/// For each face reached, the earliest place in `reached` it leads back to.
|
||||
low: Vec<usize>,
|
||||
/// The path from the first face reached to the one being looked at.
|
||||
path: Vec<Step>,
|
||||
/// The `limit` the faces reached were reached under; `None` with none reached yet.
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
/// A face on the path of [`RingFinder`]: its place in `reached`, and the entry of its list being
|
||||
/// looked at.
|
||||
struct Step {
|
||||
place: usize,
|
||||
entry: usize,
|
||||
}
|
||||
|
||||
impl RingFinder {
|
||||
/// A finder for the faces of `after`, the faces drawn after each face.
|
||||
fn new(after: &Lists) -> Self {
|
||||
let n = after.starts.len() - 1;
|
||||
let before = Lists::from_pairs(n, after.pairs().map(|(back, front)| (front, back)));
|
||||
let ends = before.starts.get(1..).unwrap_or_default().to_vec();
|
||||
RingFinder { before, ends, marks: vec![NONE; n], reached: vec![], low: vec![], path: vec![], limit: None }
|
||||
}
|
||||
|
||||
/// The face to draw next when `start`, the first face not `drawn`, whose `position` is before
|
||||
/// `limit`, waits for a face. Of the faces that are not drawn and come before `limit`, those
|
||||
/// that go before `start` are followed back to the first group found whose faces wait for no
|
||||
/// other such face: a ring of faces that go before each other, or one face. The answer is the
|
||||
/// face of that group with the lowest `position`. Every face and every pair looked at takes
|
||||
/// one from `room`; `None` when it runs out.
|
||||
///
|
||||
/// The faces are followed depth first, each face's faces before it lowest first, and the first
|
||||
/// strongly connected component completed is the group (Tarjan's algorithm, stopped there):
|
||||
/// it leads to no other component. The search is kept, less that group, and the next call
|
||||
/// goes on with it: the faces drawn since are the group's own and faces that waited for
|
||||
/// nothing else, and none of those is in a group with a face still on the path, so what the
|
||||
/// search knows of the faces left still holds. It starts afresh when `limit` moves, which
|
||||
/// brings in faces it passed over.
|
||||
fn behind(&mut self, start: usize, drawn: &[bool], position: &[usize], limit: usize, room: &mut usize) -> Option<usize> {
|
||||
if self.limit != Some(limit) {
|
||||
self.forget(0);
|
||||
self.limit = Some(limit);
|
||||
}
|
||||
// The end of the path may be drawn: faces that only waited for the last group.
|
||||
while let Some(place) = self.path.last().map(|step| step.place).filter(|&place| drawn[self.reached[place]]) {
|
||||
self.forget(place);
|
||||
}
|
||||
if self.reached.first() != Some(&start) {
|
||||
self.forget(0);
|
||||
if !self.reach(start, drawn, room) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
while let Some(step) = self.path.last_mut() {
|
||||
if *room == 0 {
|
||||
return None;
|
||||
}
|
||||
*room -= 1;
|
||||
let place = step.place;
|
||||
let face = self.reached[place];
|
||||
if step.entry < self.ends[face] as usize {
|
||||
let earlier = self.before.faces[step.entry] as usize;
|
||||
if drawn[earlier] || position[earlier] >= limit {
|
||||
step.entry += 1;
|
||||
} else if self.marks[earlier] != NONE {
|
||||
self.low[place] = self.low[place].min(self.marks[earlier]);
|
||||
step.entry += 1;
|
||||
} else {
|
||||
// The entry is passed once the faces behind it are looked at.
|
||||
if !self.reach(earlier, drawn, room) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Every face before this one is looked at: it ends a group when it leads no further
|
||||
// back than itself.
|
||||
let leads = self.low[place];
|
||||
if leads == place {
|
||||
let found = self.reached[place..].iter().copied().min_by_key(|&face| position[face]);
|
||||
// The face before it on the path keeps its entry for this one, to look at what is
|
||||
// left of the group next time.
|
||||
self.forget(place);
|
||||
return found;
|
||||
}
|
||||
self.path.pop();
|
||||
if let Some(parent) = self.path.last_mut() {
|
||||
self.low[parent.place] = self.low[parent.place].min(leads);
|
||||
parent.entry += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Adds `face` to the faces reached and to the end of the path, at the start of its list, with
|
||||
/// the faces now `drawn` dropped from the list: a step from `room` for each face the list held,
|
||||
/// taken before the list is read. `false`, with `room` emptied and nothing read, when the list
|
||||
/// is longer than the room left.
|
||||
fn reach(&mut self, face: usize, drawn: &[bool], room: &mut usize) -> bool {
|
||||
let (start, end) = (self.before.starts[face] as usize, self.ends[face] as usize);
|
||||
let Some(left) = room.checked_sub(end - start) else {
|
||||
*room = 0;
|
||||
return false;
|
||||
};
|
||||
*room = left;
|
||||
let mut kept = start;
|
||||
for entry in start..end {
|
||||
let earlier = self.before.faces[entry];
|
||||
#[cfg(test)]
|
||||
LIST_ENTRIES_READ.with(|read| read.set(read.get() + 1));
|
||||
if !drawn[earlier as usize] {
|
||||
self.before.faces[kept] = earlier;
|
||||
kept += 1;
|
||||
}
|
||||
}
|
||||
// `kept` is no more than the end it replaces.
|
||||
self.ends[face] = kept as u32;
|
||||
let place = self.reached.len();
|
||||
self.marks[face] = place;
|
||||
self.path.push(Step { place, entry: start });
|
||||
self.low.push(place);
|
||||
self.reached.push(face);
|
||||
true
|
||||
}
|
||||
|
||||
/// Takes out the faces reached from `place` on, and their part of the path.
|
||||
fn forget(&mut self, place: usize) {
|
||||
for face in self.reached.drain(place.min(self.reached.len())..) {
|
||||
self.marks[face] = NONE;
|
||||
}
|
||||
self.low.truncate(place);
|
||||
while self.path.last().is_some_and(|step| step.place >= place) {
|
||||
self.path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing,
|
||||
/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is
|
||||
/// not convex, or when they are at the same depth there.
|
||||
@@ -1673,7 +1971,8 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
|
||||
/// of overlapping faces with a convex polygon and a plane goes in the order of its depths there,
|
||||
/// the face nearer the viewer after the other ([`local_order`]), and each step draws the face that
|
||||
/// comes first in the given order of those whose faces before are drawn, so a face without a plane
|
||||
/// or a convex polygon can also move. Otherwise the order given.
|
||||
/// or a convex polygon can also move. Faces that lie in front of one another in a ring give up one
|
||||
/// of the ring's own faces ([`drawn_in_pairs_order`]). Otherwise the order given.
|
||||
pub(crate) fn surface_order<'a>(faces: impl IntoIterator<Item = (&'a [Point], Option<DepthPlane>, f64)>) -> Vec<usize> {
|
||||
let placed: Vec<Placed> = faces
|
||||
.into_iter()
|
||||
|
||||
@@ -933,10 +933,10 @@ fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap
|
||||
/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at
|
||||
/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer
|
||||
/// than 0. 3 is the cap.
|
||||
/// A cycle of overlapping stroke faces is broken at its own face that comes first by depth, and a
|
||||
/// cap drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8;
|
||||
/// 2 at x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2
|
||||
/// nearer than 0. 3 is the cap.
|
||||
#[test]
|
||||
fn a_depth_cycle_keeps_the_cap_last() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
@@ -964,6 +964,450 @@ fn a_depth_cycle_keeps_the_cap_last() {
|
||||
assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]);
|
||||
}
|
||||
|
||||
/// A face that lies in front of a face of a cycle, without being part of the cycle, waits for that
|
||||
/// face. 0, 1 and 2 overlap in a cycle (as in `a_depth_cycle_keeps_the_cap_last`); 3, at x 16 to
|
||||
/// 26 and flat at z 2, is nearer than 2 where they overlap, but its center is the farthest of all,
|
||||
/// so it comes first by depth. The cycle is broken at 0, its first face by depth, and 3 follows 2.
|
||||
/// Breaking it at the first face by depth of all the faces left drew 3 first, under 2.
|
||||
#[test]
|
||||
fn a_face_in_front_of_a_cycle_waits_for_it() {
|
||||
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
|
||||
let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed {
|
||||
depth,
|
||||
side: true,
|
||||
away: false,
|
||||
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
|
||||
member: 0,
|
||||
paints: Paints::Other,
|
||||
outline: square(x),
|
||||
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
|
||||
};
|
||||
let flat = [0.0, 0.0, 1.0];
|
||||
let walls = || [at(1.0, 0.0, flat, 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, flat, 1.0), at(-5.0, 16.0, flat, 2.0)];
|
||||
assert_eq!(draw_order(&walls(), true), [0, 2, 3, 1]);
|
||||
// With the cap of `a_depth_cycle_keeps_the_cap_last` as well, it still goes last.
|
||||
let cap =
|
||||
Placed { depth: f64::MAX, side: false, bounds: Rect::new(0.0, 0.0, 26.0, 10.0), outline: vec![], plane: None, ..at(0.0, 0.0, flat, 0.0) };
|
||||
let capped: Vec<Placed> = walls().into_iter().chain([cap]).collect();
|
||||
assert_eq!(draw_order(&capped, true), [0, 2, 3, 1, 4]);
|
||||
}
|
||||
|
||||
/// `order` with the pairs `before` (each first face drawn before the second) in their own order
|
||||
/// ([`drawn_in_pairs_order`]), within `room` steps of looking for rings, and the steps taken; the
|
||||
/// faces of `last` are drawn last.
|
||||
fn in_pairs_order(order: &[usize], before: &[(usize, usize)], last: &[usize], room: usize) -> (Vec<usize>, usize) {
|
||||
let n = order.len();
|
||||
let mut position = vec![0; n];
|
||||
for (at, &k) in order.iter().enumerate() {
|
||||
position[k] = at;
|
||||
}
|
||||
let last: Vec<bool> = (0..n).map(|k| last.contains(&k)).collect();
|
||||
let mut left = room;
|
||||
let drawn = drawn_in_pairs_order(order.to_vec(), &position, &last, narrow(before), &mut left);
|
||||
(drawn, room - left)
|
||||
}
|
||||
|
||||
/// What [`drawn_in_pairs_order`] is to give with room enough, worked out plainly: at every stop
|
||||
/// the faces behind the first face left are followed afresh, with nothing kept and no face taken
|
||||
/// out of a list.
|
||||
fn in_pairs_order_plainly(order: &[usize], before: &[(usize, usize)], last: &[usize]) -> Vec<usize> {
|
||||
/// The first group completed behind `face`, among the faces `open`: its faces, or `None` while
|
||||
/// its group goes on. `earlier` lists the faces before each face, lowest first.
|
||||
fn group(face: usize, open: &[bool], earlier: &[Vec<usize>], reached: &mut Vec<usize>, low: &mut Vec<usize>) -> Option<Vec<usize>> {
|
||||
let place = reached.len();
|
||||
reached.push(face);
|
||||
low.push(place);
|
||||
for &e in earlier[face].iter().filter(|&&e| open[e]) {
|
||||
match reached.iter().position(|&f| f == e) {
|
||||
Some(at) => low[place] = low[place].min(at),
|
||||
None => {
|
||||
let found = group(e, open, earlier, reached, low);
|
||||
if found.is_some() {
|
||||
return found;
|
||||
}
|
||||
low[place] = low[place].min(low[reached.iter().position(|&f| f == e).unwrap()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
(low[place] == place).then(|| reached[place..].to_vec())
|
||||
}
|
||||
let n = order.len();
|
||||
let mut at = vec![0; n];
|
||||
for (place, &k) in order.iter().enumerate() {
|
||||
at[k] = place;
|
||||
}
|
||||
let mut earlier = vec![vec![]; n];
|
||||
for &(first, then) in before {
|
||||
earlier[then].push(first);
|
||||
}
|
||||
earlier.iter_mut().for_each(|list| list.sort_unstable());
|
||||
let mut drawn = vec![false; n];
|
||||
let mut out: Vec<usize> = vec![];
|
||||
while out.len() < n {
|
||||
let left: Vec<usize> = order.iter().copied().filter(|&k| !drawn[k]).collect();
|
||||
let limit = left.iter().find(|k| last.contains(k)).map_or(usize::MAX, |&k| at[k]);
|
||||
let waits = |k: usize| earlier[k].iter().any(|&e| !drawn[e]);
|
||||
let next = match left.iter().copied().find(|&k| at[k] < limit && !waits(k)) {
|
||||
Some(ready) => ready,
|
||||
None if at[left[0]] >= limit => left[0],
|
||||
None => {
|
||||
let open: Vec<bool> = (0..n).map(|k| !drawn[k] && at[k] < limit).collect();
|
||||
let found = group(left[0], &open, &earlier, &mut vec![], &mut vec![]).unwrap();
|
||||
found.into_iter().min_by_key(|&k| at[k]).unwrap()
|
||||
}
|
||||
};
|
||||
drawn[next] = true;
|
||||
out.push(next);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `pairs` as [`drawn_in_pairs_order`] takes them.
|
||||
fn narrow(pairs: &[(usize, usize)]) -> Vec<(u32, u32)> {
|
||||
pairs.iter().map(|&(first, then)| (first as u32, then as u32)).collect()
|
||||
}
|
||||
|
||||
/// The pairs of `before` that `drawn` draws the wrong way round.
|
||||
fn broken(drawn: &[usize], before: &[(usize, usize)]) -> Vec<(usize, usize)> {
|
||||
let mut at = vec![0; drawn.len()];
|
||||
for (place, &k) in drawn.iter().enumerate() {
|
||||
at[k] = place;
|
||||
}
|
||||
before.iter().copied().filter(|&(first, then)| at[first] > at[then]).collect()
|
||||
}
|
||||
|
||||
/// After a ring's face is released, the faces left are looked at afresh: they may be a smaller
|
||||
/// ring and faces in none. Two rings share face 1: 0 before 1 before 4 before 0, and 1 before 2
|
||||
/// before 3 before 1. By depth the order is 3, 2, 0, 4, 1. The five wait for no other face, so the
|
||||
/// first stop releases 3, the first of them by depth. That leaves the one ring 0, 1, 4 and face
|
||||
/// 2, which only waits for 1: 0 is released, and 2 follows 1. Only pairs of a ring are drawn the
|
||||
/// wrong way round. Taking the first face left by depth at each stop drew 2 before 1 as well.
|
||||
#[test]
|
||||
fn the_faces_left_are_looked_at_afresh_after_each_face_released() {
|
||||
let before = [(0, 1), (1, 4), (4, 0), (1, 2), (2, 3), (3, 1)];
|
||||
let (drawn, _) = in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [3, 0, 1, 2, 4]);
|
||||
assert_eq!(broken(&drawn, &before), [(4, 0), (2, 3)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[3, 2, 0, 4, 1], &before, &[], 0).0, &before), [(4, 0), (1, 2), (2, 3)]);
|
||||
}
|
||||
|
||||
/// A ring is the one behind the first face left by depth that waits for no face outside it: 0
|
||||
/// comes first by depth and waits for the ring 1, 2, 3, which waits for the ring 4, 5, 6. The far
|
||||
/// ring is broken first (at 4) and drawn, then the near one (at 1), and 0 follows 1; one pair of
|
||||
/// each ring is drawn the wrong way round, and no pair between them. Taking the first face left by
|
||||
/// depth drew 0 first, under 1.
|
||||
#[test]
|
||||
fn the_ring_released_waits_for_no_face_outside_it() {
|
||||
let before = [(1, 0), (1, 2), (2, 3), (3, 1), (4, 1), (4, 5), (5, 6), (6, 4)];
|
||||
let (drawn, _) = in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [4, 5, 6, 1, 0, 2, 3]);
|
||||
assert_eq!(broken(&drawn, &before), [(3, 1), (6, 4)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[0, 1, 2, 3, 4, 5, 6], &before, &[], 0).0, &before), [(1, 0), (3, 1), (4, 1), (6, 4)]);
|
||||
}
|
||||
|
||||
/// A ring is looked for among the faces that come before the next face drawn last: 1 comes first
|
||||
/// by depth and waits for 4, a face of the ring 2, 3, 4, and for 0, which is drawn last. 0 waits
|
||||
/// for no face, so it is a group of its own behind 1, but no face before it by depth can wait for
|
||||
/// it. The ring gives up 2, and 1 follows 4; the pair of 1 and 0 cannot be kept. Stopping at 0
|
||||
/// drew 1 first, under 4.
|
||||
#[test]
|
||||
fn a_ring_is_looked_for_before_the_next_face_drawn_last() {
|
||||
let before = [(2, 3), (3, 4), (4, 2), (4, 1), (0, 1)];
|
||||
let (drawn, _) = in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], usize::MAX);
|
||||
assert_eq!(drawn, [2, 3, 4, 1, 0]);
|
||||
assert_eq!(broken(&drawn, &before), [(4, 2), (0, 1)]);
|
||||
assert_eq!(broken(&in_pairs_order(&[1, 2, 3, 4, 0], &before, &[0], 0).0, &before), [(4, 2), (4, 1), (0, 1)]);
|
||||
// A face that waits only for a face after the one drawn last goes before the faces that wait
|
||||
// for it: 0 waits for 1, 1 for 3, and 2 is drawn last.
|
||||
let before = [(1, 0), (3, 1)];
|
||||
assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], usize::MAX).0, [1, 0, 2, 3]);
|
||||
assert_eq!(in_pairs_order(&[0, 1, 2, 3], &before, &[2], 0).0, [0, 1, 2, 3]);
|
||||
}
|
||||
|
||||
/// Looking for rings is counted, and past the room given the first face not drawn yet goes next,
|
||||
/// as before rings were looked for: the pairs of `a_face_in_front_of_a_cycle_waits_for_it`. A
|
||||
/// face drawn last keeps every face before it by depth before it, ring or not. An order and
|
||||
/// places in it that do not agree (an order that is not each face once), or a pair of a face that
|
||||
/// is not in them, give the order back.
|
||||
#[test]
|
||||
fn breaking_rings_stops_at_its_room() {
|
||||
let before = [(1, 0), (0, 2), (2, 1), (2, 3)];
|
||||
let order = [3, 0, 1, 2];
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, [0, 2, 3, 1]);
|
||||
// The faces and pairs behind 3.
|
||||
assert!((4..=16).contains(&steps), "{steps} steps");
|
||||
assert_eq!(in_pairs_order(&order, &before, &[], steps), (vec![0, 2, 3, 1], steps));
|
||||
for room in [0, 1, steps - 1] {
|
||||
let (drawn, taken) = in_pairs_order(&order, &before, &[], room);
|
||||
assert_eq!(drawn, [3, 0, 2, 1], "{room}");
|
||||
assert!(taken <= room, "{room}");
|
||||
}
|
||||
// 0 is drawn last: 3, before it by depth, goes before it, and the ring's other faces after.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[0], usize::MAX).0, [3, 0, 2, 1]);
|
||||
// 2 is drawn last: every other face is before it by depth, so 3 and 1, which wait only for
|
||||
// it, go when they come first of the faces behind the first face left, and 0 follows 1.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[2], usize::MAX).0, [3, 1, 0, 2]);
|
||||
assert_eq!(in_pairs_order(&order, &before, &[2], 0).0, [3, 0, 1, 2]);
|
||||
let mut room = usize::MAX;
|
||||
let position = [1, 2, 3, 0];
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 3], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(9, 0)], &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position, &[false; 4], vec![(0, 4)], &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order[..3].to_vec(), &position, &[false; 4], narrow(&before), &mut room), order[..3]);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &position[..3], &[false; 4], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(order.to_vec(), &[1, 2, 0, 3], &[false; 4], narrow(&before), &mut room), order);
|
||||
assert_eq!(drawn_in_pairs_order(vec![0, 0, 1, 2], &[0, 2, 3, 0], &[false; 4], narrow(&before), &mut room), [0, 0, 1, 2]);
|
||||
assert_eq!(drawn_in_pairs_order(vec![0, 1, 2, 4], &[0, 1, 2, 3], &[false; 4], narrow(&before), &mut room), [0, 1, 2, 4]);
|
||||
assert_eq!(room, usize::MAX);
|
||||
}
|
||||
|
||||
/// A first face left that waits only for the face drawn last goes next with no search: 1,000
|
||||
/// such faces before a ring cost nothing, and the ring behind them still has its room. Each face
|
||||
/// i < 1,000 waits for 1,004, which is drawn last; 1,000 to 1,003 are the pairs of
|
||||
/// `breaking_rings_stops_at_its_room`, where 1,003 comes first by depth and waits for the ring.
|
||||
#[test]
|
||||
fn a_face_that_waits_only_for_the_face_drawn_last_costs_no_search() {
|
||||
let waiting = 1000usize;
|
||||
let (r, last) = (waiting, waiting + 4);
|
||||
let mut before: Vec<(usize, usize)> = (0..waiting).map(|f| (last, f)).collect();
|
||||
before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]);
|
||||
let order: Vec<usize> = (0..waiting).chain([r + 3, r, r + 1, r + 2, last]).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[last], usize::MAX);
|
||||
let expected: Vec<usize> = (0..waiting).chain([r, r + 2, r + 3, r + 1, last]).collect();
|
||||
assert_eq!(drawn, expected);
|
||||
assert!(steps < 20, "{steps} steps");
|
||||
// The room the ring takes is enough, whatever waits before it.
|
||||
assert_eq!(in_pairs_order(&order, &before, &[last], before.len().div_ceil(4).max(steps)).0, expected);
|
||||
}
|
||||
|
||||
/// The lists of the faces before each face are made only when the room left is at least a
|
||||
/// quarter of the pairs: with less, no ring is looked for, however few steps the ring would take.
|
||||
/// A ring of three behind 3,000 faces in a chain (each before the next).
|
||||
#[test]
|
||||
fn the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs() {
|
||||
let chain = 3000usize;
|
||||
let r = chain;
|
||||
let mut before: Vec<(usize, usize)> = (0..chain - 1).map(|f| (f, f + 1)).collect();
|
||||
before.extend([(r + 1, r), (r, r + 2), (r + 2, r + 1), (r + 2, r + 3)]);
|
||||
// As in `breaking_rings_stops_at_its_room`: 3 comes first by depth of the four and waits for
|
||||
// the ring.
|
||||
let order: Vec<usize> = (0..chain).chain([r + 3, r, r + 1, r + 2]).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn[chain..], [r, r + 2, r + 3, r + 1]);
|
||||
assert!(steps < 20, "{steps} steps");
|
||||
let quarter = before.len().div_ceil(4);
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], quarter - 1);
|
||||
assert_eq!(drawn[chain..], [r + 3, r, r + 2, r + 1]);
|
||||
assert_eq!(steps, 0);
|
||||
assert_eq!(in_pairs_order(&order, &before, &[], quarter).0[chain..], [r, r + 2, r + 3, r + 1]);
|
||||
}
|
||||
|
||||
/// A list of the faces before a face is read only when the room left holds it: with less, no
|
||||
/// entry of it is read, and the first face left goes next. Face 0 comes first by depth and waits
|
||||
/// for 1, which waits for 2,000 faces after it in `order`, each waiting for 1: a ring of 1 with
|
||||
/// each of them.
|
||||
#[test]
|
||||
fn a_list_longer_than_the_room_left_is_not_read() {
|
||||
let wide = 2000usize;
|
||||
let mut before = vec![(1, 0)];
|
||||
before.extend((2..2 + wide).flat_map(|f| [(f, 1), (1, f)]));
|
||||
let order: Vec<usize> = (0..2 + wide).collect();
|
||||
// Room for the lists (a quarter of the pairs) but not for 1's list, and room for it.
|
||||
// With too little room only 0's one-entry list is read; with room for both, 1's list as well.
|
||||
for (room, want) in [(before.len().div_ceil(4), 1), (wide - 1, 1), (wide + 3, wide + 1)] {
|
||||
super::LIST_ENTRIES_READ.with(|read| read.set(0));
|
||||
let (drawn, taken) = in_pairs_order(&order, &before, &[], room);
|
||||
let read = super::LIST_ENTRIES_READ.with(|read| read.get());
|
||||
assert_eq!(read, want, "room {room}: {read} entries read, {taken} steps");
|
||||
assert!(read <= taken && taken <= room, "room {room}: {read} entries read, {taken} steps");
|
||||
assert_eq!(drawn.len(), order.len());
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps of breaking rings are counted, not timed, and for rings of a few faces they are a
|
||||
/// few a face however the rings lie: apart, each with a face in front of it that comes first by
|
||||
/// depth; all behind one face, itself in a ring whose other faces come first in its list; and one
|
||||
/// behind the other. The search goes on from where it stopped, and a face drawn is dropped from
|
||||
/// a list the next time the list is looked at. A ring that is still a ring after it gives up a
|
||||
/// face is walked again, so a large ring can take about its pairs for each face it gives up, the
|
||||
/// square of its faces even when each waits for few others. With too little room the rings not
|
||||
/// reached are broken at the first face left by depth, as before.
|
||||
#[test]
|
||||
fn breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs() {
|
||||
// Ring r: faces 4r, 4r + 1 and 4r + 2 in a ring, and 4r + 3 after 4r + 2.
|
||||
let rings = 2000usize;
|
||||
let mut before = vec![];
|
||||
for r in 0..rings {
|
||||
let f = 4 * r;
|
||||
before.extend([(f + 1, f), (f, f + 2), (f + 2, f + 1), (f + 2, f + 3)]);
|
||||
}
|
||||
// By depth: every fourth face first, then the rings.
|
||||
let order: Vec<usize> = (0..rings).map(|r| 4 * r + 3).chain((0..rings).flat_map(|r| [4 * r, 4 * r + 1, 4 * r + 2])).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(broken(&drawn, &before), (0..rings).map(|r| (4 * r + 1, 4 * r)).collect::<Vec<_>>());
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings apart");
|
||||
// With no room the fourth faces go first, under the faces they are in front of.
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 2 * rings);
|
||||
|
||||
// Face 0, first by depth, is in a ring with 1 and 2, which come first in its list, and after a
|
||||
// face of each ring r: faces 3r + 3, 3r + 4 and 3r + 5.
|
||||
let rings = 3000usize;
|
||||
let mut before = vec![(1, 0), (0, 2), (2, 1)];
|
||||
for r in 0..rings {
|
||||
let f = 3 * r + 3;
|
||||
before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f), (f, 0)]);
|
||||
}
|
||||
let order: Vec<usize> = (0..3 * rings + 3).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
// One pair of each ring, face 0's among them, and no pair of face 0 with another ring's face.
|
||||
assert_eq!(broken(&drawn, &before), [(1, 0)].into_iter().chain((0..rings).map(|r| (3 * r + 5, 3 * r + 3))).collect::<Vec<_>>());
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings behind one face");
|
||||
// The same with a face drawn last that every ring's first face waits for: it is passed over
|
||||
// each time, and nothing after it in a list is looked at twice for that.
|
||||
let cap = 3 * rings + 3;
|
||||
let capped: Vec<(usize, usize)> = (0..rings).map(|r| (cap, 3 * r + 3)).chain(before.iter().copied()).collect();
|
||||
let order: Vec<usize> = (0..=cap).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &capped, &[cap], usize::MAX);
|
||||
assert_eq!(broken(&drawn, &capped).len(), 2 * rings + 1);
|
||||
assert!(steps <= 5 * order.len(), "{steps} steps for {rings} rings behind one face, before a face drawn last");
|
||||
|
||||
// Ring r: faces 3r, 3r + 1 and 3r + 2, the first after the last face of ring r + 1.
|
||||
let rings = 3000usize;
|
||||
let mut before = vec![];
|
||||
for r in 0..rings {
|
||||
let f = 3 * r;
|
||||
before.extend([(f, f + 1), (f + 1, f + 2), (f + 2, f)]);
|
||||
if r + 1 < rings {
|
||||
before.push((f + 5, f));
|
||||
}
|
||||
}
|
||||
let order: Vec<usize> = (0..3 * rings).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
// One pair of each ring, and no pair between rings.
|
||||
assert_eq!(broken(&drawn, &before).len(), rings);
|
||||
assert!(broken(&drawn, &before).iter().all(|&(first, then)| first / 3 == then / 3));
|
||||
assert!(steps <= 4 * order.len(), "{steps} steps for {rings} rings one behind the other");
|
||||
let (short, taken) = in_pairs_order(&order, &before, &[], steps / 2);
|
||||
assert!(broken(&short, &before).len() > rings && taken <= steps / 2, "{} pairs, {taken} steps", broken(&short, &before).len());
|
||||
assert_eq!(short.len(), order.len());
|
||||
|
||||
// One ring: each of 200 faces before the next 99.
|
||||
let faces = 200usize;
|
||||
let before: Vec<(usize, usize)> = (0..faces).flat_map(|f| (1..100).map(move |d| (f, (f + d) % faces))).collect();
|
||||
let order: Vec<usize> = (0..faces).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn, order);
|
||||
// Each face it gives up walks the ring again, so it takes many times its pairs (the cost the
|
||||
// docs name), but no more than about its pairs for each face.
|
||||
assert!(steps < 2 * faces * before.len(), "{steps} steps for a ring of {} pairs", before.len());
|
||||
|
||||
// Pairs at random, about four a face: one large ring and faces around it.
|
||||
let steps_of = |faces: usize| {
|
||||
let mut next = numbers(faces as u64);
|
||||
let before: Vec<(usize, usize)> = (0..2 * faces)
|
||||
.map(|_| ((next() * faces as f64) as usize, (next() * faces as f64) as usize))
|
||||
.filter(|(first, then)| first != then)
|
||||
.collect();
|
||||
let order: Vec<usize> = (0..faces).collect();
|
||||
let (drawn, steps) = in_pairs_order(&order, &before, &[], usize::MAX);
|
||||
assert_eq!(drawn.len(), faces);
|
||||
steps
|
||||
};
|
||||
// No more than the square of the faces.
|
||||
let (few, more) = (steps_of(800), steps_of(1600));
|
||||
assert!(few < 800 * 800 && more < 1600 * 1600, "{few} steps for 800 faces, {more} for 1,600");
|
||||
}
|
||||
|
||||
/// Numbers from 0 to 1 that are the same on every run.
|
||||
fn numbers(mut seed: u64) -> impl FnMut() -> f64 {
|
||||
move || {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(seed >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
}
|
||||
|
||||
/// A ring gives up its own face that comes first by depth, which draws no more pairs the wrong
|
||||
/// way round than taking the first face left by depth, ring or not, as before: on 6,000 sets of
|
||||
/// pairs at random (4 to 30 faces, sparse and dense, agreeing with the depths mostly or half the
|
||||
/// time, the pairs in any order and some twice, with up to four faces drawn last) none has more, and they have fewer in all. Every face
|
||||
/// is drawn once, a face drawn last follows every face before it by depth, and the order of every
|
||||
/// set is the one that looking afresh at every stop gives. One of them is a
|
||||
/// set where the ring's face that waits for the fewest faces drew 4 pairs wrong against 3.
|
||||
#[test]
|
||||
fn breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth() {
|
||||
let order = [3, 6, 4, 1, 0, 2, 5];
|
||||
let before = [
|
||||
(1, 0),
|
||||
(2, 0),
|
||||
(0, 3),
|
||||
(0, 4),
|
||||
(5, 0),
|
||||
(6, 0),
|
||||
(1, 2),
|
||||
(1, 3),
|
||||
(4, 1),
|
||||
(5, 1),
|
||||
(4, 2),
|
||||
(5, 2),
|
||||
(6, 2),
|
||||
(3, 4),
|
||||
(3, 6),
|
||||
(5, 4),
|
||||
(6, 4),
|
||||
(5, 6),
|
||||
];
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], 0).0, &before).len(), 3);
|
||||
assert_eq!(broken(&in_pairs_order(&order, &before, &[], usize::MAX).0, &before).len(), 3);
|
||||
|
||||
let mut next = numbers(7023);
|
||||
let (mut with_rings, mut without, mut fewer) = (0usize, 0usize, 0usize);
|
||||
for set in 0..6000 {
|
||||
let n = 4 + (next() * 27.0) as usize;
|
||||
let (dense, agrees) = (0.05 + 0.8 * next() * next(), if set % 2 == 0 { 0.5 } else { 0.85 });
|
||||
// The order by depth: the faces shuffled.
|
||||
let mut order: Vec<usize> = (0..n).collect();
|
||||
for k in (1..n).rev() {
|
||||
order.swap(k, (next() * (k + 1) as f64) as usize);
|
||||
}
|
||||
let mut before = vec![];
|
||||
for a in 0..n {
|
||||
for b in a + 1..n {
|
||||
if next() < dense {
|
||||
before.push(if next() < agrees { (order[a], order[b]) } else { (order[b], order[a]) });
|
||||
}
|
||||
}
|
||||
}
|
||||
// The pairs in any order, and in every fifth set some of them twice.
|
||||
for k in (1..before.len()).rev() {
|
||||
before.swap(k, (next() * (k + 1) as f64) as usize);
|
||||
}
|
||||
if set % 5 == 0 {
|
||||
let again: Vec<(usize, usize)> = before.iter().copied().filter(|_| next() < 0.3).collect();
|
||||
before.extend(again);
|
||||
}
|
||||
// No face drawn last, or up to four.
|
||||
let last: Vec<usize> = (0..set % 5).map(|_| order[(next() * n as f64) as usize]).collect();
|
||||
let (drawn, _) = in_pairs_order(&order, &before, &last, usize::MAX);
|
||||
// Keeping the search from stop to stop gives what looking afresh at every stop gives.
|
||||
assert_eq!(drawn, in_pairs_order_plainly(&order, &before, &last), "set {set}: {order:?} {before:?} {last:?}");
|
||||
let (plainly, _) = in_pairs_order(&order, &before, &last, 0);
|
||||
let mut once = drawn.clone();
|
||||
once.sort_unstable();
|
||||
assert_eq!(once, (0..n).collect::<Vec<_>>(), "set {set}");
|
||||
for &cap in &last {
|
||||
let (at, place) = (order.iter().position(|&f| f == cap).unwrap(), drawn.iter().position(|&f| f == cap).unwrap());
|
||||
assert!(order[..at].iter().all(|f| drawn[..place].contains(f)), "set {set}");
|
||||
}
|
||||
let (rings, plain) = (broken(&drawn, &before).len(), broken(&plainly, &before).len());
|
||||
assert!(rings <= plain, "set {set}: {rings} pairs wrong, {plain} with the first face by depth; {order:?} {before:?} {last:?}");
|
||||
with_rings += rings;
|
||||
without += plain;
|
||||
fewer += usize::from(rings < plain);
|
||||
}
|
||||
assert!(fewer > 500 && with_rings < without, "{with_rings} pairs wrong, {without} with the first face by depth, fewer in {fewer} sets");
|
||||
}
|
||||
|
||||
/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a
|
||||
/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A
|
||||
/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an
|
||||
|
||||
@@ -865,11 +865,11 @@ pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use paint::PAINTS_READ;
|
||||
/// What the fill and stroke proxies read from the selected objects, kept with the selection
|
||||
/// ([`crate::doc_state::SelectionRecord`]).
|
||||
pub(crate) use paint::SelectionPaints;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paint::{PAINTS_READ, WEIGHTS_READ};
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
/// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`.
|
||||
|
||||
@@ -13,13 +13,16 @@
|
||||
//! a new document whose artboard is their bounds (or, to place, the art of one group), and nothing
|
||||
//! opens or is placed when the importer fails, declines, is cancelled or returns objects that don't
|
||||
//! pass the checks a filter's output does.
|
||||
//! An importer at plug-in API level 4 may also return point type, embedded images, top-level
|
||||
//! layers and artboards (its manifest's `outputKinds`): the artboards it returns replace the one
|
||||
//! around the art of a new document, and File › Place leaves them out.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Document, MAX_COORD, NodeId};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_plugins::import::Mode;
|
||||
use vectorcraft_doc::{CharStyle, Document, ImageObject, LAYER_COLORS, LayerColor, MAX_COORD, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_plugins::import::{ImportObject, Mode};
|
||||
use vectorcraft_plugins::{Manifest, Plugin, export, import, objects};
|
||||
|
||||
use super::super::{Result, bad, str_param};
|
||||
@@ -210,17 +213,15 @@ pub(crate) fn place_source<'a>(p: &'a Value, cmd: &str) -> Result<Source<'a>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`read`] gives: the importer's format, the new document, its objects' ids, the artboards
|
||||
/// the importer returned and its warnings.
|
||||
type Read = (&'static Format, Document, Vec<NodeId>, Vec<import::OutArtboard>, Vec<String>);
|
||||
|
||||
/// The file `name` holding `bytes` read by importer `plugin` for `mode` with command `cmd`'s params
|
||||
/// `p` (`params`: the importer's own parameters) → the importer's format, a new document holding its
|
||||
/// objects on its first layer, their ids, and its warnings.
|
||||
fn read(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
plugin: &Plugin,
|
||||
p: &Value,
|
||||
cmd: &str,
|
||||
mode: Mode,
|
||||
) -> Result<(&'static Format, Document, Vec<NodeId>, Vec<String>)> {
|
||||
/// objects (on its first layer, or in the layers the importer returned), their ids, the artboards
|
||||
/// the importer returned, and its warnings.
|
||||
fn read(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str, mode: Mode) -> Result<Read> {
|
||||
let m = plugin.manifest();
|
||||
let format = format(&export::format_id(&m.id)).filter(|f| f.read).ok_or_else(|| err(vectorcraft_plugins::Error::NotFound(m.id.clone())))?;
|
||||
let (ext, stem) = (extension(name), file_stem(name));
|
||||
@@ -234,15 +235,24 @@ fn read(
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let admit = |fx: &[vectorcraft_doc::Effect], n: &vectorcraft_doc::Node| crate::cmd::plugin::admit_effects_for(cmd, fx, n);
|
||||
let ids = objects::apply_output(&mut doc, &[], imported.objects, layer, &admit).map_err(|e| failed(mode, name, e))?;
|
||||
Ok((format, doc, ids, imported.warnings))
|
||||
let mut warnings = Vec::new();
|
||||
let (ids, artboards) = if imported.paths_only() {
|
||||
let paths = imported.objects.into_iter().filter_map(|o| if let ImportObject::Path(o) = o { Some(o) } else { None }).collect();
|
||||
(objects::apply_output(&mut doc, &[], paths, layer, &admit).map_err(|e| failed(mode, name, e))?, Vec::new())
|
||||
} else {
|
||||
let ids = build(&mut doc, imported.objects, imported.layers, &admit, &mut warnings).map_err(|e| failed(mode, name, e))?;
|
||||
(ids, imported.artboards)
|
||||
};
|
||||
warnings.splice(0..0, imported.warnings);
|
||||
Ok((format, doc, ids, artboards, warnings))
|
||||
}
|
||||
|
||||
/// The file `name` holding `bytes` read by importer `plugin` to place it, with `file.place`'s params
|
||||
/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects on its
|
||||
/// first layer, and its warnings. Importer `plugin`'s manifest must set `place`.
|
||||
/// `p` (errors of command `cmd`) → the importer's format, the document holding its objects in its
|
||||
/// layers, and its warnings; artboards the importer returned are left out. Importer `plugin`'s
|
||||
/// manifest must set `place`.
|
||||
pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value, cmd: &str) -> Result<(&'static Format, Document, Vec<String>)> {
|
||||
let (format, doc, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?;
|
||||
let (format, doc, _, _, warnings) = read(name, bytes, plugin, p, cmd, Mode::Place)?;
|
||||
Ok((format, doc, warnings))
|
||||
}
|
||||
|
||||
@@ -250,14 +260,148 @@ pub(crate) fn read_for_place(name: &str, bytes: &[u8], plugin: &Plugin, p: &Valu
|
||||
/// (`params`: the importer's own parameters) into a new document, its artboard the bounds of what
|
||||
/// the importer returned.
|
||||
pub(super) fn load(name: &str, bytes: &[u8], plugin: &Plugin, p: &Value) -> Result<Loaded> {
|
||||
let (format, mut doc, ids, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?;
|
||||
if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) {
|
||||
board.rect = artboard_rect(bounds);
|
||||
let (format, mut doc, ids, artboards, warnings) = read(name, bytes, plugin, p, C, Mode::Import)?;
|
||||
if artboards.is_empty() {
|
||||
if let (Some(bounds), Some(board)) = (doc.bounds_of(&ids, true), doc.artboards.first_mut()) {
|
||||
board.rect = artboard_rect(bounds);
|
||||
}
|
||||
} else {
|
||||
set_artboards(&mut doc, artboards);
|
||||
}
|
||||
doc.title = file_name(name);
|
||||
Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None })
|
||||
}
|
||||
|
||||
/// Puts `objects`, what an importer at plug-in API level 4 returned, into `doc`, a new document of
|
||||
/// one layer: in `layers`, bottom first, each holding the objects it lists in their order, or all in
|
||||
/// that one layer when there are none. Paths are made as a filter's new ones are (their effects let
|
||||
/// in by `admit`), type is laid out, and each image is stored in the document as a PNG of its
|
||||
/// pixels. A warning for type whose font isn't there, or doesn't have its style, goes to `warnings`.
|
||||
/// An object that reaches more than [`MAX_COORD`] from the origin is an error. Returns the objects'
|
||||
/// ids in order.
|
||||
fn build(
|
||||
doc: &mut Document,
|
||||
objects: Vec<ImportObject>,
|
||||
layers: Vec<import::OutLayer>,
|
||||
admit: objects::AdmitEffects,
|
||||
warnings: &mut Vec<String>,
|
||||
) -> std::result::Result<Vec<NodeId>, String> {
|
||||
let count = objects.len();
|
||||
let first = doc.layers.first().map(|l| (**l).clone());
|
||||
let first = first.unwrap_or_else(|| Node::layer(doc.alloc_id(), "Layer 1", LayerColor::Preset(0)));
|
||||
let mut owner = vec![0usize; count];
|
||||
for (li, l) in layers.iter().enumerate() {
|
||||
for &k in &l.objects {
|
||||
if let Some(o) = owner.get_mut(k) {
|
||||
*o = li;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut members: Vec<Vec<Arc<Node>>> = vec![Vec::new(); layers.len().max(1)];
|
||||
let mut ids = Vec::with_capacity(count);
|
||||
let mut fonts = std::collections::BTreeSet::new();
|
||||
for (i, o) in objects.into_iter().enumerate() {
|
||||
let at = format!("objects[{i}]");
|
||||
let node = match o {
|
||||
ImportObject::Path(o) => objects::new_object(doc, o, &at, admit).map_err(|e| e.to_string())?,
|
||||
ImportObject::Type(t) => {
|
||||
let node = type_node(doc, t);
|
||||
if let NodeKind::Text(t) = &node.kind {
|
||||
fonts.extend(t.runs.iter().flat_map(crate::cmd::fonts::run_fonts));
|
||||
}
|
||||
node
|
||||
}
|
||||
ImportObject::Image(im) => image_node(doc, im).map_err(|e| e.to_string())?,
|
||||
};
|
||||
if node.geometric_bounds().is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)) {
|
||||
return Err(format!("plug-in output: {at}: it reaches more than {MAX_COORD} pt from the origin"));
|
||||
}
|
||||
ids.push(node.id);
|
||||
if let Some(list) = owner.get(i).and_then(|&li| members.get_mut(li)) {
|
||||
list.push(Arc::new(node));
|
||||
}
|
||||
}
|
||||
let built: Vec<Arc<Node>> = if layers.is_empty() {
|
||||
let mut layer = first;
|
||||
if let Some(children) = layer.children_mut() {
|
||||
*children = members.into_iter().next().unwrap_or_default();
|
||||
}
|
||||
vec![Arc::new(layer)]
|
||||
} else {
|
||||
layers
|
||||
.into_iter()
|
||||
.zip(members)
|
||||
.enumerate()
|
||||
.map(|(li, (l, children))| {
|
||||
let mut layer = Node::layer(doc.alloc_id(), &l.name, LayerColor::Preset((li % LAYER_COLORS.len()) as u8));
|
||||
layer.visible = l.visible;
|
||||
layer.locked = l.locked;
|
||||
if let Some(c) = layer.children_mut() {
|
||||
*c = children;
|
||||
}
|
||||
Arc::new(layer)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
doc.layers = built;
|
||||
warnings.extend(crate::cmd::fonts::set_font_warning(fonts));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Point type `t` as a new node of `doc`, in [Normal Character Style] with the face, size and fill
|
||||
/// `t` gives, laid out.
|
||||
fn type_node(doc: &mut Document, t: import::OutType) -> Node {
|
||||
let mut style = crate::cmd::textstyles::normal_char_style(doc);
|
||||
style.font_version = None;
|
||||
style.font_axes.clear();
|
||||
style.font_family = t.font_family;
|
||||
match t.font_style {
|
||||
Some(s) => style.font_style = s,
|
||||
None => {
|
||||
style.font_style = CharStyle::default().font_style;
|
||||
crate::cmd::textedit::fit_font_style(&mut style);
|
||||
}
|
||||
}
|
||||
style.size = t.font_size;
|
||||
if let Some(fill) = t.fill {
|
||||
style.fill = fill;
|
||||
}
|
||||
let mut text = TextObject::point(Point::ZERO, &t.text, style);
|
||||
text.xf = t.transform;
|
||||
text.para = crate::cmd::create::new_type_para();
|
||||
text.system_layout = doc.setup.system_layout;
|
||||
crate::cmd::typecmd::refresh_bounds(&mut text);
|
||||
let mut n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(text)));
|
||||
n.name = t.name;
|
||||
n
|
||||
}
|
||||
|
||||
/// Image `im` as a new node of `doc`, its pixels stored in `doc` as a PNG.
|
||||
fn image_node(doc: &mut Document, im: import::OutImage) -> Result<Node> {
|
||||
let pixels = image::RgbaImage::from_raw(im.width, im.height, im.rgba).ok_or_else(|| err("the image's pixels don't match its size"))?;
|
||||
let stored = super::load::as_png(pixels, None, None)?;
|
||||
let image = ImageObject {
|
||||
key: stored.key.clone(),
|
||||
width: stored.width,
|
||||
height: stored.height,
|
||||
xf: im.transform,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
doc.images.insert(stored.key, stored.blob);
|
||||
let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(image)));
|
||||
n.name = im.name;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Gives `doc` the artboards `boards` an importer returned, in order, in place of its one.
|
||||
fn set_artboards(doc: &mut Document, boards: Vec<import::OutArtboard>) {
|
||||
let Some(template) = doc.artboards.first().cloned() else { return };
|
||||
doc.artboards =
|
||||
boards.into_iter().zip(1u32..).map(|(b, id)| vectorcraft_doc::Artboard { id, name: b.name, rect: b.rect, ..template.clone() }).collect();
|
||||
}
|
||||
|
||||
/// The artboard of art with bounds `r`: `r` within ±[`MAX_COORD`], at least 1 pt wide and high
|
||||
/// about its center (the artboard of a single line or point). A side that would pass the edge
|
||||
/// moves inward, so art at the edge keeps an artboard the document's edits accept.
|
||||
|
||||
@@ -576,23 +576,36 @@ struct ObjectOpacity {
|
||||
knockout_shape: bool,
|
||||
}
|
||||
|
||||
/// The series `id` belongs to when it is a graph series group or a path directly in one, as [`series_members`] finds
|
||||
/// it. Looked up through its parents, with no pass over the document.
|
||||
fn series_group_or_mark(doc: &Document, id: NodeId) -> Option<SeriesRef> {
|
||||
let node = doc.node(id)?;
|
||||
let chain = doc.ancestry(id)?;
|
||||
let parent = doc.node(*chain.iter().rev().nth(1)?)?;
|
||||
let in_graph = |group: &Node, graph: &Node| {
|
||||
let index = group.extras().series_index.and_then(|i| usize::try_from(i).ok())?;
|
||||
graph.extras().graph.as_deref().filter(|spec| index < series_count(spec)).map(|_| SeriesRef { graph: graph.id, group: group.id, index })
|
||||
};
|
||||
if let Some(r) = in_graph(node, parent) {
|
||||
return Some(r);
|
||||
}
|
||||
// Only the paths the graph draws again, not the copy of a graph design.
|
||||
if !matches!(node.kind, NodeKind::Path { .. }) {
|
||||
return None;
|
||||
}
|
||||
in_graph(parent, doc.node(*chain.iter().rev().nth(2)?)?)
|
||||
}
|
||||
|
||||
/// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object
|
||||
/// transparency of each of `edited` that is one of those, in order.
|
||||
/// transparency of each of `edited` that is one of those, in order. Each object is looked up through its parents
|
||||
/// ([`series_group_or_mark`]), so an edit of a few objects does not read the rest of the document.
|
||||
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> {
|
||||
if edited.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let members = series_members(doc);
|
||||
if members.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
edited
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let r = members.get(id)?;
|
||||
let r = series_group_or_mark(doc, *id)?;
|
||||
let group = r.group == *id;
|
||||
// Only the series group and the paths the graph draws again, not the copy of a graph design.
|
||||
let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?;
|
||||
let node = doc.node(*id)?;
|
||||
let mut look = ObjectOpacity {
|
||||
opacity: (node.opacity < 1.0).then_some(node.opacity),
|
||||
blend: (node.blend != BlendMode::Normal).then_some(node.blend),
|
||||
@@ -675,6 +688,25 @@ fn graph_labels(doc: &Document) -> HashMap<NodeId, (NodeId, Role)> {
|
||||
out
|
||||
}
|
||||
|
||||
/// The graph and kind of generated label `id`, as [`graph_labels`] finds it. Only the graphs among its parent and
|
||||
/// grandparent are read, with no pass over the document; `own` keeps each graph's labels read so far.
|
||||
fn graph_label_of(doc: &Document, id: NodeId, own: &mut HashMap<NodeId, HashMap<NodeId, Role>>) -> Option<(NodeId, Role)> {
|
||||
if !doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) {
|
||||
return None;
|
||||
}
|
||||
let chain = doc.ancestry(id)?;
|
||||
// The nearer graph first: [`graph_labels`] visits it later, so its entry is the one kept.
|
||||
for graph in chain.iter().rev().skip(1).take(2) {
|
||||
let Some(n) = doc.node(*graph) else { continue };
|
||||
let Some(spec) = n.extras().graph.as_deref() else { continue };
|
||||
let labels = own.entry(*graph).or_insert_with(|| own_labels(n, spec).into_iter().collect());
|
||||
if let Some(role) = labels.get(&id) {
|
||||
return Some((*graph, *role));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The generated labels of graph `n` (with spec `g`) and what each shows, as [`graph_labels`] finds them.
|
||||
fn own_labels(n: &Node, g: &GraphSpec) -> Vec<(NodeId, Role)> {
|
||||
let mut out = vec![];
|
||||
@@ -1725,9 +1757,9 @@ fn label_rows_of(doc: &Document, ids: &[NodeId]) -> Vec<(NodeId, Role, Option<ve
|
||||
if !ids.iter().any(|id| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))) {
|
||||
return vec![];
|
||||
}
|
||||
let labels = graph_labels(doc);
|
||||
let mut own = HashMap::new();
|
||||
let mut picked: Vec<(NodeId, Role, Option<vectorcraft_doc::LabelRows>)> = vec![];
|
||||
for (&(g, role), n) in ids.iter().rev().filter_map(|id| Some((labels.get(id)?, doc.node(*id)?))) {
|
||||
for ((g, role), n) in ids.iter().rev().filter_map(|id| Some((graph_label_of(doc, *id, &mut own)?, doc.node(*id)?))) {
|
||||
if !picked.iter().any(|(pg, pr, _)| *pg == g && *pr == role) {
|
||||
picked.push((g, role, label_rows(n)));
|
||||
}
|
||||
|
||||
@@ -398,21 +398,26 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'
|
||||
thread_local! {
|
||||
/// Tests: how many fills [`SelectionPaints`] read or took out on this thread.
|
||||
pub(crate) static PAINTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many stroke weights [`SelectionPaints`] read or took out on this thread.
|
||||
pub(crate) static WEIGHTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The objects that reading objects `ids` meets, one item each ([`SelectionPaints::reads_no_more_than`]):
|
||||
/// each id, and the contents of a group, a layer, a Live Paint group or a container inside a group,
|
||||
/// as [`painted`] expands them. An id with no object and a ruler guide count once each.
|
||||
/// as [`painted`] expands them. An id with no object and a ruler guide count once each. A type
|
||||
/// object counts once for each of its runs, since the stroke weights are read run by run.
|
||||
struct Reads<'a> {
|
||||
doc: &'a Document,
|
||||
ids: std::slice::Iter<'a, NodeId>,
|
||||
/// The contents not counted yet of the objects met, innermost last.
|
||||
left: Vec<std::slice::Iter<'a, std::sync::Arc<Node>>>,
|
||||
/// The runs not counted yet of the type object met last.
|
||||
runs: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reads<'a> {
|
||||
fn new(doc: &'a Document, ids: &'a [NodeId]) -> Self {
|
||||
Self { doc, ids: ids.iter(), left: vec![] }
|
||||
Self { doc, ids: ids.iter(), left: vec![], runs: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,6 +425,10 @@ impl Iterator for Reads<'_> {
|
||||
type Item = ();
|
||||
|
||||
fn next(&mut self) -> Option<()> {
|
||||
if self.runs > 0 {
|
||||
self.runs -= 1;
|
||||
return Some(());
|
||||
}
|
||||
loop {
|
||||
let (n, top) = match self.left.last_mut() {
|
||||
Some(contents) => match contents.next() {
|
||||
@@ -447,6 +456,9 @@ impl Iterator for Reads<'_> {
|
||||
if let Some(contents) = n.children().filter(|_| expand) {
|
||||
self.left.push(contents.iter());
|
||||
}
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
self.runs = t.runs.len().saturating_sub(1);
|
||||
}
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
@@ -618,6 +630,8 @@ impl SelectionPaints {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| r.style.stroke_layer().width).collect(),
|
||||
_ => n.appearance.stroke().map(|s| s.width).into_iter().collect(),
|
||||
};
|
||||
#[cfg(test)]
|
||||
WEIGHTS_READ.with(|c| c.set(c.get() + widths.len()));
|
||||
for w in widths {
|
||||
if add {
|
||||
self.weight.add(w, |a, b| a == b);
|
||||
|
||||
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Place…",
|
||||
["File"],
|
||||
Some("Cmd+Shift+P"),
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a c
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed
Line truncated
|
||||
has_doc,
|
||||
place
|
||||
),
|
||||
@@ -867,6 +867,38 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
|
||||
Affine::translate(c - natural.center())
|
||||
}
|
||||
};
|
||||
let mut retained = natural;
|
||||
match &loaded.art {
|
||||
Art::Vector { src, nodes, .. } => {
|
||||
let symbols = src.symbol_boxes();
|
||||
for node in nodes {
|
||||
node.walk(&mut |node| {
|
||||
if let Some(bounds) = node.geometric_bounds_with(&symbols) {
|
||||
retained = retained.union(bounds);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Art::Image(image, _) => {
|
||||
let (sx, sy) = pt_per_px(image.ppi);
|
||||
retained = retained.union(Rect::new(0.0, 0.0, f64::from(image.width) * sx, f64::from(image.height) * sy));
|
||||
}
|
||||
Art::Dcs(art) => {
|
||||
let pixels = Rect::new(0.0, 0.0, f64::from(art.img.width), f64::from(art.img.height));
|
||||
retained = retained.union(art.xf.transform_rect_bbox(pixels));
|
||||
if let Some(clip) = &art.clip {
|
||||
clip.walk(&mut |node| {
|
||||
if let Some(bounds) = node.geometric_bounds() {
|
||||
retained = retained.union(bounds);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Art::Text(_) | Art::Document(..) => {}
|
||||
}
|
||||
if !crate::sanity::rect_in_range(m.transform_rect_bbox(retained)) {
|
||||
return Err(bad(PLACE, "placed art lies outside the canvas"));
|
||||
}
|
||||
let parent = st.insertion_parent();
|
||||
let below = st.current_layer().or_else(|| parent.and_then(|p| st.doc.layer_of(p)));
|
||||
let link = loaded.link.take().filter(|_| bool_or(p, "link", true));
|
||||
|
||||
@@ -119,6 +119,9 @@ pub fn describe(p: &Plugin) -> Value {
|
||||
if !m.inputs.is_empty() {
|
||||
v["inputs"] = json!(m.inputs);
|
||||
}
|
||||
if !m.output_kinds.is_empty() {
|
||||
v["outputKinds"] = json!(m.output_kinds);
|
||||
}
|
||||
if !m.writes.is_empty() {
|
||||
v["writes"] = json!(m.writes);
|
||||
}
|
||||
@@ -2408,7 +2411,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List Plug-ins",
|
||||
[],
|
||||
None,
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1, 2 or 3), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\"|\"generator\" (a generator draws art from its parameters, see plugin.generate), author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), place?: true (an importer whose files file.place also reads, see file.place's importer), outputKinds?: [\"type\"|\"image\"|\"layer\"|\"artboard\"] (what an importer at API level 4 returns besides paths, see docs/plugins.md), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), writes?: [\"type\"|\"image\"|\"symbolInstance\"] (the kinds among inputs a filter may change, see plugin.run), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 to 4), runtime?: \"js\" and script?: its .js file name (a JavaScript filter, see docs/plugins.md), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), appearanceOutput?: true (a live effect whose pieces, fills and strokes may also have opacity, a blending mode and effects), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path?: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there), context?: [{menu: \"canvas\"|\"layers\", when?: \"selection\"|\"oneObject\"|\"typeObject\"|\"layerRow\"}] (the context menus that also list it)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), failed: [{file, error, from: \"store\"|\"folder\"}] (the plug-in files that didn't load in this process and that plugin.retry loads again: those of the plug-in store that didn't install, until they install or the store is loaded again, then those of the folder report's failed, without the disabled ones and ones skipped because another install or removal of their id came first), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
|
||||
always,
|
||||
list
|
||||
),
|
||||
|
||||
+126
-35
@@ -4,8 +4,9 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling, SymbolBoxes};
|
||||
use vectorcraft_geom::{Affine, Homography, Point, Rect, Vec2};
|
||||
use vectorcraft_tools::distort::project_node;
|
||||
|
||||
use super::edit::{outermost, selected_roots};
|
||||
use super::{
|
||||
@@ -21,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Free Distort",
|
||||
[],
|
||||
None,
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
|
||||
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); the corners of a type object's or symbol instance's box go exactly where the warp takes them too, and it stays type or an instance, drawn through the warp after any projection it had (the same errors, naming the object); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
|
||||
has_doc,
|
||||
distort
|
||||
),
|
||||
@@ -105,6 +106,21 @@ impl Projective {
|
||||
Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w)
|
||||
}
|
||||
|
||||
/// Whether the warp is a perspective map rather than an affine one.
|
||||
fn is_projective(&self) -> bool {
|
||||
let [.., g, h] = self.m;
|
||||
g != 0.0 || h != 0.0
|
||||
}
|
||||
|
||||
/// The warp as one page-to-page map, which [`Self::apply`] matches in front of the horizon.
|
||||
fn homography(&self) -> Homography {
|
||||
let [a, b, c, d, e, f, g, h] = self.m;
|
||||
let scale = |len: f64| if len.abs() > 1e-12 { 1.0 / len } else { 0.0 };
|
||||
let (sx, sy) = (scale(self.src.width()), scale(self.src.height()));
|
||||
let to_unit = Affine::new([sx, 0.0, 0.0, sy, -self.src.x0 * sx, -self.src.y0 * sy]) * self.pre;
|
||||
Homography([[a, b, c], [d, e, f], [g, h, 1.0]]).then_after(&Homography::from_affine(to_unit))
|
||||
}
|
||||
|
||||
/// Affine approximation at a point (for objects that can't be warped: text, images, symbols).
|
||||
fn affine_near(&self, p: Point) -> Affine {
|
||||
let eps = 1.0;
|
||||
@@ -127,6 +143,8 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
n.pin_gradients();
|
||||
// The children before these are left out of a group's or compound path's bounds.
|
||||
let skip = n.children().map_or(0, Vec::len) - n.editing_children().len();
|
||||
// Type and symbol instances drawn through the warp keep their gradients in their own art.
|
||||
let mut projected = false;
|
||||
let before = match &mut n.kind {
|
||||
NodeKind::Path { path, live, .. } => {
|
||||
let b = path.bounds();
|
||||
@@ -156,6 +174,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
}
|
||||
b
|
||||
}
|
||||
// Type and symbol instances keep their art and are drawn through the warp, after the
|
||||
// projection they had ([`project_node`]), so the corners of their box follow it exactly;
|
||||
// [`distort`] has checked that the projection stays finite and their corners in front of
|
||||
// the horizon.
|
||||
NodeKind::Text(_) | NodeKind::SymbolInstance { .. } if pr.is_projective() => {
|
||||
let b = n.geometric_bounds();
|
||||
projected = project_node(n, &pr.homography());
|
||||
b
|
||||
}
|
||||
_ => {
|
||||
// No editable points: the affine approximation (which maps the gradients too).
|
||||
let b = n.geometric_bounds();
|
||||
@@ -171,7 +198,9 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
|
||||
if let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) {
|
||||
warp_node(Arc::make_mut(&mut m.art), pr);
|
||||
}
|
||||
n.appearance.warp_gradients(&|p| pr.affine_near(p));
|
||||
if !projected {
|
||||
n.appearance.warp_gradients(&|p| pr.affine_near(p));
|
||||
}
|
||||
before
|
||||
}
|
||||
|
||||
@@ -199,17 +228,19 @@ fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(us
|
||||
})
|
||||
}
|
||||
|
||||
/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`]
|
||||
/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with
|
||||
/// why.
|
||||
fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> {
|
||||
/// The first image, type object or symbol instance in `n` (its children and the art of linked
|
||||
/// opacity masks, as [`warp_node`] reaches them) whose corners `pr` would fold, collapse or carry
|
||||
/// past the warp's horizon, or type being edited flat, with why. `symbols` measures the boxes of
|
||||
/// symbol instances.
|
||||
fn unwarpable(n: &Node, pr: &Projective, symbols: &SymbolBoxes) -> Option<(vectorcraft_doc::NodeId, Cornered, Unwarpable)> {
|
||||
if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) {
|
||||
if !q.iter().all(|p| pr.in_front(*p)) {
|
||||
return Some((n.id, Unwarpable::Horizon));
|
||||
return Some((n.id, Cornered::Image, Unwarpable::Horizon));
|
||||
}
|
||||
if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) {
|
||||
return Some((
|
||||
n.id,
|
||||
Cornered::Image,
|
||||
match e {
|
||||
vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex,
|
||||
vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow,
|
||||
@@ -217,24 +248,79 @@ fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeI
|
||||
));
|
||||
}
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr))
|
||||
// Type and symbol instances are drawn through the warp ([`warp_node`]): their box's corners
|
||||
// must stay in front of its horizon, and the projection they end with must be one that draws.
|
||||
if let Some(kind) = Cornered::of(n).filter(|k| *k != Cornered::Image && pr.is_projective()) {
|
||||
if kind == Cornered::Type && n.extras().perspective.as_deref().is_some_and(|p| p.editing) {
|
||||
return Some((n.id, kind, Unwarpable::EditingFlat));
|
||||
}
|
||||
if n.drawn_corners(symbols).is_some_and(|q| !q.iter().all(|p| pr.in_front(*p))) {
|
||||
return Some((n.id, kind, Unwarpable::Horizon));
|
||||
}
|
||||
let had = n.extras().perspective.as_deref().and_then(|p| p.homography()).unwrap_or(Homography::IDENTITY);
|
||||
let Some(after) = pr.homography().checked_then_after(&had).and_then(|h| Homography::from_array(h.to_array())) else {
|
||||
return Some((n.id, kind, Unwarpable::TooNarrow));
|
||||
};
|
||||
// The map it ends with must place its flat corners by the rules it is drawn with.
|
||||
let flat = match n.extras().perspective.is_some() {
|
||||
true => {
|
||||
let mut flat = n.clone();
|
||||
flat.extras_mut().perspective = None;
|
||||
flat.drawn_corners(symbols)
|
||||
}
|
||||
false => n.drawn_corners(symbols),
|
||||
};
|
||||
if flat.is_some_and(|q| q.iter().any(|p| after.apply(*p).is_none())) {
|
||||
return Some((n.id, kind, Unwarpable::Horizon));
|
||||
}
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(|c| unwarpable(c, pr, symbols))
|
||||
}
|
||||
|
||||
/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity
|
||||
/// masks).
|
||||
fn first_image(n: &Node) -> Option<vectorcraft_doc::NodeId> {
|
||||
if matches!(n.kind, NodeKind::Image(_)) {
|
||||
return Some(n.id);
|
||||
/// The first image, type object or symbol instance in `n` that [`warp_node`] reaches (its children
|
||||
/// and the art of linked opacity masks), whose corners follow the warp exactly.
|
||||
fn first_cornered(n: &Node) -> Option<(vectorcraft_doc::NodeId, Cornered)> {
|
||||
if let Some(kind) = Cornered::of(n) {
|
||||
return Some((n.id, kind));
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(first_cornered)
|
||||
}
|
||||
|
||||
/// The objects whose corners follow a distort exactly.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Cornered {
|
||||
Image,
|
||||
Type,
|
||||
Symbol,
|
||||
}
|
||||
|
||||
impl Cornered {
|
||||
fn of(n: &Node) -> Option<Self> {
|
||||
match n.kind {
|
||||
NodeKind::Image(_) => Some(Self::Image),
|
||||
NodeKind::Text(_) => Some(Self::Type),
|
||||
NodeKind::SymbolInstance { .. } => Some(Self::Symbol),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The object's name in an error.
|
||||
fn noun(self) -> &'static str {
|
||||
match self {
|
||||
Self::Image => "image",
|
||||
Self::Type => "type object",
|
||||
Self::Symbol => "symbol instance",
|
||||
}
|
||||
}
|
||||
warped_parts(n).into_iter().find_map(first_image)
|
||||
}
|
||||
|
||||
/// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups
|
||||
/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other
|
||||
/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole.
|
||||
/// and compound paths, and the art of a linked opacity mask on those, paths, images, type and
|
||||
/// symbol instances. Other objects (blends, envelopes, repeats and the rest) take the warp's affine
|
||||
/// approximation whole.
|
||||
fn warped_parts(n: &Node) -> Vec<&Node> {
|
||||
let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. });
|
||||
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_));
|
||||
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_) | NodeKind::Text(_) | NodeKind::SymbolInstance { .. });
|
||||
let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c);
|
||||
let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art);
|
||||
children.chain(mask).collect()
|
||||
@@ -246,9 +332,11 @@ pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId)
|
||||
bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0))
|
||||
}
|
||||
|
||||
/// Why an image cannot follow the corners of a distort.
|
||||
/// Why an image, type object or symbol instance cannot follow the corners of a distort.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Unwarpable {
|
||||
/// Type is being edited flat in Edit Text.
|
||||
EditingFlat,
|
||||
/// Its corners would fold over, meet or fall on one line.
|
||||
NotConvex,
|
||||
/// A corner would cross the warp's horizon.
|
||||
@@ -257,14 +345,16 @@ enum Unwarpable {
|
||||
TooNarrow,
|
||||
}
|
||||
|
||||
/// The error of `object.distort` when image `id` cannot follow its corners.
|
||||
fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError {
|
||||
/// The error of `object.distort` when object `id` (`kind`) cannot follow its corners.
|
||||
fn unwarpable_error(id: vectorcraft_doc::NodeId, kind: Cornered, why: Unwarpable) -> EngineError {
|
||||
const C: &str = "object.distort";
|
||||
let noun = kind.noun();
|
||||
match why {
|
||||
Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
|
||||
Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
|
||||
Unwarpable::EditingFlat => bad(C, format!("{noun} {} cannot be distorted this way: it is being edited flat in Edit Text", id.0)),
|
||||
Unwarpable::NotConvex => bad(C, format!("{noun} {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
|
||||
Unwarpable::Horizon => bad(C, format!("{noun} {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
|
||||
Unwarpable::TooNarrow => {
|
||||
bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
|
||||
bad(C, format!("{noun} {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,25 +401,26 @@ fn distort(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(ids_json);
|
||||
}
|
||||
let pr = Projective::from_box(src, [tl, tr, br, bl]);
|
||||
// An image's corners follow the handles exactly, so they must stay a convex shape: nothing
|
||||
// changes when one would not.
|
||||
// The corners of an image, a type object or a symbol instance follow the handles exactly, so
|
||||
// they must stay a convex shape: nothing changes when one would not.
|
||||
let doc = &s.doc()?.doc;
|
||||
// Corners that do not make a convex shape give no perspective map (the warp falls back to an
|
||||
// affine one), so an image cannot follow them.
|
||||
// affine one), so such an object cannot follow them.
|
||||
if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err()
|
||||
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
|
||||
&& let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered)
|
||||
{
|
||||
return Err(unwarpable_error(id, Unwarpable::NotConvex));
|
||||
return Err(unwarpable_error(id, kind, Unwarpable::NotConvex));
|
||||
}
|
||||
// Corners so close together that the map falls back to an affine one: the box's corners do
|
||||
// not reach the handles, so an image cannot follow them either.
|
||||
// not reach the handles, so such an object cannot follow them either.
|
||||
if !reaches_corners(src, [tl, tr, br, bl])
|
||||
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
|
||||
&& let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered)
|
||||
{
|
||||
return Err(unwarpable_error(id, Unwarpable::TooNarrow));
|
||||
return Err(unwarpable_error(id, kind, Unwarpable::TooNarrow));
|
||||
}
|
||||
if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) {
|
||||
return Err(unwarpable_error(id, why));
|
||||
let symbols = doc.symbol_boxes();
|
||||
if let Some((id, kind, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable(n, &pr, &symbols)) {
|
||||
return Err(unwarpable_error(id, kind, why));
|
||||
}
|
||||
s.edit("Free Distort", |d, _| {
|
||||
for id in &ids {
|
||||
|
||||
@@ -59,11 +59,12 @@
|
||||
//! A center outside the canvas after coordinate conversion throws a `RangeError`.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so, and `reflect`
|
||||
//! leaves them out.
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an
|
||||
//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change
|
||||
//! nothing, even for the value the object has. The exception is `opacity` given the value the
|
||||
//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps
|
||||
//! another opacity it would still change the graph, so it is refused too. Its `name` and `note`
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or
|
||||
//! `height` to an object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit`
|
||||
//! and change nothing, even for the value the object has. The exception is `opacity` or
|
||||
//! `blendingMode` given the value the object has when that changes nothing; on a graph's mark or
|
||||
//! label whose series or kind keeps another opacity or blend mode it would still change the graph,
|
||||
//! so it is refused too. Its `name` and `note`
|
||||
//! still change. An object that is hidden or locked itself, or is in a hidden or locked group,
|
||||
//! takes them.
|
||||
//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives.
|
||||
@@ -81,6 +82,7 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_js::{
|
||||
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
|
||||
@@ -2031,6 +2033,56 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
|
||||
}
|
||||
|
||||
/// The members of `BlendModes` with the blend mode each one names.
|
||||
const BLEND_MODES: [(&str, BlendMode); 16] = [
|
||||
("COLORBLEND", BlendMode::Color),
|
||||
("COLORBURN", BlendMode::ColorBurn),
|
||||
("COLORDODGE", BlendMode::ColorDodge),
|
||||
("DARKEN", BlendMode::Darken),
|
||||
("DIFFERENCE", BlendMode::Difference),
|
||||
("EXCLUSION", BlendMode::Exclusion),
|
||||
("HARDLIGHT", BlendMode::HardLight),
|
||||
("HUE", BlendMode::Hue),
|
||||
("LIGHTEN", BlendMode::Lighten),
|
||||
("LUMINOSITY", BlendMode::Luminosity),
|
||||
("MULTIPLY", BlendMode::Multiply),
|
||||
("NORMAL", BlendMode::Normal),
|
||||
("OVERLAY", BlendMode::Overlay),
|
||||
("SATURATIONBLEND", BlendMode::Saturation),
|
||||
("SCREEN", BlendMode::Screen),
|
||||
("SOFTLIGHT", BlendMode::SoftLight),
|
||||
];
|
||||
|
||||
fn item_blending_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
read_item(h, a, |_, n| {
|
||||
let name = BLEND_MODES.iter().find(|(_, m)| *m == n.blend).map_or("NORMAL", |(name, _)| name);
|
||||
Ok(text(format!("BlendModes.{name}")))
|
||||
})
|
||||
}
|
||||
|
||||
/// `blendingMode = BlendModes.<MODE>`: the object's own blend mode, as `object.setProps` sets it.
|
||||
/// The mode the object already has may be assigned while its layer is hidden or locked, unless it
|
||||
/// would still replace the blend mode a graph keeps for the item's series or kind.
|
||||
fn item_set_blending_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) => s.strip_prefix("BlendModes.").and_then(|m| BLEND_MODES.iter().find(|(name, _)| *name == m)).map(|(_, mode)| *mode),
|
||||
_ => None,
|
||||
};
|
||||
let mode = mode.ok_or_else(|| HostError::Type("blendingMode needs a BlendModes value".into()))?;
|
||||
let item = this_item(h, a)?;
|
||||
let (same, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let same = d.node(item.id).is_some_and(|n| n.blend == mode);
|
||||
let keeps_other =
|
||||
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
|
||||
(same, keeps_other)
|
||||
});
|
||||
if !same || keeps_other {
|
||||
refuse_protected_edit(h, item)?;
|
||||
}
|
||||
set_props(h, a, |_| false, json!({"blend": mode.label()}))
|
||||
}
|
||||
|
||||
fn item_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
Ok(Data::Bool(with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id))))
|
||||
@@ -2550,6 +2602,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
realm.define_host_object("BlendModes", blend_modes)?;
|
||||
variables::define_enums(realm)?;
|
||||
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
let l = link;
|
||||
@@ -2706,6 +2760,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("locked", property(l, item_locked, item_set_locked), typed("boolean")),
|
||||
("selected", property(l, item_selected, item_set_selected), typed("boolean")),
|
||||
("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
|
||||
("blendingMode", property(l, item_blending_mode, item_set_blending_mode), typed("BlendModes")),
|
||||
("position", property(l, item_position, item_set_position), typed("Array")),
|
||||
("left", property(l, item_left, item_set_left), typed("number")),
|
||||
("top", property(l, item_top, item_set_top), typed("number")),
|
||||
@@ -2731,7 +2786,6 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
page_item.extend(
|
||||
[
|
||||
"artworkKnockout",
|
||||
"blendingMode",
|
||||
"isIsolated",
|
||||
"layer",
|
||||
"pixelAligned",
|
||||
|
||||
@@ -788,3 +788,28 @@ fn deselecting_a_small_group_beside_a_large_one_takes_out_only_its_objects() {
|
||||
let fills = read() - before;
|
||||
assert!(fills <= 100, "read or took out {fills} fills");
|
||||
}
|
||||
|
||||
/// Taking a type object of 10,000 runs out of a selection that keeps two squares reads the two
|
||||
/// squares' stroke weights again instead of taking the 10,000 run weights out of them.
|
||||
#[test]
|
||||
fn deselecting_type_of_many_runs_reads_the_objects_left() {
|
||||
let mut s = session(3, |d, k| match k {
|
||||
0 => {
|
||||
let style = vectorcraft_doc::CharStyle::default();
|
||||
let mut t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(10.0, 40.0), "x", style.clone());
|
||||
t.runs = (0..10_000).map(|_| vectorcraft_doc::TextRun::new("x", style.clone())).collect();
|
||||
Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)))
|
||||
}
|
||||
_ => square(d, k),
|
||||
});
|
||||
let ids = layer(&s, 0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
|
||||
assert!(selected(&s, &ids));
|
||||
let read = || crate::cmd::WEIGHTS_READ.with(std::cell::Cell::get);
|
||||
let before = read();
|
||||
s.execute("select.toggle", &json!({"id": ids[0].0})).unwrap();
|
||||
assert!(selected(&s, &ids[1..]));
|
||||
let weights = read() - before;
|
||||
assert!(weights <= 100, "read or took out {weights} stroke weights");
|
||||
}
|
||||
@@ -394,6 +394,52 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() {
|
||||
assert_eq!(kept(&s), None);
|
||||
}
|
||||
|
||||
/// A blend mode a graph mark or axis label already has still replaces the blend mode another object
|
||||
/// of its series or kind left on the graph, and is refused in a hidden or locked layer.
|
||||
#[test]
|
||||
fn a_blend_mode_a_graph_mark_or_label_already_has_replaces_the_one_the_graph_keeps() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
|
||||
let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let spec = |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().clone();
|
||||
let kept_mark = |s: &Session| spec(s).series_paints.first().and_then(|p| p.blend);
|
||||
let kept_label = |s: &Session| spec(s).label_styles.values_rows.as_ref().and_then(|r| r.paint.blend);
|
||||
let graph = s.active().unwrap().doc.node(id).unwrap().clone();
|
||||
let group = graph.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone();
|
||||
let marks: Vec<NodeId> = group.children().unwrap().iter().map(|m| m.id).collect();
|
||||
let axes = graph.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Axes")).unwrap().clone();
|
||||
// The value axis numbers come first among the Axes group's labels.
|
||||
let labels: Vec<NodeId> = axes.children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Text(_))).map(|c| c.id).collect();
|
||||
s.execute("object.setProps", &json!({"id": marks[0].0, "blend": "Multiply"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"id": labels[0].0, "blend": "Screen"})).unwrap();
|
||||
let both = (Some(vectorcraft_color::BlendMode::Multiply), Some(vectorcraft_color::BlendMode::Screen));
|
||||
assert_eq!((kept_mark(&s), kept_label(&s)), both);
|
||||
s.execute("object.setProps", &json!({"id": marks[1].0, "name": "mark"})).unwrap();
|
||||
s.execute("object.setProps", &json!({"id": labels[1].0, "name": "label"})).unwrap();
|
||||
let layer = s.active().unwrap().doc.layers[0].id;
|
||||
for (on, off) in [
|
||||
(json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})),
|
||||
(json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})),
|
||||
] {
|
||||
s.execute("object.setProps", &on).unwrap();
|
||||
for name in ["mark", "label"] {
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, &format!("var m = app.activeDocument.pageItems.getByName('{name}'); m.blendingMode = m.blendingMode;"));
|
||||
assert!(e.contains("Cannot edit"), "{on} {name}: {e}");
|
||||
assert_eq!((kept_mark(&s), kept_label(&s)), both, "{on} {name}");
|
||||
assert_eq!(undo_steps(&s), steps, "{on} {name}");
|
||||
}
|
||||
s.execute("object.setProps", &off).unwrap();
|
||||
}
|
||||
log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems; p.getByName('mark').blendingMode = BlendModes.NORMAL; p.getByName('label').blendingMode = BlendModes.NORMAL;",
|
||||
);
|
||||
assert_eq!((kept_mark(&s), kept_label(&s)), (None, None));
|
||||
}
|
||||
|
||||
/// `app.redraw()` returns `undefined` and leaves the art and the undo history as they were.
|
||||
#[test]
|
||||
fn redraw_returns_and_changes_nothing() {
|
||||
@@ -431,6 +477,51 @@ fn assigning_the_reported_opacity_changes_nothing() {
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
/// `blendingMode` reads and sets the object's own blend mode as a `BlendModes` value; the mode it
|
||||
/// already has adds no undo step, and any other value throws and changes nothing.
|
||||
#[test]
|
||||
fn blending_mode_reads_and_sets_the_objects_blend_mode() {
|
||||
let (mut s, a, b) = doc();
|
||||
let blend = |s: &Session, id: NodeId| s.active().unwrap().doc.node(id).unwrap().blend;
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[1]; vc.log(i.blendingMode);\
|
||||
i.blendingMode = BlendModes.MULTIPLY; vc.log(i.blendingMode);\
|
||||
vc.log([i.hasOwnProperty('blendingMode'), BlendModes.SATURATIONBLEND, BlendModes.COLORBLEND]);",
|
||||
);
|
||||
assert_eq!(out[..2], [json!("BlendModes.NORMAL"), json!("BlendModes.MULTIPLY")]);
|
||||
assert_eq!(out[2], json!([true, "BlendModes.SATURATIONBLEND", "BlendModes.COLORBLEND"]));
|
||||
assert_ne!(blend(&s, a), blend(&s, b), "only the assigned object changed");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
|
||||
let (before, steps) = (blend(&s, a), undo_steps(&s));
|
||||
log(&mut s, "var i = app.activeDocument.pageItems[1]; i.blendingMode = BlendModes.MULTIPLY; i.blendingMode = i.blendingMode;");
|
||||
assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "the mode the object has adds no step");
|
||||
// Two modes the help page names with a suffix set the modes the Transparency panel calls Color
|
||||
// and Saturation.
|
||||
log(&mut s, "var p = app.activeDocument.pageItems; p[1].blendingMode = BlendModes.COLORBLEND; p[0].blendingMode = BlendModes.SATURATIONBLEND;");
|
||||
assert_eq!((blend(&s, a).label(), blend(&s, b).label()), ("Color", "Saturation"));
|
||||
let (before, steps) = (blend(&s, a), undo_steps(&s));
|
||||
for value in
|
||||
["'BlendModes.SCREEN '", "'MULTIPLY'", "'Multiply'", "'BlendModes.multiply'", "'BlendModes.NOPE'", "5", "null", "ZOrderMethod.BRINGTOFRONT"]
|
||||
{
|
||||
// The error is caught in the script, so the run does not roll back and the mode read right
|
||||
// after it is the one the setter left.
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var i = app.activeDocument.pageItems[1], e = '';\
|
||||
try {{ i.blendingMode = {value}; }} catch (x) {{ e = String(x); }}\
|
||||
vc.log(e); vc.log(i.blendingMode);"
|
||||
),
|
||||
);
|
||||
let e = out[0].as_str().unwrap_or_default();
|
||||
assert!(e.contains("blendingMode needs a BlendModes value"), "{value}: {e}");
|
||||
assert_eq!(out[1], json!("BlendModes.COLORBLEND"), "{value}");
|
||||
assert_eq!((blend(&s, a), undo_steps(&s)), (before, steps), "{value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_assignment_is_atomic_across_invalid_items() {
|
||||
let (mut s, a, b) = doc();
|
||||
@@ -1138,13 +1229,13 @@ fn a_startup_preset_alone_gives_its_first_size() {
|
||||
fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
|
||||
let (mut s, _, _) = doc();
|
||||
for source in
|
||||
["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"]
|
||||
["app.activeDocument.pageItems[0].isIsolated;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"]
|
||||
{
|
||||
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
|
||||
}
|
||||
assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet"));
|
||||
// A deleted item or an earlier run's document is stale first.
|
||||
let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.blendingMode;");
|
||||
let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.isIsolated;");
|
||||
assert!(e.contains("Stale page item"), "{e}");
|
||||
run(&mut s, "#targetengine keep\nvar d = app.activeDocument;").unwrap();
|
||||
let e = failure(&mut s, "#targetengine keep\nd.layers;");
|
||||
@@ -1923,7 +2014,7 @@ fn unsupported_members_say_so() {
|
||||
|
||||
/// A script that names each visible selected object after its place in `app.selection`, testing
|
||||
/// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not
|
||||
/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is
|
||||
/// available yet, such as `isIsolated`, is read only when `hasOwnProperty` reports it, so it is
|
||||
/// never read.
|
||||
const NAME_PICKED: &str = "\
|
||||
var picked = app.selection, k = picked.length, named = 0;\
|
||||
@@ -1931,7 +2022,7 @@ const NAME_PICKED: &str = "\
|
||||
while (k--) {\
|
||||
var obj = picked[k];\
|
||||
var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\
|
||||
if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\
|
||||
if (obj.hasOwnProperty('isIsolated') && obj.isIsolated) usable = false;\
|
||||
if (usable) { obj.name = 'picked ' + k; named += 1; }\
|
||||
}\
|
||||
if (picked.length && named < picked.length) alert('Some objects were skipped.');";
|
||||
@@ -2010,9 +2101,9 @@ fn page_items_report_their_available_members_as_their_own() {
|
||||
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
|
||||
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
|
||||
app.hasOwnProperty('activeDocument')]);\
|
||||
vc.log([p.hasOwnProperty('blendingMode'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('rotate'), d.hasOwnProperty('layers'),\
|
||||
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
|
||||
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('blendingMode')]);",
|
||||
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);",
|
||||
);
|
||||
assert_eq!(out[0], json!([true, true, true, true, true, true, true]));
|
||||
// Members that are not available yet, unknown names and inherited ones are not the object's own.
|
||||
@@ -2141,7 +2232,7 @@ fn a_collection_read_with_a_name_gives_the_named_object() {
|
||||
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]);
|
||||
}
|
||||
|
||||
/// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or
|
||||
/// `opacity`, `blendingMode`, `hidden`, `locked` and the position and size setters on an object in a hidden or
|
||||
/// locked layer throw and the run changes nothing, while its name and note still change; an object
|
||||
/// that is hidden or locked itself takes them.
|
||||
#[test]
|
||||
@@ -2161,6 +2252,7 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() {
|
||||
// `hidden` and `locked` are refused even when the value is the one the object has.
|
||||
for set in [
|
||||
"opacity = 50",
|
||||
"blendingMode = BlendModes.MULTIPLY",
|
||||
"hidden = true",
|
||||
"hidden = false",
|
||||
"locked = true",
|
||||
@@ -2182,9 +2274,9 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() {
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var c = app.activeDocument.pageItems.getByName('closed'); c.note = 'n'; c.name = 'renamed'; c.opacity = c.opacity;\
|
||||
vc.log([c.name, c.note, c.opacity]); c.name = 'closed'; c.note = '';",
|
||||
c.blendingMode = c.blendingMode; vc.log([c.name, c.note, c.opacity, c.blendingMode]); c.name = 'closed'; c.note = '';",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["renamed", "n", 100])], "{on}");
|
||||
assert_eq!(out, vec![json!(["renamed", "n", 100, "BlendModes.NORMAL"])], "{on}");
|
||||
s.execute("object.setProps", &off).unwrap();
|
||||
}
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap();
|
||||
@@ -2192,9 +2284,11 @@ fn setters_refuse_art_in_a_hidden_or_locked_layer() {
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems; p.getByName('locked').opacity = 50; p.getByName('free').opacity = 40;\
|
||||
vc.log([p.getByName('locked').opacity, p.getByName('free').opacity]);",
|
||||
p.getByName('locked').blendingMode = BlendModes.SCREEN; p.getByName('free').blendingMode = BlendModes.DARKEN;\
|
||||
vc.log([p.getByName('locked').opacity, p.getByName('free').opacity, p.getByName('locked').blendingMode,\
|
||||
p.getByName('free').blendingMode]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([50, 40])]);
|
||||
assert_eq!(out, vec![json!([50, 40, "BlendModes.SCREEN", "BlendModes.DARKEN"])]);
|
||||
}
|
||||
|
||||
/// `name` takes a number or a Boolean as the text `String` gives it, and nothing else.
|
||||
|
||||
@@ -1234,6 +1234,166 @@ fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_recor
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
}
|
||||
|
||||
/// A type object or (`symbol`) a symbol instance made of a 100 × 60 rectangle, selected alone.
|
||||
fn type_or_instance(s: &mut Session, symbol: bool) -> NodeId {
|
||||
let r = if symbol {
|
||||
rect(s, 20.0, 30.0, 100.0, 60.0);
|
||||
s.execute("symbol.new", &json!({"name": "Box"})).unwrap()
|
||||
} else {
|
||||
s.execute("text.create", &json!({"x": 20, "y": 80, "text": "Distort", "size": 40})).unwrap()
|
||||
};
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Where the corners of `id`'s box are drawn (top left, top right, bottom right, bottom left).
|
||||
fn drawn_corners(s: &Session, id: NodeId) -> [Point; 4] {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
doc.node(id).unwrap().drawn_corners(&doc.symbol_boxes()).unwrap()
|
||||
}
|
||||
|
||||
fn assert_near_corners(got: [Point; 4], want: [Point; 4]) {
|
||||
for (g, w) in got.iter().zip(want) {
|
||||
assert!(g.distance(w) < 1e-6, "{got:?} against {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Perspective Distort and Free Distort put the corners of a type object's box and of a symbol
|
||||
/// instance's box exactly on the handles, in one undo step: the object stays type or an instance,
|
||||
/// drawn through the warp, it is bounded by those corners, a move takes them along, and undo gives
|
||||
/// back the flat object.
|
||||
#[test]
|
||||
fn distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles() {
|
||||
// Perspective Distort, then Free Distort, as fractions of the box.
|
||||
let quads = [[(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)], [(0.1, 0.05), (0.9, 0.0), (1.2, 1.1), (0.0, 1.0)]];
|
||||
for symbol in [false, true] {
|
||||
for quad in quads {
|
||||
let mut s = session();
|
||||
let id = type_or_instance(&mut s, symbol);
|
||||
let b = bounds(&s, id);
|
||||
let flat = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y));
|
||||
assert_near_corners(drawn_corners(&s, id), flat);
|
||||
let want = quad.map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height()));
|
||||
let undo = undo_len(&s);
|
||||
s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap();
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
assert_near_corners(drawn_corners(&s, id), want);
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Text(_) | vectorcraft_doc::NodeKind::SymbolInstance { .. }), "{:?}", n.kind);
|
||||
assert!(n.projection().is_some());
|
||||
let got = bounds(&s, id);
|
||||
let (xs, ys) = (want.map(|p| p.x), want.map(|p| p.y));
|
||||
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
|
||||
assert!(
|
||||
near(got.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(got.x1, xs.iter().copied().fold(f64::MIN, f64::max)),
|
||||
"{got:?}"
|
||||
);
|
||||
assert!(
|
||||
near(got.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(got.y1, ys.iter().copied().fold(f64::MIN, f64::max)),
|
||||
"{got:?}"
|
||||
);
|
||||
s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap();
|
||||
assert_near_corners(drawn_corners(&s, id), want.map(|p| p + Vec2::new(10.0, 20.0)));
|
||||
// Distorted type opens flat in Edit Text.
|
||||
assert_eq!(s.execute("perspective.editText", &json!({"id": id.0})).is_ok(), !symbol);
|
||||
if !symbol {
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().projection().is_none());
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
assert_near_corners(drawn_corners(&s, id), want.map(|p| p + Vec2::new(10.0, 20.0)));
|
||||
}
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
if !symbol {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(id).unwrap().projection().is_none());
|
||||
assert_near_corners(drawn_corners(&s, id), flat);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Distorted together with paths, the corners of a type object's box and of a symbol instance's
|
||||
/// box follow the same warp as the anchors of a path drawn on that box.
|
||||
#[test]
|
||||
fn distort_moves_type_and_symbol_instances_with_a_path_as_one() {
|
||||
for symbol in [false, true] {
|
||||
let mut s = session();
|
||||
let id = type_or_instance(&mut s, symbol);
|
||||
let b = bounds(&s, id);
|
||||
// A path on the object's box, and one beside it so that the box is not the selection's.
|
||||
let frame = rect(&mut s, b.x0, b.y0, b.width(), b.height());
|
||||
let side = rect(&mut s, b.x1 + 50.0, b.y0 - 40.0, 80.0, 80.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0, frame.0, side.0]})).unwrap();
|
||||
let all = s.doc().unwrap().doc.bounds_of(&[id, frame, side], false).unwrap();
|
||||
let corners = [[all.x0 + 30.0, all.y0], [all.x1 - 10.0, all.y0 + 20.0], [all.x1 + 40.0, all.y1], [all.x0, all.y1 - 5.0]];
|
||||
s.execute("object.distort", &json!({ "corners": corners })).unwrap();
|
||||
let anchors = match &s.doc().unwrap().doc.node(frame).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Path { path, .. } => path.subpaths[0].anchors.iter().map(|a| a.p).collect::<Vec<_>>(),
|
||||
k => panic!("not a path: {k:?}"),
|
||||
};
|
||||
let got = drawn_corners(&s, id);
|
||||
// The rectangle's first anchor may be any of its corners: each drawn corner is one of them.
|
||||
for c in got {
|
||||
assert!(anchors.iter().any(|p| p.distance(c) < 1e-6), "{got:?} against {anchors:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Corners that would carry a type object's or a symbol instance's box past the warp's horizon,
|
||||
/// or fold it over, are refused, and nothing changes.
|
||||
#[test]
|
||||
fn distort_refuses_corners_type_and_symbol_instances_cannot_follow() {
|
||||
for symbol in [false, true] {
|
||||
let mut s = session();
|
||||
let id = type_or_instance(&mut s, symbol);
|
||||
let noun = if symbol { "symbol instance" } else { "type object" };
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
|
||||
// The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at
|
||||
// y = 15, across the object.
|
||||
let e =
|
||||
s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("{noun} {}", id.0)) && e.contains("horizon"), "{e}");
|
||||
let b = bounds(&s, id);
|
||||
let folded = [[b.x0, b.y0], [b.x1, b.y1], [b.x1, b.y0], [b.x0, b.y1]];
|
||||
let e = s.execute("object.distort", &json!({ "corners": folded })).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("{noun} {}", id.0)) && e.contains("convex"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
// Near the edge of the canvas, the corners still reach the handles.
|
||||
s.execute("object.move", &json!({"dx": 0, "dy": 3.9e6})).unwrap();
|
||||
let b = bounds(&s, id);
|
||||
let want = [(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height()));
|
||||
s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap();
|
||||
let got = drawn_corners(&s, id);
|
||||
assert!(got.iter().zip(want).all(|(g, w)| g.distance(w) < 1e-3), "{got:?} against {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Projective distort refuses type being edited flat without changing the document or history;
|
||||
/// the same warp works after Edit Text ends.
|
||||
#[test]
|
||||
fn distort_refuses_type_being_edited_flat() {
|
||||
let mut s = session();
|
||||
let id = type_or_instance(&mut s, false);
|
||||
let b = bounds(&s, id);
|
||||
let corners = [(0.2, 0.0), (0.8, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| [b.x0 + u * b.width(), b.y0 + v * b.height()]);
|
||||
let p = json!({"ids": [id.0], "from": [b.x0, b.y0, b.x1, b.y1], "corners": corners});
|
||||
s.execute("object.distort", &p).unwrap();
|
||||
s.execute("perspective.editText", &json!({"id": id.0})).unwrap();
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
|
||||
let e = s.execute("object.distort", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("object.distort") && e.contains(&format!("type object {}", id.0)) && e.contains("being edited flat in Edit Text"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(undo_len(&s), undo);
|
||||
s.execute("object.exitIsolation", &json!({})).unwrap();
|
||||
let before = drawn_corners(&s, id);
|
||||
let undo = undo_len(&s);
|
||||
s.execute("object.distort", &p).unwrap();
|
||||
assert_ne!(drawn_corners(&s, id), before);
|
||||
assert_eq!(undo_len(&s), undo + 1);
|
||||
}
|
||||
|
||||
/// Image info gives a distorted image's resolution at its middle, not the resolution it had
|
||||
/// before the distort.
|
||||
#[test]
|
||||
|
||||
@@ -81,7 +81,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
(
|
||||
"",
|
||||
"activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
|
||||
"activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
|
||||
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
|
||||
Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= Tag Tags View Views \
|
||||
ZOrderMethod",
|
||||
@@ -132,6 +132,11 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Tags.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
("Tag.", "prototype"),
|
||||
("Tag.prototype.", "constructor name name= parent remove typename value value="),
|
||||
(
|
||||
"BlendModes.",
|
||||
"COLORBLEND COLORBURN COLORDODGE DARKEN DIFFERENCE EXCLUSION HARDLIGHT HUE LIGHTEN LUMINOSITY MULTIPLY NORMAL \
|
||||
OVERLAY SATURATIONBLEND SCREEN SOFTLIGHT",
|
||||
),
|
||||
("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"),
|
||||
("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"),
|
||||
("DocumentColorSpace.", "CMYK RGB"),
|
||||
|
||||
@@ -273,7 +273,7 @@ fn failures_open_nothing() {
|
||||
("test.fail.notjson", "not json", "JSON"),
|
||||
("test.fail.empty", r#"{"objects":[]}"#, "the importer returned no objects"),
|
||||
("test.fail.key", r#"{"objects":[],"layers":[]}"#, "an importer returns `objects` and `warnings`, not `layers`"),
|
||||
("test.fail.id", r#"{"objects":[{"id":3}]}"#, "is not the id of an input object"),
|
||||
("test.fail.id", r#"{"objects":[{"id":3}]}"#, "an importer returns new paths without `id`"),
|
||||
("test.fail.far", far, "4000000"),
|
||||
("test.fail.warnings", bad_warnings.as_str(), "`warnings` must be a list of strings"),
|
||||
];
|
||||
@@ -441,3 +441,161 @@ fn a_built_in_file_past_the_input_limit_still_opens() {
|
||||
assert_eq!(s.execute("document.open", &encoded).unwrap()["format"], "png");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// An importer at plug-in API level 4 `id` reading `.trc` files, listing `kinds` (a JSON list) in
|
||||
/// `outputKinds`, whose output is the file it is given.
|
||||
fn rich_echo(s: &mut Session, id: &str, kinds: &str) -> Value {
|
||||
let manifest =
|
||||
format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"importer","api":4,"extensions":["trc"],"outputKinds":{kinds}}}"#);
|
||||
install(s, &tpl::module(&manifest, tpl::ECHO, "", 1))
|
||||
}
|
||||
|
||||
/// The pixels of a 2 × 1 image: opaque red, then half-transparent blue.
|
||||
const PIXELS: [u8; 8] = [255, 0, 0, 255, 0, 0, 255, 128];
|
||||
|
||||
/// Rich importer output: type, the image of [`PIXELS`] and the rectangle of [`RECT`], with two
|
||||
/// layers (the image and the rectangle in "Art", the type in the hidden, locked "Words") and two
|
||||
/// artboards.
|
||||
fn rich_output() -> Value {
|
||||
let rect: Value = serde_json::from_str(RECT).unwrap();
|
||||
json!({
|
||||
"objects": [
|
||||
{"type": "type", "text": "Hello\nWorld", "fontFamily": "No Such Family Q9617", "fontSize": 24,
|
||||
"fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"},
|
||||
{"type": "image", "pixelSize": [2, 1], "pixelsBase64": vectorcraft_format::base64_encode(&PIXELS), "transform": [10, 0, 0, 10, 0, 100]},
|
||||
rect["objects"][0],
|
||||
],
|
||||
"layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}],
|
||||
"artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}],
|
||||
"warnings": ["from the importer"],
|
||||
})
|
||||
}
|
||||
|
||||
/// The active document's layers (name, shown, locked, kinds of its objects), its artboards (name
|
||||
/// and rectangle), its type (text, family, size, fill), the RGBA of its first image, and the transforms
|
||||
/// of its text and images.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn structure(
|
||||
s: &Session,
|
||||
) -> (Vec<(String, bool, bool, Vec<&'static str>)>, Vec<(String, [f64; 4])>, Vec<(String, String, f64, String)>, Vec<u8>, Vec<(&'static str, [f64; 6])>)
|
||||
{
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let kind = |n: &vectorcraft_doc::Node| match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Text(_) => "type",
|
||||
vectorcraft_doc::NodeKind::Image(_) => "image",
|
||||
vectorcraft_doc::NodeKind::Path { .. } => "path",
|
||||
_ => "other",
|
||||
};
|
||||
let layers = d
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| (l.name.clone().unwrap_or_default(), l.visible, l.locked, l.children().unwrap().iter().map(|c| kind(c)).collect()))
|
||||
.collect();
|
||||
let boards = d.artboards.iter().map(|a| (a.name.clone(), [a.rect.x0, a.rect.y0, a.rect.x1, a.rect.y1])).collect();
|
||||
let (mut types, mut pixels, mut transforms) = (Vec::new(), Vec::new(), Vec::new());
|
||||
d.walk(|n| match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => {
|
||||
transforms.push(("type", t.xf.as_coeffs()));
|
||||
let st = &t.runs[0].style;
|
||||
let text: String = t.runs.iter().map(|r| r.text.as_str()).collect();
|
||||
types.push((text, st.font_family.clone(), st.size, serde_json::to_string(&st.fill).unwrap()));
|
||||
}
|
||||
vectorcraft_doc::NodeKind::Image(im) => {
|
||||
transforms.push(("image", im.xf.as_coeffs()));
|
||||
// Read back through the filter input's own decoder, not the importer's.
|
||||
if pixels.is_empty() {
|
||||
let o = vectorcraft_plugins::objects::encode_read_only(d, n).unwrap();
|
||||
pixels = vectorcraft_format::base64_decode(o["pixelsBase64"].as_str().unwrap()).unwrap();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
(layers, boards, types, pixels, transforms)
|
||||
}
|
||||
|
||||
/// An importer at API level 4 that lists every output kind opens editable type, an embedded image,
|
||||
/// paths, layers and artboards as it returned them; the artboards replace the one around the art,
|
||||
/// a missing font is reported with the importer's warnings, and the document saves and opens again
|
||||
/// in the native format with all of it.
|
||||
#[test]
|
||||
fn an_api_4_importer_opens_type_images_layers_and_artboards() {
|
||||
let mut s = Session::new();
|
||||
let entry = rich_echo(&mut s, "test.rich", r#"["type","image","layer","artboard"]"#);
|
||||
assert_eq!((&entry["api"], &entry["outputKinds"]), (&json!(4), &json!(["type", "image", "layer", "artboard"])));
|
||||
assert_eq!(entry["permissions"], json!(["import.read"]));
|
||||
let r = open(&mut s, "Rich.trc", rich_output().to_string().as_bytes(), json!({})).unwrap();
|
||||
let warnings = r["warnings"].as_array().unwrap();
|
||||
assert_eq!(warnings.first(), Some(&json!("from the importer")));
|
||||
assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("No Such Family Q9617")), "{warnings:?}");
|
||||
let opened = structure(&s);
|
||||
let blue = serde_json::to_string(&vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))).unwrap();
|
||||
assert_eq!(opened.0, [("Art".to_string(), true, false, vec!["image", "path"]), ("Words".to_string(), false, true, vec!["type"])]);
|
||||
assert_eq!(opened.1, [("Front".to_string(), [0.0, 0.0, 200.0, 100.0]), ("Back".to_string(), [220.0, 0.0, 420.0, 100.0])]);
|
||||
assert_eq!(opened.2, [("Hello\nWorld".to_string(), "No Such Family Q9617".to_string(), 24.0, blue)]);
|
||||
assert_eq!(opened.3, PIXELS);
|
||||
assert_eq!(opened.4, [("image", [10.0, 0.0, 0.0, 10.0, 0.0, 100.0]), ("type", [1.0, 0.0, 0.0, 1.0, 10.0, 40.0])]);
|
||||
// The type is laid out at the place the transform gives: its first baseline starts at (10, 40).
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let words = d.layers[1].children().unwrap()[0].clone();
|
||||
let b = d.bounds_of(&[words.id], false).unwrap();
|
||||
assert!(b.x0 >= 9.0 && b.x0 < 12.0 && b.y0 < 40.0 && b.y1 > 40.0, "{b:?}");
|
||||
|
||||
let native = fileio::encode(&s.doc().unwrap().doc, "vectorcraft", &json!({})).unwrap();
|
||||
open(&mut s, "Again.vectorcraft", &native, json!({})).unwrap();
|
||||
assert_eq!(structure(&s), opened, "saved and opened again");
|
||||
}
|
||||
|
||||
/// An importer at API level 4 that lists only some kinds: output with another kind, a malformed
|
||||
/// image, a bad layer, or an image or type that reaches past the canvas opens nothing and leaves the open document as it was; a blank document of
|
||||
/// artboards alone opens.
|
||||
#[test]
|
||||
fn rich_output_that_fails_its_checks_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
rich_echo(&mut s, "test.richsome", r#"["type","image","layer"]"#);
|
||||
let before = open_edited(&mut s, "test.richsome.edited");
|
||||
let mut short = rich_output();
|
||||
short["objects"][1]["pixelsBase64"] = json!(vectorcraft_format::base64_encode(&PIXELS[..4]));
|
||||
let mut twice = rich_output();
|
||||
twice["layers"][1]["objects"] = json!([0, 2]);
|
||||
let mut wide = rich_output();
|
||||
wide["objects"][1]["transform"] = json!([4000000, 0, 0, 1, 0, 0]);
|
||||
let mut far = rich_output();
|
||||
far["objects"][0]["transform"] = json!([1, 0, 0, 1, 4000000, 40]);
|
||||
let cases = [
|
||||
(rich_output(), "`artboard`"),
|
||||
(short, "= 8 bytes"),
|
||||
(twice, "exactly one layer"),
|
||||
(wide, "objects[1]: it reaches more than 4000000 pt"),
|
||||
(far, "objects[0]: it reaches more than 4000000 pt"),
|
||||
(json!({"objects": [], "layers": [{"name": "A\u{202E}B"}]}), "text direction"),
|
||||
];
|
||||
for (mut output, says) in cases {
|
||||
if says != "`artboard`" {
|
||||
output.as_object_mut().unwrap().remove("artboards");
|
||||
}
|
||||
let e = open(&mut s, "x.trc", output.to_string().as_bytes(), json!({"importer": "plugin.test.richsome"})).unwrap_err();
|
||||
assert!(e.to_string().contains(says) && e.to_string().contains("x.trc"), "{says}: {e}");
|
||||
assert_eq!(state(&mut s), before, "{says}");
|
||||
}
|
||||
rich_echo(&mut s, "test.richboards", r#"["artboard"]"#);
|
||||
let blank = json!({"objects": [], "artboards": [{"name": "Only", "rect": [0, 0, 50, 60]}]});
|
||||
open(&mut s, "Blank.trc", blank.to_string().as_bytes(), json!({"importer": "plugin.test.richboards"})).unwrap();
|
||||
let (layers, boards, types, _, _) = structure(&s);
|
||||
assert_eq!((layers.len(), layers[0].3.len(), boards, types.len()), (1, 0, vec![("Only".to_string(), [0.0, 0.0, 50.0, 60.0])], 0));
|
||||
}
|
||||
|
||||
/// An importer below API level 4 reads paths alone, as it always has: type is not a path, and it
|
||||
/// can't return layers.
|
||||
#[test]
|
||||
fn an_older_importer_reads_paths_alone() {
|
||||
let mut s = Session::new();
|
||||
echo(&mut s, "test.older", r#"["tol"]"#);
|
||||
let e = open(&mut s, "x.tol", rich_output().to_string().as_bytes(), json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("an importer returns `objects` and `warnings`, not `"), "{e}");
|
||||
let typed = json!({"objects": [rich_output()["objects"][0]]});
|
||||
let e = open(&mut s, "x.tol", typed.to_string().as_bytes(), json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("`type` must be \"path\" or \"compound\""), "{e}");
|
||||
assert!(s.documents().is_empty());
|
||||
open(&mut s, "Shapes.tol", RECT.as_bytes(), json!({})).unwrap();
|
||||
assert_eq!((objects(&s), artboard(&s), s.doc().unwrap().doc.layers.len()), (1, (10.0, 20.0, 110.0, 70.0), 1));
|
||||
}
|
||||
@@ -58,6 +58,56 @@ fn state(s: &mut Session) -> (usize, usize, usize, Value) {
|
||||
(d.history.undo.len(), d.history.redo.len(), d.doc.layers.len(), content)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placing_importer_checks_the_transformed_bounds_before_editing() {
|
||||
let image = json!({"objects": [{
|
||||
"type": "image", "pixelSize": [1, 1], "pixelsBase64": vectorcraft_format::base64_encode(&[255, 0, 0, 255]),
|
||||
"transform": [20, 0, 0, 10, 0, 0],
|
||||
}]})
|
||||
.to_string();
|
||||
for (index, output, half_width) in [(0, ART, 50.0), (1, image.as_str(), 10.0)] {
|
||||
let mut s = with_document();
|
||||
let mut manifest: Value = serde_json::from_str(&placing(&format!("test.place.canvas{index}"), r#"["tpc"]"#)).unwrap();
|
||||
if index == 1 {
|
||||
manifest["api"] = json!(4);
|
||||
manifest["outputKinds"] = json!(["image"]);
|
||||
}
|
||||
install(&mut s, &tpl::returning(&manifest.to_string(), output));
|
||||
let importer = format!("plugin.test.place.canvas{index}");
|
||||
let before = state(&mut s);
|
||||
for at in [[4_000_000.0, 400.0], [-4_000_000.0, 400.0], [400.0, 4_000_000.0], [400.0, -4_000_000.0]] {
|
||||
for template in [false, true] {
|
||||
assert!(
|
||||
place(&mut s, "Art.tpc", b"?", json!({"at": at, "template": template, "importer": importer})).is_err(),
|
||||
"{index}: {at:?}, template: {template}"
|
||||
);
|
||||
assert_eq!(state(&mut s), before);
|
||||
}
|
||||
}
|
||||
let inside = place(&mut s, "Art.tpc", b"?", json!({"at": [4_000_000.0 - half_width, 400.0], "importer": importer}));
|
||||
assert!(inside.is_ok(), "{index}: {inside:?}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.0 + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cropped_svg_placement_checks_art_outside_its_frame_before_editing() {
|
||||
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><path d="M-20 -20 L120 -20 L120 120 L-20 120 Z"/></svg>"#;
|
||||
for at in [[3_999_940.0, 400.0], [-3_999_940.0, 400.0], [400.0, 3_999_940.0], [400.0, -3_999_940.0]] {
|
||||
for template in [false, true] {
|
||||
let mut s = with_document();
|
||||
let before = state(&mut s);
|
||||
assert!(
|
||||
place(&mut s, "cropped.svg", svg, json!({"at": at, "crop": "crop", "template": template})).is_err(),
|
||||
"{at:?}, template: {template}"
|
||||
);
|
||||
assert_eq!(state(&mut s), before);
|
||||
}
|
||||
}
|
||||
let mut s = with_document();
|
||||
assert!(place(&mut s, "cropped.svg", svg, json!({"at": [3_999_930.0, 400.0], "crop": "crop"})).is_ok());
|
||||
}
|
||||
|
||||
/// A placed group: its name, the names of its children, and its bounds as `(x0, y0, x1, y1)`.
|
||||
type Placed = (Option<String>, Vec<Option<String>>, (f64, f64, f64, f64));
|
||||
|
||||
@@ -159,6 +209,37 @@ fn guides_are_left_out_of_what_is_placed() {
|
||||
assert_eq!(state(&mut s), before);
|
||||
}
|
||||
|
||||
/// An importer at plug-in API level 4 places its type and images with its paths: the objects of its
|
||||
/// visible layers go in the group, in order, the objects of a hidden layer are left out, and its
|
||||
/// artboards leave the document's as they were.
|
||||
#[test]
|
||||
fn an_api_4_importer_places_type_and_images_of_its_visible_layers() {
|
||||
let mut s = with_document();
|
||||
let manifest = r#"{"id":"test.place.rich","name":"Test test.place.rich","version":"1","kind":"importer","api":4,"extensions":["tpr"],"place":true,"outputKinds":["type","image","layer","artboard"]}"#;
|
||||
let rect: Value = serde_json::from_str(ART).unwrap();
|
||||
let output = json!({
|
||||
"objects": [
|
||||
{"type": "type", "text": "Hello", "fontFamily": "No Such Family P9129", "fontSize": 24, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"},
|
||||
{"type": "image", "pixelSize": [2, 1], "pixelsBase64": vectorcraft_format::base64_encode(&[255, 0, 0, 255, 0, 0, 255, 128]), "transform": [10, 0, 0, 10, 0, 100], "name": "Pic"},
|
||||
rect["objects"][0],
|
||||
],
|
||||
"layers": [{"name": "Shown", "objects": [0, 1]}, {"name": "Hidden", "visible": false, "objects": [2]}],
|
||||
"artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}],
|
||||
});
|
||||
install(&mut s, &tpl::returning(manifest, &output.to_string()));
|
||||
let boards = s.doc().unwrap().doc.artboards.clone();
|
||||
let r = place(&mut s, "Rich.tpr", b"?", json!({"at": [300, 400]})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let NodeKind::Group { children, .. } = &d.node(id).expect("placed").kind else { panic!("not a group") };
|
||||
let kinds: Vec<(Option<&str>, bool, bool)> = children
|
||||
.iter()
|
||||
.map(|c| (c.name.as_deref(), matches!(c.kind, NodeKind::Text(_)), matches!(&c.kind, NodeKind::Image(im) if d.images.contains_key(&im.key))))
|
||||
.collect();
|
||||
assert_eq!(kinds, [(Some("Title"), true, false), (Some("Pic"), false, true)]);
|
||||
assert_eq!(d.artboards, boards);
|
||||
}
|
||||
|
||||
/// The importer is told it places the file (`_context.mode`), with the file's extension and name,
|
||||
/// and is given its parameters.
|
||||
#[test]
|
||||
|
||||
@@ -67,6 +67,27 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `new.target` of the function the running code is in, for a direct `eval` it calls:
|
||||
/// `None` outside a function. A function that calls `eval` keeps its `new.target` in a hidden
|
||||
/// binding ([`Interp::function_bindings`]). Each scope looked at takes a unit of fuel.
|
||||
pub(crate) fn caller_new_target(&mut self) -> JsResult<Option<Value>> {
|
||||
let mut cur = Some(self.frame()?.env);
|
||||
while let Some(e) = cur {
|
||||
self.use_fuel()?;
|
||||
cur = match self.heap.env(e) {
|
||||
Some(Env::Decl { bindings, outer }) => {
|
||||
if bindings.contains(NEW_TARGET) {
|
||||
return self.binding_value(e, NEW_TARGET).map(Some);
|
||||
}
|
||||
*outer
|
||||
}
|
||||
Some(Env::Obj { outer, .. }) => *outer,
|
||||
None => None,
|
||||
};
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Adds the hidden bindings of a call to `code` to its function environment `env`: a derived
|
||||
/// class constructor's `this`, function object and `new.target`, and the `new.target` of a
|
||||
/// function whose arrow functions read it. Gives the environment of a derived constructor's
|
||||
|
||||
@@ -1950,6 +1950,9 @@ impl<'a> FnCompiler<'a> {
|
||||
if eval {
|
||||
self.uses_arguments = true;
|
||||
self.uses_this = true;
|
||||
// The eval code may read `new.target`, even when a later run reads
|
||||
// scripts as ECMAScript 2015 and this code was read as ES5.1.
|
||||
self.uses_new_target = true;
|
||||
}
|
||||
if self.has_spread(args) {
|
||||
self.spread_args(args)?;
|
||||
|
||||
@@ -1624,6 +1624,21 @@ fn new_target_names_the_constructor_new_was_applied_to() {
|
||||
truth("function F() { this.t = new.target; } var B = F.bind(null); new B().t === F");
|
||||
}
|
||||
|
||||
/// A direct `eval` inside a function reads the function's `new.target`, from an arrow function
|
||||
/// and a nested `eval` too; outside a function, and through an indirect `eval`, it is a
|
||||
/// `SyntaxError`.
|
||||
#[test]
|
||||
fn eval_inside_a_function_reads_its_new_target() {
|
||||
truth("function F() { return eval('new.target'); } new F() === F && F() === undefined");
|
||||
truth("function F() { 'use strict'; return eval('new.target'); } new F() === F");
|
||||
truth("function F() { return (() => eval('new.target'))(); } new F() === F");
|
||||
truth("function F() { return eval('eval(\"new.target\")'); } new F() === F");
|
||||
truth("class A { constructor() { this.t = eval('new.target'); } } class B extends A {} new B().t === B");
|
||||
throws("eval('new.target')", "SyntaxError");
|
||||
throws("(() => eval('new.target'))()", "SyntaxError");
|
||||
throws("function F() { return (0, eval)('new.target'); } new F()", "SyntaxError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_class_chains_stay_within_the_limits() {
|
||||
let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();";
|
||||
|
||||
@@ -698,6 +698,8 @@ pub(crate) const ENV_BYTES: usize = 64;
|
||||
pub(crate) const ROPE_BYTES: usize = 48;
|
||||
/// The estimated bytes of each argument a bound function holds.
|
||||
pub(crate) const BOUND_ARG_BYTES: usize = 24;
|
||||
/// The estimated bytes of each entry an `arguments` object holds in its map of argument names.
|
||||
pub(crate) const ARG_NAME_BYTES: usize = std::mem::size_of::<Option<Key>>();
|
||||
/// The estimated bytes of an XML node without its names and text.
|
||||
pub(crate) const XML_NODE_BYTES: usize = 160;
|
||||
/// The estimated bytes of an XML list without its items.
|
||||
@@ -1097,7 +1099,10 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
}
|
||||
extra = BOUND_ARG_BYTES * args.len();
|
||||
}
|
||||
Class::Arguments(map) => work.push(map.env.0),
|
||||
Class::Arguments(map) => {
|
||||
work.push(map.env.0);
|
||||
extra = ARG_NAME_BYTES * map.names.len();
|
||||
}
|
||||
Class::String(s) => strings.add(s),
|
||||
Class::RegExp(re) => {
|
||||
if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) {
|
||||
|
||||
+24
-6
@@ -561,9 +561,11 @@ fn scope_bytes(code: &Code, i: u32) -> usize {
|
||||
}
|
||||
|
||||
/// At least the bytes that the `arguments` object of a call with `args` arguments adds to the
|
||||
/// heap: the object, an element for each argument and its other properties.
|
||||
/// heap: the object, its map of argument names, an element for each argument and its other
|
||||
/// properties.
|
||||
fn arguments_bytes(args: usize) -> usize {
|
||||
OBJECT_BYTES.saturating_add(args.saturating_add(4).saturating_mul(binding_bytes(10)))
|
||||
let names = crate::heap::ARG_NAME_BYTES.saturating_mul(args);
|
||||
OBJECT_BYTES.saturating_add(names).saturating_add(args.saturating_add(4).saturating_mul(binding_bytes(10)))
|
||||
}
|
||||
|
||||
/// A call to a function written in JavaScript, ready to enter; `new_target` is set when it is
|
||||
@@ -3158,7 +3160,8 @@ impl Interp {
|
||||
return Err(Abrupt::Limit(LimitKind::Frames));
|
||||
}
|
||||
let params = code.params.iter().chain(&code.pattern_names).fold(0usize, |total, p| total.saturating_add(binding_bytes(p.len())));
|
||||
let arguments = if code.uses_arguments { arguments_bytes(args.len()) } else { 0 };
|
||||
// An arrow function reads the `arguments` object of the function around it.
|
||||
let arguments = if code.uses_arguments && !code.arrow { arguments_bytes(args.len()) } else { 0 };
|
||||
// The array a rest parameter gets: its binding and one property for each extra argument.
|
||||
let rest = match &code.rest {
|
||||
Some(name) => {
|
||||
@@ -3373,7 +3376,10 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
let proto = self.intrinsics.object_proto;
|
||||
let extra = crate::heap::ARG_NAME_BYTES.saturating_mul(names.len());
|
||||
self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(extra))?;
|
||||
let a = self.heap.alloc_object(Object::new(Class::Arguments(Box::new(ArgMap { env, names })), Some(proto)));
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(extra);
|
||||
for (i, v) in args.iter().enumerate() {
|
||||
self.define(a, index_key(u32::try_from(i).unwrap_or(u32::MAX)), Prop::Data { value: v.clone(), flags: OPEN })?;
|
||||
}
|
||||
@@ -3539,10 +3545,17 @@ impl Interp {
|
||||
|
||||
/// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`.
|
||||
pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result<Rc<Code>, CompileError> {
|
||||
self.compile_units(units, strict, writes, kind, false)
|
||||
}
|
||||
|
||||
/// [`Interp::compile_source_writes`]; `in_function` reads eval code run inside a function,
|
||||
/// where `new.target` is allowed.
|
||||
fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, in_function: bool) -> Result<Rc<Code>, CompileError> {
|
||||
self.source_units = self.source_units.saturating_add(units.len());
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { strict, max_source_units: remaining, ..self.options.clone() };
|
||||
let program = crate::parse_utf16(units, &options).map_err(CompileError::Syntax)?;
|
||||
let parse = if in_function { crate::parse_utf16_in_function } else { crate::parse_utf16 };
|
||||
let program = parse(units, &options).map_err(CompileError::Syntax)?;
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes });
|
||||
compile_program(&program, &source, kind).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
@@ -3569,7 +3582,10 @@ impl Interp {
|
||||
self.prepare_source(s.len())?;
|
||||
let units = self.flat_reserved(s)?;
|
||||
self.observe_code(&units);
|
||||
let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
// Inside a function the eval code reads the function's `new.target` (section 18.2.1.1).
|
||||
let new_target = self.caller_new_target()?;
|
||||
let writes = self.writes_mode();
|
||||
let code = self.compile_units(&units, strict, writes, CodeKind::Eval, new_target.is_some()).map_err(|e| self.compile_error_to_abrupt(e))?;
|
||||
self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?;
|
||||
let frame = self.frame()?;
|
||||
let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env);
|
||||
@@ -3584,7 +3600,9 @@ impl Interp {
|
||||
let env = self.instantiate_pending(&code, env, var_env, true)?;
|
||||
self.push_code_frame(code, env, var_env, this, false)?;
|
||||
// The eval code reads `this` the way the code that called it does (section 18.2.1.1).
|
||||
self.frame_mut()?.this_in_env = this_in_env;
|
||||
let frame = self.frame_mut()?;
|
||||
frame.this_in_env = this_in_env;
|
||||
frame.new_target = new_target.and_then(|v| v.as_object());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -600,6 +600,35 @@ fn a_lower_heap_limit_applies_to_what_is_already_live() {
|
||||
assert_eq!(limit(&mut realm, "var more = []; for (var j = 0; j < 20000; j++) more[j] = {j: j};"), LimitKind::Heap);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_arguments_objects_name_map_counts_toward_the_heap() {
|
||||
let mut realm = Realm::new();
|
||||
realm.run("function f() { return arguments; }").unwrap();
|
||||
// The growth from 100 objects to 200, each with its elements deleted, so the script's own code
|
||||
// and strings cancel out and only the map of argument names stays.
|
||||
let mut per_hundred = |len: usize| {
|
||||
let mut grown = |count: usize| {
|
||||
realm.run("var kept = []; var a = null;").unwrap();
|
||||
let before = realm.collect_garbage();
|
||||
let src = format!(
|
||||
"var args = []; for (var j = 0; j < {len}; j++) args[j] = 0; \
|
||||
for (var i = 0; i < {count}; i++) {{ var a = f.apply(null, args); \
|
||||
for (var j = 0; j < {len}; j++) delete a[j]; kept.push(a); }} args = null;"
|
||||
);
|
||||
realm.run(&src).unwrap();
|
||||
realm.collect_garbage() - before
|
||||
};
|
||||
grown(200) - grown(100)
|
||||
};
|
||||
// The first runs also leave bindings and names the later ones reuse.
|
||||
per_hundred(1);
|
||||
let short = per_hundred(1);
|
||||
let long = per_hundred(65);
|
||||
// The longer runs also keep up to a property's worth more per object besides the names.
|
||||
let names = 100 * 64 * crate::heap::ARG_NAME_BYTES;
|
||||
assert!((names..names + 100 * crate::heap::PROP_BYTES).contains(&(long - short)), "{} of {names}", long - short);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_keeps_its_arguments_alive_while_a_native_function_runs() {
|
||||
// The first argument's toString makes 20,000 objects, more than a 1 MiB heap holds, so a
|
||||
|
||||
@@ -219,6 +219,13 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
|
||||
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// [`parse_utf16`] for code a direct `eval` runs inside a function, where `new.target` is allowed
|
||||
/// (ECMA-262 2015 section 18.2.1.1).
|
||||
pub(crate) fn parse_utf16_in_function(source: &[u16], options: &Options) -> Result<Program, SyntaxError> {
|
||||
check_length(source.len(), options)?;
|
||||
parser::Parser::new(source, options, false)?.with_new_target().parse_program().map(|(program, _)| program)
|
||||
}
|
||||
|
||||
/// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and
|
||||
/// each `/` read as division or as the start of a regular expression literal as the grammar
|
||||
/// decides. The source must be a valid script.
|
||||
|
||||
@@ -176,6 +176,12 @@ impl<'s> Parser<'s> {
|
||||
Ok(parser)
|
||||
}
|
||||
|
||||
/// Allows `new.target` at the top of the source: eval code run inside a function.
|
||||
pub(crate) fn with_new_target(mut self) -> Self {
|
||||
self.supers.new_target = self.es2015;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn parse_program(mut self) -> Result<(Program, Vec<Token>)> {
|
||||
let body = self.parse_body(false)?;
|
||||
if self.tok.kind != TokenKind::Eof {
|
||||
|
||||
@@ -1006,7 +1006,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.paramDialog",
|
||||
"Command Dialog",
|
||||
"",
|
||||
"{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
"{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
),
|
||||
(
|
||||
"ui.recolorDialog",
|
||||
@@ -2070,7 +2070,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.runScript",
|
||||
"Other Script…",
|
||||
"Cmd+F12",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
),
|
||||
(
|
||||
"ui.runInstalledScript",
|
||||
|
||||
+619
-12
@@ -14,6 +14,8 @@
|
||||
//! The host hands the importer the file's bytes as they are, at most [`MAX_INPUT_BYTES`] of them,
|
||||
//! and reads back the objects of the new document in the same form filters return them
|
||||
//! ([`crate::objects`]): `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline.
|
||||
//! An importer at plug-in API level 4 whose manifest lists `outputKinds` may also return point type
|
||||
//! and embedded images in `objects`, and `layers` and `artboards` ([`decode_with`]).
|
||||
//! An import is one run the user asked for, so it gets an export's budget ([`crate::export::FUEL`]
|
||||
//! and [`crate::export::WALL_TIME_MS`]), and Cancel stops it between two slices of the budget
|
||||
//! ([`Error::Cancelled`]).
|
||||
@@ -21,9 +23,11 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use crate::objects::{OutObject, declined, printable};
|
||||
use crate::{Error, Kind, Limits, Plugin, Result, registry};
|
||||
use crate::objects::{MAX_COORD, MAX_OBJECTS, OutObject, declined, out_err, printable};
|
||||
use crate::{Error, Kind, Limits, OutputKind, Plugin, Result, registry};
|
||||
|
||||
/// The largest file an importer is given, in bytes: 128 MiB, a quarter of a plug-in's memory
|
||||
/// limit, so the file and the objects made from it fit beside each other.
|
||||
@@ -100,13 +104,109 @@ impl Mode {
|
||||
/// What an importer returned.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Imported {
|
||||
/// The objects of the new document, in paint order (bottom first), checked as a filter's are.
|
||||
pub objects: Vec<OutObject>,
|
||||
/// The objects of the new document, in paint order (bottom first): paths and compound paths
|
||||
/// checked as a filter's are, and type and images when the importer lists them in `outputKinds`.
|
||||
pub objects: Vec<ImportObject>,
|
||||
/// The top-level layers, bottom first, each holding the objects it lists (`layers`, with
|
||||
/// `outputKinds` `layer`); empty: every object goes in one layer.
|
||||
pub layers: Vec<OutLayer>,
|
||||
/// The artboards (`artboards`, with `outputKinds` `artboard`); empty: one artboard around the art.
|
||||
pub artboards: Vec<OutArtboard>,
|
||||
/// What the import left out or changed, for the user (at most
|
||||
/// [`crate::export::MAX_WARNINGS`]).
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Imported {
|
||||
/// Whether it holds paths and compound paths alone, as an importer below API level 4 returns.
|
||||
pub fn paths_only(&self) -> bool {
|
||||
self.layers.is_empty() && self.artboards.is_empty() && self.objects.iter().all(|o| matches!(o, ImportObject::Path(_)))
|
||||
}
|
||||
}
|
||||
|
||||
/// One object of an import.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ImportObject {
|
||||
/// A path or a compound path (`"type": "path"` or `"compound"`, or no `type`).
|
||||
Path(OutObject),
|
||||
/// Point type (`"type": "type"`).
|
||||
Type(OutType),
|
||||
/// An embedded image (`"type": "image"`).
|
||||
Image(OutImage),
|
||||
}
|
||||
|
||||
/// Point type an importer returned: `{"type": "type", text, fontFamily, fontStyle?, fontSize,
|
||||
/// fill?, transform?, name?}`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OutType {
|
||||
/// Its text, a line break (`\n`) between two paragraphs.
|
||||
pub text: String,
|
||||
pub font_family: String,
|
||||
/// `None`: the family's regular style.
|
||||
pub font_style: Option<String>,
|
||||
/// In points, from [`TYPE_SIZES`]`.0` to [`TYPE_SIZES`]`.1`.
|
||||
pub font_size: f64,
|
||||
/// `None`: the default fill (black).
|
||||
pub fill: Option<Paint>,
|
||||
/// Maps the type's own space (the first baseline starts at its origin) into the document.
|
||||
pub transform: Affine,
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
/// An embedded image an importer returned: `{"type": "image", pixelSize: [w, h], pixelsBase64,
|
||||
/// transform?, name?}`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OutImage {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Straight RGBA, 8 bits a channel, row by row from the top: `4 × width × height` bytes.
|
||||
pub rgba: Vec<u8>,
|
||||
/// Maps pixel space (one unit a pixel, y down) into the document.
|
||||
pub transform: Affine,
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
/// A top-level layer an importer returned: `{name, visible?, locked?, objects: [index…]}`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct OutLayer {
|
||||
pub name: String,
|
||||
pub visible: bool,
|
||||
pub locked: bool,
|
||||
/// Indexes into [`Imported::objects`], increasing: the layer's objects in paint order.
|
||||
pub objects: Vec<usize>,
|
||||
}
|
||||
|
||||
/// An artboard an importer returned: `{name, rect: [x, y, width, height]}`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct OutArtboard {
|
||||
pub name: String,
|
||||
pub rect: Rect,
|
||||
}
|
||||
|
||||
/// Most layers an import may return.
|
||||
pub const MAX_LAYERS: usize = 256;
|
||||
|
||||
/// Most artboards an import may return.
|
||||
pub const MAX_ARTBOARDS: usize = 100;
|
||||
|
||||
/// Longest layer, artboard, object or font name an import may return, in characters.
|
||||
pub const MAX_NAME_CHARS: usize = 256;
|
||||
|
||||
/// Most bytes of UTF-8 text one type object may hold.
|
||||
pub const MAX_TYPE_TEXT: usize = 1 << 20;
|
||||
|
||||
/// Most bytes of UTF-8 text all the type of one import may hold.
|
||||
pub const MAX_TEXT_TOTAL: usize = 16 << 20;
|
||||
|
||||
/// Most pixels an image may have along either side.
|
||||
pub const MAX_IMAGE_SIDE: u64 = 16_384;
|
||||
|
||||
/// Most bytes of RGBA all the images of one import may hold.
|
||||
pub const MAX_PIXEL_BYTES: u64 = 32 << 20;
|
||||
|
||||
/// The type sizes an import may give, in points (those Character panel sizes take).
|
||||
pub const TYPE_SIZES: (f64, f64) = (0.1, 1296.0);
|
||||
|
||||
/// The file an import reads, as the importer is told in `_context`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Source<'a> {
|
||||
@@ -148,23 +248,68 @@ pub fn run_as(plugin: &Plugin, file: &[u8], params: &Value, source: Source, mode
|
||||
let mut params = Value::Object(m.resolve_params(params)?);
|
||||
params["_context"] = json!({"mode": mode.name(), "extension": source.extension, "name": source.name});
|
||||
let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?;
|
||||
decode(&plugin.run_limited(file, ¶ms, &limits(plugin))?)
|
||||
decode_with(&plugin.run_limited(file, ¶ms, &limits(plugin))?, &m.output_kinds())
|
||||
}
|
||||
|
||||
/// An importer's output: `{"objects": [...], "warnings"?: ["…"]}`, or `{"error": "…"}` to decline
|
||||
/// with a message for the user. The objects are new ones (no `id`), checked as a filter's are; an
|
||||
/// output without any, or with keys of its own, is refused.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Imported> {
|
||||
decode_with(bytes, &[])
|
||||
}
|
||||
|
||||
/// [`decode`] for an importer whose manifest lists `kinds` (`outputKinds`): `objects` may also
|
||||
/// hold type and images, and the output `layers` and `artboards`, of the kinds listed. Content of
|
||||
/// a kind not listed is refused naming the kind. Everything is checked before anything is returned,
|
||||
/// against the limits of this module, and one bad entry refuses the whole output. With `kinds`
|
||||
/// listing layers or artboards, an output of no objects is an empty document when it has any.
|
||||
pub fn decode_with(bytes: &[u8], kinds: &[OutputKind]) -> Result<Imported> {
|
||||
let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?;
|
||||
if let Some(e) = declined(&v) {
|
||||
return Err(e);
|
||||
}
|
||||
if let Some(key) = v.as_object().and_then(|o| o.keys().find(|k| !OUTPUT_KEYS.contains(&k.as_str()))) {
|
||||
let key = printable(&json!(key), 64);
|
||||
return Err(Error::Output(format!("an importer returns `objects` and `warnings`, not `{key}`")));
|
||||
for key in v.as_object().into_iter().flat_map(|o| o.keys()).filter(|k| !OUTPUT_KEYS.contains(&k.as_str())) {
|
||||
let rich = match key.as_str() {
|
||||
"layers" => Some(OutputKind::Layer),
|
||||
"artboards" => Some(OutputKind::Artboard),
|
||||
_ => None,
|
||||
};
|
||||
match rich {
|
||||
Some(kind) if kinds.contains(&kind) => {}
|
||||
Some(kind) if !kinds.is_empty() => return Err(undeclared(kind)),
|
||||
_ => {
|
||||
let key = printable(&json!(key), 64);
|
||||
return Err(Error::Output(format!("an importer returns `objects` and `warnings`, not `{key}`")));
|
||||
}
|
||||
}
|
||||
}
|
||||
let objects = crate::objects::decode(bytes)?;
|
||||
if objects.is_empty() {
|
||||
let (objects, layers, artboards) = if kinds.is_empty() {
|
||||
let objects = crate::objects::decode(bytes)?;
|
||||
(objects.into_iter().map(ImportObject::Path).collect::<Vec<_>>(), Vec::new(), Vec::new())
|
||||
} else {
|
||||
let objects = rich_objects(&v, kinds)?;
|
||||
let layers = match v.get("layers") {
|
||||
None => Vec::new(),
|
||||
Some(l) => decode_layers(l, objects.len())?,
|
||||
};
|
||||
let artboards = match v.get("artboards") {
|
||||
None => Vec::new(),
|
||||
Some(a) => decode_artboards(a)?,
|
||||
};
|
||||
(objects, layers, artboards)
|
||||
};
|
||||
for (i, object) in objects.iter().enumerate() {
|
||||
if let ImportObject::Path(path) = object {
|
||||
let at = format!("objects[{i}]");
|
||||
if path.id.is_some() {
|
||||
return Err(out_err(&at, "an importer returns new paths without `id`"));
|
||||
}
|
||||
if path.path.is_none() {
|
||||
return Err(out_err(&at, "an imported path must include its geometry in `path`"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if objects.is_empty() && layers.is_empty() && artboards.is_empty() {
|
||||
return Err(Error::Output("the importer returned no objects".into()));
|
||||
}
|
||||
let warnings = match v.get("warnings") {
|
||||
@@ -172,7 +317,299 @@ pub fn decode(bytes: &[u8]) -> Result<Imported> {
|
||||
Some(Value::Array(w)) => w.iter().take(crate::export::MAX_WARNINGS).map(|w| printable(w, crate::export::MAX_WARNING_CHARS)).collect(),
|
||||
Some(_) => return Err(Error::Output("`warnings` must be a list of strings".into())),
|
||||
};
|
||||
Ok(Imported { objects, warnings })
|
||||
Ok(Imported { objects, layers, artboards, warnings })
|
||||
}
|
||||
|
||||
/// The error of output holding content of `kind`, which the importer's `outputKinds` doesn't list.
|
||||
fn undeclared(kind: OutputKind) -> Error {
|
||||
let kind = kind.name();
|
||||
Error::Output(format!("the output holds `{kind}`, which the importer's `outputKinds` doesn't list"))
|
||||
}
|
||||
|
||||
/// The keys a type object may have.
|
||||
const TYPE_KEYS: &[&str] = &["type", "text", "fontFamily", "fontStyle", "fontSize", "fill", "transform", "name"];
|
||||
|
||||
/// The keys an image object may have.
|
||||
const IMAGE_KEYS: &[&str] = &["type", "pixelSize", "pixelsBase64", "transform", "name"];
|
||||
|
||||
/// The keys a layer may have.
|
||||
const LAYER_KEYS: &[&str] = &["name", "visible", "locked", "objects"];
|
||||
|
||||
/// The keys an artboard may have.
|
||||
const ARTBOARD_KEYS: &[&str] = &["name", "rect"];
|
||||
|
||||
/// The objects of output `v` of an importer listing `kinds`: paths and compound paths as a
|
||||
/// filter's, type and images of the kinds listed.
|
||||
fn rich_objects(v: &Value, kinds: &[OutputKind]) -> Result<Vec<ImportObject>> {
|
||||
let objects = v.get("objects").and_then(Value::as_array).ok_or_else(|| Error::Output("expected {\"objects\": [...]}".into()))?;
|
||||
if objects.len() > MAX_OBJECTS {
|
||||
return Err(Error::Output(format!("{} objects (limit {MAX_OBJECTS})", objects.len())));
|
||||
}
|
||||
let kind_of = |o: &Value| match o.get("type").and_then(Value::as_str) {
|
||||
Some("type") => Some(OutputKind::Type),
|
||||
Some("image") => Some(OutputKind::Image),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(kind) = objects.iter().filter_map(kind_of).find(|k| !kinds.contains(k)) {
|
||||
return Err(undeclared(kind));
|
||||
}
|
||||
check_totals(objects)?;
|
||||
let mut anchors = 0;
|
||||
objects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, o)| {
|
||||
let at = format!("objects[{i}]");
|
||||
match kind_of(o) {
|
||||
Some(OutputKind::Type) => decode_type(o, &at).map(ImportObject::Type),
|
||||
Some(_) => decode_image(o, &at).map(ImportObject::Image),
|
||||
None => crate::objects::decode_object(o, &at, &mut anchors).map(ImportObject::Path),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Refuses `objects` whose type, all together, holds more than [`MAX_TEXT_TOTAL`] bytes of text, or
|
||||
/// whose images, by the sizes they give, more than [`MAX_PIXEL_BYTES`] bytes of pixels, before any
|
||||
/// object is read further or any pixels are decoded.
|
||||
fn check_totals(objects: &[Value]) -> Result<()> {
|
||||
let (mut text, mut pixel_bytes) = (0usize, 0u64);
|
||||
for (i, o) in objects.iter().enumerate() {
|
||||
let at = format!("objects[{i}]");
|
||||
match o.get("type").and_then(Value::as_str) {
|
||||
Some("type") => {
|
||||
text = text.saturating_add(o.get("text").and_then(Value::as_str).map_or(0, str::len));
|
||||
if text > MAX_TEXT_TOTAL {
|
||||
return Err(out_err(&at, format!("the type holds more than {MAX_TEXT_TOTAL} bytes of text")));
|
||||
}
|
||||
}
|
||||
Some("image") => {
|
||||
let side = |k: usize| o.get("pixelSize").and_then(|s| s.get(k)).and_then(Value::as_u64).unwrap_or(0);
|
||||
let (w, h) = (side(0), side(1));
|
||||
if w > MAX_IMAGE_SIDE || h > MAX_IMAGE_SIDE {
|
||||
return Err(out_err(&at, format!("{w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side)")));
|
||||
}
|
||||
pixel_bytes = pixel_bytes.saturating_add(w.saturating_mul(h).saturating_mul(4));
|
||||
if pixel_bytes > MAX_PIXEL_BYTES {
|
||||
return Err(out_err(&at, format!("the images hold more than {MAX_PIXEL_BYTES} bytes of pixels")));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuses a key of JSON object `o` that isn't one of `keys`.
|
||||
fn known_keys(o: &serde_json::Map<String, Value>, keys: &[&str], at: &str) -> Result<()> {
|
||||
match o.keys().find(|k| !keys.contains(&k.as_str())) {
|
||||
Some(key) => {
|
||||
let key = printable(&json!(key), 64);
|
||||
Err(out_err(at, format!("unknown field `{key}`")))
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `c` a character that changes the direction text is laid out in (an embedding, override,
|
||||
/// isolate or mark)?
|
||||
fn is_direction_mark(c: char) -> bool {
|
||||
matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
|
||||
}
|
||||
|
||||
/// The name `key` of `o` (`at` names it): 1 to [`MAX_NAME_CHARS`] characters, none of them a
|
||||
/// control character or a direction mark, and not only spaces. `None` when it is left out and not
|
||||
/// `required`.
|
||||
fn name(o: &serde_json::Map<String, Value>, key: &str, required: bool, at: &str) -> Result<Option<String>> {
|
||||
let v = match o.get(key) {
|
||||
None | Some(Value::Null) if required => return Err(out_err(at, format!("missing field `{key}`"))),
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(v) => v,
|
||||
};
|
||||
let s = v.as_str().ok_or_else(|| out_err(at, format!("`{key}` must be a string")))?;
|
||||
let count = s.chars().count();
|
||||
if count == 0 || count > MAX_NAME_CHARS || s.trim().is_empty() || s.chars().any(|c| c.is_control() || is_direction_mark(c)) {
|
||||
return Err(out_err(at, format!("`{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters")));
|
||||
}
|
||||
Ok(Some(s.to_string()))
|
||||
}
|
||||
|
||||
/// The affine `key` of `o` (`at` names it): six finite numbers within ±[`MAX_COORD`] that don't
|
||||
/// flatten what it places. Left out, no change of place.
|
||||
fn transform(o: &serde_json::Map<String, Value>, key: &str, at: &str) -> Result<Affine> {
|
||||
let Some(v) = o.get(key).filter(|v| !v.is_null()) else { return Ok(Affine::IDENTITY) };
|
||||
let wrong = || out_err(at, format!("`{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object"));
|
||||
let list = v.as_array().filter(|a| a.len() == 6).ok_or_else(wrong)?;
|
||||
let mut c = [0.0; 6];
|
||||
for (slot, n) in c.iter_mut().zip(list) {
|
||||
*slot = n.as_f64().filter(|x| x.is_finite() && x.abs() <= MAX_COORD).ok_or_else(wrong)?;
|
||||
}
|
||||
let det = c[0] * c[3] - c[1] * c[2];
|
||||
if !det.is_normal() {
|
||||
return Err(wrong());
|
||||
}
|
||||
Ok(Affine::new(c))
|
||||
}
|
||||
|
||||
/// A type object of the output (`at` names it).
|
||||
fn decode_type(v: &Value, at: &str) -> Result<OutType> {
|
||||
let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?;
|
||||
known_keys(o, TYPE_KEYS, at)?;
|
||||
let text = match o.get("text") {
|
||||
None | Some(Value::Null) => {
|
||||
let key = "text";
|
||||
return Err(out_err(at, format!("missing field `{key}`")));
|
||||
}
|
||||
Some(t) => t.as_str().ok_or_else(|| {
|
||||
let key = "text";
|
||||
out_err(at, format!("`{key}` must be a string"))
|
||||
})?,
|
||||
};
|
||||
let len = text.len();
|
||||
if len > MAX_TYPE_TEXT {
|
||||
return Err(out_err(at, format!("`text` is {len} bytes (limit {MAX_TYPE_TEXT})")));
|
||||
}
|
||||
if text.chars().any(|c| c.is_control() && c != '\n' && c != '\t') {
|
||||
return Err(out_err(at, "`text` must not hold control characters other than line breaks and tabs"));
|
||||
}
|
||||
let font_family = name(o, "fontFamily", true, at)?.unwrap_or_default();
|
||||
let font_style = name(o, "fontStyle", false, at)?;
|
||||
let key = "fontSize";
|
||||
let font_size = match o.get(key) {
|
||||
None | Some(Value::Null) => return Err(out_err(at, format!("missing field `{key}`"))),
|
||||
Some(s) => s.as_f64().ok_or_else(|| out_err(at, format!("`{key}` must be a number")))?,
|
||||
};
|
||||
let (min, max) = TYPE_SIZES;
|
||||
if !(min..=max).contains(&font_size) {
|
||||
let x = font_size;
|
||||
return Err(out_err(at, format!("`{key}` must be between {min} and {max} (got {x})")));
|
||||
}
|
||||
let fill = match o.get("fill") {
|
||||
None => None,
|
||||
Some(f) => {
|
||||
let paint = crate::objects::decode_paint(f, &format!("{at}.fill"))?;
|
||||
if matches!(paint, Paint::Pattern { .. }) {
|
||||
return Err(out_err(at, "a type fill must be a color or a gradient"));
|
||||
}
|
||||
Some(crate::objects::unlinked(paint))
|
||||
}
|
||||
};
|
||||
Ok(OutType {
|
||||
text: text.to_string(),
|
||||
font_family,
|
||||
font_style,
|
||||
font_size,
|
||||
fill,
|
||||
transform: transform(o, "transform", at)?,
|
||||
name: name(o, "name", false, at)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// An image object of the output (`at` names it). Its size has been checked against the limits
|
||||
/// ([`check_totals`]), and its base64's length is checked against its size before anything is
|
||||
/// decoded.
|
||||
fn decode_image(v: &Value, at: &str) -> Result<OutImage> {
|
||||
let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?;
|
||||
known_keys(o, IMAGE_KEYS, at)?;
|
||||
let size = o.get("pixelSize").and_then(Value::as_array).filter(|a| a.len() == 2).and_then(|a| {
|
||||
let side = |v: &Value| v.as_u64().filter(|n| (1..=MAX_IMAGE_SIDE).contains(n));
|
||||
Some((side(a.first()?)?, side(a.get(1)?)?))
|
||||
});
|
||||
let (w, h) = size.ok_or_else(|| out_err(at, format!("`pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE}")))?;
|
||||
let want = w * h * 4;
|
||||
let wrong = || out_err(at, format!("`pixelsBase64` must hold 4 × width × height = {want} bytes as base64"));
|
||||
let b64 = o.get("pixelsBase64").and_then(Value::as_str).ok_or_else(wrong)?;
|
||||
// The length is checked first, so nothing of the wrong size is decoded.
|
||||
if b64.len() as u64 != want.div_ceil(3) * 4 || craft_vectorcraft_format::base64::decoded_len(b64) != want {
|
||||
return Err(wrong());
|
||||
}
|
||||
let rgba = craft_vectorcraft_format::base64::decode(b64).filter(|p| p.len() as u64 == want).ok_or_else(wrong)?;
|
||||
Ok(OutImage { width: w as u32, height: h as u32, rgba, transform: transform(o, "transform", at)?, name: name(o, "name", false, at)? })
|
||||
}
|
||||
|
||||
/// The `layers` of the output, for `count` objects: 1 to [`MAX_LAYERS`] layers, bottom first,
|
||||
/// each listing the indexes of its objects in increasing order, and every object in exactly one.
|
||||
fn decode_layers(v: &Value, count: usize) -> Result<Vec<OutLayer>> {
|
||||
let key = "layers";
|
||||
let list = entries(v, key, MAX_LAYERS)?;
|
||||
let mut owner: Vec<bool> = vec![false; count];
|
||||
let mut layers = Vec::with_capacity(list.len());
|
||||
for (i, l) in list.iter().enumerate() {
|
||||
let at = format!("layers[{i}]");
|
||||
let o = l.as_object().ok_or_else(|| out_err(&at, format!("`{key}` must be an object")))?;
|
||||
known_keys(o, LAYER_KEYS, &at)?;
|
||||
let flag = |key: &str, default: bool| -> Result<bool> {
|
||||
match o.get(key) {
|
||||
None | Some(Value::Null) => Ok(default),
|
||||
Some(v) => v.as_bool().ok_or_else(|| out_err(&at, format!("`{key}` must be true or false"))),
|
||||
}
|
||||
};
|
||||
let wrong = || out_err(&at, format!("`objects` must list object indexes in increasing order, each below {count}"));
|
||||
let indexes = match o.get("objects") {
|
||||
None | Some(Value::Null) => &[][..],
|
||||
Some(v) => v.as_array().ok_or_else(wrong)?.as_slice(),
|
||||
};
|
||||
let mut objects = Vec::with_capacity(indexes.len().min(count));
|
||||
for v in indexes {
|
||||
let k = v.as_u64().and_then(|k| usize::try_from(k).ok()).filter(|k| *k < count).ok_or_else(wrong)?;
|
||||
if objects.last().is_some_and(|last| *last >= k) {
|
||||
return Err(wrong());
|
||||
}
|
||||
if std::mem::replace(&mut owner[k], true) {
|
||||
return Err(out_err(&at, format!("object {k} must be in exactly one layer")));
|
||||
}
|
||||
objects.push(k);
|
||||
}
|
||||
layers.push(OutLayer {
|
||||
name: name(o, "name", true, &at)?.unwrap_or_default(),
|
||||
visible: flag("visible", true)?,
|
||||
locked: flag("locked", false)?,
|
||||
objects,
|
||||
});
|
||||
}
|
||||
if let Some(k) = owner.iter().position(|owned| !owned) {
|
||||
return Err(out_err("layers", format!("object {k} must be in exactly one layer")));
|
||||
}
|
||||
Ok(layers)
|
||||
}
|
||||
|
||||
/// The `artboards` of the output: 1 to [`MAX_ARTBOARDS`], each named once, their rectangles
|
||||
/// within ±[`MAX_COORD`].
|
||||
fn decode_artboards(v: &Value) -> Result<Vec<OutArtboard>> {
|
||||
let key = "artboards";
|
||||
let list = entries(v, key, MAX_ARTBOARDS)?;
|
||||
let mut boards: Vec<OutArtboard> = Vec::with_capacity(list.len());
|
||||
for (i, a) in list.iter().enumerate() {
|
||||
let at = format!("artboards[{i}]");
|
||||
let o = a.as_object().ok_or_else(|| out_err(&at, format!("`{key}` must be an object")))?;
|
||||
known_keys(o, ARTBOARD_KEYS, &at)?;
|
||||
let name = name(o, "name", true, &at)?.unwrap_or_default();
|
||||
if boards.iter().any(|b| b.name == name) {
|
||||
let shown = printable(&json!(name), 64);
|
||||
return Err(out_err(&at, format!("artboard name `{shown}` is used twice")));
|
||||
}
|
||||
let wrong = || out_err(&at, format!("`rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0"));
|
||||
let r = o.get("rect").and_then(Value::as_array).filter(|r| r.len() == 4).ok_or_else(wrong)?;
|
||||
let n: Vec<f64> = r.iter().map(Value::as_f64).collect::<Option<_>>().ok_or_else(wrong)?;
|
||||
let (x, y, w, h) = (n[0], n[1], n[2], n[3]);
|
||||
let (x1, y1) = (x + w, y + h);
|
||||
let inside = |v: f64| v.is_finite() && v.abs() <= MAX_COORD;
|
||||
if !(w > 0.0 && h > 0.0 && x1 > x && y1 > y && inside(x) && inside(y) && inside(x1) && inside(y1)) {
|
||||
return Err(wrong());
|
||||
}
|
||||
boards.push(OutArtboard { name, rect: Rect::new(x, y, x1, y1) });
|
||||
}
|
||||
Ok(boards)
|
||||
}
|
||||
|
||||
/// The list `v`, the output's `key`, of 1 to `max` entries.
|
||||
fn entries<'a>(v: &'a Value, key: &str, max: usize) -> Result<&'a Vec<Value>> {
|
||||
let list = v.as_array().ok_or_else(|| Error::Output(format!("`{key}` must be an array")))?;
|
||||
let n = list.len();
|
||||
if !(1..=max).contains(&n) {
|
||||
return Err(Error::Output(format!("`{key}` must hold 1 to {max} entries (it holds {n})")));
|
||||
}
|
||||
Ok(list)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -184,8 +621,9 @@ mod tests {
|
||||
#[test]
|
||||
fn output_is_the_objects_and_the_warnings_or_a_decline() {
|
||||
let out = decode(format!(r#"{{"objects":[{SQUARE}],"warnings":["a",2]}}"#).as_bytes()).unwrap();
|
||||
assert!(out.paths_only());
|
||||
assert!(out.objects.iter().all(|o| matches!(o, ImportObject::Path(o) if o.id.is_none() && o.path.is_some())));
|
||||
assert_eq!((out.objects.len(), out.warnings), (1, vec!["a".to_string(), "2".to_string()]));
|
||||
assert!(out.objects.iter().all(|o| o.id.is_none() && o.path.is_some()));
|
||||
assert_eq!(decode(format!(r#"{{"objects":[{SQUARE}]}}"#).as_bytes()).unwrap().warnings, Vec::<String>::new());
|
||||
assert_eq!(decode(br#"{"error": "Not a\nplot file."}"#), Err(Error::Failed("Not aplot file.".into())));
|
||||
// A decline is reported as one, also with keys the host doesn't read beside it.
|
||||
@@ -216,6 +654,175 @@ mod tests {
|
||||
assert!(decode(warns.as_bytes()).unwrap_err().to_string().contains("`warnings`"));
|
||||
}
|
||||
|
||||
const ALL: &[OutputKind] = &OutputKind::ALL;
|
||||
|
||||
/// A change made to [`rich`] output.
|
||||
type Edit = Box<dyn FnOnce(&mut Value)>;
|
||||
|
||||
/// Type, an image of 2 × 1 pixels, the square, two layers and two artboards.
|
||||
fn rich() -> Value {
|
||||
let pixels = craft_vectorcraft_format::base64::encode(&[255, 0, 0, 255, 0, 0, 255, 128]);
|
||||
json!({
|
||||
"objects": [
|
||||
{"type": "type", "text": "Hello\nWorld", "fontFamily": "Source Sans 3", "fontStyle": "Bold", "fontSize": 24,
|
||||
"fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40], "name": "Title"},
|
||||
{"type": "image", "pixelSize": [2, 1], "pixelsBase64": pixels, "transform": [10, 0, 0, 10, 0, 100]},
|
||||
serde_json::from_str::<Value>(SQUARE).unwrap(),
|
||||
],
|
||||
"layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}],
|
||||
"artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}],
|
||||
})
|
||||
}
|
||||
|
||||
fn rich_with(edit: impl FnOnce(&mut Value)) -> Result<Imported> {
|
||||
let mut v = rich();
|
||||
edit(&mut v);
|
||||
decode_with(v.to_string().as_bytes(), ALL)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn importer_output_rejects_filter_only_path_updates() {
|
||||
let square: Value = serde_json::from_str(SQUARE).unwrap();
|
||||
let mut identified = square.clone();
|
||||
identified["id"] = json!(3);
|
||||
for object in [json!({"id": 3}), json!({"type": "path"}), identified] {
|
||||
let output = json!({"objects": [object]});
|
||||
for kinds in [&[OutputKind::Type][..], &[][..]] {
|
||||
assert!(decode_with(output.to_string().as_bytes(), kinds).is_err(), "{kinds:?}: {output}");
|
||||
}
|
||||
}
|
||||
let mut untyped = square.clone();
|
||||
untyped.as_object_mut().unwrap().remove("type");
|
||||
for object in [square, untyped] {
|
||||
let output = json!({"objects": [object]});
|
||||
for kinds in [&[OutputKind::Type][..], &[][..]] {
|
||||
assert!(decode_with(output.to_string().as_bytes(), kinds).is_ok(), "{kinds:?}: {output}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn importer_output_rejects_artboards_with_collapsed_endpoints() {
|
||||
for rect in [[1_000_000.0, 0.0, 1e-12, 10.0], [0.0, 1_000_000.0, 10.0, 1e-12]] {
|
||||
assert!(rich_with(|v| v["artboards"][0]["rect"] = json!(rect)).is_err(), "{rect:?}");
|
||||
}
|
||||
assert!(rich_with(|v| v["artboards"][0]["rect"] = json!([3_999_999.0, 3_999_999.0, 1.0, 1.0])).is_ok());
|
||||
}
|
||||
|
||||
/// An importer listing every output kind returns type, an embedded image, paths, layers and
|
||||
/// artboards, each read as it was given.
|
||||
#[test]
|
||||
fn each_output_kind_is_read_as_given() {
|
||||
let out = decode_with(rich().to_string().as_bytes(), ALL).unwrap();
|
||||
assert!(!out.paths_only());
|
||||
let [ImportObject::Type(t), ImportObject::Image(im), ImportObject::Path(p)] = out.objects.as_slice() else { panic!("{:?}", out.objects) };
|
||||
assert_eq!(
|
||||
(t.text.as_str(), t.font_family.as_str(), t.font_style.as_deref(), t.font_size),
|
||||
("Hello\nWorld", "Source Sans 3", Some("Bold"), 24.0)
|
||||
);
|
||||
assert_eq!((t.transform, t.name.as_deref()), (Affine::translate((10.0, 40.0)), Some("Title")));
|
||||
assert!(matches!(t.fill, Some(Paint::Solid { .. })));
|
||||
assert_eq!((im.width, im.height, im.rgba.as_slice()), (2, 1, &[255, 0, 0, 255, 0, 0, 255, 128][..]));
|
||||
assert!(p.path.is_some());
|
||||
let layers: Vec<_> = out.layers.iter().map(|l| (l.name.as_str(), l.visible, l.locked, l.objects.clone())).collect();
|
||||
assert_eq!(layers, [("Art", true, false, vec![1, 2]), ("Words", false, true, vec![0])]);
|
||||
let boards: Vec<_> = out.artboards.iter().map(|a| (a.name.as_str(), a.rect)).collect();
|
||||
assert_eq!(boards, [("Front", Rect::new(0.0, 0.0, 200.0, 100.0)), ("Back", Rect::new(220.0, 0.0, 420.0, 100.0))]);
|
||||
// Artboards alone are a blank document.
|
||||
let blank = decode_with(br#"{"objects":[],"artboards":[{"name":"A","rect":[0,0,10,10]}]}"#, &[OutputKind::Artboard]).unwrap();
|
||||
assert_eq!((blank.objects.len(), blank.artboards.len()), (0, 1));
|
||||
}
|
||||
|
||||
/// Output of a kind the manifest doesn't list is refused naming the kind; an importer listing
|
||||
/// none reads paths alone, as before.
|
||||
#[test]
|
||||
fn a_kind_not_listed_is_refused_naming_it() {
|
||||
let v = rich().to_string();
|
||||
for (kinds, named) in [
|
||||
(&[OutputKind::Image, OutputKind::Layer, OutputKind::Artboard][..], "`type`"),
|
||||
(&[OutputKind::Type, OutputKind::Layer, OutputKind::Artboard][..], "`image`"),
|
||||
(&[OutputKind::Type, OutputKind::Image, OutputKind::Artboard][..], "`layer`"),
|
||||
(&[OutputKind::Type, OutputKind::Image, OutputKind::Layer][..], "`artboard`"),
|
||||
] {
|
||||
let e = decode_with(v.as_bytes(), kinds).unwrap_err().to_string();
|
||||
assert!(e.contains(named) && e.contains("`outputKinds` doesn't list"), "{named}: {e}");
|
||||
}
|
||||
let typed = r#"{"objects":[{"type":"type","text":"a","fontFamily":"x","fontSize":12}]}"#;
|
||||
assert!(decode(typed.as_bytes()).unwrap_err().to_string().contains("`type` must be \"path\" or \"compound\""));
|
||||
let layered = format!(r#"{{"objects":[{SQUARE}],"layers":[{{"name":"A","objects":[0]}}]}}"#);
|
||||
assert!(decode(layered.as_bytes()).unwrap_err().to_string().contains("not `layers`"));
|
||||
assert!(decode(br#"{"objects":[],"artboards":[]}"#).unwrap_err().to_string().contains("not `artboards`"));
|
||||
}
|
||||
|
||||
/// Each limit refuses the whole output and names the limit.
|
||||
#[test]
|
||||
fn each_limit_is_enforced_naming_it() {
|
||||
let names = |n: usize| (0..n).map(|i| json!({"name": format!("L{i}")})).collect::<Vec<_>>();
|
||||
let cases: Vec<(Edit, String)> = vec![
|
||||
(Box::new(move |v: &mut Value| v["layers"] = json!(names(MAX_LAYERS + 1))), format!("1 to {MAX_LAYERS} entries")),
|
||||
(Box::new(|v: &mut Value| v["layers"] = json!([])), "1 to".into()),
|
||||
(
|
||||
Box::new(|v: &mut Value| {
|
||||
v["artboards"] = json!((0..=MAX_ARTBOARDS).map(|i| json!({"name": format!("A{i}"), "rect": [0, 0, 1, 1]})).collect::<Vec<_>>())
|
||||
}),
|
||||
format!("1 to {MAX_ARTBOARDS} entries"),
|
||||
),
|
||||
(Box::new(|v: &mut Value| v["objects"][0]["text"] = json!("x".repeat(MAX_TYPE_TEXT + 1))), format!("(limit {MAX_TYPE_TEXT})")),
|
||||
(
|
||||
Box::new(|v: &mut Value| v["objects"][1]["pixelSize"] = json!([MAX_IMAGE_SIDE + 1, 1])),
|
||||
format!("(limit {MAX_IMAGE_SIDE} pixels a side)"),
|
||||
),
|
||||
(Box::new(|v: &mut Value| v["objects"][0]["fontSize"] = json!(TYPE_SIZES.1 * 2.0)), "`fontSize` must be between".into()),
|
||||
(
|
||||
Box::new(|v: &mut Value| v["objects"][0]["fontFamily"] = json!("f".repeat(MAX_NAME_CHARS + 1))),
|
||||
format!("1-{MAX_NAME_CHARS} characters"),
|
||||
),
|
||||
];
|
||||
for (edit, says) in cases {
|
||||
let e = rich_with(edit).unwrap_err().to_string();
|
||||
assert!(e.contains(&says), "{says}: {e}");
|
||||
}
|
||||
// Totals over all type and all images, found from the sizes they give before any pixels are
|
||||
// decoded: these images carry no pixels at all.
|
||||
let big = json!({"type": "image", "pixelSize": [MAX_IMAGE_SIDE, MAX_IMAGE_SIDE]});
|
||||
let e = decode_with(json!({"objects": [big]}).to_string().as_bytes(), ALL).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("more than {MAX_PIXEL_BYTES} bytes of pixels")), "{e}");
|
||||
let text = "t".repeat(MAX_TYPE_TEXT);
|
||||
let many: Vec<Value> = (0..=MAX_TEXT_TOTAL / MAX_TYPE_TEXT).map(|_| json!({"type": "type", "text": text, "fontSize": 12})).collect();
|
||||
let e = decode_with(json!({"objects": many}).to_string().as_bytes(), ALL).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("more than {MAX_TEXT_TOTAL} bytes of text")), "{e}");
|
||||
}
|
||||
|
||||
/// An image whose bytes aren't 4 × width × height, or aren't base64, is refused; so are names
|
||||
/// holding control or direction characters, text holding control characters, layers that don't
|
||||
/// hold each object once in order, and bad artboards.
|
||||
#[test]
|
||||
fn malformed_content_is_refused() {
|
||||
let cases: Vec<(Edit, &str)> = vec![
|
||||
(Box::new(|v: &mut Value| v["objects"][1]["pixelsBase64"] = json!(craft_vectorcraft_format::base64::encode(&[1, 2, 3, 4]))), "= 8 bytes"),
|
||||
(Box::new(|v: &mut Value| v["objects"][1]["pixelsBase64"] = json!("!!!!!!!!!!!!")), "= 8 bytes"),
|
||||
(Box::new(|v: &mut Value| v["objects"][1]["pixelSize"] = json!([0, 1])), "`pixelSize`"),
|
||||
(Box::new(|v: &mut Value| v["objects"][1]["linked"] = json!(true)), "unknown field `linked`"),
|
||||
(Box::new(|v: &mut Value| v["objects"][0]["kind"] = json!("area")), "unknown field `kind`"),
|
||||
(Box::new(|v: &mut Value| v["objects"][0]["text"] = json!("a\u{7}b")), "control characters"),
|
||||
(Box::new(|v: &mut Value| v["objects"][0]["fill"] = json!({"type": "pattern", "pattern": "p"})), "objects[0]"),
|
||||
(Box::new(|v: &mut Value| v["objects"][0]["transform"] = json!([0, 0, 0, 0, 0, 0])), "six finite numbers"),
|
||||
(Box::new(|v: &mut Value| v["layers"][0]["name"] = json!("Art\u{202E}txt")), "text direction characters"),
|
||||
(Box::new(|v: &mut Value| v["artboards"][0]["name"] = json!("A\u{0}")), "text direction characters"),
|
||||
(Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([2, 1])), "increasing order"),
|
||||
(Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([0, 1, 2])), "object 0 must be in exactly one layer"),
|
||||
(Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([1])), "object 2 must be in exactly one layer"),
|
||||
(Box::new(|v: &mut Value| v["layers"][0]["objects"] = json!([1, 2, 3])), "each below 3"),
|
||||
(Box::new(|v: &mut Value| v["artboards"][1]["name"] = json!("Front")), "`Front` is used twice"),
|
||||
(Box::new(|v: &mut Value| v["artboards"][0]["rect"] = json!([0, 0, 0, 10])), "width and height above 0"),
|
||||
(Box::new(|v: &mut Value| v["artboards"][0]["rect"] = json!([3_999_999, 0, 10, 10])), "within ±4000000"),
|
||||
];
|
||||
for (edit, says) in cases {
|
||||
let e = rich_with(edit).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{says}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warnings_are_capped_in_number_and_length() {
|
||||
let many: Vec<String> = (0..crate::export::MAX_WARNINGS + 5).map(|i| format!("w{i}")).collect();
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
//! time it is drawn, from an appearance stack, and at `api` 2 may paint what it returns
|
||||
//! ([`painted`]); an **exporter** ([`export`]) writes the whole
|
||||
//! document in a file format of its own; an **importer** ([`import`]) reads a file in a format of
|
||||
//! its own into a new document; a **generator** ([`generate`]) draws art from its parameters alone,
|
||||
//! its own into a new document, and at `api` 4 may also return type, embedded images, layers and
|
||||
//! artboards ([`OutputKind`]); a **generator** ([`generate`]) draws art from its parameters alone,
|
||||
//! which the document keeps with them so the art can be drawn again. The process-wide [`registry`] holds the installed
|
||||
//! plug-ins; in [`safe_mode`] none of them loads or runs. A plug-in's parameters ([`manifest`]) come with what the host's dialogs need to show
|
||||
//! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is
|
||||
@@ -65,7 +66,8 @@ pub mod worker;
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{
|
||||
Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec, Runtime,
|
||||
Budget, Command, ContextMenu, ContextPlace, ContextSection, ContextWhen, InputKind, Kind, Manifest, MenuPlace, OutputKind, Param, ParamSpec,
|
||||
Runtime,
|
||||
};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, RunJob, Step, heavy_terms, keep_modules};
|
||||
#[doc(hidden)]
|
||||
|
||||
@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::dialog::ParamUi;
|
||||
use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::permissions::{self, API_LEVEL, APPEARANCE_API, CONTEXT_API, INPUTS_API, OUTPUT_KINDS_API, PROGRESS_API, Permission, WRITES_API};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Longest manifest the host reads.
|
||||
@@ -289,6 +289,41 @@ impl InputKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// A kind of content an importer may return besides paths and compound paths (its manifest's
|
||||
/// `outputKinds`, plug-in API level 4). Output holding a kind its manifest doesn't list is refused
|
||||
/// ([`crate::import::decode_with`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum OutputKind {
|
||||
/// Point type: its text, font family and style, size and fill.
|
||||
Type,
|
||||
/// An embedded image: its size in pixels and its RGBA pixels.
|
||||
Image,
|
||||
/// Top-level layers: their names, whether they show and are locked, and the objects each holds.
|
||||
Layer,
|
||||
/// Artboards: their names and rectangles.
|
||||
Artboard,
|
||||
}
|
||||
|
||||
impl OutputKind {
|
||||
/// Every kind, in the order the docs list them.
|
||||
pub const ALL: [OutputKind; 4] = [OutputKind::Type, OutputKind::Image, OutputKind::Layer, OutputKind::Artboard];
|
||||
|
||||
/// Its name in `outputKinds`. A type or an image object's `type` in the output is this name too.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
OutputKind::Type => "type",
|
||||
OutputKind::Image => "image",
|
||||
OutputKind::Layer => "layer",
|
||||
OutputKind::Artboard => "artboard",
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind named `name`.
|
||||
pub fn parse(name: &str) -> Option<OutputKind> {
|
||||
OutputKind::ALL.into_iter().find(|k| k.name() == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// A part of the active document a filter or a plug-in command asks to be given in
|
||||
/// `_context.document`, with or without a selection (its manifest's `context`, plug-in API level 3):
|
||||
/// plain values to read, never objects.
|
||||
@@ -639,6 +674,11 @@ pub struct Manifest {
|
||||
/// lists them. Left out or empty, it is given paths and compound paths alone.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty", deserialize_with = "input_names")]
|
||||
pub inputs: Vec<String>,
|
||||
/// The kinds of content an importer returns besides paths and compound paths, by
|
||||
/// [`OutputKind::name`]: only an importer at `api` 4 or later lists them. Left out or empty, it
|
||||
/// returns paths and compound paths alone.
|
||||
#[serde(default, rename = "outputKinds", skip_serializing_if = "Vec::is_empty", deserialize_with = "output_kind_names")]
|
||||
pub output_kinds: Vec<String>,
|
||||
/// The kinds among `inputs` the filter may change, by [`InputKind::name`]: only a filter at
|
||||
/// `api` 3 or later whose `permissions` list `doc.read` and `doc.write` lists them. Left out or
|
||||
/// empty, every kind it reads stays read-only.
|
||||
@@ -727,6 +767,7 @@ impl Manifest {
|
||||
api: 1,
|
||||
permissions: None,
|
||||
inputs: Vec::new(),
|
||||
output_kinds: Vec::new(),
|
||||
writes: Vec::new(),
|
||||
context: Vec::new(),
|
||||
params: Vec::new(),
|
||||
@@ -818,6 +859,7 @@ impl Manifest {
|
||||
return Err(Error::Manifest(format!("permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API}")));
|
||||
}
|
||||
self.validate_inputs()?;
|
||||
self.validate_output_kinds()?;
|
||||
self.validate_writes()?;
|
||||
self.validate_context()?;
|
||||
if self.paint_output && (self.kind != Kind::Effect || self.api < 2) {
|
||||
@@ -948,6 +990,30 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `outputKinds` names each [`OutputKind`] at most once, and only an importer at `api`
|
||||
/// [`OUTPUT_KINDS_API`] or later lists any.
|
||||
fn validate_output_kinds(&self) -> Result<()> {
|
||||
if self.output_kinds.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if self.kind != Kind::Importer {
|
||||
return Err(Error::Manifest("only an importer declares `outputKinds`".into()));
|
||||
}
|
||||
for (i, name) in self.output_kinds.iter().enumerate() {
|
||||
let shown = permissions::display_text(name, permissions::MAX_SHOWN_FIELD);
|
||||
if OutputKind::parse(name).is_none() {
|
||||
return Err(Error::Manifest(format!("`outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard")));
|
||||
}
|
||||
if self.output_kinds.get(..i).is_some_and(|before| before.contains(name)) {
|
||||
return Err(Error::Manifest(format!("`outputKinds` lists `{shown}` twice")));
|
||||
}
|
||||
}
|
||||
if self.api < OUTPUT_KINDS_API {
|
||||
return Err(Error::Manifest(format!("`outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `writes` names each [`InputKind`] at most once, each one `inputs` lists, and only a filter at
|
||||
/// `api` 3 or later lists any, with a `permissions` list that holds `doc.read` and `doc.write`.
|
||||
fn validate_writes(&self) -> Result<()> {
|
||||
@@ -1001,6 +1067,11 @@ impl Manifest {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The kinds of content besides paths and compound paths an importer returns (`outputKinds`).
|
||||
pub fn output_kinds(&self) -> Vec<OutputKind> {
|
||||
self.output_kinds.iter().filter_map(|n| OutputKind::parse(n)).collect()
|
||||
}
|
||||
|
||||
/// The parts of the document it asks to be given (`context`).
|
||||
pub fn context_sections(&self) -> Vec<ContextSection> {
|
||||
self.context.iter().filter_map(|n| ContextSection::parse(n)).collect()
|
||||
@@ -1226,6 +1297,17 @@ fn input_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Ve
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `outputKinds`: a list of names (`null`: none). Anything else is an error that names the
|
||||
/// key, as [`Manifest::validate_output_kinds`] names a wrong entry.
|
||||
fn output_kind_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
let wrong = || serde::de::Error::custom("`outputKinds` must be a list of kinds: type, image, layer or artboard");
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(Vec::new()),
|
||||
Value::Array(names) => names.into_iter().map(|n| if let Value::String(s) = n { Ok(s) } else { Err(wrong()) }).collect(),
|
||||
_ => Err(wrong()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `writes` as [`input_names`] reads `inputs`.
|
||||
fn write_names<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Vec<String>, D::Error> {
|
||||
let wrong = || serde::de::Error::custom("`writes` must be a list of object kinds: type, image or symbolInstance");
|
||||
@@ -1689,7 +1771,7 @@ mod tests {
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["progress"]}"#, "`progress` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","permissions":["settings"]}"#, "`settings` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":1,"permissions":["doc.read","cache"]}"#, "`cache` needs plug-in API level 2"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":4}"#, "`api` is 4; this host implements plug-in API levels 1 to 3"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":5}"#, "`api` is 5; this host implements plug-in API levels 1 to 4"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":0}"#, "`api` is 0"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":-1}"#, "manifest"),
|
||||
] {
|
||||
@@ -1698,6 +1780,46 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// An importer at `api` 4 lists the kinds it returns besides paths (`outputKinds`), each once;
|
||||
/// another kind of plug-in, an earlier level, an unknown kind or a repeat is refused naming
|
||||
/// `outputKinds`. Left out or empty, it lists none and isn't written back.
|
||||
#[test]
|
||||
fn an_importer_at_api_4_lists_the_kinds_it_returns() {
|
||||
let m = Manifest::parse(
|
||||
br#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["type","image","layer","artboard"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(m.output_kinds(), OutputKind::ALL);
|
||||
assert_eq!(serde_json::to_value(&m).unwrap()["outputKinds"], json!(["type", "image", "layer", "artboard"]));
|
||||
assert_eq!(m.permissions(), [Permission::ImportRead]);
|
||||
for none in [
|
||||
r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":[]}"#,
|
||||
r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"],"outputKinds":null}"#,
|
||||
] {
|
||||
let m = Manifest::parse(none.as_bytes()).unwrap();
|
||||
assert!(m.output_kinds().is_empty(), "{none}");
|
||||
assert!(serde_json::to_value(&m).unwrap().get("outputKinds").is_none(), "{none}");
|
||||
}
|
||||
for (bad, says) in [
|
||||
(r#"{"id":"a","name":"x","kind":"importer","extensions":["tst"],"outputKinds":["type"]}"#, "`outputKinds` needs plug-in API level 4"),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","api":2,"extensions":["tst"],"outputKinds":["layer"]}"#, "give `api` 4"),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","api":3,"extensions":["tst"],"outputKinds":["image"]}"#, "give `api` 4"),
|
||||
(r#"{"id":"a","name":"x","kind":"filter","api":4,"outputKinds":["type"]}"#, "only an importer declares `outputKinds`"),
|
||||
(
|
||||
r#"{"id":"a","name":"x","kind":"exporter","api":4,"extensions":["tst"],"outputKinds":["image"]}"#,
|
||||
"only an importer declares `outputKinds`",
|
||||
),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["text"]}"#, "unknown kind `text`"),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":["image","image"]}"#, "lists `image` twice"),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":"type"}"#, "`outputKinds` must be a list"),
|
||||
(r#"{"id":"a","name":"x","kind":"importer","api":4,"extensions":["tst"],"outputKinds":[1]}"#, "`outputKinds` must be a list"),
|
||||
] {
|
||||
let e = Manifest::parse(bad.as_bytes()).unwrap_err().to_string();
|
||||
assert!(e.contains(says), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter at `api` 2 may ask for type, images and symbol instances (`inputs`), each kind once,
|
||||
/// with a `permissions` list holding `doc.read`, so installing it asks for approval. Left out
|
||||
/// or empty, it asks for none and isn't written back. Anything else is refused naming `inputs`.
|
||||
|
||||
@@ -603,7 +603,7 @@ pub(crate) fn clamp_color(c: Color) -> Color {
|
||||
|
||||
/// A paint from plug-in output (`null`: none), with colors, process plates, opacities and
|
||||
/// offsets clamped and gradient and pattern placements checked.
|
||||
fn decode_paint(v: &Value, at: &str) -> Result<Paint> {
|
||||
pub(crate) fn decode_paint(v: &Value, at: &str) -> Result<Paint> {
|
||||
if v.is_null() {
|
||||
return Ok(Paint::None);
|
||||
}
|
||||
@@ -693,7 +693,7 @@ fn opt<'a>(o: &'a serde_json::Map<String, Value>, key: &str) -> Option<&'a Value
|
||||
/// Object `v` of a plug-in's output (`at` names it in errors), its anchors added to `anchors` and
|
||||
/// held to [`MAX_ANCHORS`]: each key it has checked, numbers clamped into range, as [`decode`] reads
|
||||
/// them.
|
||||
fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result<OutObject> {
|
||||
pub(crate) fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result<OutObject> {
|
||||
let o = v.as_object().ok_or_else(|| out_err(at, "an object must be a JSON object"))?;
|
||||
let mut out = OutObject::default();
|
||||
if let Some(id) = opt(o, "id") {
|
||||
@@ -1061,7 +1061,7 @@ fn paints(ap: &Appearance, fill: bool) -> Vec<&Paint> {
|
||||
/// `p` without swatch links: a plug-in's colours are its own, so only paints it returned
|
||||
/// unchanged keep theirs. A gradient stop also loses its process plates, which print only with
|
||||
/// a spot swatch.
|
||||
fn unlinked(mut p: Paint) -> Paint {
|
||||
pub(crate) fn unlinked(mut p: Paint) -> Paint {
|
||||
match &mut p {
|
||||
Paint::Solid { swatch, tint, .. } => {
|
||||
*swatch = None;
|
||||
@@ -1358,6 +1358,21 @@ impl Plan {
|
||||
}
|
||||
}
|
||||
|
||||
/// New object `o` of a plug-in's output (`at` names it in errors) as a node of `doc`, not yet in it:
|
||||
/// a path or a compound path made as [`apply_output`] makes one, its effects admitted by `admit`.
|
||||
/// An object with an `id` or without a `path` is an error.
|
||||
pub fn new_object(doc: &mut Document, o: OutObject, at: &str, admit: AdmitEffects) -> Result<Node> {
|
||||
if let Some(id) = o.id {
|
||||
return Err(out_err(at, format!("{} is not the id of an input object", id.0)));
|
||||
}
|
||||
if o.path.is_none() {
|
||||
return Err(out_err(at, "a new object needs a `path`"));
|
||||
}
|
||||
let mut n = Node::path(doc.alloc_id(), PathData::default(), Appearance::default());
|
||||
write(doc, &mut n, o, at, admit)?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Applies an object filter's output to `doc`.
|
||||
///
|
||||
/// `inputs` are the objects the plug-in was given, in paint order ([`filter_targets`]). Output
|
||||
|
||||
@@ -16,8 +16,13 @@ use crate::{Error, Kind, Result};
|
||||
/// The plug-in API level this host implements. A manifest's `api` (1 when left out) may be at most
|
||||
/// this. Level 2 adds the host imports ([`PROGRESS_API`]) and a live effect's `paintOutput`
|
||||
/// ([`crate::painted`]); level 3 adds a filter's `writes` ([`WRITES_API`]), a live effect's
|
||||
/// `appearanceOutput` ([`APPEARANCE_API`]) and a manifest's `context` ([`CONTEXT_API`]).
|
||||
pub const API_LEVEL: u32 = 3;
|
||||
/// `appearanceOutput` ([`APPEARANCE_API`]) and a manifest's `context` ([`CONTEXT_API`]). Level 4
|
||||
/// adds an importer's `outputKinds` ([`OUTPUT_KINDS_API`]).
|
||||
pub const API_LEVEL: u32 = 4;
|
||||
|
||||
/// The API level that adds an importer's `outputKinds` ([`crate::OutputKind`]): type, embedded
|
||||
/// images, layers and artboards in what it returns ([`crate::import`]).
|
||||
pub const OUTPUT_KINDS_API: u32 = 4;
|
||||
|
||||
/// The API level that adds a painted live effect's `appearanceOutput`: opacity, a blending mode
|
||||
/// and effects on the pieces it returns and on their fills and strokes ([`crate::painted`]).
|
||||
|
||||
+280
-34
@@ -9,12 +9,19 @@ use vectorcraft_geom::BezPath;
|
||||
/// Vello flattens the two sides of a filled stroke independently at 0.25 device pixels.
|
||||
/// For strokes narrower than four times the raster tolerance, fit and preflatten the
|
||||
/// band more tightly. Wider strokes and the document/export geometry are unchanged.
|
||||
///
|
||||
/// A plain stroke (no dashes, no width profile) along a line with curves is drawn as lines first
|
||||
/// ([`thin_line`]) and outlined by [`thin_band`], with one line on each side for each line of the
|
||||
/// path. Other thin strokes are fitted and flattened at the fine tolerance.
|
||||
pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> BezPath {
|
||||
if width >= tol * 4.0 {
|
||||
return effects::stroke::line_outline(line, st, width, tol);
|
||||
}
|
||||
// Closed endpoint rounding must not consume a substantial part of a subpixel band.
|
||||
let fine = (tol / 8.0).min(width / 32.0).max(1e-4);
|
||||
if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) {
|
||||
return band;
|
||||
}
|
||||
let outline = effects::stroke::line_outline(line, st, width, fine);
|
||||
let mut flat = BezPath::new();
|
||||
// Keep upstream's per-curve work cap for untrusted or extreme coordinates.
|
||||
@@ -22,6 +29,169 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) ->
|
||||
flat
|
||||
}
|
||||
|
||||
/// The lines a thin stroke's curves are drawn with lie within about this share of its width of the
|
||||
/// curve, before their ends are moved out ([`draw_lines`]).
|
||||
const THIN_CHORD: f64 = 1.0 / 6.0;
|
||||
/// Where two lines of a thin stroke meet at an angle whose sine is at most this, and turn by less
|
||||
/// than a right angle, [`thin_band`] offsets both sides to where the two lines' offsets cross,
|
||||
/// whatever the stroke's join.
|
||||
const THIN_SMOOTH: f64 = 0.8;
|
||||
|
||||
/// `line` with all its curves drawn as lines within about [`THIN_CHORD`] of `width` of them, for a
|
||||
/// stroke `st` narrower than four raster tolerances ([`outline`]). `None` for a stroke with a width
|
||||
/// profile or dashes, for a line with no curves, and when a curve can't be drawn as lines
|
||||
/// ([`lines`]).
|
||||
fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option<BezPath> {
|
||||
if st.profile.is_some() || st.dash.is_some() || !(width > 0.0 && width.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let lines = lines(line, 0.0, width * THIN_CHORD)?;
|
||||
lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines)
|
||||
}
|
||||
|
||||
/// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill
|
||||
/// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet
|
||||
/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the
|
||||
/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as
|
||||
/// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a
|
||||
/// point that isn't finite, or is closed and no wider or taller than the stroke: those take
|
||||
/// [`effects::stroke::line_outline`].
|
||||
fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option<BezPath> {
|
||||
let h = width / 2.0;
|
||||
// The angle between two points of an arc of radius `h` drawn as lines within `fine` of it.
|
||||
let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3);
|
||||
let mut out = BezPath::new();
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
let mut closed = false;
|
||||
let flush = |pts: &mut Vec<Point>, closed: bool, out: &mut BezPath| -> Option<()> {
|
||||
if pts.is_empty() {
|
||||
return Some(());
|
||||
}
|
||||
if closed && pts.len() > 1 && pts.first() == pts.last() {
|
||||
pts.pop();
|
||||
}
|
||||
if pts.len() < 2 || !pts.iter().all(|p| p.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
if closed {
|
||||
let (lo, hi) =
|
||||
pts.iter().fold((pts[0], pts[0]), |(lo, hi), p| (Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y))));
|
||||
if (hi.x - lo.x).min(hi.y - lo.y) <= width {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
band_sub(out, pts, closed, st, h, step);
|
||||
pts.clear();
|
||||
Some(())
|
||||
};
|
||||
for el in lines.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut pts, closed, &mut out)?;
|
||||
closed = false;
|
||||
pts.push(p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
if pts.last() != Some(&p) {
|
||||
pts.push(p);
|
||||
}
|
||||
}
|
||||
PathEl::ClosePath => closed = true,
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None,
|
||||
}
|
||||
}
|
||||
flush(&mut pts, closed, &mut out)?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Adds the outline of one subpath with the distinct points `pts` (at least two, the last not
|
||||
/// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side,
|
||||
/// the end cap, its right side backward and the start cap; for a closed one its left side and its
|
||||
/// right side backward, as two contours. `h` is half the width and `step` the angle between the
|
||||
/// points of a round join or cap.
|
||||
fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) {
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
let n = pts.len();
|
||||
let chords = if closed { n } else { n - 1 };
|
||||
// The direction of line `i` (from point `i` to the next) as a unit vector, and its normal.
|
||||
let dir = |i: usize| (pts[(i + 1) % n] - pts[i % n]).normalize();
|
||||
let norm = |u: Vec2| Vec2::new(-u.y, u.x);
|
||||
// Points on an arc of radius `h` around `c` from `from` to `to` (both of length `h`), turning
|
||||
// by `angle` (positive: from `from` toward its normal), without its first point.
|
||||
let arc = |side: &mut Vec<Point>, c: Point, from: Vec2, angle: f64| {
|
||||
let k = (angle.abs() / step).ceil().max(1.0) as usize;
|
||||
for j in 1..=k {
|
||||
let a = angle * j as f64 / k as f64;
|
||||
let (s, co) = a.sin_cos();
|
||||
side.push(c + Vec2::new(from.x * co - from.y * s, from.x * s + from.y * co));
|
||||
}
|
||||
};
|
||||
let (mut left, mut right) = (Vec::with_capacity(n + 2), Vec::with_capacity(n + 2));
|
||||
let join = |left: &mut Vec<Point>, right: &mut Vec<Point>, p: Point, ua: Vec2, ub: Vec2| {
|
||||
let (na, nb) = (norm(ua) * h, norm(ub) * h);
|
||||
let (cross, dot) = (ua.cross(ub), ua.dot(ub));
|
||||
// Where the offsets of the two lines cross, on the right side; the left one is opposite.
|
||||
let miter = (na + nb) / (1.0 + dot);
|
||||
if dot > 0.0 && cross.abs() <= THIN_SMOOTH {
|
||||
left.push(p - miter);
|
||||
right.push(p + miter);
|
||||
return;
|
||||
}
|
||||
// The outer side of the turn: the left side when the path turns toward its normal.
|
||||
let (outer, inner, sign) = if cross > 0.0 { (left, right, -1.0) } else { (right, left, 1.0) };
|
||||
inner.push(p - na * sign);
|
||||
inner.push(p);
|
||||
inner.push(p - nb * sign);
|
||||
outer.push(p + na * sign);
|
||||
match st.join {
|
||||
LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign),
|
||||
LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)),
|
||||
LineJoin::Miter | LineJoin::Bevel => {}
|
||||
}
|
||||
outer.push(p + nb * sign);
|
||||
};
|
||||
if closed {
|
||||
for (i, &p) in pts.iter().enumerate() {
|
||||
join(&mut left, &mut right, p, dir(i + n - 1), dir(i));
|
||||
}
|
||||
contour(out, left.iter().copied());
|
||||
contour(out, right.iter().rev().copied());
|
||||
return;
|
||||
}
|
||||
let (first, last) = (dir(0), dir(chords - 1));
|
||||
let square = |u: Vec2| if st.cap == LineCap::Square { u * h } else { Vec2::ZERO };
|
||||
left.push(pts[0] - norm(first) * h - square(first));
|
||||
right.push(pts[0] + norm(first) * h - square(first));
|
||||
for (i, &p) in pts.iter().enumerate().take(chords).skip(1) {
|
||||
join(&mut left, &mut right, p, dir(i - 1), dir(i));
|
||||
}
|
||||
let end = pts[n - 1];
|
||||
left.push(end - norm(last) * h + square(last));
|
||||
right.push(end + norm(last) * h + square(last));
|
||||
let mut ring = left;
|
||||
if st.cap == LineCap::Round {
|
||||
arc(&mut ring, end, -norm(last) * h, std::f64::consts::PI);
|
||||
ring.pop();
|
||||
}
|
||||
ring.extend(right.iter().rev().copied());
|
||||
if st.cap == LineCap::Round {
|
||||
arc(&mut ring, pts[0], norm(first) * h, std::f64::consts::PI);
|
||||
ring.pop();
|
||||
}
|
||||
contour(out, ring.into_iter());
|
||||
}
|
||||
|
||||
/// Adds the closed contour through `pts` to `out`.
|
||||
fn contour(out: &mut BezPath, mut pts: impl Iterator<Item = Point>) {
|
||||
if let Some(p) = pts.next() {
|
||||
out.move_to(p);
|
||||
for p in pts {
|
||||
out.line_to(p);
|
||||
}
|
||||
out.close_path();
|
||||
}
|
||||
}
|
||||
|
||||
/// Strokes at least this many tolerances wide (8 device pixels at a tolerance of 0.25 px) have
|
||||
/// their long curves drawn as lines by [`wide`].
|
||||
const WIDE: f64 = 32.0;
|
||||
@@ -63,7 +233,7 @@ pub(crate) fn wide(outline: BezPath, width: f64, tol: f64) -> BezPath {
|
||||
if !(tol > 0.0 && tol.is_finite() && width >= tol * WIDE) {
|
||||
return outline;
|
||||
}
|
||||
lines(&outline, tol).unwrap_or(outline)
|
||||
lines(&outline, tol * SPAN, tol * CHORD).unwrap_or(outline)
|
||||
}
|
||||
|
||||
/// One subpath: where it starts, its segments, each with the most steps it is drawn with as lines
|
||||
@@ -74,11 +244,11 @@ struct Sub {
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
/// `path` with its long curves drawn as lines ([`wide`]); `None` when it has no long curve, would
|
||||
/// `path` with its curves whose control points span at least `span` across or down drawn as lines
|
||||
/// within about `chord` of them ([`wide`], [`thin_line`]); `None` when it has no such curve, would
|
||||
/// take more than [`MAX_LINES`] lines, or does not start each subpath with a move.
|
||||
fn lines(path: &BezPath, tol: f64) -> Option<BezPath> {
|
||||
let chord = tol * CHORD;
|
||||
let subs = subpaths(path.elements(), tol, chord)?;
|
||||
fn lines(path: &BezPath, span: f64, chord: f64) -> Option<BezPath> {
|
||||
let subs = subpaths(path.elements(), span, chord)?;
|
||||
let mut total = 0usize;
|
||||
for (_, steps) in subs.iter().flat_map(|s| &s.segs) {
|
||||
if *steps > 0 {
|
||||
@@ -98,7 +268,7 @@ fn lines(path: &BezPath, tol: f64) -> Option<BezPath> {
|
||||
/// The subpaths of `els`, each segment with its steps ([`steps`]). A close adds a line back to the
|
||||
/// start when the subpath ends elsewhere. `None` when a segment comes before any move or after a
|
||||
/// close without a move.
|
||||
fn subpaths(els: &[PathEl], tol: f64, chord: f64) -> Option<Vec<Sub>> {
|
||||
fn subpaths(els: &[PathEl], span: f64, chord: f64) -> Option<Vec<Sub>> {
|
||||
let mut subs: Vec<Sub> = Vec::new();
|
||||
for el in els {
|
||||
if let PathEl::MoveTo(p) = *el {
|
||||
@@ -122,7 +292,7 @@ fn subpaths(els: &[PathEl], tol: f64, chord: f64) -> Option<Vec<Sub>> {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
sub.segs.push((seg, steps(seg, tol, chord)));
|
||||
sub.segs.push((seg, steps(seg, span, chord)));
|
||||
}
|
||||
Some(subs)
|
||||
}
|
||||
@@ -137,10 +307,10 @@ fn cubic(seg: PathSeg) -> Option<CubicBez> {
|
||||
}
|
||||
|
||||
/// How many equal steps of its parameter keep the chords of curve `seg` within `chord` of it (by
|
||||
/// the second differences of its control points), when its control points span at least [`SPAN`]
|
||||
/// times `tol`; 0 for a line, a shorter curve, a curve with a point that isn't finite, and a curve
|
||||
/// that would take more than [`MAX_LINES`] steps.
|
||||
fn steps(seg: PathSeg, tol: f64, chord: f64) -> usize {
|
||||
/// the second differences of its control points), when its control points span at least `min`
|
||||
/// across or down; 0 for a line, a shorter curve, a curve with a point that isn't finite, and a
|
||||
/// curve that would take more than [`MAX_LINES`] steps.
|
||||
fn steps(seg: PathSeg, min: f64, chord: f64) -> usize {
|
||||
let Some(c) = cubic(seg) else { return 0 };
|
||||
let pts = [c.p0, c.p1, c.p2, c.p3];
|
||||
if !pts.iter().all(|p| p.is_finite()) {
|
||||
@@ -150,7 +320,7 @@ fn steps(seg: PathSeg, tol: f64, chord: f64) -> usize {
|
||||
(Point::new(lo.x.min(p.x), lo.y.min(p.y)), Point::new(hi.x.max(p.x), hi.y.max(p.y)))
|
||||
});
|
||||
let span = (hi.x - lo.x).max(hi.y - lo.y);
|
||||
if !span.is_finite() || span < tol * SPAN {
|
||||
if !span.is_finite() || span < min {
|
||||
return 0;
|
||||
}
|
||||
let second = |a: Point, b: Point, c: Point| (a.to_vec2() - b.to_vec2() * 2.0 + c.to_vec2()).hypot();
|
||||
@@ -175,13 +345,19 @@ fn end_tangent(c: &CubicBez) -> Option<Vec2> {
|
||||
/// How many pieces of a curve [`params`] measures its bending on.
|
||||
const SAMPLES: usize = 32;
|
||||
|
||||
/// A chord whose curve lies more than this many times `chord` from it ([`off_chord`]) is drawn with
|
||||
/// more steps ([`params`]).
|
||||
const FIT: f64 = 2.0;
|
||||
|
||||
/// The parameters curve `c` has its line ends at, and whether its first and its last step are
|
||||
/// halves. Each step holds an equal share of the curve's bending (the integral of the square root
|
||||
/// of its curvature along it), and there are as many as keep each chord within about `chord` of the
|
||||
/// curve, at most `most` (its equal steps, [`steps`]). The steps are equal when the bending can't
|
||||
/// be measured (a cusp, or a point that isn't finite) or is 0. The first or last step is halved
|
||||
/// when that end stays on the curve (`pin_start`, `pin_end`); a curve of one step is then drawn
|
||||
/// in two halves.
|
||||
/// curve, at most `most` (its equal steps, [`steps`]). When the curve between two line ends lies
|
||||
/// more than [`FIT`] times `chord` from their chord ([`off_chord`]), as where a curve turns back
|
||||
/// within a step, the count doubles, up to `most`; when `most` such steps still don't fit, the
|
||||
/// steps are equal. The steps are also equal when the bending can't be measured (a cusp, or a point
|
||||
/// that isn't finite) or is 0. The first or last step is halved when that end stays on the curve
|
||||
/// (`pin_start`, `pin_end`); a curve of one step is then drawn in two halves.
|
||||
fn params(c: &CubicBez, most: usize, chord: f64, pin_start: bool, pin_end: bool) -> (Vec<f64>, (bool, bool)) {
|
||||
let (d1, d2) = (c.deriv(), c.deriv().deriv());
|
||||
let bend = |u: f64| {
|
||||
@@ -197,39 +373,109 @@ fn params(c: &CubicBez, most: usize, chord: f64, pin_start: bool, pin_end: bool)
|
||||
}
|
||||
let total = sums[SAMPLES];
|
||||
let most = most.max(1);
|
||||
let n = if total.is_finite() && total > 0.0 { ((total / SAMPLES as f64 / (8.0 * chord).sqrt()).ceil() as usize).clamp(1, most) } else { most };
|
||||
// The parameter at which a share `s` (0 to 1) of the bending lies before it.
|
||||
let at = |s: f64| -> f64 {
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
return s;
|
||||
}
|
||||
let want = s * total;
|
||||
let j = sums.partition_point(|&x| x <= want).clamp(1, SAMPLES);
|
||||
let (lo, hi) = (sums[j - 1], sums[j]);
|
||||
let part = if hi > lo { ((want - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(j as f64 - 1.0 + part) / SAMPLES as f64
|
||||
};
|
||||
if n == 1 && (pin_start || pin_end) {
|
||||
return (vec![0.0, at(0.5), 1.0], (true, true));
|
||||
// The line ends of `n` steps, each holding a share `step(s)` of the curve.
|
||||
let cut = |n: usize, step: &dyn Fn(f64) -> f64| -> (Vec<f64>, (bool, bool)) {
|
||||
if n == 1 && (pin_start || pin_end) {
|
||||
return (vec![0.0, step(0.5), 1.0], (true, true));
|
||||
}
|
||||
let h = 1.0 / n as f64;
|
||||
let mut t = Vec::with_capacity(n + 3);
|
||||
t.push(0.0);
|
||||
if pin_start {
|
||||
t.push(step(h / 2.0));
|
||||
}
|
||||
t.extend((1..n).map(|k| step(k as f64 * h)));
|
||||
if pin_end {
|
||||
t.push(step(1.0 - h / 2.0));
|
||||
}
|
||||
t.push(1.0);
|
||||
(t, (pin_start, pin_end))
|
||||
};
|
||||
if total.is_finite() && total > 0.0 {
|
||||
let mut n = ((total / SAMPLES as f64 / (8.0 * chord).sqrt()).ceil() as usize).clamp(1, most);
|
||||
loop {
|
||||
let fit = cut(n, &at);
|
||||
if fit.0.windows(2).all(|w| off_chord(c, w[0], w[1]) <= FIT * chord) {
|
||||
return fit;
|
||||
}
|
||||
if n >= most {
|
||||
break;
|
||||
}
|
||||
n = n.saturating_mul(2).min(most);
|
||||
}
|
||||
}
|
||||
let h = 1.0 / n as f64;
|
||||
let mut t = Vec::with_capacity(n + 3);
|
||||
t.push(0.0);
|
||||
if pin_start {
|
||||
t.push(at(h / 2.0));
|
||||
cut(most, &|s| s)
|
||||
}
|
||||
|
||||
/// How far curve `c` between parameters `a` and `b` lies from the chord between its points there:
|
||||
/// the farthest it lies to either side of the chord's line, or before the chord's start or past its
|
||||
/// end along it. For a chord of no length, the farthest the curve's control points between `a` and
|
||||
/// `b` lie from it.
|
||||
fn off_chord(c: &CubicBez, a: f64, b: f64) -> f64 {
|
||||
let (p, q) = (c.eval(a), c.eval(b));
|
||||
let along = q - p;
|
||||
let len = along.hypot();
|
||||
if !(len > 0.0 && len.is_finite()) {
|
||||
let s = c.subsegment(a..b);
|
||||
return [s.p1, s.p2, s.p3].iter().map(|x| (*x - p).hypot()).fold(0.0, f64::max);
|
||||
}
|
||||
t.extend((1..n).map(|k| at(k as f64 * h)));
|
||||
if pin_end {
|
||||
t.push(at(1.0 - h / 2.0));
|
||||
let u = along / len;
|
||||
// The derivative, t² k2 + t k1 + k0.
|
||||
let d = c.deriv();
|
||||
let (k2, k1, k0) = (d.p0.to_vec2() - d.p1.to_vec2() * 2.0 + d.p2.to_vec2(), (d.p1 - d.p0) * 2.0, d.p0.to_vec2());
|
||||
let mut far: f64 = 0.0;
|
||||
// Where the curve moves along the chord's line or across it, its distance across it or its
|
||||
// position along it is largest or smallest.
|
||||
for (a2, a1, a0) in [(k2.cross(u), k1.cross(u), k0.cross(u)), (k2.dot(u), k1.dot(u), k0.dot(u))] {
|
||||
for t in roots(a2, a1, a0) {
|
||||
if t > a && t < b {
|
||||
let v = c.eval(t) - p;
|
||||
let ahead = v.dot(u);
|
||||
far = far.max(v.cross(u).abs()).max(-ahead).max(ahead - len);
|
||||
}
|
||||
}
|
||||
}
|
||||
t.push(1.0);
|
||||
(t, (pin_start, pin_end))
|
||||
far
|
||||
}
|
||||
|
||||
/// The real roots of `a2 t² + a1 t + a0`, with NaN in place of a root that doesn't exist (none when
|
||||
/// every coefficient is 0).
|
||||
fn roots(a2: f64, a1: f64, a0: f64) -> [f64; 2] {
|
||||
if a2 == 0.0 {
|
||||
return [-a0 / a1, f64::NAN];
|
||||
}
|
||||
let disc = a1 * a1 - 4.0 * a2 * a0;
|
||||
if disc < 0.0 {
|
||||
return [f64::NAN; 2];
|
||||
}
|
||||
// The root that adds two numbers of the same sign, and the other from their product.
|
||||
let r = -(a1 + a1.signum() * disc.sqrt()) / 2.0;
|
||||
if r == 0.0 {
|
||||
return [0.0, f64::NAN];
|
||||
}
|
||||
[r / a2, a0 / r]
|
||||
}
|
||||
|
||||
/// How far the curve `c` lies from the chord between parameters `a` and `b`, at its parameter
|
||||
/// midway: the curve's point there minus the chord's middle.
|
||||
/// midway: the part across the chord of the curve's point there minus the chord's middle. A chord
|
||||
/// of no length keeps the whole difference.
|
||||
fn bulge(c: &CubicBez, a: f64, b: f64) -> Vec2 {
|
||||
c.eval((a + b) / 2.0) - c.eval(a).midpoint(c.eval(b))
|
||||
let (p, q) = (c.eval(a), c.eval(b));
|
||||
let gap = c.eval((a + b) / 2.0) - p.midpoint(q);
|
||||
let along = q - p;
|
||||
let len2 = along.hypot2();
|
||||
if !(len2 > 0.0 && len2.is_finite()) {
|
||||
return gap;
|
||||
}
|
||||
gap - along * (gap.dot(along) / len2)
|
||||
}
|
||||
|
||||
/// A curve of a subpath drawn as lines: the curve, its line ends' parameters, whether its first and
|
||||
|
||||
@@ -1,6 +1,137 @@
|
||||
use super::*;
|
||||
use crate::stroke::outline as raster_stroke_outline;
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
use vectorcraft_doc::{LineCap, LineJoin, StrokeLayer};
|
||||
|
||||
/// How many lines a fill of `path` takes once flattened at `tol`.
|
||||
fn lines_at(path: &BezPath, tol: f64) -> usize {
|
||||
let mut n = 0;
|
||||
vectorcraft_geom::flatten(path.iter(), tol, |el| n += usize::from(matches!(el, kurbo::PathEl::LineTo(_) | kurbo::PathEl::ClosePath)));
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether `path` holds lines only.
|
||||
fn lines_only(path: &BezPath) -> bool {
|
||||
path.elements().iter().all(|el| !matches!(el, kurbo::PathEl::QuadTo(..) | kurbo::PathEl::CurveTo(..)))
|
||||
}
|
||||
|
||||
/// A thin curved stroke's outline takes at most twice the lines the stroke's plain outline takes
|
||||
/// at the raster tolerance (#7257). 200 cubic curves, each about 100 device pixels across.
|
||||
#[test]
|
||||
fn thin_curved_strokes_take_at_most_twice_the_lines_of_their_plain_outline() {
|
||||
let mut seed: u64 = 7;
|
||||
let mut r = |lo: f64, hi: f64| {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64)
|
||||
};
|
||||
let mut paths = Vec::new();
|
||||
for _ in 0..200 {
|
||||
let (x, y) = (r(20.0, 980.0), r(20.0, 980.0));
|
||||
let mut q = [kurbo::Point::ZERO; 3];
|
||||
for p in &mut q {
|
||||
*p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71);
|
||||
}
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((x * 1.71, y * 1.71));
|
||||
path.curve_to(q[0], q[1], q[2]);
|
||||
paths.push(path);
|
||||
}
|
||||
let tol = 0.25;
|
||||
for width in [0.5, 0.75, 0.99] {
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), width);
|
||||
let (mut plain, mut thin) = (0, 0);
|
||||
for path in &paths {
|
||||
plain += lines_at(&crate::effects::stroke::line_outline(path, &st, width, tol), tol);
|
||||
let outline = raster_stroke_outline(path, &st, width, tol);
|
||||
assert!(lines_only(&outline), "width {width}: lines only");
|
||||
thin += lines_at(&outline, tol);
|
||||
}
|
||||
assert!(thin <= plain * 2, "width {width}: {thin} lines, plain outline {plain}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin stroke drawn as lines keeps its caps, its joins and the hole of a closed path.
|
||||
#[test]
|
||||
fn thin_strokes_drawn_as_lines_keep_caps_joins_and_holes() {
|
||||
let (w, tol) = (0.5, 0.25);
|
||||
// A quarter circle from (100, 100) heading right, then a right-angle corner at (200, 200).
|
||||
let mut open = BezPath::new();
|
||||
open.move_to((100.0, 100.0));
|
||||
open.curve_to((155.23, 100.0), (200.0, 144.77), (200.0, 200.0));
|
||||
open.line_to((100.0, 200.0));
|
||||
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
|
||||
for join in [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel] {
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
st.cap = cap;
|
||||
st.join = join;
|
||||
let o = raster_stroke_outline(&open, &st, w, tol);
|
||||
assert!(lines_only(&o), "{cap:?} {join:?}: lines only");
|
||||
let inside = |x: f64, y: f64| o.winding(kurbo::Point::new(x, y)) != 0;
|
||||
assert_eq!(inside(100.0 - 0.4 * w, 100.0), cap != LineCap::Butt, "{cap:?} {join:?}: start cap");
|
||||
assert!(!inside(100.0 - 0.6 * w, 100.0), "{cap:?} {join:?}: past the start cap");
|
||||
assert_eq!(inside(100.0 - 0.45 * w, 100.0 + 0.45 * w), cap == LineCap::Square, "{cap:?} {join:?}: cap corner");
|
||||
assert!(
|
||||
inside(200.0 + 0.4 * w, 199.0) && inside(200.0 - 0.4 * w, 199.0) && !inside(200.0 + 0.6 * w, 199.0),
|
||||
"{cap:?} {join:?}: curve end"
|
||||
);
|
||||
assert_eq!(inside(200.0 + 0.3 * w, 200.0 + 0.3 * w), join != LineJoin::Bevel, "{cap:?} {join:?}: corner");
|
||||
assert_eq!(inside(200.0 + 0.45 * w, 200.0 + 0.45 * w), join == LineJoin::Miter, "{cap:?} {join:?}: miter tip");
|
||||
assert!(inside(150.0, 200.0 + 0.4 * w) && !inside(150.0, 200.0 + 0.6 * w), "{cap:?} {join:?}: line");
|
||||
}
|
||||
}
|
||||
let ring = kurbo::Circle::new((300.0, 300.0), 50.0).to_path(0.01);
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&ring, &st, w, tol);
|
||||
assert!(lines_only(&o), "closed: lines only");
|
||||
for k in 0..36 {
|
||||
let a = f64::from(k) * 10f64.to_radians();
|
||||
let at = |r: f64| o.winding(kurbo::Point::new(300.0 + r * a.cos(), 300.0 + r * a.sin()));
|
||||
assert!(at(50.0 - 0.4 * w) != 0 && at(50.0 + 0.4 * w) != 0, "ring band at {k}");
|
||||
assert!(at(50.0 - 0.6 * w) == 0 && at(50.0 + 0.6 * w) == 0, "ring edges at {k}");
|
||||
}
|
||||
assert_eq!(o.winding(kurbo::Point::new(300.0, 300.0)), 0, "the hole");
|
||||
}
|
||||
|
||||
/// A thin curve that runs out and back along almost the same line ends where the curve turns
|
||||
/// back. The curve goes from (0, 0) to x = 75 and back; its outline reaches no further than half
|
||||
/// the stroke's width past that.
|
||||
#[test]
|
||||
fn thin_strokes_drawn_as_lines_stop_where_a_curve_turns_back() {
|
||||
let (w, tol, e) = (0.5, 0.25, 1e-9);
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.curve_to((100.0, e / 3.0), (100.0, 2.0 * e / 3.0), (0.0, e));
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&path, &st, w, tol);
|
||||
let inside = |x: f64| o.winding(kurbo::Point::new(x, 0.0)) != 0;
|
||||
assert!(inside(10.0) && inside(70.0), "the band");
|
||||
let far = o.bounding_box().x1;
|
||||
assert!(far <= 75.0 + w / 2.0 + 1e-6, "the outline reaches x = {far}");
|
||||
}
|
||||
|
||||
/// A thin curve that turns back twice keeps both of its turns. The curve runs from (0, 0) out to
|
||||
/// x = 28.87, back past its start to x = -28.87, and back to (0, 0.001). Its outline covers every
|
||||
/// point of the curve more than a third of the stroke's width from a turn, reaches both turns to
|
||||
/// within that, and reaches no further than two thirds of the stroke's width past either turn.
|
||||
#[test]
|
||||
fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() {
|
||||
let (w, tol, e) = (0.5, 0.25, 1e-3);
|
||||
let c = kurbo::CubicBez::new((0.0, 0.0), (100.0, e / 3.0), (-100.0, 2.0 * e / 3.0), (0.0, e));
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(c.p0);
|
||||
path.curve_to(c.p1, c.p2, c.p3);
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&path, &st, w, tol);
|
||||
assert!(lines_only(&o), "lines only");
|
||||
let turn = kurbo::ParamCurve::eval(&c, (3.0 - 3f64.sqrt()) / 6.0).x;
|
||||
let near = w / 3.0;
|
||||
for k in 1..200 {
|
||||
let p = kurbo::ParamCurve::eval(&c, f64::from(k) / 200.0);
|
||||
assert!(p.x.abs() > turn - near || o.winding(p) != 0, "the curve at {p:?}");
|
||||
}
|
||||
let (bounds, past) = (o.bounding_box(), w * 2.0 / 3.0);
|
||||
assert!(bounds.x1 >= turn - near && bounds.x0 <= -turn + near, "the outline reaches both turns: {bounds:?}");
|
||||
assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}");
|
||||
}
|
||||
|
||||
/// Independently integrate coverage in radial/angle bins of an original notched ring. Checking
|
||||
/// only the outline geometry misses raster flattening that cancels its two nearby contours.
|
||||
|
||||
@@ -355,7 +355,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let kept = read_rows(app);
|
||||
let rows = &kept.rows;
|
||||
let source = Positional { rows, label: |row| role_label(&row.0) };
|
||||
// The four roles: the list is as tall as its rows, so the Fold Angle row, Check and Fold Preview show under them.
|
||||
let out = List::<usize>::new(tl!("Fold line roles").to_string())
|
||||
.natural_height(true)
|
||||
.select(SelectMode::None)
|
||||
.activate(ActivateOn::Click)
|
||||
.enabled(selected)
|
||||
|
||||
@@ -229,7 +229,6 @@ fn canceling_a_fold_angle_edit_restores_the_angle_and_enter_is_one_undo_step() {
|
||||
let doc = panel.app().session.active().unwrap().doc.clone();
|
||||
let angle = read_rows(&mut panel.app()).angle;
|
||||
let undo = undo_len(&panel.app());
|
||||
// The role list fills the panel's height, so the field below it takes the focus as a screen reader gives it.
|
||||
panel.focus("Fold Angle");
|
||||
panel.key(Key::A, Modifiers::COMMAND);
|
||||
panel.type_text(text);
|
||||
@@ -250,3 +249,22 @@ fn canceling_a_fold_angle_edit_restores_the_angle_and_enter_is_one_undo_step() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// At the size the panel floats at, the role list is as tall as its rows, and the Fold Angle row,
|
||||
/// Check and Fold Preview under it lie inside the panel.
|
||||
#[test]
|
||||
fn the_fold_angle_row_check_and_fold_preview_show_under_the_roles() {
|
||||
let (mut app, a, _) = app();
|
||||
app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let mut panel = Panel::new(app, show);
|
||||
let room = crate::panel_docking::floating_size(ID);
|
||||
panel.room(room).frame();
|
||||
panel.frame();
|
||||
let (list, last) = (panel.rect("Fold line roles"), panel.rect("Perforation Line"));
|
||||
assert!(list.bottom() <= last.bottom() + 8.0, "the list ends at its last role: {list:?} {last:?}");
|
||||
for name in ["Fold Angle", "Check", "Fold Preview"] {
|
||||
let rect = panel.rect(name);
|
||||
assert!(rect.top() >= list.bottom() && rect.bottom() <= room.y, "{name} at {rect:?} lies under the list {list:?}, inside {room:?}");
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ use craft::ui::pickers::{Select, SelectLook};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::TypeRole;
|
||||
use craft::ui::text::ZoomField;
|
||||
use vectorcraft_engine::WindowView;
|
||||
|
||||
/// Shows the status bar: zoom, rotation, artboard navigator, the info field with its Show menu, the readouts, Stop,
|
||||
/// the background-work progress and last the message, so a narrow bar elides the message before anything else.
|
||||
@@ -47,6 +48,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let render = crate::i18n::tr_ctx(lang, "diagnostics", "render");
|
||||
let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui");
|
||||
let busy = busy_labels(app);
|
||||
let shown_zoom = view.map(|v| crate::state::zoom_display_percent(v.zoom, print));
|
||||
|
||||
let (mut show_pick, mut stop) = (None, false);
|
||||
let mut snapping = None;
|
||||
@@ -95,6 +97,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
document,
|
||||
scaling,
|
||||
print,
|
||||
shown_zoom,
|
||||
has_view: view.is_some(),
|
||||
turned,
|
||||
degrees,
|
||||
@@ -140,11 +143,12 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
crate::menus::invoke(app, id, params);
|
||||
}
|
||||
// The last choice of each kind counts, as the controls report one choice of each in a pass.
|
||||
let (mut zoom_to, mut invalid_zoom, mut rotate_to, mut go) = (None, None, None, None);
|
||||
let (mut zoom_to, mut invalid_zoom, mut preset_pick, mut rotate_to, mut go) = (None, None, None, None, None);
|
||||
for pick in picks {
|
||||
match pick {
|
||||
NavigationPick::Zoom(zoom) => zoom_to = Some(zoom),
|
||||
NavigationPick::InvalidZoom(message) => invalid_zoom = Some(message),
|
||||
NavigationPick::Preset(preset) => preset_pick = Some(preset),
|
||||
NavigationPick::Rotate(i) => rotate_to = Some(i),
|
||||
NavigationPick::Artboard(to) => go = Some(to),
|
||||
}
|
||||
@@ -153,6 +157,18 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if let Some(zoom) = zoom_to {
|
||||
app.run("view.setZoom", json!({"zoom": zoom})).ok();
|
||||
}
|
||||
match preset_pick {
|
||||
Some(ZoomPreset::Percent(zoom)) => {
|
||||
app.run("view.setZoom", json!({ "zoom": zoom })).ok();
|
||||
}
|
||||
Some(ZoomPreset::FitOnScreen) => {
|
||||
app.run("view.fitArtboard", json!({})).ok();
|
||||
}
|
||||
Some(ZoomPreset::FitAll) => {
|
||||
app.run("view.fitAll", json!({})).ok();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some(&(_, angle)) = rotate_to.and_then(|i| ROTATE_VIEW_ANGLES.get(i)) {
|
||||
app.run("view.rotate", json!({"angle": angle})).ok();
|
||||
}
|
||||
@@ -184,6 +200,8 @@ struct Navigation<'a> {
|
||||
scaling: f32,
|
||||
/// The density zoom percentages count from ([`VectorcraftApp::print_ppi`]).
|
||||
print: Option<f64>,
|
||||
/// The view's zoom percentage, which the Zoom Presets menu checks.
|
||||
shown_zoom: Option<f64>,
|
||||
/// Whether the active document has a view to turn.
|
||||
has_view: bool,
|
||||
/// The Rotate View preset the view is turned to, else `usize::MAX`.
|
||||
@@ -208,6 +226,8 @@ enum NavigationPick {
|
||||
Zoom(f64),
|
||||
/// The message of a zoom the Zoom field could not read.
|
||||
InvalidZoom(String),
|
||||
/// The entry chosen in the Zoom Presets menu.
|
||||
Preset(ZoomPreset),
|
||||
/// The Rotate View preset chosen (an index into [`ROTATE_VIEW_ANGLES`]).
|
||||
Rotate(usize),
|
||||
/// The `index` of `view.goToArtboard`: an artboard's index, or first, previous, next or last.
|
||||
@@ -232,6 +252,11 @@ fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) {
|
||||
p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui))));
|
||||
}
|
||||
}
|
||||
let presets = zoom_presets(p.shown_zoom, p.print);
|
||||
let open_presets = IconButton::new(IconId::new("chevron_down")).label(tl!("Zoom Presets")).enabled(p.has_view).show(ui);
|
||||
if let Some(preset) = Menu::new(tl!("Zoom Presets")).values().opened_by(open_presets.response(), Trigger::Press).pick(ui, &presets).picked {
|
||||
p.picked.send(NavigationPick::Preset(preset));
|
||||
}
|
||||
let angles: Vec<Entry<usize>> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect();
|
||||
let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view);
|
||||
let mut rotate_to = None;
|
||||
@@ -287,6 +312,7 @@ fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use craft::ui::canvas::ViewCommands;
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
#[test]
|
||||
@@ -397,6 +423,83 @@ mod tests {
|
||||
assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_zoom_presets_menu_sets_a_stop_and_fits_the_view() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0));
|
||||
app.run("view.setZoom", json!({"zoom": 800})).unwrap();
|
||||
app.view_mut().unwrap().request = None;
|
||||
// The canvas applies a fit on its next frame; the status bar alone leaves the request queued.
|
||||
let requested = |panel: &Panel| panel.app().view().and_then(|v| v.request.map(|(r, _)| r.command()));
|
||||
let document = app.session.active().unwrap().doc.clone();
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
let mut panel = Panel::new(app, status_bar);
|
||||
// Room for the whole menu, so the entries at its foot are on screen.
|
||||
panel.room(egui::vec2(1200.0, 1600.0));
|
||||
|
||||
panel.click_role("Zoom Presets", Role::BUTTON);
|
||||
panel.click_role("200%", Role::MENU_ITEM_RADIO);
|
||||
let print = panel.app().print_ppi();
|
||||
assert!((crate::state::zoom_display_percent(panel.app().view().unwrap().zoom, print) - 200.0).abs() < 1e-6, "a stop sets its zoom");
|
||||
|
||||
panel.click_role("Zoom Presets", Role::BUTTON);
|
||||
panel.click_role("Fit on Screen", Role::MENU_ITEM_RADIO);
|
||||
assert_eq!(requested(&panel), Some(ViewCommands::FitArtboard), "Fit on Screen runs view.fitArtboard");
|
||||
panel.app().view_mut().unwrap().request = None;
|
||||
|
||||
panel.click_role("Zoom Presets", Role::BUTTON);
|
||||
panel.click_role("Fit All", Role::MENU_ITEM_RADIO);
|
||||
assert_eq!(requested(&panel), Some(ViewCommands::FitOnScreen), "Fit All runs view.fitAll");
|
||||
|
||||
let app = panel.app();
|
||||
assert_eq!(app.session.active().unwrap().doc, document);
|
||||
assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "zooming records no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_zoom_presets_list_the_stops_from_the_highest_and_check_the_shown_zoom() {
|
||||
let presets = zoom_presets(Some(200.0), None);
|
||||
let labels: Vec<String> = presets.iter().filter(|e| e.is_item()).map(|e| e.label().as_str().to_owned()).collect();
|
||||
assert_eq!(labels.first().map(String::as_str), Some("64000%"));
|
||||
assert_eq!(labels.iter().rev().take(3).rev().map(String::as_str).collect::<Vec<_>>(), ["3.13%", "Fit on Screen", "Fit All"]);
|
||||
let checked: Vec<_> = presets.iter().filter(|e| e.is_checked()).filter_map(|e| e.value().copied()).collect();
|
||||
assert_eq!(checked, [ZoomPreset::Percent(200.0)]);
|
||||
assert!(zoom_presets(None, None).iter().all(|e| !e.is_checked()), "without a view no stop is checked");
|
||||
}
|
||||
|
||||
/// With Display Print Size on, 100% is more or less than one screen point per document point, so the stops at
|
||||
/// the ends of the list can fall outside the view's zoom range; the menu lists only the stops a pick sets exactly.
|
||||
#[test]
|
||||
fn the_zoom_presets_leave_out_stops_outside_the_zoom_range_at_print_size() {
|
||||
let percents = |print: Option<f64>| -> Vec<f64> {
|
||||
zoom_presets(None, print)
|
||||
.iter()
|
||||
.filter_map(|e| match e.value() {
|
||||
Some(ZoomPreset::Percent(pct)) => Some(*pct),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let stops: Vec<f64> = crate::state::zoom_stop_percents().collect();
|
||||
let n = stops.len();
|
||||
assert_eq!(percents(None).len(), n, "at 1:1 every stop is in range");
|
||||
let dense = crate::state::print_ppi(true, Some(96.0));
|
||||
assert_eq!(percents(dense).first(), Some(&stops[n - 2]), "64000% at 96 PPI is past the highest zoom, 25600% is not");
|
||||
assert_eq!(percents(dense).last(), Some(&stops[0]), "3.13% at 96 PPI is in range");
|
||||
let sparse = crate::state::print_ppi(true, Some(40.0));
|
||||
assert_eq!(percents(sparse).first(), Some(&stops[n - 1]), "64000% at 40 PPI is in range");
|
||||
assert_eq!(percents(sparse).last(), Some(&stops[2]), "3.13% and 4.17% at 40 PPI are below the lowest zoom, 6.25% is not");
|
||||
let (min, max) = WindowView::ZOOM_RANGE;
|
||||
for print in [None, dense, sparse] {
|
||||
for pct in percents(print) {
|
||||
let zoom = crate::state::zoom_from_display_percent(pct, print);
|
||||
let set = crate::state::zoom_display_percent(zoom.clamp(min, max), print);
|
||||
assert!((set - pct).abs() < 1e-6, "{pct}% at {print:?} sets {set}%");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_no_document_the_artboard_navigator_shows_a_dash() {
|
||||
let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
@@ -420,6 +523,41 @@ fn busy_labels(app: &VectorcraftApp) -> Vec<&str> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An entry of the Zoom Presets menu beside the status bar's zoom field.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum ZoomPreset {
|
||||
/// A zoom stop, in the percent `view.setZoom` takes.
|
||||
Percent(f64),
|
||||
/// Fit on Screen (`view.fitArtboard`).
|
||||
FitOnScreen,
|
||||
/// Fit All (`view.fitAll`).
|
||||
FitAll,
|
||||
}
|
||||
|
||||
/// The Zoom Presets menu: the zoom stops from the highest, the one at the `shown` percent checked, then Fit on Screen
|
||||
/// and Fit All. A stop whose zoom falls outside the view's zoom range ([`WindowView::ZOOM_RANGE`]) at the `print`
|
||||
/// setting is left out, since `view.setZoom` would set the nearest end of the range instead.
|
||||
fn zoom_presets(shown: Option<f64>, print: Option<f64>) -> Vec<Entry<ZoomPreset>> {
|
||||
let (min, max) = WindowView::ZOOM_RANGE;
|
||||
let reachable = |pct: &f64| {
|
||||
let zoom = crate::state::zoom_from_display_percent(*pct, print);
|
||||
zoom >= min * (1.0 - 1e-9) && zoom <= max * (1.0 + 1e-9)
|
||||
};
|
||||
let stops = crate::state::zoom_stop_percents();
|
||||
let mut entries: Vec<Entry<ZoomPreset>> = stops
|
||||
.rev()
|
||||
.filter(reachable)
|
||||
.map(|pct| {
|
||||
let label = crate::state::zoom_label(crate::state::zoom_from_display_percent(pct, print), print);
|
||||
Entry::new(ZoomPreset::Percent(pct), label).checked(shown.is_some_and(|s| (s - pct).abs() < 0.01))
|
||||
})
|
||||
.collect();
|
||||
entries.push(Entry::separator());
|
||||
entries.push(Entry::new(ZoomPreset::FitOnScreen, tl!("Fit on Screen")));
|
||||
entries.push(Entry::new(ZoomPreset::FitAll, tl!("Fit All")));
|
||||
entries
|
||||
}
|
||||
|
||||
/// What the status bar's info field shows, chosen from the Show menu that a click on the field
|
||||
/// opens (`view.statusBarShow`). Kept with the UI state ([`crate::UiState::status_bar_show`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
|
||||
|
||||
@@ -44,8 +44,8 @@ struct Open {
|
||||
preview: LivePreview,
|
||||
/// Set Role Swatch: the role the Swatch row was last filled for.
|
||||
filled_for: Option<String>,
|
||||
/// The uid of the document whose objects the dialog opened on (`__doc`), for Set Fold Angle, and its revert count
|
||||
/// then.
|
||||
/// The uid of the document whose objects the dialog edits, when its caller supplies `__doc`, and its revert count
|
||||
/// when the dialog opened.
|
||||
doc: Option<(u64, u64)>,
|
||||
/// The document checked for File > Revert, with its revert count when the dialog opened: `doc`, or the active
|
||||
/// document for a dialog that previews.
|
||||
@@ -75,8 +75,13 @@ impl Setting {
|
||||
/// fixed ones, `__rowGutterLinked` for Area Type Options' linked Row Gutter and `__doc` for the uid of the document
|
||||
/// whose objects the dialog edits).
|
||||
pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut params: Map<String, Value>) -> Result<Value, String> {
|
||||
let doc = match params.remove("__doc") {
|
||||
None => None,
|
||||
Some(value) => Some(value.as_u64().ok_or("`__doc` must be a document id")?),
|
||||
};
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window")?;
|
||||
if let Some(old) = app.command_dialog.open.take()
|
||||
&& on_document(app, &old)
|
||||
&& !reverted(app, &old)
|
||||
{
|
||||
old.preview.cancel(app);
|
||||
@@ -86,7 +91,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par
|
||||
_ => Map::new(),
|
||||
};
|
||||
let linked = params.remove("__rowGutterLinked").and_then(|v| v.as_f64());
|
||||
let doc = params.remove("__doc").and_then(|v| v.as_u64()).map(|uid| {
|
||||
let doc = doc.map(|uid| {
|
||||
let reverts = app.session.documents().iter().find(|st| st.uid == uid).map_or(0, |st| st.reverts);
|
||||
(uid, reverts)
|
||||
});
|
||||
@@ -139,6 +144,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
fn step(app: &mut VectorcraftApp, open: &mut Open) {
|
||||
if !on_document(app, open) {
|
||||
return;
|
||||
}
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
let id = open.id;
|
||||
let seen = dialogs.with(|h| h.get_by_id::<HostedParamDialog>(id).map(|d| (d.fields().clone(), d.is_previewing())));
|
||||
@@ -189,8 +197,7 @@ fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) ->
|
||||
app.command_dialog.open = Some(open);
|
||||
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
|
||||
}
|
||||
if open.doc.is_some_and(|(uid, _)| app.session.active().is_none_or(|st| st.uid != uid)) {
|
||||
open.preview.cancel(app);
|
||||
if !on_document(app, &open) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let params = command_params(&open.command, &open.opening, Setting::of(app));
|
||||
@@ -214,12 +221,17 @@ fn confirm(app: &mut VectorcraftApp, token: &Arc<()>, fields: &DialogFields) ->
|
||||
/// Cancel: rolls back the preview of the dialog `token` names.
|
||||
fn cancel(app: &mut VectorcraftApp, token: &Arc<()>) {
|
||||
if let Some(open) = app.command_dialog.open.take_if(|o| Arc::ptr_eq(&o.token, token))
|
||||
&& on_document(app, &open)
|
||||
&& !reverted(app, &open)
|
||||
{
|
||||
open.preview.cancel(app);
|
||||
}
|
||||
}
|
||||
|
||||
fn on_document(app: &VectorcraftApp, open: &Open) -> bool {
|
||||
open.doc.is_none_or(|(uid, _)| app.session.active().is_some_and(|st| st.uid == uid))
|
||||
}
|
||||
|
||||
/// Whether the active document is the one the dialog opened on (`__doc`, or the active one for a dialog that
|
||||
/// previews), with its content replaced by File > Revert since: a preview shown before belonged to the content
|
||||
/// thrown away.
|
||||
@@ -907,6 +919,41 @@ mod tests {
|
||||
|
||||
/// The choices this dialog lists for Rasterize, Create Gradient Mesh and Repeat Options are the
|
||||
/// values their commands take (#8020, #7991): each one runs, and every language with complete
|
||||
#[test]
|
||||
fn document_scoped_dialog_confirms_only_in_its_opening_document() {
|
||||
for (scoped, switch) in [(true, false), (true, true), (false, true)] {
|
||||
let mut app = windowed();
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let mut params = json!({"x": 10, "y": 10, "width": 20, "height": 20}).as_object().unwrap().clone();
|
||||
if scoped {
|
||||
params.insert("__doc".into(), json!(app.session.active().unwrap().uid));
|
||||
}
|
||||
open(&mut app, "shape.rectangle", "Rectangle", params).unwrap();
|
||||
pump(&mut app);
|
||||
if switch {
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
}
|
||||
answer_ok(&mut app);
|
||||
assert!(app.command_dialog.open.is_none());
|
||||
assert_eq!(app.session.active().unwrap().selection.is_empty(), scoped && switch);
|
||||
if switch {
|
||||
assert!(app.session.set_active(0));
|
||||
assert!(app.session.active().unwrap().selection.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_scoped_dialog_rejects_an_invalid_document_id() {
|
||||
for doc in [json!(null), json!("1"), json!(-1), json!(1.5)] {
|
||||
let mut app = windowed();
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
let params = json!({"width": 20, "height": 20, "__doc": doc}).as_object().unwrap().clone();
|
||||
assert!(open(&mut app, "shape.rectangle", "Rectangle", params).is_err(), "{doc}");
|
||||
assert!(app.command_dialog.open.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// menus has a row for each label.
|
||||
#[test]
|
||||
fn choice_fields_list_the_values_their_commands_take() {
|
||||
|
||||
@@ -26,6 +26,7 @@ use craft::ui::choice::{Checkbox, Segmented};
|
||||
use craft::ui::contract::{Bind, Entry, FieldLayout, Gap, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing, clicked};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout::CellAlign;
|
||||
use craft::ui::layout_components::{Grid, Row, Stack};
|
||||
use craft::ui::patterns::form_dialogs::{
|
||||
CardCx, CardSource, DetailsCx, DocumentCard, DocumentSettings, HostedNewDocument, NewDocumentDialog, Orientation, PresetCategory,
|
||||
@@ -299,10 +300,8 @@ impl DocumentSettings for VcNewDocument {
|
||||
}
|
||||
});
|
||||
});
|
||||
// Three shares: the grid stacks the three fields when the column has no room for them side by side, so
|
||||
// Artboards is never cut off at its right edge.
|
||||
Grid::new(&THIRDS).fill().show(ui, |ui, _| {
|
||||
Field::new(height.clone()).layout(FieldLayout::Above).id_salt("height").show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths));
|
||||
let compact = compact_details(ui);
|
||||
let mut orientation_field = |ui: &mut egui::Ui| {
|
||||
Field::new(orientation.clone()).layout(FieldLayout::Above).id_salt("orientation").show(ui, |ui, _| {
|
||||
let entries = [
|
||||
Entry::new(Orientation::Portrait, portrait.clone()).icon(IconId::new("orientation_portrait")),
|
||||
@@ -310,6 +309,15 @@ impl DocumentSettings for VcNewDocument {
|
||||
];
|
||||
picked = Segmented::new(orientation.clone(), Bind::given(current), &entries).show(ui).events.committed().cloned();
|
||||
});
|
||||
};
|
||||
// A wide column holds Height, Orientation and Artboards in one row. A narrow one holds Height and Artboards in
|
||||
// two equal shares and Orientation under them, so its two buttons stay side by side.
|
||||
let columns: &'static [ColumnWidth] = if compact { &HALVES } else { &THIRDS };
|
||||
Grid::new(columns).fill().cells(CellAlign::Top).show(ui, |ui, _| {
|
||||
Field::new(height.clone()).layout(FieldLayout::Above).id_salt("height").show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths));
|
||||
if !compact {
|
||||
orientation_field(ui);
|
||||
}
|
||||
Field::new(artboards.clone()).layout(FieldLayout::Above).id_salt("artboards").show(ui, |ui, _| {
|
||||
let field = NumberField::new(artboards.clone(), Bind::given(Some(f64::from(s.artboards))))
|
||||
.range(1.0..=f64::from(MAX_ARTBOARDS))
|
||||
@@ -321,6 +329,9 @@ impl DocumentSettings for VcNewDocument {
|
||||
}
|
||||
});
|
||||
});
|
||||
if compact {
|
||||
orientation_field(ui);
|
||||
}
|
||||
if let Some(o) = picked
|
||||
&& o != current
|
||||
{
|
||||
@@ -329,7 +340,7 @@ impl DocumentSettings for VcNewDocument {
|
||||
}
|
||||
|
||||
let bleed = text(tl!("Bleed"));
|
||||
Field::new(bleed.clone()).layout(FieldLayout::Above).id_salt("bleed").show(ui, |ui, _| bleed_row(ui, s, &mut memory, lengths));
|
||||
Field::new(bleed.clone()).layout(FieldLayout::Above).id_salt("bleed").show(ui, |ui, _| bleed_row(ui, s, &mut memory, lengths, compact));
|
||||
|
||||
Field::new(background.clone()).layout(FieldLayout::Above).id_salt("background").show(ui, |ui, _| {
|
||||
let entries: Vec<Entry<Background>> = BACKGROUNDS.iter().map(|(b, name)| Entry::new(*b, text(tl!(name)))).collect();
|
||||
@@ -419,36 +430,55 @@ fn pixels_per_inch() -> f64 {
|
||||
72.0 / Unit::Pixels.to_pt(1.0)
|
||||
}
|
||||
|
||||
/// The four Bleed fields in one row, each under its side's name, and the link button at the end; linked, an edit to
|
||||
/// one side sets all four, and turning the link on sets all four to Top's. Each field is as wide as the widest bleed it
|
||||
/// takes, and the row wraps when the column has no room for all of them.
|
||||
fn bleed_row(ui: &mut egui::Ui, s: &mut DocSettings, memory: &mut Memory, lengths: LengthUnits) {
|
||||
/// The four Bleed fields, each under its side's name, and the link button at the end; linked, an edit to one side sets
|
||||
/// all four, and turning the link on sets all four to Top's. Each field is as wide as the widest bleed it takes. A wide
|
||||
/// column holds them in one row. A narrow (`compact`) column holds them in two rows, Top and Bottom above Left and
|
||||
/// Right, with the link button after Right.
|
||||
fn bleed_row(ui: &mut egui::Ui, s: &mut DocSettings, memory: &mut Memory, lengths: LengthUnits, compact: bool) {
|
||||
let mut linked = !memory.bleed_split;
|
||||
let link = LinkMode::Equal.label(&Env::of(ui).words::<LinkedWords>());
|
||||
let sides = [text(tl!("Top")), text(tl!("Bottom")), text(tl!("Left")), text(tl!("Right"))];
|
||||
let mut edited = None;
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
for (i, side) in sides.iter().enumerate() {
|
||||
// A drag on the side's name scrubs its field.
|
||||
let field = Field::new(side.clone()).layout(FieldLayout::Above).side(SideLabel::new().scrub(true)).sizing(Sizing::Content);
|
||||
field.id_salt(("bleed", i)).show(ui, |ui, _| {
|
||||
let field = NumberField::length(side.clone(), Bind::given(Some(s.bleed[i])), lengths)
|
||||
.range(0.0..=vectorcraft_doc::setup::MAX_BLEED)
|
||||
.scrub_by_label()
|
||||
.sizing(Sizing::Content);
|
||||
if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) {
|
||||
edited = Some((i, v.clamp(0.0, vectorcraft_doc::setup::MAX_BLEED)));
|
||||
}
|
||||
});
|
||||
}
|
||||
// Turning the link on sets every side to Top's bleed.
|
||||
if let Some(on) = link_toggle(link.clone(), Bind::given(linked)).id_salt("bleed-link").show(ui).value().copied() {
|
||||
linked = on;
|
||||
if on {
|
||||
s.bleed = [s.bleed[0]; 4];
|
||||
let mut side_field = |ui: &mut egui::Ui, i: usize| {
|
||||
// A drag on the side's name scrubs its field.
|
||||
let field = Field::new(sides[i].clone()).layout(FieldLayout::Above).side(SideLabel::new().scrub(true)).sizing(Sizing::Content);
|
||||
field.id_salt(("bleed", i)).show(ui, |ui, _| {
|
||||
let field = NumberField::length(sides[i].clone(), Bind::given(Some(s.bleed[i])), lengths)
|
||||
.range(0.0..=vectorcraft_doc::setup::MAX_BLEED)
|
||||
.scrub_by_label()
|
||||
.sizing(Sizing::Content);
|
||||
if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) {
|
||||
edited = Some((i, v.clamp(0.0, vectorcraft_doc::setup::MAX_BLEED)));
|
||||
}
|
||||
});
|
||||
};
|
||||
let mut turned_on = None;
|
||||
// Turning the link on sets every side to Top's bleed.
|
||||
let mut link_button = |ui: &mut egui::Ui| {
|
||||
if let Some(on) = link_toggle(link.clone(), Bind::given(linked)).id_salt("bleed-link").show(ui).value().copied() {
|
||||
turned_on = Some(on);
|
||||
}
|
||||
});
|
||||
};
|
||||
if compact {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| (0..2).for_each(|i| side_field(ui, i)));
|
||||
Row::new().show(ui, |ui, _| {
|
||||
(2..4).for_each(|i| side_field(ui, i));
|
||||
link_button(ui);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
(0..sides.len()).for_each(|i| side_field(ui, i));
|
||||
link_button(ui);
|
||||
});
|
||||
}
|
||||
if let Some(on) = turned_on {
|
||||
linked = on;
|
||||
if on {
|
||||
s.bleed = [s.bleed[0]; 4];
|
||||
}
|
||||
}
|
||||
if let Some((i, v)) = edited {
|
||||
if linked {
|
||||
s.bleed = follow_equal(s.bleed, i, v);
|
||||
@@ -459,10 +489,21 @@ fn bleed_row(ui: &mut egui::Ui, s: &mut DocSettings, memory: &mut Memory, length
|
||||
memory.bleed_split = !linked;
|
||||
}
|
||||
|
||||
/// The Height, Orientation and Artboards row. Orientation's share keeps its two buttons side by side in a 900-point
|
||||
/// window.
|
||||
/// The Height, Orientation and Artboards row of a wide details column.
|
||||
const THIRDS: [ColumnWidth; 3] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.4), ColumnWidth::fill(1.0)];
|
||||
|
||||
/// The Height and Artboards row of a narrow details column.
|
||||
const HALVES: [ColumnWidth; 2] = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0)];
|
||||
|
||||
/// The least width of a wide details column, in control heights: the four Bleed fields and the link button in one row,
|
||||
/// and Orientation's two buttons side by side between Height and Artboards.
|
||||
const WIDE_DETAILS: f32 = 11.0;
|
||||
|
||||
/// Whether the details column is narrower than [`WIDE_DETAILS`] control heights.
|
||||
fn compact_details(ui: &egui::Ui) -> bool {
|
||||
ui.available_width() < WIDE_DETAILS * Env::of(ui).tokens.size.control.md
|
||||
}
|
||||
|
||||
/// A side of the page in points, shown in the chosen units.
|
||||
fn size_field(ui: &mut egui::Ui, name: &Label, points: &mut f64, lengths: LengthUnits) {
|
||||
let field = NumberField::length(name.clone(), Bind::given(Some(*points)), lengths).range(MIN_SIDE..=MAX_SIDE).sizing(Sizing::FillWidth);
|
||||
@@ -1514,4 +1555,30 @@ mod tests {
|
||||
assert!(portrait.y0 == landscape.y0 && portrait.x1 <= landscape.x0, "{width}x{height}: Portrait and Landscape side by side");
|
||||
}
|
||||
}
|
||||
|
||||
/// In small windows Height and Artboards share a row, Orientation's two buttons stand side by side under them, and
|
||||
/// the Bleed fields form two rows of two, Top and Bottom above Left and Right, with the link button after Right;
|
||||
/// before, at 800 by 600 Orientation's buttons stood one above the other between Height and Artboards.
|
||||
#[test]
|
||||
fn new_document_details_stay_in_rows_in_small_windows() {
|
||||
use egui::accesskit::Role;
|
||||
for (width, height) in [(800.0, 600.0), (640.0, 500.0), (900.0, 700.0)] {
|
||||
let nodes = dialog_nodes(width, height);
|
||||
let at = format!("{width}x{height}");
|
||||
let dialog = nodes.iter().find(|(r, _, _)| *r == Role::Dialog).map(|(_, _, b)| *b).expect("the dialog");
|
||||
let (portrait, landscape) = (node(&nodes, "Portrait", Role::RadioButton), node(&nodes, "Landscape", Role::RadioButton));
|
||||
assert!(portrait.y0 == landscape.y0 && portrait.x1 <= landscape.x0, "{at}: Portrait {portrait:?} beside Landscape {landscape:?}");
|
||||
let (h, a) = (node(&nodes, "Height", Role::SpinButton), node(&nodes, "Artboards", Role::SpinButton));
|
||||
assert!(h.y0 == a.y0 && h.x1 <= a.x0, "{at}: Height {h:?} and Artboards {a:?} share a row");
|
||||
assert!(a.y1 <= portrait.y0 || landscape.x1 <= a.x0, "{at}: Orientation {landscape:?} stays clear of Artboards {a:?}");
|
||||
let [top, bottom, left, right] = ["Top", "Bottom", "Left", "Right"].map(|side| node(&nodes, side, Role::SpinButton));
|
||||
assert!(top.y0 == bottom.y0 && left.y0 == right.y0 && top.y1 <= left.y0, "{at}: two Bleed rows: {top:?} {bottom:?} {left:?} {right:?}");
|
||||
assert!(
|
||||
top.x0 == left.x0 && bottom.x0 == right.x0 && top.x1 <= bottom.x0,
|
||||
"{at}: two Bleed columns: {top:?} {bottom:?} {left:?} {right:?}"
|
||||
);
|
||||
let link = node(&nodes, "Make all settings the same", Role::Button);
|
||||
assert!(right.x1 <= link.x0 && link.x1 <= dialog.x1, "{at}: the link button {link:?} follows Right {right:?} inside {dialog:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,7 @@ pub(crate) fn problem_label(code: &str) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
/// Where something is: `line 12`, or `lib/a.jsxinc, line 3` in an included file.
|
||||
fn place(item: &Value) -> String {
|
||||
pub(super) fn place(item: &Value) -> String {
|
||||
let line = item["line"].as_u64().map(|l| l.to_string());
|
||||
match (item["file"].as_str(), line) {
|
||||
(Some(file), Some(line)) => crate::i18n::fmt(tl!("{file}, line {line}"), &[("file", file), ("line", &line)]),
|
||||
@@ -136,7 +136,7 @@ fn lines(item: &Value) -> String {
|
||||
}
|
||||
|
||||
/// `count` and `lines` of an entry as a note: `3 · lines 4, 9, 12`.
|
||||
fn tally(item: &Value) -> String {
|
||||
pub(super) fn tally(item: &Value) -> String {
|
||||
let count = item["count"].as_u64().unwrap_or_default();
|
||||
match lines(item) {
|
||||
l if l.is_empty() => count.to_string(),
|
||||
@@ -144,7 +144,7 @@ fn tally(item: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn list<'r>(r: &'r Value, key: &str) -> &'r [Value] {
|
||||
pub(super) fn list<'r>(r: &'r Value, key: &str) -> &'r [Value] {
|
||||
r[key].as_array().map_or(&[][..], Vec::as_slice)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,20 @@
|
||||
//! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show
|
||||
//! External Script Warning off, the chosen script runs at once. With General › Run Startup Scripts
|
||||
//! on, the startup scripts run first (`script.startup.run`). The warning (kind `scriptRun`) is a
|
||||
//! prompt: its `choice` field (`proceed` runs, `cancel` does not) and `skip` (true: turn the
|
||||
//! warning off). The growth question (`scriptGrowth`) and the question quitting asks
|
||||
//! (`scriptClose`) have the `choice` field alone.
|
||||
//! prompt: its `choice` field (`proceed` runs, `cancel` does not), `skip` (true: turn the warning
|
||||
//! off) and `reaches`, which `ui.dialog.set` cannot set: the `kind`, `needs`, `outside`, `includes`
|
||||
//! and `truncated` of `script.check`'s report on the script, read without running it (a path also
|
||||
//! checks the files its `#include` lines name), or null when the check fails. The warning lists
|
||||
//! what the report finds the script reaches outside the document (each of `script.check`'s
|
||||
//! `outside` categories, such as files it writes, moves or deletes, files it opens in other apps,
|
||||
//! the network, native code, environment variables and code the checker can't read), the files
|
||||
//! and dialogs it needs, features only the reference app has, and its includes (at most
|
||||
//! [`SHOWN_INCLUDES`], then the count of the rest). It says when the script is too large to check,
|
||||
//! compiled or not a script, when the check failed, and when a list was cut short at its limit.
|
||||
//! The listing is information: Run runs the script as before, after checking it again. When the
|
||||
//! report has changed since the warning opened, nothing runs and the warning opens again with the
|
||||
//! new report. The growth question
|
||||
//! (`scriptGrowth`) and the question quitting asks (`scriptClose`) have the `choice` field alone.
|
||||
//!
|
||||
//! A script's dialog (kind `scriptDialog`) has the fields `kind` (alert, confirm or prompt),
|
||||
//! `message`, `title` (null: Script Alert), `errorIcon`, `noAsDefault`, `value` (the prompt's
|
||||
@@ -37,7 +48,7 @@ use craft::theme::variant::Tone;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Outcome as _, Props as _, Scroll, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{
|
||||
DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, PromptChoice, StackDialog, StandardPrompt, dialog_id,
|
||||
DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, Prompt, PromptAnswer, PromptChoice, StackDialog, StandardPrompt, dialog_id,
|
||||
};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::Stack;
|
||||
@@ -77,7 +88,53 @@ const PICKED_LIST_HEIGHT: f32 = 120.0;
|
||||
/// The warning before a script runs. One type per question, so the host's per-type results never
|
||||
/// mix the three questions of this area.
|
||||
pub(crate) struct RunQuestion(pub(crate) StandardPrompt);
|
||||
crate::dialogs::confirm::wrapped_dialog!(RunQuestion, StandardPrompt, KIND);
|
||||
|
||||
/// The prompt's own dialog, with `reaches` added to its fields: what the warning lists.
|
||||
impl StackDialog for RunQuestion {
|
||||
type Result = PromptAnswer;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
dialog_id(KIND)
|
||||
}
|
||||
|
||||
fn instance(&self) -> Option<DialogId> {
|
||||
StackDialog::instance(&self.0)
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KIND)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<PromptAnswer>> {
|
||||
StackDialog::show(&mut self.0, ui, stack)
|
||||
}
|
||||
|
||||
fn confirm(&mut self, ctx: &egui::Context) -> Option<PromptAnswer> {
|
||||
self.0.confirm(ctx)
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.0.held_state()
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
let mut fields = self.0.json_fields()?;
|
||||
fields["reaches"] = self.0.tag_as::<RunWarning>().map_or(Value::Null, |w| w.reaches.clone());
|
||||
Some(fields)
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> {
|
||||
self.0.set_json_field(ctx, field, value)
|
||||
}
|
||||
|
||||
fn cancelled(&mut self, ctx: &egui::Context) {
|
||||
self.0.cancelled(ctx);
|
||||
}
|
||||
|
||||
fn preview_color(&mut self, key: &str, color: Option<craft::theme::Srgba>) {
|
||||
self.0.preview_color(key, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// The question a run asks when it has added a great deal.
|
||||
pub(crate) struct GrowthQuestion(pub(crate) StandardPrompt);
|
||||
@@ -87,9 +144,11 @@ crate::dialogs::confirm::wrapped_dialog!(GrowthQuestion, StandardPrompt, GROWTH_
|
||||
pub(crate) struct CloseQuestion(pub(crate) StandardPrompt);
|
||||
crate::dialogs::confirm::wrapped_dialog!(CloseQuestion, StandardPrompt, CLOSE_KIND);
|
||||
|
||||
/// The tag of the warning: the params `script.run` takes once the warning is answered.
|
||||
/// The tag of the warning: the params `script.run` takes once the warning is answered, and the
|
||||
/// parts of `script.check`'s report the warning lists ([`reaches`]).
|
||||
struct RunWarning {
|
||||
params: Value,
|
||||
reaches: Value,
|
||||
/// The automation roots in force when asked: the script runs under them, and under any in force
|
||||
/// when the warning is answered.
|
||||
scope: ScopeHandle,
|
||||
@@ -509,19 +568,111 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result<Value, S
|
||||
if !app.session.prefs.show_external_script_warning {
|
||||
return crate::script_runs::run_chosen(app, params);
|
||||
}
|
||||
let reaches = reaches(app, ¶ms);
|
||||
let automated = app.automation_asked();
|
||||
warn(app, params, reaches, ScopeHandle::capture(), automated)
|
||||
}
|
||||
|
||||
/// Opens the warning for the script `params` name, listing `reaches`; the script runs under
|
||||
/// `scope`, and as automation when `automated` ([`RunWarning`]).
|
||||
fn warn(app: &mut VectorcraftApp, params: Value, reaches: Value, scope: ScopeHandle, automated: bool) -> Result<Value, String> {
|
||||
let path = params.get("path").and_then(Value::as_str);
|
||||
let name = params.get("name").and_then(Value::as_str).or(path).map_or_else(|| "script".to_string(), vectorcraft_engine::cmd::fileio::file_name);
|
||||
// The script's name is the message: it is what the person reads first.
|
||||
let prompt = StandardPrompt::custom(name)
|
||||
.title(tl!("Run Script"))
|
||||
.paragraph(tl!("A script can change the open documents and can write files through the commands it runs. Run only scripts you trust."))
|
||||
.paragraph(tl!("A script can change the open documents and can write files through the commands it runs. Run only scripts you trust."));
|
||||
let prompt = listed(prompt, &reaches)
|
||||
.dont_show_again()
|
||||
.button(PromptChoice::Proceed, tl!("Run"))
|
||||
.button(PromptChoice::Cancel, tl!("Cancel"))
|
||||
.tag(RunWarning { params, scope: ScopeHandle::capture(), automated: app.automation_asked() });
|
||||
.tag(RunWarning { params, reaches, scope, automated });
|
||||
with_host(app, |host, _| host.open(RunQuestion(prompt))).ok_or_else(|| "there is no window to ask in".to_string())?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The status when Run finds that the script's report changed since the warning opened: the
|
||||
/// warning opens again with the new report, and nothing runs.
|
||||
pub(crate) const CHANGED_SINCE_WARNING: &str = "The script changed after its warning opened: check the warning again";
|
||||
|
||||
/// The most includes the warning lists; a line after them gives the count of the rest.
|
||||
pub(crate) const SHOWN_INCLUDES: usize = 20;
|
||||
|
||||
/// The parts of `script.check`'s report on the script `script.run`'s `params` name that the
|
||||
/// warning lists, read without running the script; a path also checks the files its `#include`
|
||||
/// lines name. Null when the check fails: the run reports why the script can't be read.
|
||||
fn reaches(app: &mut VectorcraftApp, params: &Value) -> Value {
|
||||
checked(app, params).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// [`reaches`], with the check's error when it fails, for example when the request asking can't
|
||||
/// read the script.
|
||||
fn checked(app: &mut VectorcraftApp, params: &Value) -> Result<Value, String> {
|
||||
let check = match (params.get("path"), params.get("source")) {
|
||||
(Some(path), _) => json!({"path": path, "includes": true}),
|
||||
(None, Some(source)) => json!({"data": source}),
|
||||
(None, None) => return Ok(Value::Null),
|
||||
};
|
||||
let r = app.session.execute("script.check", &check).map_err(|e| e.to_string())?;
|
||||
Ok(json!({"kind": r["kind"], "needs": r["needs"], "outside": r["outside"], "includes": r["includes"], "truncated": r["truncated"]}))
|
||||
}
|
||||
|
||||
/// `prompt` with what the report `r` finds the script reaches outside the document, one line each;
|
||||
/// nothing more for a script that was checked and reaches nothing. A failed check (null) says the
|
||||
/// script was not read.
|
||||
fn listed(prompt: StandardPrompt, r: &Value) -> StandardPrompt {
|
||||
use super::script_check::{list, need_label, outside_label, place, status_label, tally};
|
||||
let unchecked = match r["kind"].as_str() {
|
||||
Some("script") => None,
|
||||
Some("compiled") => Some(tl!("Compiled script: ask its author for the .jsx file")),
|
||||
Some("tooLarge") => Some(tl!("Too large to check")),
|
||||
_ if r.is_null() => Some(tl!("Not read")),
|
||||
_ => Some(tl!("Not a script for the reference app")),
|
||||
};
|
||||
if let Some(text) = unchecked {
|
||||
return prompt.note(text);
|
||||
}
|
||||
// A row: its text, then its count, lines or status when it has them.
|
||||
let row = |text: &str, note: &str| if note.is_empty() { text.to_string() } else { format!("{text} · {note}") };
|
||||
let outside: Vec<String> = list(r, "outside")
|
||||
.iter()
|
||||
.filter_map(|o| {
|
||||
let label = o["id"].as_str().and_then(outside_label)?;
|
||||
let modes: Vec<&str> = list(o, "modes").iter().filter_map(Value::as_str).collect();
|
||||
let label = if modes.is_empty() { label.to_string() } else { format!("{label} ({})", modes.join(", ")) };
|
||||
Some(row(&label, &tally(o)))
|
||||
})
|
||||
.collect();
|
||||
let needs = list(r, "needs").iter().filter_map(Value::as_str).filter(|n| matches!(*n, "files" | "dialogs" | "hostOnly")).filter_map(need_label);
|
||||
// The needs come first, each a sentence of its own; the heading names only what the script does
|
||||
// outside the document.
|
||||
let mut lines: Vec<String> = needs.map(str::to_string).collect();
|
||||
if !outside.is_empty() {
|
||||
lines.push(crate::i18n::colon(tl!("Outside the document")));
|
||||
lines.extend(outside);
|
||||
}
|
||||
let includes = list(r, "includes");
|
||||
if !includes.is_empty() {
|
||||
lines.push(crate::i18n::colon(tl!("Includes")));
|
||||
for i in includes.iter().take(SHOWN_INCLUDES) {
|
||||
let status = i["status"].as_str().and_then(status_label).unwrap_or_default();
|
||||
let note = [status.to_string(), place(i)].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
lines.push(row(i["value"].as_str().unwrap_or_default(), ¬e));
|
||||
}
|
||||
if includes.len() > SHOWN_INCLUDES {
|
||||
let count = (includes.len() - SHOWN_INCLUDES).to_string();
|
||||
lines.push(crate::i18n::fmt(tl!("Included files not listed: {count}"), &[("count", &count)]));
|
||||
}
|
||||
}
|
||||
if r["truncated"].as_bool() == Some(true) {
|
||||
lines.push(tl!("Some lists were cut short at their limit.").to_string());
|
||||
}
|
||||
if lines.is_empty() {
|
||||
return prompt;
|
||||
}
|
||||
prompt.paragraph(tl!("VectorCraft read this script without running it.")).lines(lines.into_iter().map(Into::into))
|
||||
}
|
||||
|
||||
fn growth_question() -> GrowthQuestion {
|
||||
GrowthQuestion(
|
||||
StandardPrompt::custom(tl!("This script has added a great many objects. Continue, or stop it and undo what it did?"))
|
||||
@@ -611,12 +762,29 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
}
|
||||
if let Some(DialogResult::Ok(mut answer)) = run
|
||||
&& answer.choice == PromptChoice::Proceed
|
||||
&& let Some(RunWarning { params, scope, automated }) = answer.take_tag::<RunWarning>()
|
||||
&& let Some(RunWarning { params, reaches: listed, scope, automated }) = answer.take_tag::<RunWarning>()
|
||||
{
|
||||
let stored = if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) };
|
||||
let run = |app: &mut VectorcraftApp| crate::script_runs::run_chosen(app, params).map(drop);
|
||||
let automated = automated || app.automation_asked();
|
||||
if let Err(e) = stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run))) {
|
||||
// A script whose report changed while the warning was open is listed again before it runs.
|
||||
// A script read when the warning opened that the answering request can't read is
|
||||
// refused with the check's error, not listed again as changed.
|
||||
// The check reads the script under the access the run would have.
|
||||
let ran = match scope.clone().within_current().run(|| checked(app, ¶ms)) {
|
||||
Err(e) if !listed.is_null() => Err(e),
|
||||
now => Ok(now.unwrap_or(Value::Null)),
|
||||
}
|
||||
.and_then(|now| {
|
||||
if now == listed {
|
||||
let stored =
|
||||
if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) };
|
||||
let run = |app: &mut VectorcraftApp| crate::script_runs::run_chosen(app, params).map(drop);
|
||||
let automated = automated || app.automation_asked();
|
||||
stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run)))
|
||||
} else {
|
||||
app.status(CHANGED_SINCE_WARNING);
|
||||
warn(app, params, now, scope, automated).map(drop)
|
||||
}
|
||||
});
|
||||
if let Err(e) = ran {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use craft::behavior::{EditEvent, Preview};
|
||||
use craft::behavior::{EditEvent, EditPolicy, Preview};
|
||||
use craft::font_manager::picker::{FamilySet, FilterLayout, FontFilters, FontPicker, FontPickerSettings, FontPreviewSize, FontScript};
|
||||
use craft::ui::contract::{Bind, Entry, Show as _};
|
||||
use craft::ui::fonts::{FaceBytes, FaceState};
|
||||
@@ -204,7 +204,7 @@ pub(crate) fn font_fields(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let styles = FontDb::global().styles(&s.font_family);
|
||||
let entries: Vec<Entry<String>> = styles.iter().map(|name| Entry::new(name.clone(), name.clone())).collect();
|
||||
let mut shown = s.font_style.clone();
|
||||
Select::new(tl!("Style"), Bind::bound(&mut shown), &entries).show(ui);
|
||||
Select::new(tl!("Style"), Bind::bound(&mut shown).policy(EditPolicy::OnCommit), &entries).show(ui);
|
||||
if shown != s.font_style {
|
||||
apply_font(app, &s.font_family, Some(&shown), Live::Released);
|
||||
}
|
||||
|
||||
@@ -270,3 +270,43 @@ fn a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview() {
|
||||
"undo takes the type away: no step was added for the size"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_highlighted_font_style_applies_only_once_it_is_chosen() {
|
||||
use craft::ui::contract::Role;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
use crate::tests::panel_harness::Panel;
|
||||
|
||||
let styles = vectorcraft_text::FontDb::global().styles("Source Sans 3");
|
||||
assert!(styles.len() >= 2, "{styles:?}");
|
||||
let mut app = app_with_type(&[]);
|
||||
let params = serde_json::json!({"x": 20, "y": 90, "text": "Style", "font": "Source Sans 3", "style": styles[0]});
|
||||
let id = app.run("text.create", params).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", serde_json::json!({"ids": [id]})).unwrap();
|
||||
let mut panel = Panel::new(app, super::font_fields);
|
||||
let state = |panel: &Panel| {
|
||||
let app = panel.app();
|
||||
let style = match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.first_style().font_style,
|
||||
_ => String::new(),
|
||||
};
|
||||
(style, app.session.doc().unwrap().history.undo.len())
|
||||
};
|
||||
let before = state(&panel);
|
||||
assert_eq!(before.0, styles[0]);
|
||||
panel.click_role("Style", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(state(&panel), before, "a highlighted style changes nothing");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(state(&panel), before, "Escape leaves the style as it was");
|
||||
panel.click_role("Style", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Enter, Modifiers::NONE);
|
||||
panel.frame();
|
||||
let (style, undo) = state(&panel);
|
||||
assert_eq!(style, styles[1], "Enter applies the style");
|
||||
assert_eq!(undo, before.1 + 1, "the choice is one undo step");
|
||||
}
|
||||
@@ -8797,6 +8797,27 @@ breakText Glyphs Glifs
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` és un efecte dinàmic: apliqueu-lo amb effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects l’importador no ha retornat cap objecte
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` un importador retorna `objects` i `warnings`, no `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` ha d’indicar índexs d’objectes en ordre creixent, cadascun menor que {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` inclou `{shown}` dues vegades
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` indica un tipus desconegut `{shown}`: feu servir type, image, layer o artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` requereix el nivell d’API de complements {OUTPUT_KINDS_API}: indiqueu `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` ha de ser [width, height]: dos nombres enters de l’1 al {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` ha de contenir 4 × amplada × alçada = {want} bytes en base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` ha de ser [x, y, width, height]: nombres finits dins de ±{MAX_COORD}, amb amplada i alçada més grans que 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` fa {len} bytes (límit {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` no pot contenir caràcters de control llevat de salts de línia i tabulacions
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` ha de tenir 1-{MAX_NAME_CHARS} caràcters, sense caràcters de control ni de direcció del text
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` han de ser sis nombres finits dins de ±{MAX_COORD} que no aplanin l’objecte
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` ha de contenir d’1 a {max} entrades (en conté {n})
|
||||
@msg a type fill must be a color or a gradient l’emplenament d’un text ha de ser un color o un degradat
|
||||
@msg artboard name `{shown}` is used twice el nom de tauler `{shown}` s’utilitza dues vegades
|
||||
@msg object {k} must be in exactly one layer l’objecte {k} ha de ser exactament en una capa
|
||||
@msg only an importer declares `outputKinds` només un importador declara `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels les imatges contenen més de {MAX_PIXEL_BYTES} bytes de píxels
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list la sortida conté `{kind}`, que `outputKinds` de l’importador no inclou
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text el text conté més de {MAX_TEXT_TOTAL} bytes
|
||||
@msg unknown field `{key}` camp desconegut `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} píxels (límit de {MAX_IMAGE_SIDE} píxels per costat)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads el fitxer supera els {MAX_INPUT_BYTES} bytes que llegeix un importador
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` un importador declara d’1 a {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` només un exportador o un importador declara `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8776,6 +8776,27 @@ breakText Glyphs Glyfy
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` je živý efekt: použijte ho pomocí effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects importní zásuvný modul nevrátil žádné objekty
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` importní zásuvný modul vrací `objects` a `warnings`, ne `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` musí uvádět indexy objektů ve vzestupném pořadí, každý menší než {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` uvádí `{shown}` dvakrát
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` uvádí neznámý druh `{shown}`: použijte type, image, layer nebo artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` vyžaduje úroveň API zásuvných modulů {OUTPUT_KINDS_API}: zadejte `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` musí být [width, height]: dvě celá čísla od 1 do {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` musí obsahovat 4 × šířka × výška = {want} bajtů v kódování base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` musí být [x, y, width, height]: konečná čísla v rozsahu ±{MAX_COORD}, šířka a výška větší než 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` má {len} bajtů (limit {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` nesmí obsahovat jiné řídicí znaky než zalomení řádků a tabulátory
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` musí mít 1-{MAX_NAME_CHARS} znaků, bez řídicích znaků a znaků směru textu
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` musí být šest konečných čísel v rozsahu ±{MAX_COORD}, která objekt nezploští
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` musí obsahovat 1 až {max} položek (obsahuje {n})
|
||||
@msg a type fill must be a color or a gradient výplň textu musí být barva nebo přechod
|
||||
@msg artboard name `{shown}` is used twice název pracovní plochy `{shown}` je použit dvakrát
|
||||
@msg object {k} must be in exactly one layer objekt {k} musí být právě v jedné vrstvě
|
||||
@msg only an importer declares `outputKinds` `outputKinds` deklaruje pouze importní zásuvný modul
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels obrazy obsahují více než {MAX_PIXEL_BYTES} bajtů pixelů
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list výstup obsahuje `{kind}`, který `outputKinds` importního zásuvného modulu neuvádí
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text text obsahuje více než {MAX_TEXT_TOTAL} bajtů
|
||||
@msg unknown field `{key}` neznámé pole `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixelů (limit {MAX_IMAGE_SIDE} pixelů na stranu)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads soubor je větší než {MAX_INPUT_BYTES} bajtů, které importní zásuvný modul čte
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` importní zásuvný modul deklaruje 1 až {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` `extensions` deklaruje jen exportní nebo importní zásuvný modul
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -852,6 +852,27 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` er en live-effekt: anvend den med effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects importøren returnerede ingen objekter
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` en importør returnerer `objects` og `warnings`, ikke `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` skal angive objektindeks i stigende rækkefølge, hvert mindre end {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` angiver `{shown}` to gange
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` angiver en ukendt type `{shown}`: brug type, image, layer eller artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` kræver plug-in-API-niveau {OUTPUT_KINDS_API}: angiv `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` skal være [width, height]: to heltal fra 1 til {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` skal indeholde 4 × bredde × højde = {want} byte som base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` skal være [x, y, width, height]: endelige tal inden for ±{MAX_COORD}, bredde og højde over 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` er {len} byte (grænse {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` må ikke indeholde andre kontroltegn end linjeskift og tabulatorer
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` skal være 1-{MAX_NAME_CHARS} tegn uden kontroltegn eller tegn for tekstretning
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` skal være seks endelige tal inden for ±{MAX_COORD}, som ikke gør objektet fladt
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` skal indeholde 1 til {max} poster (indeholder {n})
|
||||
@msg a type fill must be a color or a gradient en tekstudfyldning skal være en farve eller en gradient
|
||||
@msg artboard name `{shown}` is used twice tegnefladenavnet `{shown}` bruges to gange
|
||||
@msg object {k} must be in exactly one layer objekt {k} skal ligge i præcis ét lag
|
||||
@msg only an importer declares `outputKinds` kun en importør angiver `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels billederne indeholder mere end {MAX_PIXEL_BYTES} byte pixels
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list outputtet indeholder `{kind}`, som importørens `outputKinds` ikke angiver
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text teksten indeholder mere end {MAX_TEXT_TOTAL} byte
|
||||
@msg unknown field `{key}` ukendt felt `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixel (grænse {MAX_IMAGE_SIDE} pixel pr. side)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads filen er større end de {MAX_INPUT_BYTES} byte, en importør læser
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` en importør angiver 1 til {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` kun en eksportør eller en importør angiver `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8399,6 +8399,27 @@ breakText Glyphs Glyphen
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` ist ein Live-Effekt: Wenden Sie ihn mit effect.apply {{"effect": "{_2}"}} an
|
||||
@msg the importer returned no objects das Import-Plug-in hat keine Objekte zurückgegeben
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` ein Import-Plug-in gibt `objects` und `warnings` zurück, nicht `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` muss Objektindizes in aufsteigender Reihenfolge aufführen, jeder kleiner als {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` führt `{shown}` doppelt auf
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` nennt eine unbekannte Art `{shown}`: verwenden Sie type, image, layer oder artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` erfordert Plug-in-API-Stufe {OUTPUT_KINDS_API}: geben Sie `api` {OUTPUT_KINDS_API} an
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` muss [width, height] sein: zwei ganze Zahlen von 1 bis {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` muss 4 × Breite × Höhe = {want} Byte als Base64 enthalten
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` muss [x, y, width, height] sein: endliche Zahlen innerhalb von ±{MAX_COORD}, Breite und Höhe größer als 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` ist {len} Byte groß (Grenze {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` darf außer Zeilenumbrüchen und Tabulatoren keine Steuerzeichen enthalten
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` muss 1-{MAX_NAME_CHARS} Zeichen lang sein, ohne Steuerzeichen oder Textrichtungszeichen
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` müssen sechs endliche Zahlen innerhalb von ±{MAX_COORD} sein, die das Objekt nicht flach drücken
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` muss 1 bis {max} Einträge enthalten (enthält {n})
|
||||
@msg a type fill must be a color or a gradient eine Textfläche muss eine Farbe oder ein Verlauf sein
|
||||
@msg artboard name `{shown}` is used twice der Zeichenflächenname `{shown}` wird doppelt verwendet
|
||||
@msg object {k} must be in exactly one layer Objekt {k} muss in genau einer Ebene liegen
|
||||
@msg only an importer declares `outputKinds` nur ein Import-Plug-in deklariert `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels die Bilder enthalten mehr als {MAX_PIXEL_BYTES} Byte Pixel
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list die Ausgabe enthält `{kind}`, das `outputKinds` des Import-Plug-ins nicht aufführt
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text der Text enthält mehr als {MAX_TEXT_TOTAL} Byte
|
||||
@msg unknown field `{key}` unbekanntes Feld `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} Pixel (Grenze {MAX_IMAGE_SIDE} Pixel je Seite)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads die Datei ist größer als die {MAX_INPUT_BYTES} Byte, die ein Import-Plug-in liest
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` ein Import-Plug-in gibt 1 bis {MAX_EXTENSIONS} `extensions` an
|
||||
@msg only an exporter or an importer declares `extensions` nur ein Export- oder Import-Plug-in gibt `extensions` an
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8769,6 +8769,27 @@ breakText Glyphs Γλύφοι
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} το `{_1}` είναι δυναμικό εφέ: εφαρμόστε το με effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects το πρόσθετο εισαγωγής δεν επέστρεψε κανένα αντικείμενο
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` ένα πρόσθετο εισαγωγής επιστρέφει `objects` και `warnings`, όχι `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} το `objects` πρέπει να αναφέρει δείκτες αντικειμένων σε αύξουσα σειρά, ο καθένας μικρότερος από {count}
|
||||
@msg `outputKinds` lists `{shown}` twice το `outputKinds` αναφέρει το `{shown}` δύο φορές
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard το `outputKinds` ορίζει άγνωστο είδος `{shown}`: χρησιμοποιήστε type, image, layer ή artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} το `outputKinds` απαιτεί επίπεδο API προσθέτων {OUTPUT_KINDS_API}: δώστε `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} το `pixelSize` πρέπει να είναι [width, height]: δύο ακέραιοι από 1 έως {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 το `pixelsBase64` πρέπει να περιέχει 4 × πλάτος × ύψος = {want} byte σε base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 το `rect` πρέπει να είναι [x, y, width, height]: πεπερασμένοι αριθμοί εντός ±{MAX_COORD}, πλάτος και ύψος πάνω από 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) το `text` είναι {len} byte (όριο {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs το `text` δεν πρέπει να περιέχει χαρακτήρες ελέγχου εκτός από αλλαγές γραμμής και στηλοθέτες
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters το `{key}` πρέπει να έχει 1-{MAX_NAME_CHARS} χαρακτήρες, χωρίς χαρακτήρες ελέγχου ή κατεύθυνσης κειμένου
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object το `{key}` πρέπει να είναι έξι πεπερασμένοι αριθμοί εντός ±{MAX_COORD} που δεν ισοπεδώνουν το αντικείμενο
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) το `{key}` πρέπει να περιέχει 1 έως {max} καταχωρίσεις (περιέχει {n})
|
||||
@msg a type fill must be a color or a gradient το γέμισμα κειμένου πρέπει να είναι χρώμα ή ντεγκραντέ
|
||||
@msg artboard name `{shown}` is used twice το όνομα πίνακα σχεδίασης `{shown}` χρησιμοποιείται δύο φορές
|
||||
@msg object {k} must be in exactly one layer το αντικείμενο {k} πρέπει να βρίσκεται σε ακριβώς ένα επίπεδο
|
||||
@msg only an importer declares `outputKinds` μόνο ένα πρόσθετο εισαγωγής δηλώνει `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels οι εικόνες περιέχουν περισσότερα από {MAX_PIXEL_BYTES} byte εικονοστοιχείων
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list η έξοδος περιέχει `{kind}`, που δεν αναφέρεται στο `outputKinds` του προσθέτου εισαγωγής
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text το κείμενο περιέχει περισσότερα από {MAX_TEXT_TOTAL} byte
|
||||
@msg unknown field `{key}` άγνωστο πεδίο `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} εικονοστοιχεία (όριο {MAX_IMAGE_SIDE} εικονοστοιχεία ανά πλευρά)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads το αρχείο είναι μεγαλύτερο από τα {MAX_INPUT_BYTES} byte που διαβάζει ένα πρόσθετο εισαγωγής
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` ένα πρόσθετο εισαγωγής δηλώνει 1 έως {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` μόνο ένα πρόσθετο εξαγωγής ή εισαγωγής δηλώνει `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8755,6 +8755,27 @@ breakText Glyphs Glifos
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` es un efecto interactivo: aplíquelo con effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects el plugin de importación no devolvió ningún objeto
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` un plugin de importación devuelve `objects` y `warnings`, no `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` debe incluir índices de objetos en orden creciente, cada uno menor que {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` incluye `{shown}` dos veces
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` nombra un tipo desconocido `{shown}`: use type, image, layer o artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` requiere el nivel de API de plugins {OUTPUT_KINDS_API}: indique `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` debe ser [width, height]: dos números enteros de 1 a {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` debe contener 4 × ancho × alto = {want} bytes en base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` debe ser [x, y, width, height]: números finitos dentro de ±{MAX_COORD}, con ancho y alto mayores que 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` tiene {len} bytes (límite {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` no debe contener caracteres de control salvo saltos de línea y tabulaciones
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` debe tener 1-{MAX_NAME_CHARS} caracteres, sin caracteres de control ni de dirección del texto
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` debe ser seis números finitos dentro de ±{MAX_COORD} que no aplanen el objeto
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` debe contener de 1 a {max} entradas (contiene {n})
|
||||
@msg a type fill must be a color or a gradient el relleno de un texto debe ser un color o un degradado
|
||||
@msg artboard name `{shown}` is used twice el nombre de mesa de trabajo `{shown}` se usa dos veces
|
||||
@msg object {k} must be in exactly one layer el objeto {k} debe estar en exactamente una capa
|
||||
@msg only an importer declares `outputKinds` solo un plugin de importación declara `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels las imágenes contienen más de {MAX_PIXEL_BYTES} bytes de píxeles
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list la salida contiene `{kind}`, que `outputKinds` del plugin de importación no incluye
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text el texto contiene más de {MAX_TEXT_TOTAL} bytes
|
||||
@msg unknown field `{key}` campo desconocido `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} píxeles (límite {MAX_IMAGE_SIDE} píxeles por lado)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads el archivo supera los {MAX_INPUT_BYTES} bytes que lee un plugin de importación
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` un plugin de importación declara de 1 a {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` solo un plugin de exportación o de importación declara `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8850,6 +8850,27 @@ breakText Glyphs Merkit
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` on live-tehoste: käytä sitä komennolla effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects tuontilaajennus ei palauttanut objekteja
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` tuontilaajennus palauttaa `objects` ja `warnings`, ei `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects`-avaimessa on lueteltava objektien indeksit nousevassa järjestyksessä, jokainen pienempi kuin {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` luettelee kohteen `{shown}` kahdesti
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` nimeää tuntemattoman lajin `{shown}`: käytä arvoa type, image, layer tai artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` edellyttää laajennus-API:n tasoa {OUTPUT_KINDS_API}: anna `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` on oltava [width, height]: kaksi kokonaislukua väliltä 1-{MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` on sisällettävä 4 × leveys × korkeus = {want} tavua base64-muodossa
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` on oltava [x, y, width, height]: äärellisiä lukuja välillä ±{MAX_COORD}, leveys ja korkeus yli 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` on {len} tavua (raja {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` ei saa sisältää muita ohjausmerkkejä kuin rivinvaihtoja ja sarkaimia
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` on oltava 1-{MAX_NAME_CHARS} merkkiä ilman ohjausmerkkejä tai tekstin suunnan merkkejä
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` on oltava kuusi äärellistä lukua välillä ±{MAX_COORD}, jotka eivät litistä objektia
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` on sisällettävä 1-{max} merkintää (siinä on {n})
|
||||
@msg a type fill must be a color or a gradient tekstin täytön on oltava väri tai liukuväri
|
||||
@msg artboard name `{shown}` is used twice piirtoalustan nimeä `{shown}` käytetään kahdesti
|
||||
@msg object {k} must be in exactly one layer objektin {k} on oltava täsmälleen yhdellä tasolla
|
||||
@msg only an importer declares `outputKinds` vain tuontilaajennus voi määrittää `outputKinds`-avaimen
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels kuvissa on yli {MAX_PIXEL_BYTES} tavua pikseleitä
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list tuloste sisältää lajin `{kind}`, jota tuontilaajennuksen `outputKinds` ei luettele
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text tekstissä on yli {MAX_TEXT_TOTAL} tavua
|
||||
@msg unknown field `{key}` tuntematon kenttä `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pikseliä (raja {MAX_IMAGE_SIDE} pikseliä sivua kohden)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads tiedosto on suurempi kuin tuontilaajennuksen lukemat {MAX_INPUT_BYTES} tavua
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` tuontilaajennus ilmoittaa 1–{MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` vain vienti- tai tuontilaajennus ilmoittaa `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8772,6 +8772,27 @@ breakText Glyphs Glyphes
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` est un effet dynamique : appliquez-le avec effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects le module externe d’importation n’a renvoyé aucun objet
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` un module externe d’importation renvoie `objects` et `warnings`, pas `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` doit indiquer des indices d’objets dans l’ordre croissant, chacun inférieur à {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` mentionne `{shown}` deux fois
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` indique un type inconnu `{shown}`. Utilisez type, image, layer ou artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` nécessite le niveau d’API de module externe {OUTPUT_KINDS_API}. Indiquez `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` doit être [width, height], soit deux nombres entiers de 1 à {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` doit contenir 4 × largeur × hauteur = {want} octets en base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` doit être [x, y, width, height], soit des nombres finis compris dans ±{MAX_COORD}, largeur et hauteur supérieures à 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` fait {len} octets (limite {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` ne doit contenir aucun caractère de contrôle autre que des sauts de ligne et des tabulations
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` doit compter 1-{MAX_NAME_CHARS} caractères, sans caractère de contrôle ni de sens du texte
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` doit être six nombres finis compris dans ±{MAX_COORD} qui n’aplatissent pas l’objet
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` doit contenir de 1 à {max} entrées (il en contient {n})
|
||||
@msg a type fill must be a color or a gradient le fond d’un texte doit être une couleur ou un dégradé
|
||||
@msg artboard name `{shown}` is used twice le nom de plan de travail `{shown}` est utilisé deux fois
|
||||
@msg object {k} must be in exactly one layer l’objet {k} doit se trouver dans un seul calque
|
||||
@msg only an importer declares `outputKinds` seul un module externe d’importation déclare `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels les images contiennent plus de {MAX_PIXEL_BYTES} octets de pixels
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list la sortie contient `{kind}`, que `outputKinds` du module externe d’importation ne mentionne pas
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text le texte contient plus de {MAX_TEXT_TOTAL} octets
|
||||
@msg unknown field `{key}` champ inconnu `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixels (limite {MAX_IMAGE_SIDE} pixels par côté)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads le fichier dépasse les {MAX_INPUT_BYTES} octets qu’un module externe d’importation lit
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` un module externe d’importation déclare de 1 à {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` seul un module externe d’exportation ou d’importation déclare `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -10238,6 +10238,27 @@ theme Appearance अपीयरेंस
|
||||
@msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` एक इंपोर्टर है: document.open {{"importer": "{_2}"}} से फ़ाइल खोलें
|
||||
@msg the importer returned no objects इंपोर्टर ने कोई ऑब्जेक्ट नहीं लौटाया
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` इंपोर्टर `objects` और `warnings` लौटाता है, `{key}` नहीं
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` में ऑब्जेक्ट इंडेक्स बढ़ते क्रम में होने चाहिए, हर एक {count} से कम
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` में `{shown}` दो बार सूचीबद्ध है
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` में अज्ञात प्रकार `{shown}` है: type, image, layer या artboard का उपयोग करें
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` के लिए प्लग-इन API स्तर {OUTPUT_KINDS_API} आवश्यक है: `api` {OUTPUT_KINDS_API} दें
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` [width, height] होना चाहिए: 1 से {MAX_IMAGE_SIDE} तक की दो पूर्ण संख्याएँ
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` में base64 के रूप में 4 × चौड़ाई × ऊँचाई = {want} बाइट होने चाहिए
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` [x, y, width, height] होना चाहिए: ±{MAX_COORD} के भीतर सीमित संख्याएँ, चौड़ाई और ऊँचाई 0 से अधिक
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` {len} बाइट का है (सीमा {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` में लाइन ब्रेक और टैब के अलावा कोई नियंत्रण वर्ण नहीं होना चाहिए
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` में 1-{MAX_NAME_CHARS} वर्ण होने चाहिए, नियंत्रण या टेक्स्ट दिशा वर्णों के बिना
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` ±{MAX_COORD} के भीतर छह सीमित संख्याएँ होनी चाहिए जो ऑब्जेक्ट को चपटा न करें
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` में 1 से {max} प्रविष्टियाँ होनी चाहिए (इसमें {n} हैं)
|
||||
@msg a type fill must be a color or a gradient टेक्स्ट का फ़िल रंग या ग्रेडिएंट होना चाहिए
|
||||
@msg artboard name `{shown}` is used twice आर्टबोर्ड नाम `{shown}` दो बार उपयोग हुआ है
|
||||
@msg object {k} must be in exactly one layer ऑब्जेक्ट {k} ठीक एक लेयर में होना चाहिए
|
||||
@msg only an importer declares `outputKinds` केवल इंपोर्टर `outputKinds` घोषित करता है
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels इमेज में {MAX_PIXEL_BYTES} बाइट से अधिक पिक्सेल हैं
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list आउटपुट में `{kind}` है, जिसे इंपोर्टर का `outputKinds` सूचीबद्ध नहीं करता
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text टेक्स्ट में {MAX_TEXT_TOTAL} बाइट से अधिक है
|
||||
@msg unknown field `{key}` अज्ञात फ़ील्ड `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} पिक्सेल (हर तरफ़ सीमा {MAX_IMAGE_SIDE} पिक्सेल)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads फ़ाइल उन {MAX_INPUT_BYTES} बाइट्स से बड़ी है जो इंपोर्टर पढ़ता है
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` इंपोर्टर 1 से {MAX_EXTENSIONS} `extensions` घोषित करता है
|
||||
@msg an importer always gets an import's budget: leave `budget` out इंपोर्टर को हमेशा इंपोर्ट का बजट मिलता है: `budget` छोड़ दें
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8762,6 +8762,27 @@ breakText Glyphs Glifák
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` élő effektus: alkalmazza az effect.apply {{"effect": "{_2}"}} paranccsal
|
||||
@msg the importer returned no objects az importáló bővítmény nem adott vissza objektumot
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` az importáló bővítmény `objects` és `warnings` értéket ad vissza, nem `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} az `objects` kulcsnak objektumindexeket kell felsorolnia növekvő sorrendben, mindegyik kisebb, mint {count}
|
||||
@msg `outputKinds` lists `{shown}` twice az `outputKinds` kétszer sorolja fel ezt: `{shown}`
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard az `outputKinds` ismeretlen fajtát ad meg: `{shown}`; használja ezeket: type, image, layer vagy artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} az `outputKinds` használatához {OUTPUT_KINDS_API}. szintű bővítmény-API szükséges: adja meg az `api` {OUTPUT_KINDS_API} értéket
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} a `pixelSize` értéke [width, height] kell legyen: két egész szám 1 és {MAX_IMAGE_SIDE} között
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 a `pixelsBase64` értéknek 4 × szélesség × magasság = {want} bájtot kell tartalmaznia base64 formában
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 a `rect` értéke [x, y, width, height] kell legyen: véges számok ±{MAX_COORD} tartományban, 0-nál nagyobb szélességgel és magassággal
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) a `text` {len} bájt (korlát: {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs a `text` nem tartalmazhat vezérlőkaraktert a sortöréseken és tabulátorokon kívül
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}`: 1-{MAX_NAME_CHARS} karakter kell, vezérlő- és szövegirány-karakterek nélkül
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}`: hat véges szám kell ±{MAX_COORD} tartományban, amely nem lapítja el az objektumot
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}`: 1 és {max} közötti számú bejegyzés kell (jelenleg {n})
|
||||
@msg a type fill must be a color or a gradient a szöveg kitöltése szín vagy színátmenet lehet
|
||||
@msg artboard name `{shown}` is used twice a(z) `{shown}` rajztáblanév kétszer szerepel
|
||||
@msg object {k} must be in exactly one layer a(z) {k}. objektumnak pontosan egy rétegben kell lennie
|
||||
@msg only an importer declares `outputKinds` `outputKinds` kulcsot csak importáló bővítmény adhat meg
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels a képek több mint {MAX_PIXEL_BYTES} bájtnyi képpontot tartalmaznak
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list a kimenet `{kind}` tartalmat hordoz, amelyet az importáló bővítmény `outputKinds` kulcsa nem sorol fel
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text a szöveg több mint {MAX_TEXT_TOTAL} bájt
|
||||
@msg unknown field `{key}` ismeretlen mező: `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} képpont (oldalanként legfeljebb {MAX_IMAGE_SIDE} képpont)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads a fájl nagyobb annál a {MAX_INPUT_BYTES} bájtnál, amit egy importáló bővítmény beolvas
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` az importáló bővítmény 1–{MAX_EXTENSIONS} `extensions` értéket ad meg
|
||||
@msg only an exporter or an importer declares `extensions` csak exportáló vagy importáló bővítmény adhat meg `extensions` értéket
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -732,6 +732,27 @@
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` adalah efek langsung: terapkan dengan effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects pengimpor tidak mengembalikan objek apa pun
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` pengimpor mengembalikan `objects` dan `warnings`, bukan `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` harus mencantumkan indeks objek dalam urutan naik, masing-masing kurang dari {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` mencantumkan `{shown}` dua kali
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` menyebut jenis yang tidak dikenal `{shown}`: gunakan type, image, layer, atau artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` memerlukan API plug-in tingkat {OUTPUT_KINDS_API}: berikan `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` harus berupa [width, height]: dua bilangan bulat dari 1 sampai {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` harus berisi 4 × lebar × tinggi = {want} byte dalam base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` harus berupa [x, y, width, height]: bilangan hingga dalam ±{MAX_COORD}, lebar dan tinggi di atas 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` berukuran {len} byte (batas {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` tidak boleh berisi karakter kontrol selain pemisah baris dan tab
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` harus terdiri dari 1-{MAX_NAME_CHARS} karakter, tanpa karakter kontrol atau karakter arah teks
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` harus berupa enam bilangan hingga dalam ±{MAX_COORD} yang tidak memipihkan objek
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` harus berisi 1 sampai {max} entri (berisi {n})
|
||||
@msg a type fill must be a color or a gradient isian teks harus berupa warna atau gradien
|
||||
@msg artboard name `{shown}` is used twice nama artboard `{shown}` digunakan dua kali
|
||||
@msg object {k} must be in exactly one layer objek {k} harus berada di tepat satu lapisan
|
||||
@msg only an importer declares `outputKinds` hanya pengimpor yang mendeklarasikan `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels gambar berisi lebih dari {MAX_PIXEL_BYTES} byte piksel
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list keluaran berisi `{kind}`, yang tidak dicantumkan oleh `outputKinds` pengimpor
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text teks berisi lebih dari {MAX_TEXT_TOTAL} byte
|
||||
@msg unknown field `{key}` bidang tidak dikenal `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} piksel (batas {MAX_IMAGE_SIDE} piksel per sisi)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads berkas lebih besar dari {MAX_INPUT_BYTES} byte yang dibaca pengimpor
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` pengimpor mendeklarasikan 1 sampai {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` hanya pengekspor atau pengimpor yang mendeklarasikan `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8437,6 +8437,27 @@ breakText Glyphs Glifi
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` è un effetto dinamico: applicalo con effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects il plug-in di importazione non ha restituito alcun oggetto
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` un plug-in di importazione restituisce `objects` e `warnings`, non `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` deve elencare indici di oggetti in ordine crescente, ciascuno minore di {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` elenca `{shown}` due volte
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` indica un tipo sconosciuto `{shown}`: usa type, image, layer o artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` richiede il livello API dei plug-in {OUTPUT_KINDS_API}: indica `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` deve essere [width, height]: due numeri interi da 1 a {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` deve contenere 4 × larghezza × altezza = {want} byte in base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` deve essere [x, y, width, height]: numeri finiti entro ±{MAX_COORD}, con larghezza e altezza maggiori di 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` è di {len} byte (limite {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` non deve contenere caratteri di controllo diversi da interruzioni di riga e tabulazioni
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` deve avere 1-{MAX_NAME_CHARS} caratteri, senza caratteri di controllo o di direzione del testo
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` deve essere sei numeri finiti entro ±{MAX_COORD} che non appiattiscano l’oggetto
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` deve contenere da 1 a {max} voci (ne contiene {n})
|
||||
@msg a type fill must be a color or a gradient il riempimento di un testo deve essere un colore o una sfumatura
|
||||
@msg artboard name `{shown}` is used twice il nome di tavola da disegno `{shown}` è usato due volte
|
||||
@msg object {k} must be in exactly one layer l’oggetto {k} deve trovarsi in un solo livello
|
||||
@msg only an importer declares `outputKinds` solo un plug-in di importazione dichiara `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels le immagini contengono più di {MAX_PIXEL_BYTES} byte di pixel
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list l’output contiene `{kind}`, che `outputKinds` del plug-in di importazione non elenca
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text il testo contiene più di {MAX_TEXT_TOTAL} byte
|
||||
@msg unknown field `{key}` campo sconosciuto `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixel (limite {MAX_IMAGE_SIDE} pixel per lato)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads il file supera i {MAX_INPUT_BYTES} byte che un plug-in di importazione legge
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` un plug-in di importazione dichiara da 1 a {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` solo un plug-in di esportazione o di importazione dichiara `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -10330,6 +10330,27 @@ breakText Glyphs 字形
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` はライブ効果です: effect.apply {{"effect": "{_2}"}} で適用してください
|
||||
@msg the importer returned no objects 読み込みプラグインがオブジェクトを返しませんでした
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` 読み込みプラグインが返すのは `objects` と `warnings` で、`{key}` ではありません
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` にはオブジェクトのインデックスを昇順で指定してください (各値は {count} 未満)
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` に `{shown}` が 2 回指定されています
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` に不明な種類 `{shown}` が指定されています: type、image、layer、artboard のいずれかを使用してください
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` にはプラグイン API レベル {OUTPUT_KINDS_API} が必要です: `api` {OUTPUT_KINDS_API} を指定してください
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` は [width, height] の形式で指定してください: 1 から {MAX_IMAGE_SIDE} までの整数 2 つ
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` には 4 × 幅 × 高さ = {want} バイトを base64 で指定してください
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` は [x, y, width, height] の形式で指定してください: ±{MAX_COORD} 以内の有限の数値で、幅と高さは 0 より大きくします
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` は {len} バイトです (上限 {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` には改行とタブ以外の制御文字を含めないでください
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` は 1-{MAX_NAME_CHARS} 文字にし、制御文字や文字方向を変える文字を含めないでください
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` は ±{MAX_COORD} 以内の有限の数値 6 つで、オブジェクトをつぶさないものにしてください
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` の項目数は 1 から {max} にしてください (現在 {n})
|
||||
@msg a type fill must be a color or a gradient テキストの塗りはカラーまたはグラデーションにしてください
|
||||
@msg artboard name `{shown}` is used twice アートボード名 `{shown}` が 2 回使われています
|
||||
@msg object {k} must be in exactly one layer オブジェクト {k} はちょうど 1 つのレイヤーに入れてください
|
||||
@msg only an importer declares `outputKinds` `outputKinds` を宣言できるのは読み込みプラグインだけです
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels 画像のピクセルが {MAX_PIXEL_BYTES} バイトを超えています
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list 出力に `{kind}` が含まれていますが、読み込みプラグインの `outputKinds` には指定されていません
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text テキストが {MAX_TEXT_TOTAL} バイトを超えています
|
||||
@msg unknown field `{key}` 不明なフィールド `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} ピクセル (1 辺の上限 {MAX_IMAGE_SIDE} ピクセル)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads ファイルが読み込みプラグインの読み取る {MAX_INPUT_BYTES} バイトを超えています
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` 読み込みプラグインは `extensions` を 1~{MAX_EXTENSIONS} 個宣言します
|
||||
@msg only an exporter or an importer declares `extensions` `extensions` を宣言できるのは書き出しプラグインと読み込みプラグインだけです
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -11035,6 +11035,27 @@ font-script Japanese იაპონური
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` ცოცხალი ეფექტია: გამოიყენეთ ის effect.apply {{"effect": "{_2}"}}-ით
|
||||
@msg the importer returned no objects იმპორტის პლაგინმა ობიექტები არ დააბრუნა
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` იმპორტის პლაგინი აბრუნებს `objects`-ს და `warnings`-ს და არა `{key}`-ს
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects`-ში ობიექტების ინდექსები ზრდადი რიგით უნდა იყოს, თითოეული {count}-ზე ნაკლები
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds`-ში `{shown}` ორჯერაა ჩამოთვლილი
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds`-ში უცნობი სახეა `{shown}`: გამოიყენეთ type, image, layer ან artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds`-ს სჭირდება პლაგინის API-ის დონე {OUTPUT_KINDS_API}: მიუთითეთ `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` უნდა იყოს [width, height]: ორი მთელი რიცხვი 1-დან {MAX_IMAGE_SIDE}-მდე
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` უნდა შეიცავდეს 4 × სიგანე × სიმაღლე = {want} ბაიტს base64-ში
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` უნდა იყოს [x, y, width, height]: სასრული რიცხვები ±{MAX_COORD}-ის ფარგლებში, სიგანე და სიმაღლე 0-ზე მეტი
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` არის {len} ბაიტი (ზღვარი {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` არ უნდა შეიცავდეს მართვის სიმბოლოებს, გარდა ხაზის გადატანისა და ტაბულაციისა
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` უნდა იყოს 1-{MAX_NAME_CHARS} სიმბოლო, მართვის და ტექსტის მიმართულების სიმბოლოების გარეშე
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` უნდა იყოს ექვსი სასრული რიცხვი ±{MAX_COORD}-ის ფარგლებში, რომლებიც ობიექტს არ აბრტყელებს
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` უნდა შეიცავდეს 1-დან {max}-მდე ჩანაწერს (შეიცავს {n}-ს)
|
||||
@msg a type fill must be a color or a gradient ტექსტის შევსება უნდა იყოს ფერი ან გრადიენტი
|
||||
@msg artboard name `{shown}` is used twice სამუშაო დაფის სახელი `{shown}` ორჯერაა გამოყენებული
|
||||
@msg object {k} must be in exactly one layer ობიექტი {k} ზუსტად ერთ შრეში უნდა იყოს
|
||||
@msg only an importer declares `outputKinds` `outputKinds`-ის გამოცხადება მხოლოდ იმპორტის პლაგინს შეუძლია
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels გამოსახულებები {MAX_PIXEL_BYTES} ბაიტზე მეტ პიქსელს შეიცავს
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list გამოტანა შეიცავს `{kind}`-ს, რომელიც იმპორტის პლაგინის `outputKinds`-ში არ არის ჩამოთვლილი
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text ტექსტი {MAX_TEXT_TOTAL} ბაიტზე მეტს შეიცავს
|
||||
@msg unknown field `{key}` უცნობი ველი `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} პიქსელი (ზღვარი {MAX_IMAGE_SIDE} პიქსელი თითო მხარეს)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads ფაილი აღემატება {MAX_INPUT_BYTES} ბაიტს, რომელსაც იმპორტის პლაგინი კითხულობს
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` იმპორტის პლაგინი აცხადებს 1-დან {MAX_EXTENSIONS}-მდე `extensions`-ს
|
||||
@msg only an exporter or an importer declares `extensions` `extensions`-ს მხოლოდ ექსპორტის ან იმპორტის პლაგინი აცხადებს
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8409,6 +8409,27 @@ breakText Glyphs 글리프
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}`은(는) 라이브 효과입니다: effect.apply {{"effect": "{_2}"}}로 적용하세요
|
||||
@msg the importer returned no objects 가져오기 플러그인이 개체를 반환하지 않았습니다
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` 가져오기 플러그인은 `{key}`가 아닌 `objects`와 `warnings`를 반환합니다
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects`에는 개체 인덱스를 오름차순으로 나열해야 하며 각 값은 {count}보다 작아야 합니다
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds`에 `{shown}`이(가) 두 번 나열되어 있습니다
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds`에 알 수 없는 종류 `{shown}`이(가) 있습니다. type, image, layer 또는 artboard를 사용하세요
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds`에는 플러그인 API 수준 {OUTPUT_KINDS_API}이(가) 필요합니다. `api`를 {OUTPUT_KINDS_API}(으)로 지정하세요
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize`는 [width, height]여야 합니다. 1에서 {MAX_IMAGE_SIDE} 사이의 정수 두 개
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64`에는 4 × 너비 × 높이 = {want}바이트가 base64로 들어 있어야 합니다
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect`는 [x, y, width, height]여야 합니다. ±{MAX_COORD} 이내의 유한한 수이며 너비와 높이는 0보다 커야 합니다
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text`가 {len}바이트입니다(한도 {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text`에는 줄 바꿈과 탭 외의 제어 문자가 없어야 합니다
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}`은(는) 제어 문자나 텍스트 방향 문자 없이 1-{MAX_NAME_CHARS}자여야 합니다
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}`은(는) 개체를 납작하게 만들지 않는 ±{MAX_COORD} 이내의 유한한 수 여섯 개여야 합니다
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}`에는 1~{max}개의 항목이 있어야 합니다(현재 {n}개)
|
||||
@msg a type fill must be a color or a gradient 텍스트 칠은 색상 또는 그레이디언트여야 합니다
|
||||
@msg artboard name `{shown}` is used twice 아트보드 이름 `{shown}`이(가) 두 번 사용되었습니다
|
||||
@msg object {k} must be in exactly one layer 개체 {k}은(는) 정확히 한 레이어에 있어야 합니다
|
||||
@msg only an importer declares `outputKinds` 가져오기 플러그인만 `outputKinds`를 선언할 수 있습니다
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels 이미지의 픽셀이 {MAX_PIXEL_BYTES}바이트를 넘습니다
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list 출력에 가져오기 플러그인의 `outputKinds`에 없는 `{kind}`이(가) 있습니다
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text 텍스트가 {MAX_TEXT_TOTAL}바이트를 넘습니다
|
||||
@msg unknown field `{key}` 알 수 없는 필드 `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h}픽셀(한 변 한도 {MAX_IMAGE_SIDE}픽셀)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads 파일이 가져오기 플러그인이 읽는 {MAX_INPUT_BYTES}바이트보다 큽니다
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` 가져오기 플러그인은 `extensions`를 1~{MAX_EXTENSIONS}개 선언합니다
|
||||
@msg only an exporter or an importer declares `extensions` `extensions`는 내보내기 또는 가져오기 플러그인만 선언합니다
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -695,6 +695,27 @@ liquify-list-end {0}, {1} {0} en {1}
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` is een live-effect: pas het toe met effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects de importplug-in heeft geen objecten teruggegeven
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` een importplug-in geeft `objects` en `warnings` terug, niet `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` moet objectindexen in oplopende volgorde noemen, elk kleiner dan {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` noemt `{shown}` twee keer
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` noemt een onbekende soort `{shown}`: gebruik type, image, layer of artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` vereist plug-in-API-niveau {OUTPUT_KINDS_API}: geef `api` {OUTPUT_KINDS_API} op
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` moet [width, height] zijn: twee gehele getallen van 1 tot en met {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` moet 4 × breedte × hoogte = {want} bytes als base64 bevatten
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` moet [x, y, width, height] zijn: eindige getallen binnen ±{MAX_COORD}, breedte en hoogte groter dan 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` is {len} bytes (limiet {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` mag geen andere stuurtekens bevatten dan regeleinden en tabs
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` moet 1-{MAX_NAME_CHARS} tekens lang zijn, zonder stuurtekens of tekens voor de tekstrichting
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` moet uit zes eindige getallen binnen ±{MAX_COORD} bestaan die het object niet plat maken
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` moet 1 tot en met {max} items bevatten (bevat er {n})
|
||||
@msg a type fill must be a color or a gradient een tekstvulling moet een kleur of een verloop zijn
|
||||
@msg artboard name `{shown}` is used twice de tekengebiednaam `{shown}` wordt twee keer gebruikt
|
||||
@msg object {k} must be in exactly one layer object {k} moet in precies één laag staan
|
||||
@msg only an importer declares `outputKinds` alleen een importplug-in declareert `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels de afbeeldingen bevatten meer dan {MAX_PIXEL_BYTES} bytes aan pixels
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list de uitvoer bevat `{kind}`, dat `outputKinds` van de importplug-in niet noemt
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text de tekst bevat meer dan {MAX_TEXT_TOTAL} bytes
|
||||
@msg unknown field `{key}` onbekend veld `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixels (limiet {MAX_IMAGE_SIDE} pixels per zijde)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads het bestand is groter dan de {MAX_INPUT_BYTES} bytes die een importplug-in leest
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` een importplug-in declareert 1 tot {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` alleen een exportplug-in of een importplug-in declareert `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8633,6 +8633,27 @@ breakText Glyphs Glify
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` to efekt na żywo: zastosuj go za pomocą effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects wtyczka importu nie zwróciła żadnych obiektów
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` wtyczka importu zwraca `objects` i `warnings`, a nie `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` musi wymieniać indeksy obiektów w kolejności rosnącej, każdy mniejszy niż {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` wymienia `{shown}` dwa razy
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` podaje nieznany rodzaj `{shown}`: użyj type, image, layer lub artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` wymaga poziomu API wtyczek {OUTPUT_KINDS_API}: podaj `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` musi mieć postać [width, height]: dwie liczby całkowite od 1 do {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` musi zawierać 4 × szerokość × wysokość = {want} bajtów w base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` musi mieć postać [x, y, width, height]: liczby skończone w zakresie ±{MAX_COORD}, szerokość i wysokość większe od 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` ma {len} bajtów (limit {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` nie może zawierać znaków sterujących innych niż podziały wierszy i tabulatory
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` musi mieć 1-{MAX_NAME_CHARS} znaków, bez znaków sterujących i znaków kierunku tekstu
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` musi być sześcioma liczbami skończonymi w zakresie ±{MAX_COORD}, które nie spłaszczają obiektu
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` musi zawierać od 1 do {max} pozycji (zawiera {n})
|
||||
@msg a type fill must be a color or a gradient wypełnienie tekstu musi być kolorem lub gradientem
|
||||
@msg artboard name `{shown}` is used twice nazwa obszaru kompozycji `{shown}` jest użyta dwa razy
|
||||
@msg object {k} must be in exactly one layer obiekt {k} musi być w dokładnie jednej warstwie
|
||||
@msg only an importer declares `outputKinds` tylko wtyczka importu deklaruje `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels obrazy zawierają więcej niż {MAX_PIXEL_BYTES} bajtów pikseli
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list wynik zawiera `{kind}`, którego nie wymienia `outputKinds` wtyczki importu
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text tekst zawiera więcej niż {MAX_TEXT_TOTAL} bajtów
|
||||
@msg unknown field `{key}` nieznane pole `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pikseli (limit {MAX_IMAGE_SIDE} pikseli na bok)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads plik jest większy niż {MAX_INPUT_BYTES} bajtów, które odczytuje wtyczka importu
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` wtyczka importu deklaruje od 1 do {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` `extensions` deklaruje tylko wtyczka eksportu lub importu
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8955,6 +8955,27 @@ swatch Yellow Green Verde-amarelado
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` é um efeito dinâmico: aplique-o com effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects o plug-in de importação não retornou nenhum objeto
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` um plug-in de importação retorna `objects` e `warnings`, não `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` deve listar índices de objetos em ordem crescente, cada um menor que {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` lista `{shown}` duas vezes
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` indica um tipo desconhecido `{shown}`: use type, image, layer ou artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` exige o nível de API de plug-ins {OUTPUT_KINDS_API}: informe `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` deve ser [width, height]: dois números inteiros de 1 a {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` deve conter 4 × largura × altura = {want} bytes em base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` deve ser [x, y, width, height]: números finitos dentro de ±{MAX_COORD}, com largura e altura maiores que 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` tem {len} bytes (limite {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` não deve conter caracteres de controle além de quebras de linha e tabulações
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` deve ter 1-{MAX_NAME_CHARS} caracteres, sem caracteres de controle nem de direção do texto
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` deve ser seis números finitos dentro de ±{MAX_COORD} que não achatem o objeto
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` deve conter de 1 a {max} entradas (contém {n})
|
||||
@msg a type fill must be a color or a gradient o preenchimento de um texto deve ser uma cor ou um gradiente
|
||||
@msg artboard name `{shown}` is used twice o nome de mesa de trabalho `{shown}` é usado duas vezes
|
||||
@msg object {k} must be in exactly one layer o objeto {k} deve estar em exatamente uma camada
|
||||
@msg only an importer declares `outputKinds` somente um plug-in de importação declara `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels as imagens contêm mais de {MAX_PIXEL_BYTES} bytes de pixels
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list a saída contém `{kind}`, que `outputKinds` do plug-in de importação não lista
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text o texto contém mais de {MAX_TEXT_TOTAL} bytes
|
||||
@msg unknown field `{key}` campo desconhecido `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixels (limite de {MAX_IMAGE_SIDE} pixels por lado)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads o arquivo é maior que os {MAX_INPUT_BYTES} bytes que um plug-in de importação lê
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` um plug-in de importação declara de 1 a {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` só um plug-in de exportação ou de importação declara `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8881,6 +8881,27 @@ shape Open Открытый
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` — динамический эффект: примените его с помощью effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects модуль импорта не вернул ни одного объекта
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` модуль импорта возвращает `objects` и `warnings`, а не `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} в `objects` должны быть индексы объектов по возрастанию, каждый меньше {count}
|
||||
@msg `outputKinds` lists `{shown}` twice в `outputKinds` `{shown}` указано дважды
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard в `outputKinds` указан неизвестный вид `{shown}`: используйте type, image, layer или artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} для `outputKinds` нужен уровень API плагинов {OUTPUT_KINDS_API}: укажите `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` должно быть [width, height]: два целых числа от 1 до {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` должно содержать 4 × ширина × высота = {want} байт в base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` должно быть [x, y, width, height]: конечные числа в пределах ±{MAX_COORD}, ширина и высота больше 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` занимает {len} байт (предел {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` не должно содержать управляющих символов, кроме разрывов строк и табуляций
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` должно содержать 1-{MAX_NAME_CHARS} символов, без управляющих символов и символов направления текста
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` должно быть шестью конечными числами в пределах ±{MAX_COORD}, которые не сплющивают объект
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` должно содержать от 1 до {max} записей (содержит {n})
|
||||
@msg a type fill must be a color or a gradient заливка текста должна быть цветом или градиентом
|
||||
@msg artboard name `{shown}` is used twice имя монтажной области `{shown}` использовано дважды
|
||||
@msg object {k} must be in exactly one layer объект {k} должен быть ровно в одном слое
|
||||
@msg only an importer declares `outputKinds` `outputKinds` может объявлять только модуль импорта
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels изображения содержат больше {MAX_PIXEL_BYTES} байт пикселей
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list вывод содержит `{kind}`, которого нет в `outputKinds` модуля импорта
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text текст занимает больше {MAX_TEXT_TOTAL} байт
|
||||
@msg unknown field `{key}` неизвестное поле `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} пикселей (предел {MAX_IMAGE_SIDE} пикселей на сторону)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads файл больше {MAX_INPUT_BYTES} байт, которые читает модуль импорта
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` модуль импорта объявляет от 1 до {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` `extensions` объявляет только модуль экспорта или импорта
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -10694,6 +10694,27 @@ digits Hindi Hindi
|
||||
@msg `{_1}` is an importer: open a file with document.open {{"importer": "{_2}"}} `{_1}` är en importfunktion: öppna en fil med document.open {{"importer": "{_2}"}}
|
||||
@msg the importer returned no objects importfunktionen returnerade inga objekt
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` en importfunktion returnerar `objects` och `warnings`, inte `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` måste ange objektindex i stigande ordning, vart och ett mindre än {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` anger `{shown}` två gånger
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` anger en okänd typ `{shown}`: använd type, image, layer eller artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` kräver plugin-API-nivå {OUTPUT_KINDS_API}: ange `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` måste vara [width, height]: två heltal från 1 till {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` måste innehålla 4 × bredd × höjd = {want} byte som base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` måste vara [x, y, width, height]: ändliga tal inom ±{MAX_COORD}, bredd och höjd över 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` är {len} byte (gräns {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` får inte innehålla andra styrtecken än radbrytningar och tabbar
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` måste vara 1-{MAX_NAME_CHARS} tecken, utan styrtecken eller textriktningstecken
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` måste vara sex ändliga tal inom ±{MAX_COORD} som inte plattar till objektet
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` måste innehålla 1 till {max} poster (innehåller {n})
|
||||
@msg a type fill must be a color or a gradient en textfyllning måste vara en färg eller en gradient
|
||||
@msg artboard name `{shown}` is used twice ritytans namn `{shown}` används två gånger
|
||||
@msg object {k} must be in exactly one layer objekt {k} måste ligga i exakt ett lager
|
||||
@msg only an importer declares `outputKinds` bara en importfunktion anger `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels bilderna innehåller mer än {MAX_PIXEL_BYTES} byte pixlar
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list utdata innehåller `{kind}`, som importfunktionens `outputKinds` inte anger
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text texten innehåller mer än {MAX_TEXT_TOTAL} byte
|
||||
@msg unknown field `{key}` okänt fält `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} pixlar (gräns {MAX_IMAGE_SIDE} pixlar per sida)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads filen är större än de {MAX_INPUT_BYTES} byte som en importfunktion läser
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` en importfunktion anger 1 till {MAX_EXTENSIONS} `extensions`
|
||||
@msg an importer always gets an import's budget: leave `budget` out en importfunktion får alltid en imports budget: utelämna `budget`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -10670,6 +10670,27 @@ breakText Glyphs Glifler
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` canlı bir efekttir: effect.apply {{"effect": "{_2}"}} ile uygulayın
|
||||
@msg the importer returned no objects içe aktarma eklentisi hiç nesne döndürmedi
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` içe aktarma eklentisi `{key}` değil, `objects` ve `warnings` döndürür
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` nesne dizinlerini artan sırada listelemelidir; her biri {count} değerinden küçük olmalıdır
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` `{shown}` değerini iki kez listeliyor
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` bilinmeyen bir tür belirtiyor: `{shown}`; type, image, layer veya artboard kullanın
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` için eklenti API düzeyi {OUTPUT_KINDS_API} gerekir: `api` {OUTPUT_KINDS_API} verin
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` [width, height] olmalıdır: 1 ile {MAX_IMAGE_SIDE} arasında iki tam sayı
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64`, base64 olarak 4 × genişlik × yükseklik = {want} bayt içermelidir
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` [x, y, width, height] olmalıdır: ±{MAX_COORD} içinde sonlu sayılar, genişlik ve yükseklik 0'dan büyük
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` {len} bayt (sınır {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` satır sonları ve sekmeler dışında denetim karakteri içermemelidir
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` denetim veya metin yönü karakterleri olmadan 1-{MAX_NAME_CHARS} karakter olmalıdır
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}`, nesneyi düzleştirmeyen ve ±{MAX_COORD} içinde kalan altı sonlu sayı olmalıdır
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` 1 ile {max} arasında öğe içermelidir ({n} öğe içeriyor)
|
||||
@msg a type fill must be a color or a gradient metin dolgusu bir renk veya degrade olmalıdır
|
||||
@msg artboard name `{shown}` is used twice çalışma yüzeyi adı `{shown}` iki kez kullanılmış
|
||||
@msg object {k} must be in exactly one layer {k} nesnesi tam olarak bir katmanda olmalıdır
|
||||
@msg only an importer declares `outputKinds` `outputKinds` yalnızca bir içe aktarma eklentisinde bildirilebilir
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels görüntüler {MAX_PIXEL_BYTES} bayttan fazla piksel içeriyor
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list çıktı, içe aktarma eklentisinin `outputKinds` listesinde olmayan `{kind}` içeriyor
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text metin {MAX_TEXT_TOTAL} bayttan fazla
|
||||
@msg unknown field `{key}` bilinmeyen alan `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} piksel (kenar başına sınır {MAX_IMAGE_SIDE} piksel)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads dosya, içe aktarma eklentisinin okuduğu {MAX_INPUT_BYTES} bayttan büyük
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` içe aktarma eklentisi 1 ile {MAX_EXTENSIONS} arasında `extensions` bildirir
|
||||
@msg only an exporter or an importer declares `extensions` `extensions` yalnızca dışa veya içe aktarma eklentisi bildirir
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8419,6 +8419,27 @@ breakText Glyphs Гліфи
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` - динамічний ефект: застосуйте його за допомогою effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects модуль імпорту не повернув жодного об’єкта
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` модуль імпорту повертає `objects` і `warnings`, а не `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} в `objects` мають бути індекси об’єктів за зростанням, кожен менший за {count}
|
||||
@msg `outputKinds` lists `{shown}` twice в `outputKinds` `{shown}` указано двічі
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard в `outputKinds` указано невідомий вид `{shown}`: використовуйте type, image, layer або artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} для `outputKinds` потрібен рівень API плагінів {OUTPUT_KINDS_API}: укажіть `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` має бути [width, height]: два цілі числа від 1 до {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` має містити 4 × ширина × висота = {want} байт у base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` має бути [x, y, width, height]: скінченні числа в межах ±{MAX_COORD}, ширина й висота більші за 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` займає {len} байт (межа {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` не має містити керівних символів, крім розривів рядків і табуляцій
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` має містити 1-{MAX_NAME_CHARS} символів, без керівних символів і символів напрямку тексту
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` має бути шістьма скінченними числами в межах ±{MAX_COORD}, які не сплющують об’єкт
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` має містити від 1 до {max} записів (містить {n})
|
||||
@msg a type fill must be a color or a gradient заливка тексту має бути кольором або градієнтом
|
||||
@msg artboard name `{shown}` is used twice назву монтажної області `{shown}` використано двічі
|
||||
@msg object {k} must be in exactly one layer об’єкт {k} має бути рівно в одному шарі
|
||||
@msg only an importer declares `outputKinds` `outputKinds` може оголошувати лише модуль імпорту
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels зображення містять понад {MAX_PIXEL_BYTES} байт пікселів
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list вивід містить `{kind}`, якого немає в `outputKinds` модуля імпорту
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text текст займає понад {MAX_TEXT_TOTAL} байт
|
||||
@msg unknown field `{key}` невідоме поле `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} пікселів (межа {MAX_IMAGE_SIDE} пікселів на сторону)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads файл більший за {MAX_INPUT_BYTES} байтів, які читає модуль імпорту
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` модуль імпорту оголошує від 1 до {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` `extensions` оголошує лише модуль експорту або імпорту
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8467,6 +8467,27 @@ breakText Glyphs Glyph
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` là hiệu ứng trực tiếp: hãy áp dụng bằng effect.apply {{"effect": "{_2}"}}
|
||||
@msg the importer returned no objects plug-in nhập không trả về đối tượng nào
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` plug-in nhập trả về `objects` và `warnings`, không phải `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` phải liệt kê chỉ mục đối tượng theo thứ tự tăng dần, mỗi chỉ mục nhỏ hơn {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` liệt kê `{shown}` hai lần
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` ghi một loại không xác định `{shown}`: hãy dùng type, image, layer hoặc artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` cần API plug-in cấp {OUTPUT_KINDS_API}: hãy đặt `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` phải là [width, height]: hai số nguyên từ 1 đến {MAX_IMAGE_SIDE}
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` phải chứa 4 × rộng × cao = {want} byte dạng base64
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` phải là [x, y, width, height]: các số hữu hạn trong khoảng ±{MAX_COORD}, chiều rộng và chiều cao lớn hơn 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` dài {len} byte (giới hạn {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` không được chứa ký tự điều khiển nào ngoài ngắt dòng và tab
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` phải dài 1-{MAX_NAME_CHARS} ký tự, không có ký tự điều khiển hay ký tự hướng văn bản
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` phải là sáu số hữu hạn trong khoảng ±{MAX_COORD} không làm dẹt đối tượng
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` phải có từ 1 đến {max} mục (hiện có {n})
|
||||
@msg a type fill must be a color or a gradient màu tô của văn bản phải là một màu hoặc một chuyển sắc
|
||||
@msg artboard name `{shown}` is used twice tên bảng vẽ `{shown}` được dùng hai lần
|
||||
@msg object {k} must be in exactly one layer đối tượng {k} phải nằm trong đúng một lớp
|
||||
@msg only an importer declares `outputKinds` chỉ plug-in nhập mới khai báo `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels các hình ảnh chứa hơn {MAX_PIXEL_BYTES} byte điểm ảnh
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list đầu ra chứa `{kind}`, mà `outputKinds` của plug-in nhập không liệt kê
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text văn bản chứa hơn {MAX_TEXT_TOTAL} byte
|
||||
@msg unknown field `{key}` trường không xác định `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} điểm ảnh (giới hạn {MAX_IMAGE_SIDE} điểm ảnh mỗi cạnh)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads tệp lớn hơn {MAX_INPUT_BYTES} byte mà plug-in nhập đọc
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` plug-in nhập khai báo từ 1 đến {MAX_EXTENSIONS} `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` chỉ plug-in xuất hoặc nhập mới khai báo `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8645,6 +8645,27 @@ breakText Glyphs 字形
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` 是实时效果:请用 effect.apply {{"effect": "{_2}"}} 应用
|
||||
@msg the importer returned no objects 导入增效工具未返回任何对象
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` 导入增效工具返回 `objects` 和 `warnings`,不是 `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` 必须按递增顺序列出对象索引,每个都小于 {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` 列出了两次 `{shown}`
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` 指定了未知类型 `{shown}`:请使用 type、image、layer 或 artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` 需要增效工具 API 级别 {OUTPUT_KINDS_API}:请指定 `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` 必须是 [width, height]:两个 1 到 {MAX_IMAGE_SIDE} 的整数
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` 必须以 base64 形式包含 4 × 宽 × 高 = {want} 字节
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` 必须是 [x, y, width, height]:±{MAX_COORD} 以内的有限数,宽和高大于 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` 有 {len} 字节 (上限 {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` 不能包含换行符和制表符以外的控制字符
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` 必须为 1-{MAX_NAME_CHARS} 个字符,且不含控制字符或文本方向字符
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` 必须是 ±{MAX_COORD} 以内、不会压扁对象的六个有限数
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` 必须包含 1 到 {max} 项 (现有 {n} 项)
|
||||
@msg a type fill must be a color or a gradient 文字的填色必须是颜色或渐变
|
||||
@msg artboard name `{shown}` is used twice 画板名称 `{shown}` 使用了两次
|
||||
@msg object {k} must be in exactly one layer 对象 {k} 必须恰好位于一个图层中
|
||||
@msg only an importer declares `outputKinds` 只有导入增效工具才能声明 `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels 图像的像素超过 {MAX_PIXEL_BYTES} 字节
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list 输出包含 `{kind}`,但导入增效工具的 `outputKinds` 没有列出它
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text 文字超过 {MAX_TEXT_TOTAL} 字节
|
||||
@msg unknown field `{key}` 未知字段 `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} 像素 (每边上限 {MAX_IMAGE_SIDE} 像素)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads 文件超过导入增效工具读取的 {MAX_INPUT_BYTES} 字节
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` 导入增效工具声明 1 到 {MAX_EXTENSIONS} 个 `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` 只有导出或导入增效工具才声明 `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8467,6 +8467,27 @@ breakText Glyphs 字符
|
||||
@msg `{_1}` is a live effect: apply it with effect.apply {{"effect": "{_2}"}} `{_1}` 是即時效果:請用 effect.apply {{"effect": "{_2}"}} 套用
|
||||
@msg the importer returned no objects 匯入增效模組未傳回任何物件
|
||||
@msg an importer returns `objects` and `warnings`, not `{key}` 匯入增效模組傳回 `objects` 和 `warnings`,不是 `{key}`
|
||||
@msg `objects` must list object indexes in increasing order, each below {count} `objects` 必須依遞增順序列出物件索引,每個都小於 {count}
|
||||
@msg `outputKinds` lists `{shown}` twice `outputKinds` 列出了兩次 `{shown}`
|
||||
@msg `outputKinds` names an unknown kind `{shown}`: use type, image, layer or artboard `outputKinds` 指定了不明的種類 `{shown}`:請使用 type、image、layer 或 artboard
|
||||
@msg `outputKinds` needs plug-in API level {OUTPUT_KINDS_API}: give `api` {OUTPUT_KINDS_API} `outputKinds` 需要增效模組 API 層級 {OUTPUT_KINDS_API}:請指定 `api` {OUTPUT_KINDS_API}
|
||||
@msg `pixelSize` must be [width, height]: two whole numbers from 1 to {MAX_IMAGE_SIDE} `pixelSize` 必須是 [width, height]:兩個 1 到 {MAX_IMAGE_SIDE} 的整數
|
||||
@msg `pixelsBase64` must hold 4 × width × height = {want} bytes as base64 `pixelsBase64` 必須以 base64 形式包含 4 × 寬 × 高 = {want} 位元組
|
||||
@msg `rect` must be [x, y, width, height]: finite numbers within ±{MAX_COORD}, width and height above 0 `rect` 必須是 [x, y, width, height]:±{MAX_COORD} 以內的有限數,寬和高大於 0
|
||||
@msg `text` is {len} bytes (limit {MAX_TYPE_TEXT}) `text` 有 {len} 位元組 (上限 {MAX_TYPE_TEXT})
|
||||
@msg `text` must not hold control characters other than line breaks and tabs `text` 不能包含換行和定位字元以外的控制字元
|
||||
@msg `{key}` must be 1-{MAX_NAME_CHARS} characters, without control or text direction characters `{key}` 必須為 1-{MAX_NAME_CHARS} 個字元,且不含控制字元或文字方向字元
|
||||
@msg `{key}` must be six finite numbers within ±{MAX_COORD} that don't flatten the object `{key}` 必須是 ±{MAX_COORD} 以內、不會壓扁物件的六個有限數
|
||||
@msg `{key}` must hold 1 to {max} entries (it holds {n}) `{key}` 必須包含 1 到 {max} 項 (目前有 {n} 項)
|
||||
@msg a type fill must be a color or a gradient 文字的填色必須是顏色或漸層
|
||||
@msg artboard name `{shown}` is used twice 工作區域名稱 `{shown}` 使用了兩次
|
||||
@msg object {k} must be in exactly one layer 物件 {k} 必須剛好位於一個圖層中
|
||||
@msg only an importer declares `outputKinds` 只有匯入增效模組才能宣告 `outputKinds`
|
||||
@msg the images hold more than {MAX_PIXEL_BYTES} bytes of pixels 影像的像素超過 {MAX_PIXEL_BYTES} 位元組
|
||||
@msg the output holds `{kind}`, which the importer's `outputKinds` doesn't list 輸出包含 `{kind}`,但匯入增效模組的 `outputKinds` 沒有列出
|
||||
@msg the type holds more than {MAX_TEXT_TOTAL} bytes of text 文字超過 {MAX_TEXT_TOTAL} 位元組
|
||||
@msg unknown field `{key}` 不明的欄位 `{key}`
|
||||
@msg {w} × {h} pixels (limit {MAX_IMAGE_SIDE} pixels a side) {w} × {h} 像素 (每邊上限 {MAX_IMAGE_SIDE} 像素)
|
||||
@msg the file is larger than the {MAX_INPUT_BYTES} bytes an importer reads 檔案超過匯入增效模組讀取的 {MAX_INPUT_BYTES} 位元組
|
||||
@msg an importer declares 1 to {MAX_EXTENSIONS} `extensions` 匯入增效模組宣告 1 到 {MAX_EXTENSIONS} 個 `extensions`
|
||||
@msg only an exporter or an importer declares `extensions` 只有匯出或匯入增效模組才宣告 `extensions`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1007,7 +1007,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.paramDialog",
|
||||
"Command Dialog",
|
||||
"",
|
||||
"{command, label?, params} open a parameter dialog for any command. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
"{command, label?, params} open a parameter dialog for any command. For commands other than edit.findReplace, params.__doc may be an unsigned document uid: the dialog previews and confirms only while that document is active, and OK after a document switch closes it without running the command. An invalid __doc is an error; omitting it keeps the existing behavior. For edit.findReplace it opens Find and Replace (dialog `findReplace`), which stays open: fields find, replace, matchCase, wholeWord, backwards, hiddenLayers, lockedLayers, and action, which ui.dialog.confirm runs: find (the next match, edit.findNext, shown in the dialog with its place among the matches), replace (the match found, edit.replaceMatch), replaceFind (both), replaceAll (edit.findReplace) or done (close). After each one action is find again. Replace and Replace & Find change a match that find reached with the find text and options as they are now, and find one otherwise. The dialog opens on the last search, with the fields params gives in its place (a null field gives none; a field of the wrong type is an error, and ui.dialog.confirm then runs no action), and Edit › Find Next goes on from it in the same document while the dialog is closed",
|
||||
),
|
||||
(
|
||||
"ui.recolorDialog",
|
||||
@@ -2071,7 +2071,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.runScript",
|
||||
"Other Script…",
|
||||
"Cmd+F12",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
),
|
||||
(
|
||||
crate::scripts_menu::COMMAND,
|
||||
|
||||
@@ -926,12 +926,14 @@ fn tab_strip_buttons_are_named_by_their_labels() {
|
||||
assert!(ids.is_empty(), "buttons named by a command id: {ids:?}");
|
||||
}
|
||||
|
||||
/// A panel the Window menu floats opens tall enough for its content: every control of Asset Export,
|
||||
/// and every Image Trace control down to the top of its Advanced section, lies between the body's
|
||||
/// top and bottom, none scrolled or clipped away.
|
||||
/// A panel the Window menu floats opens tall enough for its content: every control of Asset Export
|
||||
/// and Fold Lines, and every Image Trace control down to the top of its Advanced section, lies
|
||||
/// between the body's top and bottom, none scrolled or clipped away.
|
||||
#[test]
|
||||
fn window_menu_floats_open_tall_enough_for_their_content() {
|
||||
for (panel, title, until) in [("assetExport", "Asset Export", None), ("imageTrace", "Image Trace", Some("Advanced"))] {
|
||||
for (panel, title, until) in
|
||||
[("assetExport", "Asset Export", None), ("foldLines", "Fold Lines", None), ("imageTrace", "Image Trace", Some("Advanced"))]
|
||||
{
|
||||
let mut h = Harness::new();
|
||||
h.app.run("window.panel", json!({"panel": panel})).unwrap();
|
||||
assert!(floating_window(&h.layout(), panel).is_some(), "{panel} floats");
|
||||
|
||||
@@ -1255,6 +1255,8 @@ mod tests_maskview;
|
||||
#[cfg(test)]
|
||||
mod tests_panel_rows;
|
||||
#[cfg(test)]
|
||||
mod tests_panel_spacing;
|
||||
#[cfg(test)]
|
||||
mod tests_script_console;
|
||||
#[cfg(test)]
|
||||
mod tests_stroke;
|
||||
|
||||
@@ -30,10 +30,10 @@ use craft::ui::contract::{
|
||||
Bind, CollectionEvent, CollectionResponse, ColumnSpec, FieldLabelRole, ItemCx, ListDrag, MemoProps, PopupKind, Props as _, ReorderMove,
|
||||
ReorderRule, Show as _, ShowCollection as _, ShowContainer as _, SideLabel, ToggleColumn, Trigger, clicked,
|
||||
};
|
||||
use craft::ui::display::{Picture, Shade, Text};
|
||||
use craft::ui::display::{Elide, Picture, Shade, Text};
|
||||
use craft::ui::form::Field;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::{List, ListRow, RowDragSpot, RowEvent, RowInk, ThumbAspect, ThumbSize, ThumbTarget, ToggleCell};
|
||||
use craft::ui::list::{List, ListRow, RowDragSpot, RowEvent, RowInk, ThumbAspect, ThumbSize, ThumbTarget, ToggleCell, TreeLeaves};
|
||||
use craft::ui::menu::{Menu, MenuItem, PanelRow};
|
||||
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamRows};
|
||||
use craft::ui::patterns::presets::{
|
||||
@@ -403,6 +403,9 @@ const SWATCH_COLUMNS: u16 = 12;
|
||||
const SWATCH_ROWS: u16 = 12;
|
||||
/// The width and height of a stroke row's profile picture, as its aspect.
|
||||
const PROFILE_ASPECT: (u16, u16) = (14, 5);
|
||||
/// The most characters of a stroke's notes that set the notes' column width on every fill and stroke row; longer notes
|
||||
/// are cut at the end and show whole in a tooltip.
|
||||
const NOTES_SAMPLE_CHARS: usize = 16;
|
||||
|
||||
/// The eye column.
|
||||
const EYE: ColumnKey = ColumnKey::new("eye");
|
||||
@@ -543,6 +546,9 @@ fn show_list(
|
||||
let mut list = List::new(tl!("Appearance"))
|
||||
.id(list_id)
|
||||
.tree(true)
|
||||
// The top-level rows without a disclosure (Opacity, an object's effects) keep its column, so their labels
|
||||
// start where the Stroke and Fill labels do.
|
||||
.tree_leaves(TreeLeaves::Aligned)
|
||||
.columns(columns)
|
||||
.deletable(true)
|
||||
.selection(Bind::bound(selection))
|
||||
@@ -827,21 +833,36 @@ fn item_row<'r>(cx: &'r RowCx<'_>, key: RowKey, i: usize) -> ListRow<'r> {
|
||||
link_output(cx.pass, key),
|
||||
);
|
||||
// The first trailing part added is the outermost: the profile closes the row, the swatch sits
|
||||
// nearest the label.
|
||||
if let AppearanceItem::Stroke(st) = it {
|
||||
if let Some(points) = st.profile.as_ref().filter(|p| p.preset_id() != Some("uniform")).map(|p| p.points.clone()) {
|
||||
let aspect = ThumbAspect::new(PROFILE_ASPECT.0, PROFILE_ASPECT.1);
|
||||
let profile = Picture::painter(Label::Empty, aspect, move |painter, rect| stroke::paint_profile(painter, rect, Some(points.as_slice())));
|
||||
// nearest the label. Every fill and stroke row of the stack takes the same room for the profile, the notes and the
|
||||
// weight, kept empty where the row has none, so all their swatches stand in one column.
|
||||
let (any_profile, widest_notes) = trailing_room(stack.map_or(&[], |ap| ap.items.as_slice()));
|
||||
let stroke_layer = match it {
|
||||
AppearanceItem::Stroke(st) => Some(st),
|
||||
_ => None,
|
||||
};
|
||||
match stroke_layer.and_then(shown_profile) {
|
||||
Some(points) => {
|
||||
let profile =
|
||||
Picture::painter(Label::Empty, profile_aspect(), move |painter, rect| stroke::paint_profile(painter, rect, Some(points.as_slice())));
|
||||
row = row.trailing_field(profile, |_| {});
|
||||
}
|
||||
if let Some(notes) = stroke_notes(st) {
|
||||
row = row.trailing_field(Text::new(notes).shade(Shade::Muted), |_| {});
|
||||
}
|
||||
None if any_profile => row = row.trailing_space(Picture::painter(Label::Empty, profile_aspect(), |_, _| {})),
|
||||
None => {}
|
||||
}
|
||||
if let Some(widest) = widest_notes {
|
||||
row = match stroke_layer.and_then(stroke_notes) {
|
||||
Some(notes) => row.trailing_field(Text::new(notes).shade(Shade::Muted).sample(widest).elide(Elide::End), |_| {}),
|
||||
None => row.trailing_space(Text::new(Label::Empty).shade(Shade::Muted).sample(widest)),
|
||||
};
|
||||
}
|
||||
if let Some(st) = stroke_layer {
|
||||
let target = if new_art { WeightTarget::Shown } else { WeightTarget::Item(i) };
|
||||
let pass = cx.pass;
|
||||
row = row.trailing_field(stroke::weight_number(cx.app, Some(st.width)), move |out| {
|
||||
pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out)))
|
||||
});
|
||||
} else {
|
||||
row = row.trailing_space(stroke::weight_number(cx.app, None));
|
||||
}
|
||||
let painted = if new_art { Painted::NewArt { fill } } else { Painted::Item(i) };
|
||||
let pass = cx.pass;
|
||||
@@ -874,6 +895,31 @@ fn stroke_notes(st: &vectorcraft_doc::StrokeLayer) -> Option<String> {
|
||||
(!notes.is_empty()).then(|| notes.join(", "))
|
||||
}
|
||||
|
||||
/// The points of a stroke's width profile, when it has one other than Uniform, which its row draws.
|
||||
fn shown_profile(st: &vectorcraft_doc::StrokeLayer) -> Option<Vec<(f64, f64, f64)>> {
|
||||
st.profile.as_ref().filter(|p| p.preset_id() != Some("uniform")).map(|p| p.points.clone())
|
||||
}
|
||||
|
||||
/// The shape of a stroke row's profile picture.
|
||||
fn profile_aspect() -> ThumbAspect {
|
||||
ThumbAspect::new(PROFILE_ASPECT.0, PROFILE_ASPECT.1)
|
||||
}
|
||||
|
||||
/// The trailing room every fill and stroke row of `items` keeps before its weight: whether a stroke there shows a
|
||||
/// profile, and the longest of the strokes' notes, up to [`NOTES_SAMPLE_CHARS`] characters, which sets the notes' width
|
||||
/// on every row.
|
||||
fn trailing_room(items: &[AppearanceItem]) -> (bool, Option<String>) {
|
||||
let strokes = || {
|
||||
items.iter().filter_map(|it| match it {
|
||||
AppearanceItem::Stroke(st) => Some(st),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let any_profile = strokes().any(|st| shown_profile(st).is_some());
|
||||
let widest = strokes().filter_map(stroke_notes).max_by_key(|notes| notes.chars().count());
|
||||
(any_profile, widest.map(|notes| notes.chars().take(NOTES_SAMPLE_CHARS).collect()))
|
||||
}
|
||||
|
||||
/// An Opacity row: of the object or, under it, of a fill/stroke. "Opacity:" opens the
|
||||
/// Transparency panel on it. A mixed selection whose objects' opacity or blend mode differ
|
||||
/// reads "Mixed".
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Gap, Show as _, ShowContainer as _};
|
||||
use craft::ui::display::{Divider, Shade, Text};
|
||||
use craft::ui::layout::RowAlign;
|
||||
use craft::ui::layout_components::{Row, Stack};
|
||||
@@ -35,11 +35,20 @@ pub struct DocInfoView {
|
||||
/// the second or third click of a double or triple click.
|
||||
pub(crate) fn row(ui: &mut Ui, label: &str, value: &str) -> bool {
|
||||
let mut clicked = false;
|
||||
Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(true).show(ui, |ui, _| {
|
||||
// A row whose label and value fit on one line keeps the value at its end. A wrapping row places its children as
|
||||
// `Start` does, so the row wraps only when the two do not fit, as in a narrow panel or a longer translation.
|
||||
let width = |text: &str| {
|
||||
let font = egui::TextStyle::Body.resolve(ui.style());
|
||||
ui.painter().layout_no_wrap(text.to_string(), font, egui::Color32::WHITE).size().x
|
||||
};
|
||||
let fits = width(label) + width(value) + 2.0 * ui.spacing().item_spacing.x <= ui.available_width();
|
||||
Row::new().fill_width().align(RowAlign::SpaceBetween).wrap(!fits).show(ui, |ui, _| {
|
||||
Text::new(label.to_string()).shade(Shade::Muted).show(ui);
|
||||
// The value can be selected and copied, and a click copies all of it (#8432). A drag selects
|
||||
// and a Shift-click extends the selection, so neither copies.
|
||||
clicked = copy_value(ui, label, value, false);
|
||||
// and a Shift-click extends the selection, so neither copies. A value wider than the panel
|
||||
// wraps inside it.
|
||||
let shown = SelectableText::new(label.to_string(), value).multiline().show(ui);
|
||||
clicked = copy_shown(ui, &shown, value);
|
||||
});
|
||||
clicked
|
||||
}
|
||||
@@ -154,7 +163,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
};
|
||||
let DocInfoView { selection_only: sel_only, category } = app.ui.doc_info.clone();
|
||||
let mut copy = None;
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
// The sections fill the panel's width, so each row's value stands at its end, and a section gap sets the
|
||||
// dividers apart from the sections around them.
|
||||
Stack::new().fill_width().gap(Gap::Section).show(ui, |ui, _| {
|
||||
if sel_only && no_artwork_selected(app) {
|
||||
Text::new(tl!("(No artwork selected)").to_string()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
@@ -164,38 +175,43 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
if n > 0 {
|
||||
Divider::horizontal().show(ui);
|
||||
}
|
||||
let title = s["title"].as_str().unwrap_or_default();
|
||||
let rows = s["rows"].as_array().map_or(&[][..], Vec::as_slice);
|
||||
// Lists show how many they hold; the selection scope shows on the first.
|
||||
let title = match s["id"].as_str() {
|
||||
Some("document" | "objects") => tl!(title).to_string(),
|
||||
_ => format!("{} ({})", tl!(title), rows.len()),
|
||||
};
|
||||
let title =
|
||||
if sel_only && n == 0 && category.is_empty() { crate::i18n::fmt(tl!("{title} (selection)"), &[("title", &title)]) } else { title };
|
||||
Text::new(title).role(TypeRole::Heading).show(ui);
|
||||
if rows.is_empty() {
|
||||
Text::new(tl!("None").to_string()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
let id = s["id"].as_str().unwrap_or_default();
|
||||
let named = named_rows(id, rows);
|
||||
for (k, r) in rows.iter().enumerate() {
|
||||
let (label, value) = (r[0].as_str().unwrap_or_default(), r[1].as_str().unwrap_or_default());
|
||||
if value.is_empty() {
|
||||
if named.contains(&k) && !label.is_empty() {
|
||||
if copy_value(ui, label, label, false) {
|
||||
copy = Some(label.to_string());
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
let title = s["title"].as_str().unwrap_or_default();
|
||||
let rows = s["rows"].as_array().map_or(&[][..], Vec::as_slice);
|
||||
// Lists show how many they hold; the selection scope shows on the first.
|
||||
let title = match s["id"].as_str() {
|
||||
Some("document" | "objects") => tl!(title).to_string(),
|
||||
_ => format!("{} ({})", tl!(title), rows.len()),
|
||||
};
|
||||
let title = if sel_only && n == 0 && category.is_empty() {
|
||||
crate::i18n::fmt(tl!("{title} (selection)"), &[("title", &title)])
|
||||
} else {
|
||||
title
|
||||
};
|
||||
Text::new(title).role(TypeRole::Heading).show(ui);
|
||||
if rows.is_empty() {
|
||||
Text::new(tl!("None").to_string()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
let id = s["id"].as_str().unwrap_or_default();
|
||||
let named = named_rows(id, rows);
|
||||
for (k, r) in rows.iter().enumerate() {
|
||||
let (label, value) = (r[0].as_str().unwrap_or_default(), r[1].as_str().unwrap_or_default());
|
||||
if value.is_empty() {
|
||||
if named.contains(&k) && !label.is_empty() {
|
||||
if copy_value(ui, label, label, false) {
|
||||
copy = Some(label.to_string());
|
||||
}
|
||||
} else {
|
||||
Text::new(super::label_or_name(label, !named.contains(&k)).to_string()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
} else {
|
||||
Text::new(super::label_or_name(label, !named.contains(&k)).to_string()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
} else {
|
||||
let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string());
|
||||
if row(ui, super::label_or_name(label, !named.contains(&k)), &shown) {
|
||||
copy = Some(shown);
|
||||
let shown = shown_value(&i, id, k, (label, value), named.contains(&k)).unwrap_or_else(|| value.to_string());
|
||||
if row(ui, super::label_or_name(label, !named.contains(&k)), &shown) {
|
||||
copy = Some(shown);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some(text) = copy {
|
||||
|
||||
@@ -1574,9 +1574,10 @@ mod tests {
|
||||
|
||||
let mut p = PanelHarness::new(app, appearance_and_styles);
|
||||
let hold = |p: &mut PanelHarness| {
|
||||
// The thumbnail is the first part of the object row, at its start.
|
||||
// The thumbnail is the first part of the object row, after the empty disclosure column that lines the row's
|
||||
// label up with the Stroke and Fill labels.
|
||||
let row = p.rect("Rectangle: Drop Target");
|
||||
let (from, to) = (row.left_center() + egui::vec2(14.0, 0.0), p.rect("Drop Target").center());
|
||||
let (from, to) = (row.left_center() + egui::vec2(34.0, 0.0), p.rect("Drop Target").center());
|
||||
p.drag_hold_between(from, to);
|
||||
let carried = drag::active::<PanelDrag>(p.ctx());
|
||||
assert!(
|
||||
|
||||
@@ -10,7 +10,7 @@ use craft::color_ui::ui::{ColorPopover, PickedColor};
|
||||
use craft::theme::Srgba;
|
||||
use craft::ui::buttons::ToggleButton;
|
||||
use craft::ui::choice::{Checkbox, Segmented};
|
||||
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, Entry, FieldLayout, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::form::{Field, SliderField, SliderFieldLayout};
|
||||
use craft::ui::layout_components::Row;
|
||||
use craft::ui::pickers::Select;
|
||||
@@ -265,7 +265,14 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let mut hit = None;
|
||||
for (key, on, other, label) in [("fills", fills, strokes, tl!("Fills")), ("strokes", strokes, fills, tl!("Strokes"))] {
|
||||
if check(ui, label, on, !on || other) {
|
||||
// Inside the Create field a check box's own label is not drawn, so each box takes a field of
|
||||
// its own with the label after it.
|
||||
let enabled = !on || other;
|
||||
let mut value = on;
|
||||
Field::new(label).layout(FieldLayout::After).enabled(enabled).show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::bound(&mut value)).enabled(enabled).show(ui);
|
||||
});
|
||||
if value != on {
|
||||
hit = Some(key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
use craft::behavior::ColumnWidth;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Gap, Show as _, ShowContainer as _};
|
||||
use craft::ui::display::{Divider, Picture};
|
||||
use craft::ui::layout_components::{Grid, Row, Stack};
|
||||
use craft::ui::list::ThumbAspect;
|
||||
@@ -249,34 +249,43 @@ const HALVES: &[ColumnWidth] = &[ColumnWidth::fill(1.0); 2];
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let l = lines(app, ui.ctx());
|
||||
let mut copy = None;
|
||||
// Two equal halves of the panel, as the reference app's columns were.
|
||||
let _ = Grid::new(HALVES).show(ui, |ui, _| {
|
||||
for column in [&l.left, &l.right] {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for s in column {
|
||||
if mono(ui, s) {
|
||||
copy = Some(s.clone());
|
||||
// The numbers, the paints and the type are groups a section gap sets apart from the dividers between them.
|
||||
Stack::new().fill_width().gap(Gap::Section).show(ui, |ui, _| {
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
// Two equal halves of the panel, as the reference app's columns were.
|
||||
let _ = Grid::new(HALVES).show(ui, |ui, _| {
|
||||
for column in [&l.left, &l.right] {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for s in column {
|
||||
if mono(ui, s) {
|
||||
copy = Some(s.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
for s in l.zoom.iter().chain(&l.brush) {
|
||||
if mono(ui, s) {
|
||||
copy = Some(s.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
Divider::horizontal().show(ui);
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
copy = paint_block(ui, &l.fill).or(copy.take());
|
||||
copy = paint_block(ui, &l.stroke).or(copy.take());
|
||||
});
|
||||
if let Some((font, size)) = &l.type_block {
|
||||
Divider::horizontal().show(ui);
|
||||
Stack::new().fill_width().show(ui, |ui, _| {
|
||||
for value in [font, size] {
|
||||
if mono(ui, value) {
|
||||
copy = Some(value.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
for s in l.zoom.iter().chain(&l.brush) {
|
||||
if mono(ui, s) {
|
||||
copy = Some(s.clone());
|
||||
}
|
||||
}
|
||||
Divider::horizontal().show(ui);
|
||||
copy = paint_block(ui, &l.fill).or(copy);
|
||||
copy = paint_block(ui, &l.stroke).or(copy);
|
||||
if let Some((font, size)) = &l.type_block {
|
||||
Divider::horizontal().show(ui);
|
||||
for value in [font, size] {
|
||||
if mono(ui, value) {
|
||||
copy = Some(value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(text) = copy {
|
||||
app.clipboard_out = Some(text);
|
||||
app.status("Copied the value");
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::{Axis, EditEvent, IconId, keyed};
|
||||
use craft::behavior::{Axis, EditEvent, EditPolicy, IconId, keyed};
|
||||
use craft::host::PickRequest;
|
||||
use craft::keymap::CommandRef;
|
||||
use craft::theme::variant::Tone;
|
||||
@@ -843,7 +843,7 @@ fn header(ui: &mut Ui, libraries: &Libraries, current: &str, list_view: &mut boo
|
||||
];
|
||||
let mut picked = current.to_string();
|
||||
Row::new().fill_width().show(ui, |ui, _| {
|
||||
Select::new(tl!("Library"), Bind::bound(&mut picked), &names).sizing(Sizing::FillWidth).show(ui);
|
||||
Select::new(tl!("Library"), Bind::bound(&mut picked).policy(EditPolicy::OnCommit), &names).sizing(Sizing::FillWidth).show(ui);
|
||||
Segmented::new(tl!("View"), Bind::bound(&mut *list_view), &views).show(ui);
|
||||
});
|
||||
if picked != current {
|
||||
|
||||
@@ -566,6 +566,33 @@ fn menu_rows_and_dialogs_run_library_commands() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_highlighted_library_becomes_current_only_once_it_is_chosen() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let mut app = app();
|
||||
for name in ["Brand", "House"] {
|
||||
app.run("library.create", json!({"name": name})).unwrap();
|
||||
}
|
||||
let ids: Vec<String> = app.session.libraries.all().iter().map(|(id, _)| id.clone()).collect();
|
||||
app.run("library.setCurrent", json!({"library": ids[0]})).unwrap();
|
||||
let mut panel = Harness::new(app, show);
|
||||
let current = |panel: &Harness| panel.app().session.libraries.current().map(|id| id.to_string());
|
||||
assert_eq!(current(&panel).as_deref(), Some(ids[0].as_str()));
|
||||
panel.click_role("Library", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(current(&panel).as_deref(), Some(ids[0].as_str()), "a highlighted library does not become current");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(current(&panel).as_deref(), Some(ids[0].as_str()), "Escape leaves the current library as it was");
|
||||
panel.click_role("Library", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Enter, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(current(&panel).as_deref(), Some(ids[1].as_str()), "Enter makes the chosen library current");
|
||||
}
|
||||
|
||||
/// Export Library… writes the library's file under its name and Import Library… adds it back as a
|
||||
/// new library.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -786,8 +786,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
});
|
||||
})
|
||||
.show(ui, |ui, _| {
|
||||
let empty = if o.show == "all" { tl!("No images") } else { tl!("Nothing matches the Show filter.") };
|
||||
let mut list = List::<u64>::new(tl!("Links")).selection(Bind::bound(&mut selection)).empty(empty).row_menu();
|
||||
// With no rows the body says how to bring an image in, as the other panels' empty states do;
|
||||
// under a Show filter the document can still hold images that the filter hides.
|
||||
if row_ids.is_empty() {
|
||||
let (title, detail) = if o.show == "all" {
|
||||
(tl!("No images"), tl!("File › Place… brings in an image, linked or embedded."))
|
||||
} else {
|
||||
(tl!("No matching images"), tl!("Nothing matches the Show filter."))
|
||||
};
|
||||
super::empty_state(ui, "link", title, detail);
|
||||
return;
|
||||
}
|
||||
let mut list = List::<u64>::new(tl!("Links")).selection(Bind::bound(&mut selection)).row_menu();
|
||||
if let Some(id) = reveal {
|
||||
list = list.reveal(id);
|
||||
}
|
||||
|
||||
@@ -578,9 +578,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
// Art dropped anywhere on the list becomes a symbol; dropped on a symbol, the browser's
|
||||
// own target takes it.
|
||||
DropAction::<PanelDrag>::new(move |drag| art_of(drag, uid, reverts).is_some()).show(ui, |ui, _| {
|
||||
// With no symbols the body says how to make one, as the other panels' empty states do.
|
||||
if doc.symbols.is_empty() {
|
||||
super::empty_state(ui, "spray-can", tl!("No symbols in this document"), tl!("Select art and click New Symbol to make one."));
|
||||
return None;
|
||||
}
|
||||
let mut state = PresetState::new();
|
||||
state.zoom = zoom;
|
||||
PresetBrowser::new(tl!("Symbols"), Bind::bound(&mut state), &source)
|
||||
let shown = PresetBrowser::new(tl!("Symbols"), Bind::bound(&mut state), &source)
|
||||
.browser_id(browser_id)
|
||||
.selection(Bind::given(selection.clone()))
|
||||
.select(select)
|
||||
@@ -591,13 +596,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
.takes_drop(PresetDrop::new::<PanelDrag>(DropPlace::Onto, move |drag: &PanelDrag, _: &DropAt<SymbolKey>| {
|
||||
art_of(drag, uid, reverts).is_some()
|
||||
}))
|
||||
.empty(tl!("No symbols in this document"))
|
||||
.show(ui)
|
||||
.show(ui);
|
||||
Some(shown)
|
||||
})
|
||||
});
|
||||
let taken = shown.settle(|_, list| {
|
||||
let dropped = list.output.dropped.take().map(|drag| (drag, list.output.mods));
|
||||
(dropped, list.inner.take().map(|out| out.events).unwrap_or_default())
|
||||
(dropped, list.inner.take().flatten().map(|out| out.events).unwrap_or_default())
|
||||
});
|
||||
let footer = footer.into_inner();
|
||||
if let Some(opener) = footer.as_ref().and_then(|out| out.responses.get(AT_LIBRARY)) {
|
||||
|
||||
@@ -203,6 +203,20 @@ fn opening_the_panel_on_the_selected_image_leaves_another_document_alone() {
|
||||
assert_eq!(h.state().ui.links.show, None, "the request is dropped");
|
||||
}
|
||||
|
||||
/// A Show filter that hides every image titles the empty panel "No matching images", since the
|
||||
/// document still holds images; "No images" stays for a document with none.
|
||||
#[test]
|
||||
fn a_filter_that_hides_every_image_says_no_matching_images() {
|
||||
let dir = Folder::new("empty-filter-title");
|
||||
let (app, _, _) = app(&dir);
|
||||
let mut h = rig(app);
|
||||
command(&mut h, "ui.links.show", json!({"show": "missing"}));
|
||||
assert!(shown(&h, "No matching images"), "Show Missing with nothing missing");
|
||||
assert!(!shown(&h, "No images"), "the document holds two images");
|
||||
command(&mut h, "ui.links.show", json!({"show": "all"}));
|
||||
assert!(shown(&h, "linked.png") && !shown(&h, "No matching images"), "Show All lists the rows");
|
||||
}
|
||||
|
||||
/// A frame that fetches nothing keeps the stored rows and Link Info as they are, without a copy; the
|
||||
/// two-second recheck, another first selected image and an edit each store a new cache.
|
||||
#[test]
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Headless frames of panel rows that the framework lays out: controls side by side stay inside the panel's width.
|
||||
|
||||
use super::tests_appearance::app_with_rect;
|
||||
use serde_json::json;
|
||||
|
||||
use super::tests_appearance::{app_with_rect, run};
|
||||
use super::*;
|
||||
use crate::panel_docking::PANEL_MIN_WIDTH;
|
||||
use crate::tests::panel_harness::{Panel, Place, ROOM, floated};
|
||||
@@ -96,6 +98,50 @@ fn the_color_wheel_box_and_its_strip_stay_inside_the_panel() {
|
||||
assert!(field.right() <= ROOM.x && strip.right() <= ROOM.x, "the box {field:?} or its strip {strip:?} runs past the panel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_symbols_panel_with_no_symbols_says_how_to_make_one() {
|
||||
let panel = Panel::new(app_with_rect(), symbols::show);
|
||||
assert!(panel.shows("No symbols in this document"));
|
||||
assert!(panel.shows("Select art and click New Symbol to make one."), "the empty panel has no hint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_appearance_swatches_and_labels_line_up() {
|
||||
let panel = Panel::new(app_with_rect(), appearance::show);
|
||||
let (stroke, fill) = (panel.rect("Stroke swatch"), panel.rect("Fill swatch"));
|
||||
assert!((stroke.left() - fill.left()).abs() < 1.0, "the stroke swatch at {stroke:?} and the fill swatch at {fill:?} are in different columns");
|
||||
let opacity = panel.rect("Opacity:");
|
||||
for name in ["Stroke:", "Fill:"] {
|
||||
let at = panel.rect(name);
|
||||
assert!((at.left() - opacity.left()).abs() < 1.0, "Opacity: at {opacity:?} does not start where {name} at {at:?} does");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_swatch_lines_up_with_a_dashed_stroke_that_has_a_profile() {
|
||||
let mut panel = Panel::new(app_with_rect(), appearance::show);
|
||||
run(&mut panel.app(), "stroke.set", json!({"dash": [4, 2], "profile": "lens"}));
|
||||
panel.frame();
|
||||
assert!(panel.shows("Dashed"), "the stroke row shows no notes");
|
||||
let (stroke, fill) = (panel.rect("Stroke swatch"), panel.rect("Fill swatch"));
|
||||
assert!((stroke.left() - fill.left()).abs() < 1.0, "the stroke swatch at {stroke:?} and the fill swatch at {fill:?} are in different columns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_stroke_notes_stay_inside_a_narrow_appearance_panel() {
|
||||
let mut panel = Panel::new(app_with_rect(), appearance::show);
|
||||
let name = "A calligraphic brush with a very long name for the notes";
|
||||
run(&mut panel.app(), "brush.new", json!({"type": "calligraphic", "name": name}));
|
||||
run(&mut panel.app(), "brush.apply", json!({"name": name}));
|
||||
run(&mut panel.app(), "stroke.set", json!({"dash": [4, 2]}));
|
||||
panel.room(egui::vec2(PANEL_MIN_WIDTH, ROOM.y)).frame();
|
||||
let (stroke, fill) = (panel.rect("Stroke swatch"), panel.rect("Fill swatch"));
|
||||
assert!((stroke.left() - fill.left()).abs() < 1.0, "the stroke swatch at {stroke:?} and the fill swatch at {fill:?} are in different columns");
|
||||
for at in [stroke, fill] {
|
||||
assert!(at.right() <= PANEL_MIN_WIDTH, "the swatch at {at:?} runs past the {PANEL_MIN_WIDTH} pt panel");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_to_shares_the_distribute_spacing_line_inside_the_align_panel() {
|
||||
let panel = Panel::new(app_with_rect(), align::show);
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Headless frames of the Document Info, Info, Image Trace and Links panels: values line up, groups stand apart from
|
||||
//! their dividers, every check box shows its label, and an empty Links panel says how to bring an image in.
|
||||
|
||||
use egui::Rect;
|
||||
use serde_json::json;
|
||||
|
||||
use super::tests_appearance::{app_with_rect, run};
|
||||
use super::*;
|
||||
use crate::tests::panel_harness::{Panel, ROOM};
|
||||
|
||||
/// The first run the latest frame painted that starts with `prefix`.
|
||||
fn run_starting(panel: &Panel, prefix: &str) -> Rect {
|
||||
let texts = panel.texts();
|
||||
texts.iter().find(|(t, _)| t.starts_with(prefix)).map(|(_, r)| *r).unwrap_or_else(|| panic!("no run starting {prefix:?} in {texts:?}"))
|
||||
}
|
||||
|
||||
/// The single run of `text` the latest frame painted.
|
||||
fn one(panel: &Panel, text: &str) -> Rect {
|
||||
let rects = panel.painted(text);
|
||||
assert_eq!(rects.len(), 1, "{text:?} painted {} times in {:?}", rects.len(), panel.texts());
|
||||
rects[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_info_values_end_at_one_edge() {
|
||||
let mut panel = Panel::new(app_with_rect(), doc_info::show);
|
||||
panel.frame();
|
||||
let ends: Vec<f32> = ["Untitled-1", "RGB", "Points"].iter().map(|v| one(&panel, v).right()).collect();
|
||||
for end in &ends {
|
||||
assert!((end - ends[0]).abs() < 1.0, "the values end at {ends:?}, not at one edge");
|
||||
}
|
||||
let (label, value) = (one(&panel, "Color Mode"), one(&panel, "RGB"));
|
||||
assert!(value.left() > label.right() + label.width(), "the value {value:?} sits against its label {label:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_document_info_value_wraps_inside_a_narrow_panel() {
|
||||
let name = "A document name long enough to run past a narrow panel";
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
|
||||
run(&mut app, "file.new", json!({"width": 200, "height": 200, "name": name}));
|
||||
let mut panel = Panel::new(app, doc_info::show);
|
||||
let width = 160.0;
|
||||
panel.room(egui::vec2(width, ROOM.y));
|
||||
panel.frame();
|
||||
panel.frame();
|
||||
let texts = panel.texts();
|
||||
let runs: Vec<Rect> = texts.iter().filter(|(t, _)| t.starts_with("A document")).map(|(_, r)| *r).collect();
|
||||
assert!(!runs.is_empty(), "no run of the name in {texts:?}");
|
||||
for r in &runs {
|
||||
assert!(r.right() <= width + 0.5, "the name ends at {}, past the panel's {width}: {texts:?}", r.right());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn info_paints_stand_a_section_apart_from_the_numbers() {
|
||||
let mut app = app_with_rect();
|
||||
run(&mut app, "shape.rectangle", json!({"x": 150, "y": 60, "width": 80, "height": 50}));
|
||||
run(&mut app, "select.all", json!({}));
|
||||
let mut panel = Panel::new(app, info::show);
|
||||
panel.frame();
|
||||
let numbers = run_starting(&panel, "D:");
|
||||
let paint = run_starting(&panel, "R:");
|
||||
let gap = paint.top() - numbers.bottom();
|
||||
assert!(gap >= numbers.height(), "the paints start {gap} below the numbers, closer than a line");
|
||||
// The two columns split the panel in halves: the right column starts at the panel's middle.
|
||||
let (x, w) = (run_starting(&panel, "X:"), run_starting(&panel, "W:"));
|
||||
let half = (ROOM.x - x.left()) / 2.0;
|
||||
assert!(w.left() - x.left() >= half - 1.0, "W: starts {} in, before the half at {half}", w.left() - x.left());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_create_shows_fills_and_strokes() {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
|
||||
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
|
||||
app.ui.image_trace_advanced = true;
|
||||
let mut panel = Panel::new(app, image_trace::show);
|
||||
panel.frame();
|
||||
let create = one(&panel, "Create:");
|
||||
for label in ["Fills", "Strokes"] {
|
||||
let at = one(&panel, label);
|
||||
assert!(at.left() > create.right() && (at.center().y - create.center().y).abs() < create.height(), "{label} at {at:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_links_panel_says_how_to_bring_an_image_in() {
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()));
|
||||
run(&mut app, "file.new", json!({"width": 200, "height": 200}));
|
||||
let mut panel = Panel::new(app, links::show);
|
||||
panel.frame();
|
||||
one(&panel, "No images");
|
||||
one(&panel, "File › Place… brings in an image, linked or embedded.");
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::behavior::EditPolicy;
|
||||
use craft::behavior::IconId;
|
||||
use craft::behavior::Mixed;
|
||||
use craft::behavior::item_source::keyed;
|
||||
@@ -245,7 +246,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let entries = blend_entries();
|
||||
let mut opacity = None;
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Select::new(tl!("Blend Mode"), Bind::bound_mixed(&mut shown_blend), &entries).enabled(has).show(ui);
|
||||
Select::new(tl!("Blend Mode"), Bind::bound_mixed(&mut shown_blend).policy(EditPolicy::OnCommit), &entries).enabled(has).show(ui);
|
||||
opacity = Some(
|
||||
NumberField::new(tl!("Opacity"), Bind::given(op.map(|o| f64::from(o) * 100.0)))
|
||||
.unit_kind(UnitKind::Percent)
|
||||
@@ -692,4 +693,34 @@ mod tests {
|
||||
assert_eq!((info.opacity, undone.opacity), (Some(100.0), 1.0));
|
||||
assert!(Arc::ptr_eq(&undone, &held(&app, n.id)), "the node Undo put back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_highlighted_blend_mode_applies_only_once_it_is_chosen() {
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
let mut app = new_app();
|
||||
let id = run_cmd(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40}))["id"].clone();
|
||||
run_cmd(&mut app, "select.set", json!({"ids": [id]}));
|
||||
let mut panel = Panel::new(app, show);
|
||||
let state = |panel: &Panel| {
|
||||
let app = panel.app();
|
||||
(app.session.transparency_info().blend, app.session.active().unwrap().history.undo.len())
|
||||
};
|
||||
let before = state(&panel);
|
||||
assert_eq!(before.0, Some(vectorcraft_color::BlendMode::Normal));
|
||||
panel.click_role("Blend Mode", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(state(&panel), before, "a highlighted blend mode changes nothing");
|
||||
panel.key(Key::Escape, Modifiers::NONE);
|
||||
panel.frame();
|
||||
assert_eq!(state(&panel), before, "Escape leaves the blend mode as it was");
|
||||
panel.click_role("Blend Mode", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
panel.key(Key::Enter, Modifiers::NONE);
|
||||
panel.frame();
|
||||
let (blend, undo) = state(&panel);
|
||||
assert_ne!(blend, before.0, "Enter applies the blend mode");
|
||||
assert_eq!(undo, before.1 + 1, "the choice is one undo step");
|
||||
}
|
||||
}
|
||||
@@ -230,6 +230,11 @@ fn zoom_stops(print: Option<f64>) -> ZoomScheme {
|
||||
ZoomScheme::ILLUSTRATOR.with_hundred(zoom_baseline(print))
|
||||
}
|
||||
|
||||
/// The zoom stops in the percent the status bar shows, lowest first.
|
||||
pub fn zoom_stop_percents() -> impl DoubleEndedIterator<Item = f64> {
|
||||
zoom_stops(None).rungs.iter().map(|rung| rung * 100.0)
|
||||
}
|
||||
|
||||
/// The zoom `z` as the status bar shows it, in percent of [`zoom_baseline`].
|
||||
pub fn zoom_display_percent(z: f64, print: Option<f64>) -> f64 {
|
||||
zoom_stops(print).percent(z)
|
||||
|
||||
@@ -373,6 +373,16 @@ impl Panel {
|
||||
(shapes, images)
|
||||
}
|
||||
|
||||
/// The runs of text the latest frame painted, with their rects.
|
||||
pub(crate) fn texts(&self) -> Vec<(String, Rect)> {
|
||||
self.fixture.texts().iter().map(|t| (t.text.clone(), t.rect)).collect()
|
||||
}
|
||||
|
||||
/// Where the latest frame painted `text` as a whole run.
|
||||
pub(crate) fn painted(&self, text: &str) -> Vec<Rect> {
|
||||
self.texts().into_iter().filter(|(t, _)| t == text).map(|(_, r)| r).collect()
|
||||
}
|
||||
|
||||
/// Where the control of `role` named `name` is, where nodes of other roles share the name.
|
||||
pub(crate) fn rect_role(&self, name: &str, role: craft::ui::contract::Role) -> Rect {
|
||||
self.look_role(name, role).rect
|
||||
|
||||
@@ -9,7 +9,8 @@ use vectorcraft_engine::cmd::scripts::TOO_LARGE;
|
||||
use vectorcraft_engine::script::MAX_SOURCE_BYTES;
|
||||
use vectorcraft_engine::script::folder::Clock;
|
||||
|
||||
use super::script_dialogs::{cancel, confirm, frame, is_open, key, open_id, pump, set};
|
||||
use super::script_dialogs::{cancel, confirm, fields, frame, is_open, key, open_id, pump, set};
|
||||
use crate::dialogs::script_check;
|
||||
use crate::dialogs::script_run::{
|
||||
self, BY_PERSON, CLOSE_KIND, FilesAnswer, GROWTH_KIND, GrowthQuestion, KIND, PICKER_KIND, RunQuestion, ScriptFiles,
|
||||
};
|
||||
@@ -612,6 +613,187 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() {
|
||||
finish(&mut app);
|
||||
}
|
||||
|
||||
/// The texts the open warning draws, after a few frames of the whole app.
|
||||
fn dialog_texts(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 4000.0));
|
||||
let mut out = None;
|
||||
for i in 0..4 {
|
||||
let raw = egui::RawInput { time: Some(0.1 * f64::from(i)), screen_rect: Some(screen), ..Default::default() };
|
||||
out = Some(crate::testing::app_frame(app, &ctx, raw));
|
||||
}
|
||||
let mut v = vec![];
|
||||
out.unwrap().shapes.iter().for_each(|c| texts(&c.shape, &mut v));
|
||||
v
|
||||
}
|
||||
|
||||
/// The warning before a run lists the files the script writes, read without running it.
|
||||
#[test]
|
||||
fn the_warning_lists_the_files_a_script_writes() {
|
||||
let mut app = app();
|
||||
let source = "var f = new File(Folder.temp + '/out.txt');\nf.open('w');\nf.write('x');\nf.close();\n";
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "write.js"})).unwrap().unwrap();
|
||||
assert!(!app.session.script_running());
|
||||
let texts = dialog_texts(&mut app);
|
||||
let writes = script_check::outside_label("filesWritten").unwrap();
|
||||
assert!(texts.iter().any(|t| t.starts_with(writes) && t.contains("(w)")), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == script_check::need_label("files").unwrap()), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == "Outside the document:"), "{texts:?}");
|
||||
// The warning lists the report as `reaches`, which `ui.dialog.set` cannot change.
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"][0]["id"], "filesWritten");
|
||||
assert!(set(&app, KIND, "reaches", json!(null)).is_err());
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"][0]["id"], "filesWritten");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
}
|
||||
|
||||
/// A script that reaches nothing outside the document gets the warning with nothing more.
|
||||
#[test]
|
||||
fn the_warning_for_a_script_that_reaches_nothing_lists_nothing_more() {
|
||||
let mut app = app();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW, "name": "draw.js"})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t.starts_with("A script can change the open documents")), "{texts:?}");
|
||||
for heading in ["Outside the document:", "Includes:", "VectorCraft read this script without running it."] {
|
||||
assert!(!texts.iter().any(|t| t == heading), "{heading}: {texts:?}");
|
||||
}
|
||||
assert!(confirm(&mut app, KIND));
|
||||
finish(&mut app);
|
||||
assert_eq!(objects(&app), 2);
|
||||
}
|
||||
|
||||
/// A script file's warning also lists what the files its `#include` lines name reach.
|
||||
#[test]
|
||||
fn the_warning_lists_what_a_scripts_included_files_reach() {
|
||||
let mut app = app();
|
||||
let dir = folder("includes");
|
||||
std::fs::create_dir_all(dir.join("lib")).unwrap();
|
||||
std::fs::write(dir.join("main.jsx"), "#include 'lib/net.jsxinc'\n").unwrap();
|
||||
std::fs::write(dir.join("lib/net.jsxinc"), "var s = new Socket();\n").unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": dir.join("main.jsx").to_string_lossy()})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t.starts_with("lib/net.jsxinc · ")), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == "Includes:"), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == script_check::need_label("hostOnly").unwrap()), "{texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A script that opens a dialog and reaches nothing outside the document lists the need without the
|
||||
/// outside-the-document heading.
|
||||
#[test]
|
||||
fn the_warning_lists_a_need_without_the_outside_heading() {
|
||||
let mut app = app();
|
||||
let source = "var w = new Window('dialog', 'Title');";
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "dialog.js"})).unwrap().unwrap();
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"], json!([]));
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t == script_check::need_label("dialogs").unwrap()), "{texts:?}");
|
||||
assert!(!texts.iter().any(|t| t == "Outside the document:"), "{texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
}
|
||||
|
||||
/// A script file that changes what it reaches while its warning is open does not run on Run: the
|
||||
/// warning opens again with the new report, and the next Run runs it.
|
||||
#[test]
|
||||
fn run_lists_a_script_again_when_it_changed_after_its_warning_opened() {
|
||||
let mut app = app();
|
||||
let dir = folder("changed");
|
||||
let path = dir.join("changed.jsx");
|
||||
std::fs::write(&path, DRAW).unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap();
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"], json!([]));
|
||||
std::fs::write(&path, format!("{DRAW}\nvar s = new Socket();\n")).unwrap();
|
||||
assert!(confirm(&mut app, KIND));
|
||||
assert!(!app.session.script_running());
|
||||
assert!(is_open::<RunQuestion>(&app));
|
||||
assert_eq!(app.ui.status, script_run::CHANGED_SINCE_WARNING);
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"][0]["id"], "network");
|
||||
assert!(confirm(&mut app, KIND));
|
||||
assert!(app.session.script_running());
|
||||
finish(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A script with more includes than the warning lists gives the count of the rest.
|
||||
#[test]
|
||||
fn the_warning_counts_the_includes_it_does_not_list() {
|
||||
let mut app = app();
|
||||
let dir = folder("many-includes");
|
||||
let names: Vec<String> = (0..script_run::SHOWN_INCLUDES + 3).map(|n| format!("i{n}.jsxinc")).collect();
|
||||
for name in &names {
|
||||
std::fs::write(dir.join(name), "var x = 1;\n").unwrap();
|
||||
}
|
||||
let main: String = names.iter().map(|n| format!("#include '{n}'\n")).collect();
|
||||
std::fs::write(dir.join("main.jsx"), main).unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": dir.join("main.jsx").to_string_lossy()})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
let listed = |name: &str| texts.iter().any(|t| t.starts_with(&format!("{name} · ")));
|
||||
assert!(listed(&names[script_run::SHOWN_INCLUDES - 1]), "{texts:?}");
|
||||
assert!(!listed(&names[script_run::SHOWN_INCLUDES]), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == "Included files not listed: 3"), "{texts:?}");
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["includes"].as_array().map(Vec::len), Some(names.len()));
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A script the checker could not read as a script gets a warning that says so, not the warning of
|
||||
/// a script that was checked and reaches nothing.
|
||||
#[test]
|
||||
fn the_warning_says_when_a_script_was_not_checked() {
|
||||
let missing = std::env::temp_dir().join(format!("vc-script-run-ui-missing-{}.js", std::process::id()));
|
||||
for (params, text) in [
|
||||
(json!({"source": "export const b = 2;", "name": "module.js"}), "Not a script for the reference app"),
|
||||
(json!({"source": "var a = 1;\u{0}", "name": "binary.js"}), "Not a script for the reference app"),
|
||||
(json!({"source": "@JSXBIN@ES@2.0@MyBbyBn0ABJAnA", "name": "compiled.js"}), "Compiled script: ask its author for the .jsx file"),
|
||||
(json!({"path": missing.to_string_lossy()}), "Not read"),
|
||||
] {
|
||||
let mut app = app();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", ¶ms).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t == text), "{params}: {texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
}
|
||||
}
|
||||
|
||||
/// A script whose report was cut short at a list's limit says so, also when nothing else is listed.
|
||||
#[test]
|
||||
fn the_warning_says_when_a_list_was_cut_short() {
|
||||
let mut app = app();
|
||||
let source: String = (0..=1000).map(|n| format!("x = app.m{n};\n")).collect();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "many.js"})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t == "Some lists were cut short at their limit."), "{texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
}
|
||||
|
||||
/// A script over the checker's size limit gets a warning that says it was too large to check.
|
||||
#[test]
|
||||
fn the_warning_says_when_a_script_is_too_large_to_check() {
|
||||
let mut app = app();
|
||||
let dir = folder("large");
|
||||
let path = dir.join("large.js");
|
||||
std::fs::write(&path, vec![b' '; MAX_SOURCE_BYTES + 1]).unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t == "Too large to check"), "{texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_sees_the_window_and_sets_its_zoom_centre_and_screen_mode() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -178,8 +178,8 @@ VectorCraft choices; an original approximation, never compared with another appl
|
||||
|
||||
| Item | Ours |
|
||||
|---|---|
|
||||
| Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) |
|
||||
| Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes and custom bevels drawn as open paths in the bevels file ([add custom bevel paths](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/add-custom-bevel-paths.html), [three-d.md](three-d.md#custom-bevels)), Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) |
|
||||
| Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, a ring of them broken at one of its own faces, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) |
|
||||
| Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, a ring of overlapping faces broken at one of its own faces (Extrude & Bevel and Inflate), depth, twist, taper, solid or hollow caps, five original bevel shapes and custom bevels drawn as open paths in the bevels file ([add custom bevel paths](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/add-custom-bevel-paths.html), [three-d.md](three-d.md#custom-bevels)), Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) |
|
||||
| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate, or ray tracing |
|
||||
| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes and the custom bevels with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art for Extrude & Bevel (Classic) and Revolve (Classic): one document symbol on each numbered surface, surface navigation with visible and hidden marks and a red outline on the artboard, move, scale and rotate on the surface laid out flat, Scale to Fit, Clear, Clear All, Shade Artwork, Invisible Geometry, kept by Expand Appearance and exports, `threeD.mapArt` ([map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)) |
|
||||
| Turntable (30.0 beta) | none |
|
||||
|
||||
@@ -948,6 +948,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
It is given at most 128 MiB of the file and returns paths and compound paths, checked as a filter's output is, which
|
||||
become a new document; nothing opens when it fails, declines or is cancelled. Engine, unit and headless Open With
|
||||
regressions.
|
||||
- **Done:** importer output kinds. An importer at plug-in API level 4 whose manifest lists `outputKinds` may also
|
||||
return point type, embedded RGBA images, top-level layers and artboards; content of a kind it doesn't list, and output
|
||||
past the limits on layers, artboards, text and pixels, opens nothing. Engine and unit regressions.
|
||||
- **Done:** importer plug-ins that place files (`"place": true`). File › Place lists their files, and `file.place` reads
|
||||
a file with one when `importer` names it or no built-in format reads the file; its objects are placed as one group,
|
||||
embedded, as one undo step, and nothing is placed when it fails, declines or is cancelled. Engine regressions.
|
||||
|
||||
+56
-13
@@ -2742,7 +2742,16 @@ shares the key's existing string buffer.
|
||||
Block-scoped declaration checks retain one copy of each `var` declaration name through nested blocks.
|
||||
File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page
|
||||
https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html
|
||||
describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any
|
||||
describes that menu item. Its warning before the run lists what `script.check` finds the script reaches outside
|
||||
the document, read without running it: each `outside` category of the report (files it writes, moves or deletes,
|
||||
files it opens in other apps, messages to other apps, the network, native code, environment variables, the reference
|
||||
app's preferences and code the checker can't read), the files and dialogs it needs, features only the reference app
|
||||
has, and the files its `#include` lines name (the first 20, then the count of the rest; VectorCraft's own limit). It
|
||||
says when the script is too large to check, compiled or not a script, when the check failed, and when a list was cut
|
||||
short at its limit. The listing does not stop the run. Run checks the script again, and when the report has changed
|
||||
since the warning opened, nothing runs and the warning opens again with the new report. A script from the Scripts
|
||||
folder runs without the warning.
|
||||
Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any
|
||||
case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is
|
||||
not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and
|
||||
`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A `path` that ends in
|
||||
@@ -2752,7 +2761,10 @@ declarations scoped to their block, arrow functions, template literals and tagge
|
||||
parameters, spread in array literals, calls and `new`, `for`-`of` loops, array and object destructuring in `var`,
|
||||
`let` and `const` declarations, assignments, parameters and `catch` clauses (with defaults, holes and rest elements),
|
||||
shorthand and computed property names in object literals, and classes with `extends`, `static` members, accessors and
|
||||
computed method names, `super` calls and properties and `new.target` (https://262.ecma-international.org/11.0/). A
|
||||
computed method names, `super` calls and properties and `new.target` (https://262.ecma-international.org/11.0/).
|
||||
`new.target` in a string given to direct `eval` inside a function, or inside an arrow function within one, reads that
|
||||
function's `new.target`; at the top of a script, in an arrow function at the top of a script and through an indirect
|
||||
`eval` it is a `SyntaxError`. A
|
||||
class can extend a class, a function, `null` or the built-in constructors `Object`, `Function`, `Array`, `String`,
|
||||
`Number`, `Boolean`, `RegExp`, `Date` and the error types. A class can name another built-in constructor in
|
||||
`extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is
|
||||
@@ -2879,7 +2891,9 @@ other files through `$`:
|
||||
Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds
|
||||
or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they
|
||||
were), `opacity` (0 to
|
||||
100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the
|
||||
100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value
|
||||
throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the
|
||||
visible bounds, widened to take in the direction points of every path in the object), `editable` (false for an
|
||||
object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`,
|
||||
`duplicate(relativeObject?, insertionLocation?)`,
|
||||
@@ -2893,12 +2907,12 @@ other files through `$`:
|
||||
the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or
|
||||
locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an
|
||||
object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`,
|
||||
`locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer or on a locked artboard
|
||||
`locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer or on a locked artboard
|
||||
throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such
|
||||
an object throws `Cannot edit` too. The one exception is `opacity` given the value the object already has, which
|
||||
changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity, that
|
||||
an object throws `Cannot edit` too. The one exception is `opacity` or `blendingMode` given the value the object already has, which
|
||||
changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity or blend mode, that
|
||||
value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an
|
||||
object that is hidden or locked itself takes `hidden`, `locked` and `opacity` (VectorCraft's own rule). Position,
|
||||
object that is hidden or locked itself takes `hidden`, `locked`, `opacity` and `blendingMode` (VectorCraft's own rule). Position,
|
||||
size and stacking-order changes also require a selectable object. Other targets excluded by selection filtering,
|
||||
including guide paths while Lock Guides is on, throw `Cannot select`. `move` with the object itself
|
||||
as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move`
|
||||
@@ -2909,7 +2923,7 @@ other files through `$`:
|
||||
`Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws
|
||||
`Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that
|
||||
holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a
|
||||
`RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`,
|
||||
`RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `BlendModes`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`,
|
||||
`DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and
|
||||
`DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`.
|
||||
`pageItems` lists the art topmost first, as the example on
|
||||
@@ -2954,7 +2968,7 @@ other files through `$`:
|
||||
`..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined`
|
||||
and does not change the documents or add an undo step. In the app, the documents are drawn as they were before the
|
||||
run until the run ends, with or without the call. Some members the Application,
|
||||
Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and
|
||||
Document and PageItem pages list, such as `Document.layers`, `PageItem.isIsolated`, `PageItem.rotate` and
|
||||
`app.beep`, throw an error that says they are not available yet when they are read or assigned.
|
||||
`hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an
|
||||
object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the
|
||||
@@ -8789,6 +8803,21 @@ image between its corners and makes a plain image of the result. These rules are
|
||||
{"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}}
|
||||
```
|
||||
|
||||
## Perspective Distort and Free Distort on type and symbol instances
|
||||
|
||||
`object.distort` puts the corners of a type object's box and of a symbol instance's box (its symbol's art box placed
|
||||
by its transform) exactly where the warp takes them, alone or with other objects. The object stays type or a symbol
|
||||
instance: it keeps its flat art and is drawn through the warp, as type and symbols in perspective are, so the canvas,
|
||||
printing and exports draw its outlines in perspective. An image in a symbol's art drawn this way, on the Perspective
|
||||
Grid too, has its corners where the projection takes them and its pixels drawn in perspective between them, and its
|
||||
linked opacity mask is projected with it. It is bounded by those corners, a move or another transform
|
||||
takes them along, and Object › Perspective › Edit Text (`perspective.editText`) shows distorted type flat for editing.
|
||||
A type object or symbol instance already drawn in perspective takes the warp after its projection. Corners that would
|
||||
fold the box over, put three corners on one line, carry a corner of the box past the warp's horizon or lie too close
|
||||
together for a perspective map are an error that names the object, and nothing changes; so is a warp of type that Edit
|
||||
Text shows flat, until Edit Text ends. A warp whose corners make a
|
||||
parallelogram moves, scales, rotates or shears the object as before. These rules are VectorCraft's own.
|
||||
|
||||
## Transform Each: Relative and Absolute
|
||||
|
||||
`object.transformEach` scales by percentages of each object's size (the dialog's Relative, the default), or with
|
||||
@@ -13201,6 +13230,11 @@ the dialog on the last search, with the fields its `params` give in its place. A
|
||||
the wrong type is an error that leaves the dialog closed. Once it is open, `ui.dialog.confirm` with a field of the
|
||||
wrong type runs no action and returns the error.
|
||||
|
||||
For other command dialogs, `params.__doc` can supply a document uid. The dialog previews and confirms only while
|
||||
that document is active. Confirming after a document switch closes the dialog without running its command.
|
||||
Canceling or replacing that dialog does not cancel an interaction in another document. A supplied `__doc` must be
|
||||
an unsigned integer; omitting it preserves the command dialog's existing behavior.
|
||||
|
||||
|
||||
## Justification options
|
||||
|
||||
@@ -14796,15 +14830,24 @@ with `read: true`, and `openExtensions` holds the extensions File › Open opens
|
||||
extension, with the installed importer that lists the extension (the one whose id sorts first, when several do).
|
||||
`importer` names the importer to use, which must list the file's extension, also one a built-in format reads, such
|
||||
as `svg`. The importer is given at most 128 MiB of the file; its objects become a new document whose artboard is
|
||||
their bounds, Save then asks for a name, and `warnings` holds the importer's warnings. An importer whose manifest sets
|
||||
their bounds, Save then asks for a name, and `warnings` holds the importer's warnings. An importer at plug-in API
|
||||
level 4 whose manifest lists `outputKinds` (in its `plugin.list` entry) may also return point type, embedded images,
|
||||
top-level layers and artboards, which replace the one around the art; output that fails a check, or an image or type
|
||||
that reaches more than 4,000,000 pt from the origin, opens nothing (see docs/plugins.md). An importer whose manifest sets
|
||||
`place` (`place: true` in `document.formats` and `plugin.list`) also places its files: `file.place`, `file.place.info`
|
||||
and `file.place.queue` take `importer?: "plugin.<id>"` (one that sets `place` and lists the file's extension) and
|
||||
`params?`, and without `importer` a file no built-in format reads goes to the first such importer by id that lists its
|
||||
extension. The importer is given at most 128 MiB of the file (a larger file is refused from its size, with `importer`
|
||||
before any of it is read or decoded, and without it after its first 64 KiB are read or decoded)
|
||||
and `_context.mode` `"place"`; its objects, guides left out, are placed as one group named after the file, in the order
|
||||
it returned them, as one undo step, embedded whatever `link` says (`linked: false`). `plugin.run` of an importer is
|
||||
an error that names `document.open`. In the app, File › Open With lists the installed importers, and
|
||||
and `_context.mode` `"place"`; its visible layers' objects, or all objects when it returns no layers, are placed
|
||||
as one group named after the file. Layers are placed from bottom to top, with objects in each layer's listed order.
|
||||
Without layers, objects keep their returned order. Guides are omitted. Placement records one undo step and embeds
|
||||
the group whatever `link` says (`linked: false`). `plugin.run` of an importer is
|
||||
an error that names `document.open`. Placement rejects transformed art beyond ±4,000,000 pt on either axis,
|
||||
including geometry retained outside a crop frame and template placement, before changing the document.
|
||||
An importer returns new paths with geometry and
|
||||
without object IDs. An artboard's positive width and height must produce distinct finite endpoints within the canvas.
|
||||
In the app, File › Open With lists the installed importers, and
|
||||
`file.openWith {importer, path?, params?}` opens `path`, or a file picked among the importer's extensions, with one (on
|
||||
the web it opens File › Open's picker) and adds it to Open Recent. With `path` the reply is `document.open`'s result;
|
||||
on the desktop a picked file is read off the UI thread and the reply is `{background: true, status}`, and
|
||||
|
||||
+67
-9
@@ -18,8 +18,9 @@ There are four kinds of plug-in:
|
||||
laser cutters and the like. File › Export › Export As lists them after the built-in formats, and the host writes the
|
||||
bytes they return: a plug-in still never touches a file.
|
||||
- **Importers** read files in a format of their own, such as a plotter's or a cutting machine's, into a new document of
|
||||
paths and compound paths. File › Open lists their files, File › Open With lists the importers by name, and the host
|
||||
hands them the file's bytes.
|
||||
paths and compound paths, and at API level 4 also of point type, embedded images, layers and artboards ([importer
|
||||
output kinds](#importer-output-kinds)). File › Open lists their files, File › Open With lists the importers by name,
|
||||
and the host hands them the file's bytes.
|
||||
|
||||
An object filter may also be written in JavaScript, as a manifest and a `.js` file ([JavaScript
|
||||
filters](#javascript-filters)).
|
||||
@@ -31,7 +32,7 @@ in `crates/engine/src/cmd/plugin.rs`).
|
||||
|
||||
| Command | Params | What it does |
|
||||
|---|---|---|
|
||||
| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, context?, size, source, api, paintOutput?, appearanceOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `context` lists the [document information](#document-information) it reads; `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects), and `appearanceOutput: true` one whose pieces carry [opacity, blending and effects](#opacity-blending-and-effects-on-pieces); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `runtime: "js"` and `script` mark a [JavaScript filter](#javascript-filters); `cacheBytes` is the size of its [cache](#settings-and-cache)), `"failed": [{file, error, from}]` (the plug-in files that [didn't load](#plug-ins-that-didnt-load)) |
|
||||
| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, context?, size, source, api, paintOutput?, appearanceOutput?, outputKinds?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `context` lists the [document information](#document-information) it reads; `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects), and `appearanceOutput: true` one whose pieces carry [opacity, blending and effects](#opacity-blending-and-effects-on-pieces); `outputKinds` lists what an importer returns besides paths ([importer output kinds](#importer-output-kinds)); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `runtime: "js"` and `script` mark a [JavaScript filter](#javascript-filters); `cacheBytes` is the size of its [cache](#settings-and-cache)), `"failed": [{file, error, from}]` (the plug-in files that [didn't load](#plug-ins-that-didnt-load)) |
|
||||
| `plugin.info` | `{"id"}` | One plug-in: the `plugin.list` entry plus `manifest`, `defaults` and `lastError` (a live effect's last failure). |
|
||||
| `plugin.run` | `{"id", "params"?: {…}, "ids"?: [...]}` (plug-in params may also be top-level keys) | Runs an object filter on the selection (or `ids`; an `ids` that is not a list of object ids is an error). One undo step; the result is selected, except the objects it locked or made guides. An output that changes no object and none of the data it keeps with the document ([`documentData`](#output)) records no undo step and leaves the document unmodified. |
|
||||
| `plugin.install` | `{"path": "/x/y.wasm"}` or a [JavaScript filter's](#javascript-filters) `.vcplugin` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). |
|
||||
@@ -89,9 +90,10 @@ importers that set `place`: when no built-in format reads the file, the first su
|
||||
extension reads it, and `"importer": "plugin.<id>"` names one, which must set `place` and list the file's extension,
|
||||
also one a built-in format reads. `"params"?: {…}` holds its parameters, which take their defaults when left out. The
|
||||
importer is given at most 128 MiB of the file and `_context.mode` `"place"`, and returns its objects as it does for
|
||||
File › Open. They are placed in the open document as
|
||||
one group named after the file, in the order the importer returned them, at the place, size or object `at`, `rect`,
|
||||
`replace` and `template` give, as one undo step; guides are left out, and the group's box is the bounds of what the
|
||||
File › Open. The visible layers' objects are placed in the open document as one group named after the file,
|
||||
from the bottom layer to the top, in each layer's listed object order. Without layers, objects keep their returned
|
||||
order. The group uses the place, size or object `at`, `rect`, `replace` and `template` give, as one undo step;
|
||||
guides are left out, and the group's box is the bounds of what the
|
||||
other objects draw. The file is embedded whatever `link`
|
||||
says, as a format that can't be linked is, and the reply's `linked` is `false`. A decline, invalid output, a trap or
|
||||
Cancel places nothing and leaves the document and its undo steps as they were. An importer without `place` is not used
|
||||
@@ -559,10 +561,11 @@ capability model proposed for PhotoCraft plug-ins
|
||||
changes the document is refused. A refused output leaves the document as it was.
|
||||
- `api` is the plug-in API level the manifest is written for: `1` (the default); `2`, which adds the [host
|
||||
imports](#host-imports-api-level-2), a filter's `inputs` ([reading type, images and
|
||||
symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects); or `3`, which
|
||||
symbols](#reading-type-images-and-symbols)) and a live effect's [`paintOutput`](#painted-live-effects); `3`, which
|
||||
adds a filter's `writes` ([writing type, images and symbols](#writing-type-images-and-symbols)), a painted live
|
||||
effect's [`appearanceOutput`](#opacity-blending-and-effects-on-pieces) and `context` ([document
|
||||
information](#document-information)). A higher one is refused. `plugin.list` and
|
||||
information](#document-information)); or `4`, which adds an importer's
|
||||
[`outputKinds`](#importer-output-kinds). A higher one is refused. `plugin.list` and
|
||||
`plugin.info` give it as `api`. `inputs` is not a permission: the objects it asks for are read under `doc.read`, which
|
||||
a filter that lists `inputs` must list in `permissions`, so installing it asks the user to grant them. `context` is
|
||||
not a permission either: it is read under `doc.read` in the same way, and the install prompt says that the plug-in
|
||||
@@ -899,6 +902,12 @@ the module's start function, in a run that isn't a filter's run on a document, o
|
||||
is refused when the module is installed, and the error names `appearanceOutput`. It needs no permission beyond
|
||||
`doc.read` and `effect.render`, which every live effect already has. Hosts at `api` 2 refuse the manifest for its
|
||||
`api`, so such an effect never draws without its looks.
|
||||
- `outputKinds` (importers at `api` 4 only): the kinds of content besides paths and compound paths the importer
|
||||
returns, any of `"type"`, `"image"`, `"layer"` and `"artboard"`, each at most once (`"outputKinds": ["type",
|
||||
"layer"]`). Left out, `null` or `[]`, the importer returns paths and compound paths alone, as before. An unknown,
|
||||
repeated or wrongly typed entry, `outputKinds` on another kind, or below `api` 4 is refused when the plug-in is
|
||||
installed, and hosts from before level 4 refuse the manifest for its `api`. It needs no permission besides
|
||||
`import.read`. See [importer output kinds](#importer-output-kinds).
|
||||
- `extensions` (exporters and importers only, and required): 1–8 file extensions, lower-case letters and digits
|
||||
without the dot (`["plt"]`); the first is the one Export As gives the file. A built-in format keeps an extension both
|
||||
list (`svg`): `document.export` then writes the exporter's format only when asked for by its format id, and
|
||||
@@ -1340,6 +1349,53 @@ that fails the checks opens nothing, and neither does a decline (`{"error": …}
|
||||
returns the same output when `_context.mode` is `"place"`; an output that fails, or whose objects other than guides draw
|
||||
nothing of any width or height, places nothing.
|
||||
|
||||
#### Importer output kinds
|
||||
|
||||
An importer at `api` 4 whose manifest lists [`outputKinds`](#manifest) may return more than paths. The host checks the
|
||||
whole output before it makes the document, and one entry that fails a check opens nothing; the error names the entry
|
||||
(`objects[2]`, `layers[0]`) and the limit or field. Content of a kind the manifest doesn't list is refused, and the
|
||||
error names the kind. An importer that lists no kinds is read as before, and the keys below are errors for it.
|
||||
|
||||
```json
|
||||
{
|
||||
"objects": [
|
||||
{"type": "type", "text": "Hello", "fontFamily": "Source Sans 3", "fontStyle": "Bold", "fontSize": 24,
|
||||
"fill": {"type": "solid", "color": {"model": "rgb", "r": 0, "g": 0, "b": 1}}, "transform": [1, 0, 0, 1, 10, 40]},
|
||||
{"type": "image", "pixelSize": [2, 1], "pixelsBase64": "/wAA/wAA/4A=", "transform": [10, 0, 0, 10, 0, 100]},
|
||||
{"type": "path", "path": {"subpaths": [{"closed": true, "anchors": [{"p": [0, 0]}, {"p": [10, 0]}, {"p": [10, 10]}]}]}}
|
||||
],
|
||||
"layers": [{"name": "Art", "objects": [1, 2]}, {"name": "Words", "visible": false, "locked": true, "objects": [0]}],
|
||||
"artboards": [{"name": "Front", "rect": [0, 0, 200, 100]}, {"name": "Back", "rect": [220, 0, 200, 100]}]
|
||||
}
|
||||
```
|
||||
|
||||
- `"type": "type"` (kind `type`) is point type in the document's Normal Character Style with the face, size and fill
|
||||
it gives: `text` (at most 1,048,576 bytes of UTF-8, a `\n` between paragraphs, no control characters other than
|
||||
line breaks and tabs), `fontFamily`, `fontStyle` (left out: the family's regular style), `fontSize` (0.1–1296 pt),
|
||||
`fill` (a color or a gradient, in the filters' paint form; left out: black), `transform` and `name`. The first
|
||||
baseline starts at the origin of the type's own space. A font that isn't installed keeps its name, and the open
|
||||
reports it as missing. All the type of one output holds at most 16,777,216 bytes of text.
|
||||
- `"type": "image"` (kind `image`) is an image embedded in the document, stored as a PNG of its pixels: `pixelSize`
|
||||
(width and height, 1–16,384 each), `pixelsBase64` (straight RGBA, 8 bits a channel, rows from the top, exactly 4 ×
|
||||
width × height bytes in padded base64), `transform` (from pixel space, one unit a pixel, into the document) and
|
||||
`name`. All the images of one output hold at most 33,554,432 bytes of RGBA. The host checks both limits from the
|
||||
sizes the images give, and the length of `pixelsBase64`, before it decodes any pixels.
|
||||
- `transform` is six finite numbers `[a, b, c, d, e, f]` within ±4,000,000 that don't flatten the object; left out,
|
||||
the identity. Type or an image that then reaches more than 4,000,000 pt from the origin is refused.
|
||||
- `layers` (kind `layer`): 1–256 top-level layers, bottom first. Each has a `name`, `visible` (default `true`),
|
||||
`locked` (default `false`) and `objects`, the indexes of its objects in `objects` in increasing order. Every object
|
||||
is in exactly one layer, and a layer may hold none. Without `layers`, every object goes in one layer.
|
||||
- `artboards` (kind `artboard`): 1–100 artboards, each with a `name` used once and a `rect`, `[x, y, width, height]`
|
||||
with a width and height above 0. Each computed endpoint must differ from its origin and remain within
|
||||
±4,000,000. They replace the one artboard around the art.
|
||||
- A `name` (of type, an image, a layer or an artboard) and a font's family and style are each 1–256 characters, not
|
||||
only spaces, without control characters or characters that change the direction of text.
|
||||
- An output whose `objects` is empty opens as a blank document when it has `layers` or `artboards`.
|
||||
- To place (`_context.mode` `"place"`), the objects of the visible layers are placed in one group with their type and
|
||||
images, the objects of hidden layers are left out, and `artboards` are left out. Without layers, all objects are
|
||||
placed. Transformed art beyond ±4,000,000 pt on either axis is rejected before the edit, including template placement.
|
||||
- Imported paths require `path` geometry and cannot include an `id`, at every plug-in API level.
|
||||
|
||||
#### Opacity, blending and effects on pieces
|
||||
|
||||
A painted live effect whose manifest also has `"api": 3` and `"appearanceOutput": true` may give each piece, and each
|
||||
@@ -1480,7 +1536,9 @@ per change of their input, parameters or paints (results are cached), not per fr
|
||||
## Not in v1
|
||||
|
||||
- Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, importers
|
||||
that make type, images, layers or artboards, and placed importer files that stay linked to their file.
|
||||
that make area type, type on a path, nested layers or linked images (an importer at `api` 4 makes point type,
|
||||
embedded images, top-level layers and artboards, see [importer output kinds](#importer-output-kinds)), and placed
|
||||
importer files that stay linked to their file.
|
||||
- Filters that add or delete type, images or symbol instances or change their pixels and other fields (a filter at
|
||||
`api` 3 changes [some of their fields](#writing-type-images-and-symbols)).
|
||||
- Scripts can't run object filters (`plugin.*` commands are refused there), so a script doesn't change what Apply
|
||||
|
||||
+1
-1
@@ -111,7 +111,7 @@ with the standard command.
|
||||
- One Revolve per source object. Edit its options rather than applying another.
|
||||
- Object-level Revolve uses the top visible fill, falling back to a stroke. Per-item Revolve uses that item's paint.
|
||||
- Smooth diffuse shading, one to ten directional lights, no textures, cast shadows or physical materials. Smooth shading interpolates lighting in projected triangles; it does not smooth the silhouette or add specular highlights.
|
||||
- Faces are drawn back to front by the depths of their centers. When that order draws the nearer of two overlapping faces of a surface first, every pair of overlapping faces goes in the order of their depths at the middle of where they overlap; the sort compares at most 4,000,000 pairs (VectorCraft's own limit), and the pairs past that keep the depths of their centers. Caps facing the camera cover their rim seams; a cap facing away is drawn behind the body except where it is nearer than a body face it overlaps. Intersecting profiles can have incorrect visibility.
|
||||
- Faces are drawn back to front by the depths of their centers. When that order draws the nearer of two overlapping faces of a surface first, every pair of overlapping faces goes in the order of their depths at the middle of where they overlap; faces that lie in front of one another in a ring, so that no order draws them all correctly, give up the ring's own face that comes first by depth, as [Extrude & Bevel's do](three-d.md). The sort compares pairs and looks for rings within 4,000,000 steps in all (VectorCraft's own limit); the pairs past that keep the depths of their centers, and a ring past it is broken at the first face left by depth. When no face can go next, the sort creates ring-search lists only if the remaining steps cover a quarter of all recorded ordering pairs, including those involving drawn faces, and reuses existing lists while steps remain; without the lists, the first face left by depth goes next, even when it is outside the ring. Caps facing the camera cover their rim seams; a cap facing away is drawn behind the body except where it is nearer than a body face it overlaps. Intersecting profiles can have incorrect visibility.
|
||||
- Curves use sixteen samples per segment, and as few as four when a surface would otherwise pass its limits. Surfaces are limited to 16,384 profile points and 163,840 faces, the members of a group together. A straight segment takes one point, a curve takes at least four, and each contour takes one. Smooth shaded side quads become two triangles and share the face limit. A continuous cap retains its original radial mesh cost within this limit, and each region of a cut side counts as one face. Projected ring curves have a 0.001-point fitting tolerance and a shared 32,768-curve limit.
|
||||
- Axis, bounds and ordinary selection handles continue to refer to the editable 2D source profile.
|
||||
- Extrude & Bevel, Inflate and Rotate are described in [three-d.md](three-d.md). Materials remain unimplemented.
|
||||
|
||||
+1
-1
@@ -202,7 +202,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 |
|
||||
| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 |
|
||||
| M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 |
|
||||
| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 |
|
||||
| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets, a ring of overlapping faces broken at one of its own faces (#7023); SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 |
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
|
||||
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
|
||||
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
|
||||
|
||||
@@ -39,6 +39,8 @@ Native saves on Unix flush the destination directory after writing or replacing
|
||||
|
||||
## Feature submission evidence
|
||||
|
||||
- Command dialogs can keep the uid of the document they edit. Their preview, confirmation, and cancellation do not change another active document. Tests cover confirmation in the original and another document, unscoped dialogs, and invalid document ids.
|
||||
|
||||
Document Info › Objects reports total enclosed area (`pathArea` in square points) for eligible closed paths and compound paths according to their fill rule, subtracting holes and excluding guides and open paths, with duplicate nested compound geometry avoided. The Document Info panel inserts a formatted `Path Area` row in the document's active units (`Unit::format_area`) right after `Path Length` whenever the total area is positive. The area pass runs only for a request that covers the Objects category: `document.info` with another `category`, or with `pathArea: false`, skips it and gives `pathArea` as null, and the panel asks for the area only while it shows Objects or All Categories, so edits made with another category shown do not work it out again. Focused tests: `cmd::docinfo::tests::info_gives_the_paths_total_area`, `info_path_area_counts_selected_compound_members_once` and `info_works_out_the_path_area_only_for_the_objects_category` (vectorcraft-engine), `panels::doc_info::tests::the_path_area_is_worked_out_only_while_objects_is_shown` (vectorcraft-ui-egui) and `units::tests::format_area_formats_and_trims_cleanly` (vectorcraft-doc). Scores and estimates unchanged.
|
||||
|
||||
When startup scripts precede a chosen script, its source must compile before startup scripts run. Invalid chosen source is rejected before startup scripts execute in synchronous and sliced sessions, and a compilation failure clears the previous script report. The chosen script runs the source read before startup scripts, including when a startup script removes its installed file. Included files are read again when the chosen run starts. Each app queue pump processes at most one startup entry and preserves the remaining order after a failure. `crates/engine/tests/script_startup.rs` covers both modes.
|
||||
@@ -1110,12 +1112,13 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
|
||||
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
|
||||
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
|
||||
- Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.
|
||||
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
|
||||
- Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`.
|
||||
- Scripts: `UnitValue` measurements ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/)): the constructor with a number and a unit, with text such as `12 pt`, or with another `UnitValue`; the length units, `px` and `%` by abbreviation, singular or plural; `value`, `type` and `baseUnit` on the class and on each object; `as` and `convert`; and the arithmetic, comparison and unary operators with a number or another `UnitValue`, the right one converted to the left one's unit, with `>` and `>=` as the negations of `<=` and `<`. Realms without `UnitValue` keep the standard operators. VectorCraft's own rules: an invalid object has `type` `?` and value 0, and converting it or using it with these operators, a result that is not finite (a division by 0 included), a comparison with a number that is not finite and a base that is not a length greater than 0 throw. `crates/js/src/unit_value_tests.rs`, `crates/engine/src/tests/script_dollar.rs`.
|
||||
@@ -1176,7 +1179,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread uses the iterator protocol (see the `for`-`of` line below). Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
The collector retains tagged-template cache entries only while the site's code is reachable.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `super` and `new.target` in code given to direct `eval` are not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
|
||||
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
@@ -1312,6 +1315,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`).
|
||||
- The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) put the corners of a type object's box and of a symbol instance's box exactly where the warp takes them, alone or with other objects; the object stays type or a symbol instance and is drawn through the warp, after any perspective projection it had, as type and symbols in perspective are, with the images in a symbol's art and their linked masks drawn in perspective between the corners the projection gives them; and corners that would fold its box over, carry it past the warp's horizon or lie too close together for a perspective map are refused with an error that names it, as is a perspective warp of type that Edit Text shows flat. VectorCraft's own rule (engine `xform::distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles`, `distort_moves_type_and_symbol_instances_with_a_path_as_one`, `distort_refuses_corners_type_and_symbol_instances_cannot_follow`, `distort_refuses_type_being_edited_flat`; effects `group::tests::a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them`).
|
||||
- Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`).
|
||||
- Object › Create Object Mosaic on an image changed by Perspective Distort or Free Distort places each tile's cell of pixels between the image's corners, so the tiles are four-sided shapes that follow the perspective, in one undo step; a new size scales them from the top left of the image's bounds, and the spacing and Use Ratio measure a pixel by the mean length of the image's two sides along each axis (VectorCraft's own rule; engine `object_mosaic_tiles_of_a_distorted_image_follow_its_corners`).
|
||||
- The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`).
|
||||
@@ -1815,6 +1819,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`.
|
||||
- When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_draws_its_faces_in_one_order`, `solids::tests::a_depth_cycle_keeps_the_cap_last`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`.
|
||||
- A graphic mapped onto Extrude & Bevel's cap or onto a Plane is drawn once when the fill is a gradient with transparent stops under a colored light and the object has a stroke (dashed or plain) with the same opacity and blending mode: the fill and stroke share it, as they do without the mask, and it is drawn after the stroke's cap with the mask of the stroke's surface (none for an opaque stroke), instead of once on the fill's cap and again on the stroke's. Members of a 3D group drawn with a mask keep graphics of their own. Unmasked fills and strokes alone draw as before. Tests: `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`, `solids::graphics::tests::a_plane_in_a_transparent_gradient_with_a_stroke_draws_its_graphic_once`, `solids::graphics::tests::members_in_transparent_gradients_keep_graphics_of_their_own`.
|
||||
- Where the faces put in the order of their depths where they overlap lie in front of one another in a ring (a strongly connected component of the pairs), the faces that go before the first face left by depth are followed back, among the faces that come before the next face drawn last, to a ring that waits for no other of them, and that ring gives up its own face that comes first by depth; the faces left are then looked at afresh, since they may be a smaller ring or none. So a face that is in front of a face of a ring without being part of it is drawn after that face rather than first, and the pairs drawn the wrong way round are pairs of a ring, or pairs of a face with a face drawn last or one that follows it, when that one should have gone first (a face drawn last, such as a cap, still follows every face before it by depth). On 6,000 sets of pairs at random this drew no more pairs the wrong way round than taking the first face left by depth, in any set, and fewer in all; giving up the ring's face that waits for the fewest faces drew fewer still in all but more in one to five sets in a hundred, so it was not chosen. The steps count toward the 4,000,000 the comparing of pairs counts toward (VectorCraft's own limit, one for both): a step for each face and pair looked at while looking for rings (making the lists a ring is looked for in, a step a pair, is not counted). The search goes on from where it stopped at the last ring, and a face that is drawn is dropped from a list the next time the list is looked at, so rings of a few faces take a few steps a face whether they stand apart, all lie behind one face or lie one behind the other. A ring that is still a ring after it gives up a face is walked again from the face the search reached it by, so a large ring can cost about its pairs for each face it gives up, the square of its faces even when each waits for few others (3,200 faces with four pairs each at random take about 3,000,000 steps, and about 4,000 reach the limit); and a face at or after the next face drawn last is passed over again each time a face that waits for it is looked at. A first face left that waits only for the next face drawn last or faces after it goes next with no search, at no cost. The pairs are kept as lists of 4 bytes a pair, once for the faces after each face and once more for the faces before each face when a ring is first looked for, and only when the steps left are at least a quarter of the pairs, so making them costs no more than four times the steps left; with fewer, no ring is looked for, so a solid whose comparing of pairs leaves less than a quarter of its pairs of the limit breaks its rings at the first face left by depth, as before. Past the limit the first face left by depth goes next, ring or not, as before, and a face drawn last still follows every face before it by depth (#7023). Revolve's faces share the order. Tests: `solids::tests::a_face_in_front_of_a_cycle_waits_for_it`, `solids::tests::the_faces_left_are_looked_at_afresh_after_each_face_released`, `solids::tests::the_ring_released_waits_for_no_face_outside_it`, `solids::tests::a_ring_is_looked_for_before_the_next_face_drawn_last`, `solids::tests::breaking_a_ring_draws_no_more_pairs_wrong_than_the_first_face_by_depth`, `solids::tests::breaking_rings_stops_at_its_room`, `solids::tests::breaking_rings_takes_a_few_steps_a_face_but_for_a_ring_of_many_pairs`, `solids::tests::a_face_that_waits_only_for_the_face_drawn_last_costs_no_search`, `solids::tests::the_lists_for_rings_are_made_only_with_room_for_a_quarter_of_the_pairs`, `solids::tests::a_list_longer_than_the_room_left_is_not_read`, `solids::tests::a_depth_cycle_keeps_the_cap_last`.
|
||||
- Revolve and Revolve (Classic) draw two overlapping faces of a surface in the order of their depths where they overlap, instead of by the depths of their centers, on one object and across a group's members, so a tilted profile with long edges or a profile of several contours no longer draws a nearer face under a farther one. A surface whose faces were already in the right order keeps it. Tests: `solids::tests_revolve_order::a_revolved_surface_draws_the_nearer_of_two_overlapping_faces_last`, `solids::tests_revolve_order::a_revolved_groups_members_draw_the_nearer_of_two_overlapping_faces_last`, `solids::tests_revolve_order::a_classic_revolved_surface_draws_the_nearer_of_two_overlapping_facets_last`, `solids::tests_revolve_order::a_surface_already_in_order_keeps_it`, `solids::tests_revolve_order::surface_order_puts_the_nearer_face_where_they_overlap_last`, `tests::a_revolved_face_measures_its_depth_on_its_plane`.
|
||||
- Under a colored light, an Inflate fill and strokes in solid colors, opaque with Normal blending, also draw their faces in that one order, inside a group member's own opacity mask too, instead of each solid as one composite with the stroke's faces over every fill face. Each face keeps the composite's paint, light ramps and seam width; a lone solid, the solids of an object with a translucent or blended fill or stroke, and such solids holding more than 30,720 faces together (VectorCraft's own limit) are still drawn as one composite each. Tests: `solids::tests::colored_solid_fills_and_strokes_share_face_depth_order`, `solids::tests::a_colored_solid_face_on_its_own_keeps_the_composites_colors`, `solids::tests::colored_solid_inflate_batches_channels_and_clips_once_per_surface`, `solids::tests::colored_solids_past_the_face_limit_draw_as_composites`.
|
||||
- Without a twist, a tapered Extrude & Bevel wall (and each bevel band) is one flat face; only a twist cuts walls into slices, so no seam between slices paints a light tick or a light line on a tapered, untwisted wall (#7019). Test: `solid::tests::a_tapered_wall_is_one_flat_face_and_a_twisted_one_is_sliced`.
|
||||
@@ -2799,9 +2804,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Envelope names given as another type:** `object.envelope.makeWithWarp`, `resetWithWarp` and `options` refuse a `style` or `orientation` other than text or null, such as `5`, and an `orientation` other than `horizontal` or `vertical`; `object.envelope.options` refuses such a `preserveShape`. `object.envelope.options` checks the warp keys with no envelope or only mesh envelopes selected, too. Each leaves the document, the options new envelopes get and the undo history as they were.
|
||||
|
||||
- **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.<id>`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged.
|
||||
- **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged.
|
||||
- **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document, which Save asks a name for. The document uses returned artboards when supplied; otherwise, its artboard surrounds the imported objects. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged.
|
||||
- **Importer output kinds (G17, VectorCraft's own contract):** an importer at plug-in API level 4 lists in its manifest's `outputKinds` which of `type`, `image`, `layer` and `artboard` it returns besides paths. Its output may then hold point type (text, font family and style, size, fill, transform), embedded RGBA images (stored as PNG in the document), top-level layers with their names, visibility, lock and objects, and named artboards that replace the one around the art; output of artboards or layers alone opens as a blank document. The host checks the whole output before it makes the document: a kind the manifest doesn't list, an image whose bytes aren't 4 × width × height, a name with control or text direction characters, or output past the limits on objects, layers, artboards, text and pixels opens nothing, and the error names the kind or the limit. Imported paths require geometry and cannot name existing object IDs. Positive artboard sizes must produce distinct finite endpoints within the canvas. Importers below level 4 read paths alone, as before. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged.
|
||||
- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`. Its visible layers' objects, or all objects when it returns no layers, are placed as one group named after the file, with guides omitted, from bottom to top by layer, preserving each layer's listed object order (returned object order without layers), at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. Transformed art beyond ±4,000,000 pt on either axis is rejected before an edit, including geometry retained outside a crop frame and placement on a template layer. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged.
|
||||
- **Generator plug-ins (G17):** a WebAssembly plug-in of kind `generator` draws art from its parameters into a generated art object, a group that keeps the plug-in's id, the parameters and the art, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_plugin_group_suite) describes for plug-in groups whose art the plug-in draws and redraws. Object › Plug-ins lists generators with the filters; Edit Generated Art… and `plugin.editGenerated` draw the art again from changed parameters as one undo step (none when nothing changes), placed as the object has been transformed since, and Object › Expand makes it an ordinary group. Parameters are checked against the manifest (unknown names, wrong types, out-of-range numbers and long text are errors) and kept up to 64 KiB, and the art up to 16 MiB. The native file keeps the plug-in id, parameters, transform and a SHA-256 of the art; opening never runs a plug-in, and an object whose plug-in is missing, whose saved fields are damaged or whose art doesn't match its hash keeps its art and is named in the open's warnings. The limits and the file fields are VectorCraft's own. Regressions: `crates/engine/tests/plugin_generate.rs`, `crates/engine/tests/import_fuzz.rs` (`generated_art_saved_fields_never_panic_and_keep_the_art`), `crates/doc/src/generated.rs`, `crates/ui-egui/src/dialogs/tests_plugin_generate.rs`. Scores and hours unchanged.
|
||||
- **Importer plug-ins place their files (G17):** an importer whose manifest has `"place": true` also reads its files for File › Place, which lists them under "All placeable files" and a filter named after the importer. `file.place`, `file.place.info` and `file.place.queue` use the importer `importer` names, which must set `place`, or, for a file no built-in format reads, the first such importer by id that lists its extension. It is given at most 128 MiB of the file (a larger file is refused from its size, before any of it is read when `importer` names the importer) and `_context.mode` `"place"`, and its objects are placed as one group named after the file, in the order it returned them, at `at`, in `rect`, over the object Replace swaps or on a template layer, as one undo step, embedded whatever `link` says. A decline, invalid output, a trap or Cancel places nothing and leaves the undo steps as they were; an importer without `place` is not used by File › Place. These rules are VectorCraft's own. Regressions: `crates/engine/tests/plugin_place.rs`, `crates/plugins/src/manifest.rs`. Scores and hours unchanged.
|
||||
|
||||
- **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged.
|
||||
- **Plug-in int parameters as sliders (G17):** an `int` parameter with `"widget": "slider"` shows a slider over its range with its number field, in the filter, live-effect and exporter dialogs and in the Appearance panel's effect editor; the manifest is refused at install when the parameter cannot have one. Regressions: `crates/plugins/src/dialog.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`. Scores and hours unchanged.
|
||||
|
||||
+21
-12
@@ -253,18 +253,27 @@ The rest is our reading:
|
||||
uncovered, such as the gaps between dashes. Each face of such a stroke that passes through a face of the fill's
|
||||
solid, or through a face of another of the shape's strokes, where the two overlap in the drawing is cut where
|
||||
their depths meet, and the faces of the shape's fill and strokes that overlap are drawn in the order of their
|
||||
depths where they overlap, with caps on or off. A fill wall in a gap stays in its own depth order. Inflate's
|
||||
curved surfaces follow this only as closely as their flat facets do. A solid painted with a gradient that has
|
||||
transparent stops under a light that is not white is drawn with an opacity mask: its faces keep their places in
|
||||
this order, in runs that each carry the mask, and a graphic drawn after one of its faces carries the mask too
|
||||
([Graphics](#graphics)). Such a gradient, and a gradient with transparent stops under the classic effects'
|
||||
shading, is placed once on the whole solid when it has no placement of its own, so its colors and its
|
||||
transparency line up across the faces. A member of a 3D group with its own opacity
|
||||
mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when
|
||||
they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the
|
||||
lower item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its
|
||||
place in this order too, each of its faces drawn with its own light ramps; a lone solid of that kind is still
|
||||
drawn as one composite, and so is each such solid when they hold more than 30,720 faces together.
|
||||
depths where they overlap, with caps on or off. A fill wall in a gap stays in its own depth order. Where such
|
||||
faces lie in front of one another in a ring, so that no order draws them all correctly, a ring that waits for no
|
||||
face outside it gives up its own face that comes first in the order of their depths, and the faces left are
|
||||
looked at afresh, as they may be a smaller ring or none. A face that is only in front of a face of a ring is
|
||||
still drawn after that face. Comparing the faces and looking for rings share one limit of 4,000,000 steps
|
||||
(VectorCraft's own). Rings of a few faces take a few steps a face. A ring that is still a ring after it gives up
|
||||
a face is walked again, so a large ring can cost about the square of its faces (some 4,000 faces tangled at
|
||||
random reach the limit). The lists a ring is looked for in are made only when the steps left are at least a
|
||||
quarter of the pairs, so a solid whose comparing uses nearly all of the limit breaks its rings as before; and a
|
||||
face that waits only for a face drawn last goes in its turn with no search. Past the limit, a face that can go
|
||||
next still goes (before the next cap, when a cap is left), and the first face left by depth goes next only when no such face can. Inflate's curved surfaces follow this only as closely as their flat facets do. A
|
||||
solid painted with a gradient that has transparent stops under a light that is not white is drawn with an opacity
|
||||
mask: its faces keep their places in this order, in runs that each carry the mask, and a graphic drawn after one
|
||||
of its faces carries the mask too ([Graphics](#graphics)). Such a gradient, and a gradient with transparent stops
|
||||
under the classic effects' shading, is placed once on the whole solid when it has no placement of its own, so its
|
||||
colors and its transparency line up across the faces. A member of a 3D group with its own opacity mask or
|
||||
blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when they are
|
||||
opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the lower
|
||||
item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its place
|
||||
in this order too, each of its faces drawn with its own light ramps; a lone solid of that kind is still drawn as
|
||||
one composite, and so is each such solid when they hold more than 30,720 faces together.
|
||||
- The solids turn, twist and taper about the center of the bounds of all their shapes, Inflate's grid covers
|
||||
those bounds, and with Perspective one eye sees every solid. A stroke too narrow to hold a point of Inflate's
|
||||
grid stays flat.
|
||||
|
||||
Reference in new issue
Block a user