Merge main into fix/expand-appearance-nested-instance-effects

This commit is contained in:
dotCooCoo
2026-11-15 09:20:32 -08:00
109 changed files with 7710 additions and 420 deletions
+2 -1
View File
@@ -252,11 +252,12 @@ speaks English, German, Japanese, Korean, Vietnamese, Traditional and Simplified
The scores are self-assessed from our code against public documentation;
[target-app-parity.md](docs/target-app-parity.md#how-this-was-measured-2026-10-10) explains how far to trust them.
All 57 approximated Photoshop-style raster filters are available. The Effect Gallery includes filter thumbnails and an in-dialog preview.
**What's missing:**
- reliable exchange of .ai files (layer structure in real files; the editing copy a save writes keeps live effects only on paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports (see [docs/file-format-parity.md](docs/file-format-parity.md)), leaves out other objects' effects other than geometry effects, and writes live objects as their art);
- an interaction-fidelity pass covering every tool's modifiers and small behaviours;
- 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials);
- filter thumbnails and a preview area inside the Effect Gallery (the gallery itself and all 57 Photoshop-style raster filters, approximated, are in);
- CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface);
- scripting, and the rest of Variables (image and graph kinds, dataset import);
- generative AI features.
+145 -11
View File
@@ -266,6 +266,7 @@ pub fn hit_test_visible_skipping(doc: &Document, p: Point, opt: HitOptions, skip
/// (`opt.scope`) or on a locked artboard. On a layer whose Preview is off it counts by its
/// outline, as a click there hits it.
pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &[NodeId]) -> Option<NodeId> {
let _walk = ArtWalk::open();
let symbols = doc.symbol_boxes();
let locks = doc.locked_artboards();
selected.iter().rev().copied().find(|&id| {
@@ -322,6 +323,7 @@ fn path_options(nodes: &[&Node], chain: &[NodeId], opt: HitOptions) -> Option<Hi
/// The objects under `p` that [`Hit::top_object`] picks in `scope` (isolation mode), topmost
/// first: what clicks there select, one below the other (Cmd/Ctrl-click selects behind).
pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>) -> Vec<NodeId> {
let walk = ArtWalk::open();
let opt = HitOptions { scope: scope.or(opt.scope), ..opt };
// Normally one hit test per *object* suffices: layers and sublayers aren't selectable,
// while a group (including a clipping group) is selected as one object. Repeatedly
@@ -337,6 +339,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
for layer in doc.layers.iter().rev() {
// Malformed files may contain non-layer roots; let the general traversal handle them.
if !layer.is_layer() {
walk.restart();
return objects_at_repeated(doc, p, opt, scope);
}
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
@@ -344,7 +347,9 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
}
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
// An envelope in Edit Contents may expose objects *within* a top-level group.
// The repeated traversal handles that mixed hierarchy precisely.
// The repeated traversal handles that mixed hierarchy precisely, with the whole
// limit of symbol art to walk.
walk.restart();
return objects_at_repeated(doc, p, opt, scope);
}
}
@@ -429,6 +434,7 @@ pub const MAX_LOCKED_AT: usize = 20;
/// out. While a pattern is edited only its tile layer is searched, and in isolation mode
/// (`opt.scope`) only what is inside the isolated group or object.
pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeId> {
let _walk = ArtWalk::open();
let symbols = doc.symbol_boxes();
let mut out = Vec::new();
if let Some(scope) = opt.scope
@@ -506,6 +512,7 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
let _walk = ArtWalk::open();
let finish = |mut h: Hit| {
h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents));
h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count();
@@ -1059,9 +1066,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds)
}
// A symbol instance is hit within its bounds, and outside them where its art paints
// ([`instance_art_hit`]).
// ([`instance_art_hit`]). In the art of another instance walked outside that instance's
// bounds, it is hit only where its own art paints ([`ArtOnly`]).
NodeKind::SymbolInstance { .. } => {
if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
if !ArtOnly::on() && n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return Some(HitKind::Bounds);
}
instance_art_hit(n, p, opt, symbols)
@@ -1172,6 +1180,15 @@ impl<'a> InstanceArt<'a> {
whole.or_else(|| self.map.as_ref()?.one_cell_with(n, &self.boxes))
}
/// How many objects placing the whole art makes: the objects of the art with their opacity
/// masks' art ([`Node::count_with_masks`]), or, through the guides, the most that
/// [`crate::NineSliceMap::most_placed_with`] counts.
fn size(&self) -> u64 {
self.map
.as_ref()
.map_or_else(|| u64::try_from(self.art.count_with_masks()).unwrap_or(u64::MAX), |m| m.most_placed_with(&self.art, &self.boxes))
}
/// Object `n` of the art placed on the canvas as it is drawn, clip groups included: moved by
/// `whole` when an object around it is moved as one piece ([`Self::whole`]). `None` when
/// placing it through the guides could make more than [`crate::MAX_SYMBOL_NODES`] objects, as
@@ -1219,6 +1236,7 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
/// no editable object of its art is under `p`.
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
let _walk = ArtWalk::open();
let art = InstanceArt::of(doc, inst)?;
let symbols = doc.symbol_boxes();
let mut path = vec![];
@@ -1250,7 +1268,7 @@ impl FindPart<'_> {
/// What a click at `p` hits on object `n` of the art, with `path` the child indices that lead
/// to what it hits. `outline`: the view is in Outline, or a layer around `n` has Preview off.
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> Option<HitKind> {
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) {
if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || !ArtWalk::take(1) {
return None;
}
let outline = outline || previews_off(n);
@@ -1298,17 +1316,120 @@ impl FindPart<'_> {
/// Outline, [`HitOptions::outline`]): its strokes, and the art that the live geometry effects of a
/// clipping path in it show past the art's box. `None` for an instance of a missing symbol, of a
/// symbol that holds an instance of itself or nests too deep ([`SymbolBoxes::art`]), and of art past
/// the 9-slice object limit ([`InstanceArt::of`]).
/// the 9-slice object limit ([`InstanceArt::of`]), when `p` is outside the instance's reach
/// ([`Node::reach_bounds_with`]), and once the click has visited as many objects of symbol art as
/// [`ArtWalk`] allows.
fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option<HitKind> {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None };
if opt.outline || symbols.art(symbol).is_none() {
if opt.outline || symbols.art(symbol).is_none() || !n.reach_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return None;
}
let _walk = ArtWalk::open();
if ArtWalk::used_up() {
return None;
}
let art = InstanceArt::of(symbols.document(), n)?;
#[cfg(test)]
ARTS_WALKED.with(|c| c.set(c.get() + 1));
let opt = HitOptions { clip_outlines: false, ..opt };
let _art_only = ArtOnly::set();
FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false)
}
thread_local! {
/// Whether a symbol instance's art is being walked outside the instance's box ([`ArtOnly`]).
static ART_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// While a guard lives, a symbol instance is hit ([`hit_leaf`]) and touched by a marquee
/// ([`marquee_with`]) only where its own art is, by the same rule at every level, and not anywhere
/// in its box. [`instance_art_hit`] and the marquee's walk of an instance's art hold one: they walk
/// the art outside the instance's box, where the box of an instance nested in the art can reach
/// past it over empty space.
struct ArtOnly {
was: bool,
}
impl ArtOnly {
fn set() -> Self {
Self { was: ART_ONLY.replace(true) }
}
fn on() -> bool {
ART_ONLY.get()
}
}
impl Drop for ArtOnly {
fn drop(&mut self) {
ART_ONLY.set(self.was);
}
}
thread_local! {
/// How many more objects of symbol art the click or marquee under way may visit ([`ArtWalk`]),
/// `None` outside one.
static ART_WALK_LEFT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
thread_local! {
/// The number of objects [`ArtWalk::open`] allows on this thread in place of
/// [`crate::MAX_SYMBOL_NODES`].
static ART_WALK_LIMIT: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
/// How many symbol instances' art clicks and marquees walked on this thread.
static ARTS_WALKED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The objects of symbol art that one click or one marquee may visit: [`crate::MAX_SYMBOL_NODES`]
/// in all, the art of the instances nested in that art included, at every level. The first
/// [`ArtWalk::open`] of a click or a marquee sets the limit, and the walks opened while its guard
/// lives share it. Once the limit is used up, an instance is no longer hit or touched outside its
/// box; inside its box it still is.
struct ArtWalk {
outermost: bool,
}
impl ArtWalk {
fn open() -> Self {
let walk = Self { outermost: ART_WALK_LEFT.get().is_none() };
walk.restart();
walk
}
/// For the outermost guard, sets what is left back to the whole limit.
fn restart(&self) {
if self.outermost {
#[cfg(test)]
let limit = ART_WALK_LIMIT.get().unwrap_or(crate::MAX_SYMBOL_NODES);
#[cfg(not(test))]
let limit = crate::MAX_SYMBOL_NODES;
ART_WALK_LEFT.set(Some(limit));
}
}
/// Is nothing left?
fn used_up() -> bool {
ART_WALK_LEFT.get() == Some(0)
}
/// Takes `n` objects from what is left. `false` when fewer are left, and nothing is left after.
fn take(n: u64) -> bool {
let Some(left) = ART_WALK_LEFT.get() else { return true };
let rest = left.checked_sub(n);
ART_WALK_LEFT.set(Some(rest.unwrap_or(0)));
rest.is_some()
}
}
impl Drop for ArtWalk {
fn drop(&mut self) {
if self.outermost {
ART_WALK_LEFT.set(None);
}
}
}
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
/// does not count.
@@ -1502,6 +1623,7 @@ fn previews_off(n: &Node) -> bool {
}
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
let _walk = ArtWalk::open();
let mut out = Vec::new();
// The objects the marquee may touch ([`Top`]).
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
@@ -1613,8 +1735,9 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
// A symbol instance is touched by its box, and outside it where the live geometry
// effects of a clipping path in its art show the art.
NodeKind::SymbolInstance { .. } => box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
// effects of a clipping path in its art show the art. In the art of another instance
// walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]).
NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
_ => box_touches(n, s, r),
}
}
@@ -1628,15 +1751,26 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
}
/// Does the marquee `r` touch the art of symbol instance `n` placed as the canvas draws it, as
/// it touches a group of that art? Only for art whose clipping paths have live geometry effects
/// ([`SymbolBoxes::art`]), and only when `r` meets the instance's reach
/// ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's box.
/// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the
/// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's
/// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows.
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
if s.art(symbol).is_none_or(|a| a.reshaped.is_none()) || !n.reach_bounds_with(s).is_some_and(meets) {
if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) {
return false;
}
let _walk = ArtWalk::open();
if ArtWalk::used_up() {
return false;
}
let Some(art) = InstanceArt::of(s.document(), n) else { return false };
if !ArtWalk::take(art.size()) {
return false;
}
#[cfg(test)]
ARTS_WALKED.with(|c| c.set(c.get() + 1));
let _art_only = ArtOnly::set();
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
}
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
+179
View File
@@ -1961,6 +1961,185 @@ fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() {
assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view");
}
/// Outside a symbol instance's box, an instance nested in its art counts where its own art is, not
/// anywhere in its box: a click or a marquee on empty space in the nested box, where a moved
/// clipping path shows the art past the outer box, selects nothing, and on art drawn there it
/// selects the outer instance.
#[test]
fn a_nested_symbol_instances_box_past_the_outer_box_is_not_a_hit() {
set_clip_region(moved_clip_region);
// `Two` draws squares at the corners of 0..200 × 0..100, and with `middle` one at 140..160 ×
// 40..60. The outer symbol clips an instance of it to 0..100 × 0..100, which `test.move` moves
// to 100..200: the outer box is 0..100, the nested box 0..200.
let build = |middle: bool| {
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
let square = |d: &mut Document, r: Rect| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art()));
let mut squares = vec![square(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)), square(&mut d, Rect::new(190.0, 90.0, 200.0, 100.0))];
if middle {
squares.push(square(&mut d, Rect::new(140.0, 40.0, 160.0, 60.0)));
}
group_symbol(&mut d, "Two", squares);
let (mut mask, _) = half_clipped(&mut d);
mask.appearance.effects.push(test_move());
let nested = instance_of(&mut d, "Two");
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), nested]);
clip.set_clips(true);
group_symbol(&mut d, "Outer", vec![Arc::new(clip)]);
let inst = d.alloc_id();
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Outer".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
(d, inst)
};
let at = |d: &Document, x: f64, y: f64| hit_test(d, Point::new(x, y), HitOptions::default()).map(|h| h.leaf);
let inside = Rect::new(145.0, 45.0, 155.0, 55.0);
let (d, inst) = build(false);
assert_eq!(at(&d, 150.0, 50.0), None, "empty space in the nested box");
assert!(marquee(&d, inside, None, false).is_empty(), "marquee on empty space in the nested box");
assert_eq!(at(&d, 195.0, 95.0), Some(inst), "on the nested art past the outer box");
assert_eq!(at(&d, 50.0, 50.0), Some(inst), "in the outer box");
let (d, inst) = build(true);
assert_eq!(at(&d, 150.0, 50.0), Some(inst), "on the nested art");
// Across the middle square's left edge.
assert_eq!(marquee(&d, Rect::new(135.0, 45.0, 145.0, 55.0), None, false), [inst], "marquee on the nested art");
}
/// Adds the symbol `Clipped`: a clip group whose clipping path's region `test.move` moves to
/// 100..200 × 0..100, past the 0..100 box, over a 0..200 × 0..100 rectangle shown when `shown`.
/// A click at (150, 50) hits an instance of it on the rectangle, or, with the rectangle hidden,
/// walks its art and finds nothing.
fn clipped_symbol(d: &mut Document, shown: bool) {
set_clip_region(moved_clip_region);
let (mut mask, mut art) = half_clipped(d);
mask.appearance.effects.push(test_move());
art.visible = shown;
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
let root = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
d.symbols.push(crate::Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(root) });
}
/// A symbol named `name` whose art is a group of `members`.
fn group_symbol(d: &mut Document, name: &str, members: Vec<Arc<Node>>) {
let root = Node::group(d.alloc_id(), members);
d.symbols.push(crate::Symbol { dynamic: false, name: name.into(), art: Arc::new(root) });
}
/// An instance of the symbol named `symbol`, not moved.
fn instance_of(d: &mut Document, symbol: &str) -> Arc<Node> {
Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }))
}
/// 30 small squares at the origin, which a click at (150, 50) passes by.
fn far_squares(d: &mut Document) -> Vec<Arc<Node>> {
(0..30).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()))).collect()
}
/// Runs `f` with [`ArtWalk`] allowing `limit` objects, and returns its result with how many
/// leaves [`hit_leaf`] tested and how many instances' art was walked meanwhile.
fn with_art_limit<R>(limit: u64, f: impl FnOnce() -> R) -> (R, usize, usize) {
ART_WALK_LIMIT.with(|c| c.set(Some(limit)));
LEAVES_TESTED.with(|c| c.set(0));
ARTS_WALKED.with(|c| c.set(0));
let r = f();
ART_WALK_LIMIT.with(|c| c.set(None));
(r, LEAVES_TESTED.with(std::cell::Cell::get), ARTS_WALKED.with(std::cell::Cell::get))
}
/// One click visits at most the art walk's limit of objects in a chain of nested symbol
/// instances, though each level's art alone is well within it. A click on the art of an
/// instance nested in another is still found.
#[test]
fn a_click_walks_a_chain_of_nested_symbol_instances_within_one_limit() {
// Level 0 is `Clipped`; each level above holds an instance of the level below and 30 squares:
// 32 objects to visit at each level.
let chain = |shown: bool| {
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
clipped_symbol(&mut d, shown);
for level in 1..12 {
let below = if level == 1 { "Clipped".to_string() } else { format!("Level {}", level - 1) };
let mut members = vec![instance_of(&mut d, &below)];
members.extend(far_squares(&mut d));
group_symbol(&mut d, &format!("Level {level}"), members);
}
let inst = instance_of(&mut d, "Level 11");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
(d, id)
};
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
// Without one limit for the click, the miss walks the art of all 12 levels.
let (d, inst) = chain(false);
let (hit, _, arts) = with_art_limit(100, || at(&d, 150.0));
assert_eq!(hit, None);
assert!(arts <= 4, "{arts} levels walked");
assert_eq!(with_art_limit(100, || at(&d, 50.0)).0, Some(inst), "in the box");
// Past the limit, a click that the art would take finds only the box.
let (d, inst) = chain(true);
assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, None, "past the limit");
assert_eq!(at(&d, 150.0), Some(inst), "within the limit");
// Two levels: a click on the inner instance's art is found within the limit.
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
clipped_symbol(&mut d, true);
let inner = instance_of(&mut d, "Clipped");
group_symbol(&mut d, "Outer", vec![inner]);
let inst = instance_of(&mut d, "Outer");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
assert_eq!(with_art_limit(100, || at(&d, 150.0)).0, Some(id), "nested");
}
/// One click, and one marquee, visit at most the art walk's limit of objects in art that repeats
/// one nested instance many times, though the art of each instance alone is well within it. A
/// click on one of the nested instances' art is still found.
#[test]
fn a_click_and_a_marquee_walk_repeated_nested_symbol_instances_within_one_limit() {
// 50 instances of `Clipped` in one symbol's art, its rectangle shown when `shown`.
let repeated = |shown: bool| {
let mut d = Document::new(600.0, 400.0);
let l = d.layers[0].id;
clipped_symbol(&mut d, shown);
let members = (0..50).map(|_| instance_of(&mut d, "Clipped")).collect();
group_symbol(&mut d, "Repeated", members);
let inst = instance_of(&mut d, "Repeated");
let id = inst.id;
d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
(d, id)
};
let (d, inst) = repeated(false);
// Without one limit for the click, the miss walks the art of all 51 instances. The outer art
// takes 1 object of the 100, and each nested instance with its art 4.
let (hit, _, arts) = with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf));
assert_eq!(hit, None);
assert!(arts <= 26, "{arts} instances' art walked");
// Select Behind over 60 instances of `Clipped` on the layer shares one limit too: each walk
// takes 3 objects of the 100.
let mut stack = Document::new(600.0, 400.0);
let l = stack.layers[0].id;
clipped_symbol(&mut stack, false);
for _ in 0..60 {
let inst = instance_of(&mut stack, "Clipped");
stack.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap();
}
let (behind, _, arts) = with_art_limit(100, || objects_at(&stack, Point::new(150.0, 50.0), HitOptions::default(), None));
assert!(behind.is_empty());
assert!(arts <= 34, "Select Behind: {arts} instances' art walked");
// Without one limit for the marquee, it places the art of all 51 instances, inside the moved
// region (within each instance's reach and outside its box). Placing the outer art takes 51
// objects of the 100, and each nested art 4.
let inside = Rect::new(140.0, 40.0, 160.0, 60.0);
let (touched, _, arts) = with_art_limit(100, || marquee(&d, inside, None, false));
assert!(touched.is_empty());
assert!(arts <= 14, "{arts} instances' art placed");
assert_eq!(with_art_limit(100, || marquee(&d, Rect::new(40.0, 40.0, 60.0, 60.0), None, false)).0, [inst], "in the box");
// A click and a marquee on the nested instances' art are found within the limit.
let (d, inst) = repeated(true);
assert_eq!(with_art_limit(100, || hit_test(&d, Point::new(150.0, 50.0), HitOptions::default()).map(|h| h.leaf)).0, Some(inst), "click");
let edge = Rect::new(140.0, -5.0, 160.0, 5.0);
assert_eq!(with_art_limit(100, || marquee(&d, edge, None, false)).0, [inst], "marquee across the art's edge");
}
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
/// canvas draws nothing of it. At the art's natural size the same art is picked.
+34 -4
View File
@@ -17,22 +17,52 @@ pub enum Justify {
JustifyAll,
}
/// Paragraph composer (Paragraph panel menu): how lines are broken.
/// Paragraph composer (Paragraph panel menu): how lines are broken, and whether complex scripts
/// (Indic, Arabic, Hebrew) are shaped. `SingleLine` and `EveryLine` are the Middle Eastern & South
/// Asian composers: they shape complex scripts with the font's layout tables, as all type is set
/// here, and are what documents saved before the four composers existed use. The `Standard`
/// composers break lines the same way but set a complex script glyph by glyph as the font maps its
/// characters, with no conjuncts, marks placed or joining forms: what fonts that keep a script's
/// glyphs on Latin character codes (legacy ANSI Indic fonts) need.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Composer {
/// Break each line as soon as it is full.
/// Middle Eastern & South Asian Single-line Composer: break each line as soon as it is full.
SingleLine,
/// Total fit over the whole paragraph (Illustrator's default): justified lines get even word
/// spacing, ragged lines an even rag.
/// Middle Eastern & South Asian Every-line Composer: total fit over the whole paragraph
/// (Illustrator's default): justified lines get even word spacing, ragged lines an even rag.
#[default]
EveryLine,
/// Standard Single-line Composer: [`Composer::SingleLine`]'s breaks, complex scripts not shaped.
StandardSingleLine,
/// Standard Every-line Composer: [`Composer::EveryLine`]'s breaks, complex scripts not shaped.
StandardEveryLine,
}
impl Composer {
fn is_default(&self) -> bool {
*self == Self::default()
}
/// Does this composer break lines one at a time (as opposed to a total fit)?
pub fn is_single_line(self) -> bool {
matches!(self, Self::SingleLine | Self::StandardSingleLine)
}
/// Does this composer shape complex scripts ([`Composer::SingleLine`], [`Composer::EveryLine`])?
pub fn shapes_complex_scripts(self) -> bool {
matches!(self, Self::SingleLine | Self::EveryLine)
}
/// The same shaping with the other line breaking (`single_line`: one line at a time).
pub fn with_breaking(self, single_line: bool) -> Self {
match (single_line, self.shapes_complex_scripts()) {
(true, true) => Self::SingleLine,
(true, false) => Self::StandardSingleLine,
(false, true) => Self::EveryLine,
(false, false) => Self::StandardEveryLine,
}
}
}
/// A paragraph's hyphenation options (Paragraph panel menu › Hyphenation…): which words automatic
+56 -7
View File
@@ -171,7 +171,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
}
}
}
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0));
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| crate::solids::shadow::casts(paint_of(i).1 * s.opacity)));
return check_shadow(p, casting.map(|s| &s.path), b, options);
}
let (path, _) = object_profile(n, "Revolve")?;
@@ -350,8 +350,8 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
/// The shadow of Revolve `fx` cast by the surface of `path` in `item`'s paint about the axis of
/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
/// the surface it is cast from is past the limits.
/// the shadow off, when `item` is fully transparent or its opacity is not a finite number, or when
/// it casts nothing, and an error when the surface it is cast from is past the limits.
///
/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the
/// surface is swept again for its shadow alone.
@@ -366,7 +366,7 @@ fn shadow_of(
) -> Result<Option<Node>, String> {
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
let (_, opacity, blend) = paint_of(item);
if opacity <= 0.0 {
if !crate::solids::shadow::casts(opacity) {
return Ok(None);
}
let mut caster = vectorcraft_three_d::ShadowCaster::new();
@@ -377,7 +377,7 @@ fn shadow_of(
/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces
/// its shadow is cast from ([`surface`])?
fn casts(fx: &Effect, opacity: f32) -> bool {
opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
crate::solids::shadow::casts(opacity) && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
}
/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was
@@ -420,9 +420,9 @@ fn group_shadow(
for s in shapes {
let kept = kept.next().flatten();
let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue };
// A member whose surface is fully transparent casts nothing.
// A member whose surface is fully transparent, or whose opacity is not a finite number, casts nothing.
let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend };
if ink.opacity <= 0.0 {
if !ink.casts() {
continue;
}
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
@@ -1861,6 +1861,55 @@ mod tests {
}
}
}
/// A surface whose fill, or whose member, is at NaN or infinite opacity casts no shadow, as one
/// at 0 % does, whether the shadow is cast from the surface drawn or swept for it alone; the
/// member beside it still casts its part.
#[test]
fn a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow() {
let fx = crate::new_effect(REVOLVE, &json!({"shadow": true})).unwrap();
let group = |opacity: f32| {
let mut other = profile_node();
other.id = NodeId(2);
other.transform(Affine::translate((120.0, 0.0)), false);
other.opacity = opacity;
let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]);
g.appearance.effects.push(fx.clone());
g
};
let group_shadows = |g: &Node| {
let shapes = members(g, "").unwrap();
let b = union_bounds(&shapes).unwrap();
let options = shared_options(&shapes, fx_options(&fx)).unwrap();
let kept: Vec<Option<SolidFaces>> = shapes
.iter()
.map(|s| {
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
let cast = casts(&fx, opacity * s.opacity);
surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
})
.collect();
[group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()]
.map(|art| format!("{art:?}"))
};
let expected = group_shadows(&group(0.0));
for bad in [f32::NAN, f32::INFINITY] {
let mut n = profile_node();
if let AppearanceItem::Fill(f) = &mut n.appearance.items[0] {
f.opacity = bad;
}
let (path, _) = profile(&n).unwrap();
let b = path.bounds().unwrap();
let item = surface_item(&n.appearance.items).unwrap();
assert!(!casts(&fx, bad), "{bad}: the surface keeps no faces for a shadow");
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap(), None, "{bad} drawn");
assert_eq!(shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap(), None, "{bad} alone");
let shadows = group_shadows(&group(bad));
assert!(!expected[0].is_empty() && expected[0] != "[]", "the opaque member casts");
assert_eq!(shadows, expected, "{bad}: only the opaque member casts");
}
}
}
#[cfg(test)]
+79 -64
View File
@@ -324,8 +324,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
reshape_members(n, before, &mut shapes);
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
check_profiles(id, p, &shapes, b)?;
check_solids(id, p, &shapes)?;
return check_cast(id, p, &shapes);
return check_solids(id, p, &shapes);
}
let (path, rule) = object_profile(n, label)?;
let anchors = || format!("{label} requires a shape with at least two anchors");
@@ -342,38 +341,68 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
let b = path.bounds().ok_or_else(anchors)?;
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
check_profiles(id, p, &shapes, b)?;
check_solids(id, p, &shapes)?;
check_cast(id, p, &shapes)
check_solids(id, p, &shapes)
}
/// With the shadow of 3D effect `id` with parameters `p` on, an error when the shadow of `shapes`
/// is past the limits ([`cast_shadow`]). In wireframe mode no shadow is drawn, and none is checked.
fn check_cast(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
if wireframe::wireframe_params(id, p) {
return Ok(());
}
cast_shadow(id, p, shapes).map(|_| ())
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
/// with Shadows on, shaded? In wireframe mode no shadow is drawn, and none is checked.
fn casts_shadow(id: &str, p: &Value) -> bool {
!is_classic_three_d(id) && shadow::options(p).is_some() && !wireframe::wireframe_params(id, p)
}
/// Does `item` of a shape with opacity `member` paint anything, and so cast a shadow?
fn visible(item: &AppearanceItem, member: f32) -> bool {
paint_of(item, member).1 > 0.0
}
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: every
/// shape's for Rotate, and for Extrude & Bevel and Inflate the profile of a shape with no fill,
/// whose solids are its strokes' outlines or none. A filled shape's profile is its fill's solid,
/// which [`check_solids`] builds once, about the bounds the effect draws it about.
/// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate
/// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is
/// the fill's; for Extrude & Bevel and Inflate the profile of a shape with no fill, whose solids
/// are its strokes' outlines or none. A filled shape's profile is its fill's solid, which
/// [`check_solids`] builds once, about the bounds the effect draws it about.
fn check_profiles(id: &str, p: &Value, shapes: &[Profile], b: Rect) -> Result<(), String> {
shapes
.iter()
.filter(|s| is_plane(id) || !s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_))))
.try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
let cast = casts_shadow(id, p);
let fill = |s: &Profile| s.items.iter().any(|i| matches!(i, AppearanceItem::Fill(_)) && (!is_plane(id) || visible(i, s.opacity)));
shapes.iter().filter(|s| if is_plane(id) { !(cast && fill(s)) } else { !fill(s) }).try_for_each(|s| facets(id, &s.path, s.rule, b, p).map(|_| ()))
}
/// Do the solids 3D effect `id` with parameters `p` builds from the fills and strokes of `shapes`
/// fit, each on its own and all of them together ([`built_solids`])? Rotate's planes are not
/// counted.
/// fit, each on its own and all of them together ([`built_solids`]), and with its shadow cast, does
/// the shadow fit? The shadow is cast from the faces those same builds kept ([`cast_built`]), as
/// [`art_for`] casts it: Extrude & Bevel and Inflate build each solid once, and Rotate builds the
/// plane of each visible fill and stroke once. Rotate's planes are not counted, and without its
/// shadow Rotate builds no plane here.
fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
let Some(b) = union_bounds(shapes).filter(|_| !is_plane(id)) else { return Ok(()) };
let Some(b) = union_bounds(shapes) else { return Ok(()) };
let cast = casts_shadow(id, p);
if is_plane(id) {
if !cast {
return Ok(());
}
let mut built = vec![];
for s in shapes {
for item in &s.items {
if !visible(item, s.opacity) {
built.push(None);
continue;
}
let (area, rule) = region(&s.path, s.rule, item);
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
built.push(facets_and_faces(ROTATE, &area, rule, b, p, true)?.1);
}
}
return cast_built(id, p, shapes, built).map(|_| ());
}
let (parts, bounds) = solid_parts(shapes, b);
built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()))
if !cast {
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
}
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true)
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
.collect::<Result<Vec<_>, String>>()?;
cast_built(id, p, shapes, built).map(|_| ())
}
/// [`profile`], or the error a command reports for object `n`: type with no outlines to build from
@@ -733,7 +762,8 @@ thread_local! {
/// surfaces count too.
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
/// [`built_solids`] have built on this thread, for the tests.
/// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow
/// ([`cast_shadow`]) count too.
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
@@ -1435,7 +1465,7 @@ fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) ->
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
}
let p = crate::merged_params(&fx.id, &fx.params);
let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some();
let cast = casts_shadow(&fx.id, &p);
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
// A shadow past the limits draws the source path, as a solid past them does; commands report
// the error ([`validate_solid_in`]).
@@ -1474,8 +1504,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
let view = view_options(p);
let mut caster = vectorcraft_three_d::ShadowCaster::new();
// The faces each solid of visible art added, with its member's scopes and its ink (opacity
// and blending mode), in order. A fully transparent fill or stroke (or member) casts nothing
// and does not place the plane.
// and blending mode), in order. A fill or stroke (or member) that is fully transparent, or whose
// opacity is not a finite number, casts nothing and does not place the plane ([`shadow::Ink::casts`]).
let mut cast: Vec<shadow::Cast> = vec![];
let ink = |item: &AppearanceItem, member: f32| {
let (_, opacity, blend) = paint_of(item, member);
@@ -1483,7 +1513,7 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
};
if id == ROTATE {
for s in shapes {
for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) {
for item in s.items.iter().filter(|i| ink(i, s.opacity).casts()) {
let (area, rule) = region(&s.path, s.rule, item);
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
@@ -1497,21 +1527,25 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
// Inflate's eye is placed for every shape together, as the solids are.
let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect();
let casts: Vec<bool> = inks.iter().map(|i| i.casts()).collect();
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
#[cfg(test)]
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + casts.iter().filter(|c| **c).count()));
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
} else {
let mut added = vec![];
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0)));
added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
#[cfg(test)]
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + usize::from(ink.casts())));
added.push(if ink.casts() { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
}
added
};
for (((item, _, _, _, scopes, _), ink), faces) in parts.iter().zip(inks).zip(added) {
if ink.opacity <= 0.0 {
if !ink.casts() {
continue;
}
// A stroke whose own solid is past the limits is left out; past the shadow's limit for
@@ -1529,16 +1563,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
/// [`cast_shadow`] from `built`, the faces the solids drawn kept ([`surfaces_for`] with its shadow
/// cast), one entry for each solid in the order they are built: for Rotate each fill and stroke of
/// each shape, otherwise each part ([`solid_parts`]). A stroke's solid left out of the art (past its
/// own limits) kept no faces. Its Extrude & Bevel solid is built for the shadow alone, as
/// [`cast_shadow`] builds it, and when an Inflate solid of visible art kept no faces the whole
/// shadow is cast as [`cast_shadow`] casts it, since Inflate's solids share one eye.
/// each shape, otherwise each part ([`solid_parts`]). No solid is built here: an entry with no faces
/// (a stroke's solid left out of the art, past its own limits) casts nothing, as it draws nothing.
/// Only `built` of another length than the solids is cast as [`cast_shadow`] casts it.
fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<SolidFaces>>) -> Result<Option<Cast<'a>>, String> {
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
return Ok(None);
}
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
let view = view_options(p);
let mut caster = vectorcraft_three_d::ShadowCaster::new();
let mut cast: Vec<shadow::Cast> = vec![];
let ink = |item: &AppearanceItem, member: f32| {
@@ -1552,42 +1584,25 @@ fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<
}
for ((s, item), kept) in items.into_iter().zip(built) {
let ink = ink(item, s.opacity);
if ink.opacity <= 0.0 {
if !ink.casts() {
continue;
}
let faces = match kept {
Some(kept) => caster.add_solid(kept)?,
None => {
let (area, rule) = region(&s.path, s.rule, item);
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
caster.plane(&area, rule, b, view)?
}
};
cast.push((s.scopes.as_slice(), ink, faces));
let Some(kept) = kept else { continue };
cast.push((s.scopes.as_slice(), ink, caster.add_solid(kept)?));
}
return Ok(Some((caster, settings, cast)));
}
let (parts, bounds) = solid_parts(shapes, b);
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) {
let (parts, _) = solid_parts(shapes, b);
if parts.len() != built.len() {
return cast_shadow(id, p, shapes);
}
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
if ink.opacity <= 0.0 {
continue;
}
let faces = match kept {
Some(kept) => caster.add_solid(kept),
None => {
#[cfg(test)]
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
caster.extrude(area, *rule, bounds, extrude_options(p), view)
}
};
for ((item, member, _, _, scopes, _), kept) in parts.iter().zip(built) {
let ink = ink(item, *member);
// A fully transparent solid, or a stroke's solid left out of the art, casts nothing.
let Some(kept) = kept.filter(|_| ink.casts()) else { continue };
// A stroke whose own solid is past the limits is left out; past the shadow's limit for all
// the solids together, the shadow is refused.
let faces = match faces {
let faces = match caster.add_solid(kept) {
Ok(faces) => faces,
Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue,
Err(e) => return Err(e),
+13
View File
@@ -50,6 +50,19 @@ pub(crate) struct Ink {
pub(crate) blend: BlendMode,
}
impl Ink {
/// Whether art in this ink casts part of a shadow ([`casts`]).
pub(crate) fn casts(self) -> bool {
casts(self.opacity)
}
}
/// Whether art at `opacity` casts part of a shadow: its opacity is a finite number above zero.
/// Art at zero, negative, NaN or infinite opacity casts nothing.
pub(crate) fn casts(opacity: f32) -> bool {
opacity.is_finite() && opacity > 0.0
}
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
/// `None` when it casts nothing.
+7 -1
View File
@@ -1082,7 +1082,8 @@ fn geometry_builds(check: impl FnOnce() -> Result<(), String>) -> (usize, Result
/// The check builds each solid the effect draws once, about the bounds it draws it about: one for
/// a fill and one for each stroke, on an object, on a group's members and on an appearance item,
/// with the shadow on or off.
/// with the shadow on or off. With the shadow on, the shadow is cast from the faces those builds
/// kept, so no solid is built again for it.
#[test]
fn the_check_builds_each_drawn_solid_once() {
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
@@ -1098,6 +1099,11 @@ fn the_check_builds_each_drawn_solid_once() {
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &json!({}), (Some(0), 0))), (1, Ok(())), "{id}: on the fill");
let shadow = json!({"shadow": true});
assert_eq!(geometry_builds(|| validate_solid(&n, id, &shadow)), (2, Ok(())), "{id}: with the shadow on");
let mut other = square_node();
other.id = NodeId(2);
let g = Node::group(NodeId(9999), vec![Arc::new(square_node()), Arc::new(other)]);
assert_eq!(geometry_builds(|| validate_solid(&g, id, &shadow)), (4, Ok(())), "{id}: a group with the shadow on");
assert_eq!(geometry_builds(|| validate_three_d_at(&n, id, &shadow, (Some(0), 0))), (1, Ok(())), "{id}: the fill with the shadow on");
}
}
+122
View File
@@ -312,3 +312,125 @@ fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it()
}
}
}
/// A stroke's solid left out of the art (past its own limits) keeps no faces, and the shadow cast
/// from the faces the solids kept leaves it out without building it: it casts nothing, as it draws
/// nothing, and the fill's solid still casts.
#[test]
fn a_stroke_left_out_of_the_art_casts_no_shadow() {
for id in [EXTRUDE, INFLATE] {
let n = stroked_square(1, 0.0, 1.0);
let (path, rule) = profile(&n).unwrap();
let shapes = [Profile { path, rule, items: solid_paints(&n), opacity: 1.0, scopes: vec![] }];
let p = crate::merged_params(id, &json!({"shadow": true}));
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let mut built: Vec<Option<SolidFaces>> =
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
assert_eq!(cast.len(), 2, "{id}: the fill and the stroke cast");
built[stroke] = None;
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
let (fill, _, cast) = cast_built(id, &p, &shapes, built).unwrap().unwrap();
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get), start, "{id}: no solid is built for the shadow");
assert_eq!(cast.len(), 1, "{id}: the stroke left out casts nothing");
assert!(!fill.is_empty() && fill.len() < both.len(), "{id}: only the fill's faces are cast");
}
}
/// A command accepts each shadowed object that draws with its shadow, and with Rotate builds the
/// plane of each visible fill and stroke once for the shadow: a fully transparent one casts nothing.
#[test]
fn the_check_accepts_the_shadowed_objects_that_draw() {
for id in [EXTRUDE, INFLATE, ROTATE] {
for params in shadow_settings(id) {
for n in shadowed(id, &params) {
let mut drawn = 0;
art(&n, id).unwrap().walk(&mut |c| drawn += usize::from(shadow_opacity(c).is_some()));
assert!(drawn > 0, "{id} {params}");
assert_eq!(validate_solid(&n, id, &params), Ok(()), "{id} {params}");
}
}
}
let shadow = json!({"shadow": true});
for (stroke, planes) in [(1.0, 2), (0.5, 2), (0.0, 1)] {
let n = stroked_square(1, 0.0, stroke);
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
assert_eq!(validate_solid(&n, ROTATE, &shadow), Ok(()), "{stroke}");
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, planes, "Rotate, a stroke at {stroke}");
}
}
/// In wireframe mode no shadow is drawn, so the check casts none: with Shadows on, Rotate builds no
/// plane for a shadow, and Extrude & Bevel and Inflate build each solid once, as with the shadow off.
#[test]
fn the_check_casts_no_shadow_in_wireframe_mode() {
let n = stroked_square(1, 0.0, 1.0);
let wire = json!({"shadow": true, "render": {"mode": "wireframe"}});
for (id, solids) in [(ROTATE, 0), (EXTRUDE, 2), (INFLATE, 2)] {
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
assert_eq!(validate_solid(&n, id, &wire), Ok(()), "{id}");
assert_eq!(SOLIDS_BUILT.with(std::cell::Cell::get) - start, solids, "{id}");
}
}
/// The opacity of each part of the shadow of `n` (its 3D effect's shadow on) and the shadow's art,
/// as [`cast_shadow`] casts it from solids built for the shadow alone and as [`cast_built`] casts
/// it from the faces the solids drawn kept.
fn cast_parts(n: &Node) -> [(Vec<f32>, String); 2] {
let (_, fx) = solid(&n.appearance.effects).unwrap();
let shapes = if is_container(n) {
members(n, "").unwrap()
} else {
let (path, rule) = profile(n).unwrap();
vec![Profile { path, rule, items: solid_paint_sources(n).1, opacity: 1.0, scopes: vec![] }]
};
let p = crate::merged_params(&fx.id, &fx.params);
let (_, built) = surfaces_for(None, n, fx, &shapes, true).unwrap();
[cast_shadow(&fx.id, &p, &shapes), cast_built(&fx.id, &p, &shapes, built)].map(|c| {
let (caster, settings, cast) = c.unwrap().unwrap();
let inks = cast.iter().map(|(_, ink, _)| ink.opacity).collect();
(inks, format!("{:?}", shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes))))
})
}
/// A fill, a stroke or a member whose opacity is NaN or infinite casts no part of the shadow, as one
/// at 0 % does, whether the shadow is cast from solids built for it or from the solids drawn; the
/// art beside it still casts its part.
#[test]
fn art_whose_opacity_is_not_a_finite_number_casts_no_shadow() {
// The art with opacity `opacity` in one place: a square's stroke, the fill of a group's second
// member, and a group's second member.
let objects = |opacity: f32| {
let mut fill = square_node(2, 200.0);
for item in &mut fill.appearance.items {
if let AppearanceItem::Fill(f) = item {
f.opacity = opacity;
}
}
let mut member = square_node(2, 200.0);
member.opacity = opacity;
[
stroked_square(1, 0.0, opacity),
Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(fill)]),
Node::group(NodeId(9), vec![Arc::new(square_node(1, 0.0)), Arc::new(member)]),
]
};
for id in [EXTRUDE, INFLATE, ROTATE] {
for bad in [f32::NAN, f32::INFINITY] {
for (i, (mut n, mut clear)) in objects(bad).into_iter().zip(objects(0.0)).enumerate() {
n.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap());
clear.appearance.effects.push(crate::new_effect(id, &json!({"shadow": true})).unwrap());
let expected = cast_parts(&clear);
for (k, (inks, shadow)) in cast_parts(&n).into_iter().enumerate() {
assert_eq!(inks, vec![1.0], "{id} {bad} object {i} cast {k}: only the opaque art casts");
assert_eq!(shadow, expected[k].1, "{id} {bad} object {i} cast {k}");
}
let mut opacities = vec![];
art(&n, id).unwrap().walk(&mut |c| opacities.extend(shadow_opacity(c)));
assert_eq!(opacities, vec![0.5], "{id} {bad} object {i}");
}
}
}
}
+1 -1
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 edges counted as drawing with stroke paint match whatever they draw with, such as the edge a double-click's first click painted), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
+11 -1
View File
@@ -567,6 +567,16 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
let through: Vec<NodeId> = match p.get("through") {
None => vec![],
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
Some(v) => {
let ids = v.as_array().filter(|ids| ids.len() <= 4096).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids"))?;
ids.iter()
.map(|id| id.as_u64().map(NodeId).ok_or_else(|| bad(C, "through must be an array of at most 4096 edge ids")))
.collect::<Result<_>>()?
}
};
let (eid, count, changed) = {
let d = &s.doc()?.doc;
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
@@ -575,7 +585,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
let targets = match scope {
LpScope::One => vec![eid],
LpScope::Connected => b::connected_edges(n, eid, &like),
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
LpScope::SamePaint => std::iter::once(eid)
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
.collect(),
+6
View File
@@ -54,6 +54,7 @@ pub mod ppi;
pub mod progress;
mod psdlayers;
pub mod psdread;
mod psdslices;
mod pxrread;
mod save;
mod screens;
@@ -93,6 +94,9 @@ pub(crate) use native::preview_png;
pub use native::with_compression_pref;
pub(crate) use pdfimport::opened_page_document;
pub use pdfimport::{LoadOptions, page_document};
pub(crate) use psdlayers::import_active as psd_layers;
pub use psdlayers::{PsdInfo, info as psd_info};
pub(crate) use psdslices::over as psd_slices;
pub(crate) use save::job_for;
pub(crate) use save::save as save_document;
pub use save::{
@@ -240,6 +244,8 @@ mod tests_psd;
mod tests_psdlayers;
#[cfg(test)]
mod tests_psdread;
#[cfg(test)]
mod tests_psdslices;
#[cfg(test)]
mod tests_heifread;
File diff suppressed because one or more lines are too long
+17 -8
View File
@@ -528,17 +528,26 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
}
// A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with
// `layers: false`, its merged image opens. Layers that can't be read leave the merged image.
"psd" | "psb" if opts.layers => {
let cms = vectorcraft_color::cms::active();
match super::psdlayers::import(bytes, opts.hidden_layers, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)) {
Ok(Some((doc, warnings))) => (doc, warnings, false),
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
}
}
"psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) {
Ok(Some((doc, warnings))) => (doc, warnings, false),
Ok(None) => (raster_doc(&title, bytes)?, vec![], false),
Err(e) => (raster_doc(&title, bytes)?, vec![format!("the layers can't be read ({e}): the file opened as its merged image")], false),
},
_ if format.raster => (raster_doc(&title, bytes)?, vec![], false),
_ => return Err(err(format!("{} files can't be opened yet", format.label))),
};
// A PSD or PSB file's slices become user slices over its canvas (`importSlices`, default on),
// whether its layers or its merged image came in.
if matches!(format.id, "psd" | "psb")
&& opts.import_slices
&& let Some(canvas) = doc.artboards.first().map(|a| a.rect)
{
let (slices, notes) = super::psd_slices(bytes, canvas);
for (rect, options) in slices {
crate::cmd::slices::add_slice(&mut doc, rect, options);
}
warnings.extend(notes);
}
// A PDF, `.ai` or `.ait` read from its pages or its editing copy, not restored from the document
// it carries, opens with the File Info it gives (a PostScript `.ai` gives none).
if matches!(format.id, "pdf" | "ai" | "ait")
+9 -1
View File
@@ -36,6 +36,8 @@ pub struct LoadOptions {
pub layers: bool,
/// A PSD or PSB file's hidden layers come in, hidden (`hiddenLayers`; else they are left out).
pub hidden_layers: bool,
/// A PSD or PSB file's slices become user slices (`importSlices`; else they are left out).
pub import_slices: bool,
/// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]).
pub dxf: vectorcraft_cad::ImportOptions,
/// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its
@@ -67,6 +69,7 @@ impl Default for LoadOptions {
text_as: TextAs::default(),
layers: true,
hidden_layers: false,
import_slices: true,
dxf: Default::default(),
editing_data: true,
trust_editing_data: false,
@@ -81,7 +84,7 @@ impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
/// `editingData` (true | false | `always`),
/// `importSlices` (true | false), `editingData` (true | false | `always`),
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
/// false) and `dxf` (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
@@ -111,6 +114,10 @@ impl LoadOptions {
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "hiddenLayers must be true or false"))?,
};
let import_slices = match p.get("importSlices").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "importSlices must be true or false"))?,
};
let (editing_data, trust_editing_data) = match p.get("editingData").filter(|v| !v.is_null()) {
None => (true, false),
Some(Value::String(s)) if s.eq_ignore_ascii_case("always") => (true, true),
@@ -137,6 +144,7 @@ impl LoadOptions {
text_as,
layers,
hidden_layers,
import_slices,
dxf,
editing_data,
trust_editing_data,
+64
View File
@@ -43,6 +43,7 @@ use std::cell::Cell;
use std::sync::Arc;
use image::RgbaImage;
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
use vectorcraft_color::blend::{blend_rgb, composite};
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
@@ -51,6 +52,7 @@ use vectorcraft_geom::Affine;
use super::load::{RasterImage, as_png};
use super::psdread::{Header, Reader, byte, header, layer_channel, layer_info, long_key, row_bytes, sample, to_rgb};
use crate::cmd::Session;
use crate::cmd::place::text::mac_roman;
/// Most layer groups inside one another.
@@ -1527,3 +1529,65 @@ pub(super) fn import(
doc.limit_depth_noting(&mut warnings);
Ok(Some((doc, warnings)))
}
/// [`import`] within the memory allowed for one image, CMYK converted with the active color
/// settings: what `document.open` and `file.place` read a PSD or PSB file's layers with.
pub(crate) fn import_active(bytes: &[u8], hidden: bool) -> Result<Option<(Document, Vec<String>)>, String> {
let cms = vectorcraft_color::cms::active();
import(bytes, hidden, super::MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false))
}
/// What a PSD or PSB file holds (`document.psdInfo`, the PSD Import Options dialog).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PsdInfo {
/// The large document format.
pub psb: bool,
/// The canvas, in pixels.
pub width: u32,
pub height: u32,
/// The layers, group markers left out.
pub layers: usize,
/// The layers among them that are hidden.
pub hidden: usize,
/// The layer groups.
pub groups: usize,
/// The slices that come in with `importSlices` (those generated automatically, and those
/// outside the canvas, left out).
pub slices: usize,
}
/// What PSD or PSB file `bytes` holds, read from its header, its slices and its layer records
/// without decoding any pixels. A file without layer records, or whose layer records can't be read, has no layers: it
/// opens and places as its merged image.
pub fn info(bytes: &[u8]) -> Result<PsdInfo, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let records = layer_info(h.layers, h.psb).filter(|info| info.len() > 2).and_then(|info| records(info, h.psb).ok()).unwrap_or_default();
let layers = records.iter().filter(|r| r.divider == 0);
Ok(PsdInfo {
psb: h.psb,
width: h.width,
height: h.height,
layers: layers.clone().count(),
hidden: layers.filter(|r| r.hidden).count(),
groups: records.iter().filter(|r| matches!(r.divider, 1 | 2)).count(),
slices: super::psdslices::count(bytes),
})
}
const INFO: &str = "document.psdInfo";
/// `document.psdInfo`.
pub(super) fn psd_info(_: &mut Session, p: &Value) -> crate::cmd::Result<Value> {
let bytes = super::source(p, INFO)?.bytes;
let i = info(&bytes).map_err(super::load::err)?;
Ok(json!({
"format": if i.psb { "psb" } else { "psd" },
"width": i.width,
"height": i.height,
"layers": i.layers,
"hiddenLayers": i.hidden,
"groups": i.groups,
"slices": i.slices,
}))
}
+2 -2
View File
@@ -105,7 +105,7 @@ pub(super) struct Header<'a> {
/// Colour mode data: an indexed image's palette (256 reds, then greens, then blues).
palette: &'a [u8],
/// The image resources.
resources: &'a [u8],
pub(super) resources: &'a [u8],
/// The layer and mask information.
pub(super) layers: &'a [u8],
}
@@ -172,7 +172,7 @@ pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
/// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its
/// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the
/// blocks whose signature is `8BIM` are given.
fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
pub(super) fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
let mut r = Reader::new(resources);
std::iter::from_fn(move || {
if r.rest().is_empty() {
+408
View File
@@ -0,0 +1,408 @@
//! The slices a Photoshop document (PSD or PSB) stores, for `document.open` and `file.place`
//! with `importSlices`: image resource 1050, read from the "Slices resource format" of Adobe's
//! public Photoshop File Formats Specification
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). Version 6 stores the slices
//! as records; versions 7 and 8 store them in a descriptor. The descriptor's keys, and the meaning
//! of the origin, type and background values, are read as the MIT-licensed ag-psd reads them
//! (<https://github.com/Agamnentzar/ag-psd>, `src/imageResources.ts` and `src/descriptor.ts`),
//! which agrees with psd.rb (<https://github.com/layervault/psd.rb>,
//! `lib/psd/resources/slices.rb`) on the keys both read.
//!
//! A slice the file marks as generated automatically is left out: the document lays out its own
//! auto slices around the others. A slice that follows a layer comes in as a user slice over the
//! rectangle the file stores for it. Each slice keeps its name, its type (Image or No Image), its
//! link, target, message, alternative text, cell text and background color; text alignment isn't
//! read. The file is untrusted: every read is checked, and the slice count, the strings and the
//! descriptor's nesting and item count are capped.
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use super::psdread::{Reader, TRUNCATED, header, resources};
/// The image resource that holds the slices.
const SLICES: u16 = 1050;
/// The most slices one file brings in.
const MAX_SLICES: usize = 10_000;
/// The deepest descriptor objects and lists nest.
const MAX_DEPTH: usize = 16;
/// The most values the descriptors of one slices resource hold together, nested ones included.
const MAX_VALUES: usize = 200_000;
/// The error of descriptors that hold more than [`MAX_VALUES`].
const TOO_MANY_VALUES: &str = "the slices' descriptor holds too many values";
/// One slice as the file stores it.
#[derive(Clone, Debug, PartialEq)]
struct PsdSlice {
/// Left, top, right and bottom, in the canvas's pixels.
rect: [i64; 4],
options: SliceOptions,
}
/// The slices a file stores, those generated automatically left out, and its canvas.
struct Stored {
slices: Vec<PsdSlice>,
/// The canvas's width and height, in pixels.
size: (u32, u32),
}
/// The slices PSD or PSB file `bytes` stores. `None` when it stores none (no `8BIM` resource 1050
/// before the image resources end or are cut short). An error when the file isn't a PSD or PSB
/// file, or its slices can't be read.
fn read(bytes: &[u8]) -> Result<Option<Stored>, String> {
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
let Some((_, _, data)) = resources(h.resources, true).find(|(id, _, _)| *id == SLICES) else { return Ok(None) };
Ok(Some(Stored { slices: decode(data)?, size: (h.width, h.height) }))
}
/// The slices of resource 1050's `data`.
fn decode(data: &[u8]) -> Result<Vec<PsdSlice>, String> {
let mut r = Reader::new(data);
// The values every descriptor of the resource may hold together.
let mut budget = MAX_VALUES;
match r.u32()? {
6 => version_6(&mut r, &mut budget),
7 | 8 => {
if r.u32()? != 16 {
return Err("the slices' descriptor has a version other than 16".into());
}
let d = descriptor(&mut r, 0, &mut budget)?;
from_descriptor(&d)
}
v => Err(format!("the slices are stored in version {v}, which isn't read")),
}
}
/// Version 6: the bounds of all the slices, the group's name, the count, then each slice's record.
/// The descriptors that follow the records spend one `budget` of values between them.
fn version_6(r: &mut Reader<'_>, budget: &mut usize) -> Result<Vec<PsdSlice>, String> {
r.take(16)?;
unicode(r)?;
let count = r.u32()? as usize;
if count > MAX_SLICES {
return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read"));
}
let mut out = vec![];
for _ in 0..count {
// The ID and group ID.
r.take(8)?;
let origin = r.u32()?;
// A slice that follows a layer gives the layer's ID.
if origin == 1 {
r.take(4)?;
}
let name = unicode(r)?;
let kind = if r.u32()? == 0 { SliceKind::NoImage } else { SliceKind::Image };
let mut rect = [0i64; 4];
for v in &mut rect {
*v = i64::from(r.u32()? as i32);
}
let (url, target, message, alt) = (unicode(r)?, unicode(r)?, unicode(r)?, unicode(r)?);
let html = r.u8()? != 0;
let cell = unicode(r)?;
// The horizontal and vertical alignment.
r.take(8)?;
let [a, red, green, blue] = r.array::<4>()?;
let background = if a == 0 && red == 0 && green == 0 && blue == 0 {
String::new()
} else if a == 0 {
"matte".into()
} else {
format!("#{red:02x}{green:02x}{blue:02x}")
};
// Photoshop 7 and later may follow a record with a descriptor (version 16); a record that
// doesn't start one is the next slice. A descriptor read that uses up the budget is an
// error.
if r.rest().starts_with(&16u32.to_be_bytes()) {
let mut ahead = Reader::new(r.rest());
ahead.u32()?;
match descriptor(&mut ahead, 0, budget) {
Ok(_) => {
let used = r.rest().len() - ahead.rest().len();
r.take(used)?;
}
Err(e) if e == TOO_MANY_VALUES => return Err(e),
Err(_) => {}
}
}
// Origin 0 is a slice generated automatically.
if origin != 0 {
let options = SliceOptions { kind, name, url, target, message, alt, text: cell_text(cell, html), background, ..Default::default() };
out.push(PsdSlice { rect, options: for_kind(options) });
}
}
Ok(out)
}
/// Versions 7 and 8: the descriptor's `slices` list, each slice an object.
fn from_descriptor(d: &[(String, Value)]) -> Result<Vec<PsdSlice>, String> {
let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) };
if list.len() > MAX_SLICES {
return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len()));
}
let mut out = vec![];
for s in list {
let Value::Object(s) = s else { return Err("the slices' descriptor lists something other than a slice".into()) };
if matches!(field(s, "origin"), Some(Value::Enum(_, v)) if v == "autoGenerated") {
continue;
}
let Some(Value::Object(b)) = field(s, "bounds") else { return Err("a slice in the slices' descriptor has no bounds".into()) };
let edge = |k: &str| number(field(b, k)).ok_or_else(|| "a slice's bounds in the slices' descriptor aren't numbers".to_string());
let rect = [edge("Left")?, edge("Top ")?, edge("Rght")?, edge("Btom")?];
let text = |k: &str| match field(s, k) {
Some(Value::Text(t)) => t.clone(),
_ => String::new(),
};
let kind = if matches!(field(s, "Type"), Some(Value::Enum(_, v)) if v == "noImage") { SliceKind::NoImage } else { SliceKind::Image };
let html = matches!(field(s, "cellTextIsHTML"), Some(Value::Bool(true)));
let background = match field(s, "bgColorType") {
Some(Value::Enum(_, v)) if v == "matte" => "matte".into(),
Some(Value::Enum(_, v)) if v == "Clr " => match field(s, "bgColor") {
Some(Value::Object(c)) => {
let channel = |k: &str| number(field(c, k)).map(|v| v.clamp(0, 255));
match (channel("Rd "), channel("Grn "), channel("Bl ")) {
(Some(r), Some(g), Some(b)) => format!("#{r:02x}{g:02x}{b:02x}"),
_ => String::new(),
}
}
_ => String::new(),
},
_ => String::new(),
};
let options = SliceOptions {
kind,
name: text("Nm "),
url: text("url"),
target: text("null"),
message: text("Msge"),
alt: text("altTag"),
text: cell_text(text("cellText"), html),
background,
..Default::default()
};
out.push(PsdSlice { rect, options: for_kind(options) });
}
Ok(out)
}
/// `o` with only the options of its slice type: an Image slice's cell text isn't shown, and a No
/// Image slice has no link, target, message or alternative text.
fn for_kind(mut o: SliceOptions) -> SliceOptions {
if o.kind == SliceKind::Image {
o.text.clear();
} else {
for s in [&mut o.url, &mut o.target, &mut o.message, &mut o.alt] {
s.clear();
}
}
o
}
/// A cell's text as the HTML a No Image slice shows: plain text has `&`, `<` and `>` escaped.
fn cell_text(text: String, html: bool) -> String {
if html { text } else { text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;") }
}
/// The longest text one string, key or class ID holds (UTF-16 units or bytes).
const MAX_TEXT: usize = 65_536;
/// An error unless `n`, the length a string or ID declares, is at most [`MAX_TEXT`].
fn text_len(n: usize) -> Result<usize, String> {
if n > MAX_TEXT {
return Err(format!("a text in the slices has more than the {MAX_TEXT} characters read"));
}
Ok(n)
}
/// A Unicode string: a count of UTF-16 units, then the units; trailing NULs dropped.
fn unicode(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let bytes = r.take(n.checked_mul(2).ok_or(TRUNCATED)?)?;
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|u| u16::from_be_bytes(*u)).collect();
Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string())
}
/// A descriptor's value, as far as the slices need it.
#[derive(Clone, Debug, PartialEq)]
enum Value {
Long(i32),
Double(f64),
Bool(bool),
Text(String),
/// An enumeration's type and value.
Enum(String, String),
Object(Vec<(String, Value)>),
List(Vec<Value>),
/// A value of another type, read past.
Other,
}
/// The value with key `key`.
fn field<'a>(d: &'a [(String, Value)], key: &str) -> Option<&'a Value> {
d.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
/// A whole number: a long, or a finite double rounded.
fn number(v: Option<&Value>) -> Option<i64> {
match v? {
Value::Long(n) => Some(i64::from(*n)),
Value::Double(d) if d.is_finite() && d.abs() < 1e12 => Some(d.round() as i64),
_ => None,
}
}
/// A key or class ID: a length, then that many characters, or four when the length is 0.
fn id(r: &mut Reader<'_>) -> Result<String, String> {
let n = text_len(r.u32()? as usize)?;
let b = r.take(if n == 0 { 4 } else { n })?;
Ok(String::from_utf8_lossy(b).into_owned())
}
/// A class: its Unicode name, then its ID.
fn class(r: &mut Reader<'_>) -> Result<(), String> {
unicode(r)?;
id(r)?;
Ok(())
}
/// A descriptor: its class, the count of its items, then each item's key, type and value.
fn descriptor(r: &mut Reader<'_>, depth: usize, budget: &mut usize) -> Result<Vec<(String, Value)>, String> {
if depth > MAX_DEPTH {
return Err("the slices' descriptor nests too deep".into());
}
class(r)?;
let count = r.u32()? as usize;
let mut out = vec![];
for _ in 0..count {
let key = id(r)?;
let kind = r.array::<4>()?;
out.push((key, value(r, &kind, depth, budget)?));
}
Ok(out)
}
/// A value of type `kind`.
fn value(r: &mut Reader<'_>, kind: &[u8; 4], depth: usize, budget: &mut usize) -> Result<Value, String> {
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
Ok(match kind {
b"long" => Value::Long(r.u32()? as i32),
b"doub" => Value::Double(f64::from_be_bytes(r.array()?)),
b"UntF" => {
r.take(4)?;
Value::Double(f64::from_be_bytes(r.array()?))
}
b"UnFl" => {
r.take(4)?;
Value::Double(f64::from(f32::from_be_bytes(r.array()?)))
}
b"bool" => Value::Bool(r.u8()? != 0),
b"TEXT" => Value::Text(unicode(r)?),
b"enum" => Value::Enum(id(r)?, id(r)?),
b"Objc" | b"GlbO" => Value::Object(descriptor(r, depth + 1, budget)?),
b"VlLs" => {
if depth >= MAX_DEPTH {
return Err("the slices' descriptor nests too deep".into());
}
let count = r.u32()? as usize;
let mut items = vec![];
for _ in 0..count {
let kind = r.array::<4>()?;
items.push(value(r, &kind, depth + 1, budget)?);
}
Value::List(items)
}
b"comp" => {
r.take(8)?;
Value::Other
}
b"type" | b"GlbC" => {
class(r)?;
Value::Other
}
b"tdta" | b"alis" => {
let n = r.u32()? as usize;
r.take(n)?;
Value::Other
}
b"obj " => {
let count = r.u32()? as usize;
for _ in 0..count {
*budget = budget.checked_sub(1).ok_or(TOO_MANY_VALUES)?;
match &r.array::<4>()? {
b"prop" => {
class(r)?;
id(r)?;
}
b"Clss" => class(r)?,
b"Enmr" => {
class(r)?;
id(r)?;
id(r)?;
}
b"rele" => {
class(r)?;
r.take(4)?;
}
b"Idnt" | b"indx" => {
r.take(4)?;
}
b"name" => {
class(r)?;
unicode(r)?;
}
k => return Err(format!("the slices' descriptor has a reference of an unknown kind ({})", String::from_utf8_lossy(k))),
}
}
Value::Other
}
k => return Err(format!("the slices' descriptor has a value of an unknown type ({})", String::from_utf8_lossy(k))),
})
}
/// The slices of PSD or PSB file `bytes` laid over `canvas`, the box its canvas takes (points),
/// each clipped to the canvas, with warnings: for slices that lie wholly outside it or have no
/// size, and for slices that can't be read (the file comes in without them). Empty, without a
/// warning, when the file stores no slices.
pub(crate) fn over(bytes: &[u8], canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
match read(bytes) {
Ok(None) => (vec![], vec![]),
Ok(Some(s)) => laid_over(&s.slices, s.size, canvas),
Err(e) => (vec![], vec![format!("the slices can't be read ({e}) and were left out")]),
}
}
/// `slices` of a canvas of `size` pixels laid over `canvas` (points).
fn laid_over(slices: &[PsdSlice], (w, h): (u32, u32), canvas: Rect) -> (Vec<(Rect, SliceOptions)>, Vec<String>) {
let (sx, sy) = (canvas.width() / f64::from(w.max(1)), canvas.height() / f64::from(h.max(1)));
let mut out = vec![];
for s in slices {
let [l, t, r, b] = s.rect;
let (l, r) = (l.clamp(0, i64::from(w)), r.clamp(0, i64::from(w)));
let (t, b) = (t.clamp(0, i64::from(h)), b.clamp(0, i64::from(h)));
if l < r && t < b {
let x = |v: i64| canvas.x0 + v as f64 * sx;
let y = |v: i64| canvas.y0 + v as f64 * sy;
out.push((Rect::new(x(l), y(t), x(r), y(b)), s.options.clone()));
}
}
let warnings = match slices.len() - out.len() {
0 => vec![],
1 => vec!["1 slice lies outside the canvas or has no size and was left out".to_string()],
n => vec![format!("{n} slices lie outside the canvas or have no size and were left out")],
};
(out, warnings)
}
/// How many slices of PSD or PSB file `bytes` come in (`document.psdInfo`): 0 when it stores none
/// or they can't be read.
pub(crate) fn count(bytes: &[u8]) -> usize {
match read(bytes) {
Ok(Some(Stored { slices, size: (w, h) })) => laid_over(&slices, (w, h), Rect::new(0.0, 0.0, f64::from(w), f64::from(h))).0.len(),
_ => 0,
}
}
+187 -1
View File
@@ -1,7 +1,8 @@
//! Opening PSD and PSB files with their layers as layers (`document.open`'s `layers` and
//! `hiddenLayers`): names, visibility, opacity, blend modes, groups, layer masks, clipped layers
//! and blend modes VectorCraft lacks merged, 16-bit and PSB files, VectorCraft's own PSD export
//! read back, and damaged files read without a panic.
//! read back, and damaged files read without a panic. Placing them with their layers as objects
//! (`file.place`'s `layers` and `hiddenLayers`), and `document.psdInfo`.
use serde_json::{Value, json};
use vectorcraft_color::BlendMode;
@@ -967,10 +968,12 @@ fn damaged_layers_never_panic() {
let mut f = good.clone();
f[i] = v;
let _ = psdlayers::import(&f, true, 1 << 30, cms);
let _ = psdlayers::info(&f);
}
}
for n in 0..good.len() {
let _ = psdlayers::import(&good[..n], true, 1 << 30, cms);
let _ = psdlayers::info(&good[..n]);
}
// A layer past the memory allowed is refused, not read.
assert!(psdlayers::import(&good, true, 64, cms).unwrap_err().contains("too large"));
@@ -1015,3 +1018,186 @@ fn merges_keep_pass_through_groups_blending_with_what_is_below() {
assert!(px.iter().zip([75, 150, 38, 255]).all(|(&a, b)| a.abs_diff(b) <= 1), "{px:?}");
}
}
/// `file.place` of `f` with `p` into a new 100 × 100 pt document, centred on (50, 50).
fn place(f: &[u8], p: Value) -> (Session, crate::cmd::Result<Value>) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &merge(json!({"name": "layers.psd", "dataBase64": vectorcraft_format::base64_encode(f), "at": [50, 50]}), p));
(s, r)
}
/// The one object `file.place` placed.
fn placed(s: &Session, r: &Value) -> Node {
let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap());
s.doc().unwrap().doc.node(id).unwrap().clone()
}
#[test]
fn placing_with_layers_embeds_the_layers_as_one_group() {
let f = file(8, 8, &stack(), 8, false, false);
let (mut s, r) = place(&f, json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["format"], &r["linked"], &r["warnings"]), (&json!("psd"), &json!(false), &json!([HIDDEN_1])), "{r}");
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "one group, unclipped: its layers lie on the canvas");
assert_eq!(name(&g), "layers.psd");
let kids = g.children().unwrap();
assert_eq!(kids.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Folder", "Screens", "Faded"], "bottom first");
// A layer is its image, where the merged image would put it: the 8 pt canvas centred on (50, 50).
let ((x, y), px) = pixels_of(&s, &kids[0]);
assert_eq!(((x, y), px.dimensions(), px.get_pixel(3, 3).0), ((46.0, 46.0), (8, 8), [255, 0, 0, 255]));
// A group is a group of its layers; a pass-through group isn't isolated, another mode's is.
let folder = &kids[1];
assert!(matches!(folder.kind, NodeKind::Group { .. }) && !folder.isolate && folder.blend == BlendMode::Normal);
let inner = folder.children().unwrap();
assert_eq!(inner.iter().map(|c| name(c)).collect::<Vec<_>>(), ["Inner A"], "the hidden layer is left out");
assert!(matches!(inner[0].kind, NodeKind::Image(_)) && inner[0].blend == BlendMode::Multiply && (inner[0].opacity - 128.0 / 255.0).abs() < 1e-6);
let screens = &kids[2];
assert!(screens.isolate && screens.blend == BlendMode::Screen);
let ((x, y), px) = pixels_of(&s, &screens.children().unwrap()[0]);
assert_eq!(((x, y), px.get_pixel(0, 0).0), ((48.0, 48.0), [10, 20, 30, 128]));
assert!((kids[3].opacity - 102.0 / 255.0).abs() < 1e-6, "fill opacity: {}", kids[3].opacity);
// One undo step.
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)));
// Hidden layers come in hidden when asked for.
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
let r = r.unwrap();
assert_eq!(r["warnings"], json!([]), "{r}");
let g = placed(&s, &r);
let inner: Vec<(&str, bool)> = g.children().unwrap()[1].children().unwrap().iter().map(|c| (name(c), c.visible)).collect();
assert_eq!(inner, [("Inner A", true), ("Inner B", false)]);
// Without `layers`, the merged image, in the same box.
let (s, r) = place(&f, json!({}));
let r = r.unwrap();
let flat = placed(&s, &r);
let ((x, y), px) = pixels_of(&s, &flat);
assert_eq!(((x, y), px.dimensions(), px.get_pixel(0, 0).0), ((46.0, 46.0), (8, 8), [128, 128, 128, 255]), "{r}");
}
#[test]
fn placed_layers_keep_their_masks_and_are_clipped_to_the_canvas() {
let mut masked = layer("Masked", [0, 0, 8, 8], [255, 255, 255, 255]);
masked.mask = Some(([2, 2, 4, 4], 0, 0, vec![255, 128, 0, 255]));
let (s, r) = place(&file(8, 8, &[masked], 8, false, false), json!({"layers": true}));
let g = placed(&s, &r.unwrap());
let kids = g.children().unwrap();
assert!(matches!(kids[0].kind, NodeKind::Image(_)), "the layer is its image");
let m = kids[0].extras().mask.as_deref().expect("the layer mask as the image's opacity mask");
let ((x, y), px) = pixels_of(&s, &m.art);
assert_eq!(((x, y), px.dimensions(), m.clip), ((48.0, 48.0), (2, 2), true), "the mask moves with its layer");
// A layer that reaches past the canvas: the group is clipped to the canvas, as the merged
// image shows only the canvas.
let over = layer("Over", [-2, -2, 6, 6], [0, 255, 0, 255]);
let (s, r) = place(&file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), over], 8, false, false), json!({"layers": true}));
let r = r.unwrap();
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
let kids = g.children().unwrap();
let b = kids[0].geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap();
assert!(matches!(kids[0].kind, NodeKind::Path { clipping: true, .. }));
assert_eq!((b.x0, b.y0, b.x1, b.y1), (46.0, 46.0, 54.0, 54.0), "the clipping path is the canvas");
assert_eq!(kids[1..].iter().map(|c| name(c)).collect::<Vec<_>>(), ["Bottom", "Over"]);
assert_eq!(pixels_of(&s, &kids[2]).0, (44.0, 44.0));
// A hidden layer that reaches past the canvas clips the group too, so showing it later draws
// only the canvas. Left out, it doesn't.
let mut hidden = layer("Hidden", [-2, -2, 6, 6], [0, 255, 0, 255]);
hidden.hidden = true;
let f = file(8, 8, &[layer("Bottom", [0, 0, 8, 8], [255, 0, 0, 255]), hidden], 8, false, false);
let (s, r) = place(&f, json!({"layers": true, "hiddenLayers": true}));
let r = r.unwrap();
let g = placed(&s, &r);
assert!(matches!(g.kind, NodeKind::Group { clip: true, .. }), "{r}");
assert_eq!(g.children().unwrap()[1..].iter().map(|c| (name(c), c.visible)).collect::<Vec<_>>(), [("Bottom", true), ("Hidden", false)]);
let (s, r) = place(&f, json!({"layers": true}));
assert!(matches!(placed(&s, &r.unwrap()).kind, NodeKind::Group { clip: false, .. }));
}
#[test]
fn placing_with_layers_never_links_and_refuses_values_it_cant_use() {
let f = file(8, 8, &stack(), 8, false, false);
let dir = std::env::temp_dir().join(format!("vc-psd-place-layers-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("layers.psd");
std::fs::write(&path, &f).unwrap();
let from_path = |p: Value| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &merge(json!({"path": path.to_str().unwrap()}), p));
(s, r)
};
// From a path, `layers` embeds: `link` is then false unless given, and `link: true` is refused.
let (s, r) = from_path(json!({"layers": true}));
let r = r.unwrap();
assert_eq!(r["linked"], json!(false), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Group { .. }));
let (s, r) = from_path(json!({"layers": true, "link": true}));
assert!(r.unwrap_err().to_string().contains("a linked PSD file is placed as its flat image"));
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "nothing is placed");
// Without `layers` the file is linked as before.
let (s, r) = from_path(json!({}));
let r = r.unwrap();
assert_eq!(r["linked"], json!(true), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// A file without layers is embedded as its merged image, without a warning.
let flat = {
let mut f = file(2, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 8, false, false);
let at = 26 + 8;
let len = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) as usize;
f.splice(at..at + 4 + len, 0u32.to_be_bytes());
f
};
std::fs::write(&path, &flat).unwrap();
let (s, r) = from_path(json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["linked"], &r["warnings"]), (&json!(false), &json!([])), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Layers that are all left out: the merged image, with the importer's warnings.
let mut gone = layer("Gone", [0, 0, 2, 2], [9, 9, 9, 255]);
gone.hidden = true;
let (s, r) = place(&file(2, 2, &[gone], 8, false, false), json!({"layers": true}));
let r = r.unwrap();
assert_eq!((&r["linked"], r["warnings"].as_array().map(Vec::len)), (&json!(false), Some(1)), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Layers that can't be read: the merged image, with a warning.
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
let (s, r) = place(&cut, json!({"layers": true}));
let r = r.unwrap();
assert!(r["warnings"][0].as_str().unwrap().starts_with("the layers can't be read"), "{r}");
assert!(matches!(placed(&s, &r).kind, NodeKind::Image(_)));
// Values the command can't use are errors, and nothing is placed.
for (p, why) in [
(json!({"hiddenLayers": true}), "hiddenLayers applies to a PSD file placed with layers: true"),
(json!({"layers": true, "link": true}), "a linked PSD file is placed as its flat image"),
(json!({"layers": "yes"}), "layers must be true or false"),
(json!({"layers": true, "hiddenLayers": 1}), "hiddenLayers must be true or false"),
] {
let (s, r) = place(&f, p.clone());
assert!(r.unwrap_err().to_string().contains(why), "{p}");
assert!(s.doc().unwrap().doc.layers.iter().all(|l| l.children().is_none_or(Vec::is_empty)), "{p}");
}
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let q = s.execute("file.place.queue", &json!({"paths": [path.to_str().unwrap()], "layers": "yes"}));
assert!(q.unwrap_err().to_string().contains("`layers` must be true or false"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn psd_info_counts_the_layers_without_opening_the_file() {
let mut s = Session::new();
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": vectorcraft_format::base64_encode(f)}));
let r = info(&mut s, &file(8, 8, &stack(), 8, false, false)).unwrap();
assert_eq!(r, json!({"format": "psd", "width": 8, "height": 8, "layers": 5, "hiddenLayers": 1, "groups": 2, "slices": 0}));
let r = info(&mut s, &file(4, 2, &[layer("x", [0, 0, 2, 2], [9, 9, 9, 255])], 16, true, true)).unwrap();
assert_eq!((&r["format"], &r["width"], &r["height"], &r["layers"]), (&json!("psb"), &json!(4), &json!(2), &json!(1)), "{r}");
// Layer records that can't be read count as no layers: the file opens as its merged image.
let mut cut = file(4, 4, &[layer("x", [0, 0, 4, 4], [9, 9, 9, 255])], 8, false, false);
let at = cut.windows(4).position(|w| w == [0, 0, 0, 18]).unwrap();
cut[at..at + 4].copy_from_slice(&1000u32.to_be_bytes());
assert_eq!(info(&mut s, &cut).unwrap()["layers"], json!(0));
assert!(info(&mut s, b"not a psd").unwrap_err().to_string().contains("not a PSD file"));
}
@@ -0,0 +1,459 @@
//! A PSD or PSB file's slices (image resource 1050) opened and placed as user slices
//! (`document.open`'s and `file.place`'s `importSlices`): version 6 records and version 7 and 8
//! descriptors, built from the Photoshop File Formats Specification's "Slices resource format";
//! their options, slices outside the canvas, damaged or unknown slice data, placing scaled and
//! moved in one undo step, linked files, and `document.psdInfo`'s count.
use serde_json::{Value, json};
use vectorcraft_doc::{SliceKind, SliceOptions};
use vectorcraft_geom::Rect;
use crate::Session;
/// A Unicode string: a count of UTF-16 units, then the units.
fn ustr(s: &str) -> Vec<u8> {
let units: Vec<u16> = s.encode_utf16().collect();
let mut b = (units.len() as u32).to_be_bytes().to_vec();
b.extend(units.iter().flat_map(|u| u.to_be_bytes()));
b
}
/// One version 6 slice record.
#[derive(Clone)]
struct S {
/// 0: generated automatically, 1: follows a layer, 2: made by the user.
origin: u32,
name: &'static str,
/// 0: No Image, 1: Image.
kind: u32,
/// Left, top, right, bottom (px).
rect: [i32; 4],
url: &'static str,
target: &'static str,
message: &'static str,
alt: &'static str,
html: bool,
cell: &'static str,
/// Alpha, red, green, blue.
argb: [u8; 4],
}
fn user(name: &'static str, rect: [i32; 4]) -> S {
S { origin: 2, name, kind: 1, rect, url: "", target: "", message: "", alt: "", html: false, cell: "", argb: [0; 4] }
}
/// Resource 1050 in version 6, each record followed by `trailing` (a Photoshop 7 descriptor, or
/// nothing).
fn v6(slices: &[S], trailing: &[u8]) -> Vec<u8> {
let mut b = 6u32.to_be_bytes().to_vec();
b.extend([0u8; 16]);
b.extend(ustr("group"));
b.extend((slices.len() as u32).to_be_bytes());
for (i, s) in slices.iter().enumerate() {
b.extend((i as u32 + 1).to_be_bytes());
b.extend(0u32.to_be_bytes());
b.extend(s.origin.to_be_bytes());
if s.origin == 1 {
b.extend(7u32.to_be_bytes());
}
b.extend(ustr(s.name));
b.extend(s.kind.to_be_bytes());
for v in s.rect {
b.extend(v.to_be_bytes());
}
for t in [s.url, s.target, s.message, s.alt] {
b.extend(ustr(t));
}
b.push(u8::from(s.html));
b.extend(ustr(s.cell));
b.extend([0u8; 8]);
b.extend(s.argb);
b.extend(trailing);
}
b
}
/// A descriptor value.
enum D {
Long(i32),
Doub(f64),
Bool(bool),
Text(&'static str),
Enum(&'static str, &'static str),
Obj(Vec<(&'static str, D)>),
List(Vec<D>),
}
/// A key or class ID: a four-character one with length 0, else its length and characters.
fn key(k: &str) -> Vec<u8> {
let mut b = if k.len() == 4 { 0u32 } else { k.len() as u32 }.to_be_bytes().to_vec();
b.extend(k.as_bytes());
b
}
/// A descriptor: an empty class name, the class ID, the count, then each item.
fn descriptor(items: &[(&str, D)]) -> Vec<u8> {
let mut b = ustr("");
b.extend(key("null"));
b.extend((items.len() as u32).to_be_bytes());
for (k, v) in items {
b.extend(key(k));
b.extend(value(v));
}
b
}
/// A value's type, then the value.
fn value(v: &D) -> Vec<u8> {
let mut b = vec![];
match v {
D::Long(n) => {
b.extend(b"long");
b.extend(n.to_be_bytes());
}
D::Doub(d) => {
b.extend(b"doub");
b.extend(d.to_be_bytes());
}
D::Bool(on) => {
b.extend(b"bool");
b.push(u8::from(*on));
}
D::Text(t) => {
b.extend(b"TEXT");
b.extend(ustr(t));
}
D::Enum(t, e) => {
b.extend(b"enum");
b.extend(key(t));
b.extend(key(e));
}
D::Obj(items) => {
b.extend(b"Objc");
b.extend(descriptor(items));
}
D::List(items) => {
b.extend(b"VlLs");
b.extend((items.len() as u32).to_be_bytes());
for i in items {
b.extend(value(i));
}
}
}
b
}
/// A bounds object: top, left, bottom and right.
fn bounds(l: i32, t: i32, r: i32, b: i32) -> D {
D::Obj(vec![("Top ", D::Long(t)), ("Left", D::Long(l)), ("Btom", D::Long(b)), ("Rght", D::Long(r))])
}
/// Resource 1050 in `version` 7 or 8 holding `slices`.
fn v7(version: u32, slices: Vec<D>) -> Vec<u8> {
let mut b = version.to_be_bytes().to_vec();
b.extend(16u32.to_be_bytes());
b.extend(descriptor(&[("bounds", bounds(0, 0, 20, 20)), ("baseName", D::Text("poster")), ("slices", D::List(slices))]));
b
}
/// A 20 × 20 px PSD file written by `document.export`, with its layers (two) or flat.
fn psd(layers: bool) -> Vec<u8> {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("paint.setFill", &json!({ "color": "#ff0000" })).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
s.execute("layer.new", &json!({ "name": "Top" })).unwrap();
s.execute("shape.rectangle", &json!({"x": 8, "y": 8, "width": 10, "height": 10})).unwrap();
let r = s.execute("document.export", &json!({"format": "psd", "layers": layers})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
/// `psd` with image resource `id` holding `data` added to its image resources.
fn with_resource(psd: &[u8], id: u16, data: &[u8]) -> Vec<u8> {
let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize;
let colors = 26 + 4 + u32_at(26);
let len = u32_at(colors);
let mut block = b"8BIM".to_vec();
block.extend(id.to_be_bytes());
block.extend([0, 0]);
block.extend((data.len() as u32).to_be_bytes());
block.extend(data);
block.resize(block.len().next_multiple_of(2), 0);
let mut out = psd[..colors].to_vec();
out.extend(((len + block.len()) as u32).to_be_bytes());
out.extend(&psd[colors + 4..colors + 4 + len]);
out.extend(block);
out.extend(&psd[colors + 4 + len..]);
out
}
fn b64(f: &[u8]) -> String {
vectorcraft_format::base64_encode(f)
}
fn open(f: &[u8], extra: Value) -> (Session, Value) {
let mut s = Session::new();
let mut p = json!({"name": "poster.psd", "dataBase64": b64(f)});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let r = s.execute("document.open", &p).unwrap();
(s, r)
}
/// The document's user slices: rectangle and options.
fn slices(s: &Session) -> Vec<(Rect, SliceOptions)> {
s.doc().unwrap().doc.slices.iter().map(|x| (x.rect, x.options.clone())).collect()
}
fn warnings(r: &Value) -> Vec<String> {
r["warnings"].as_array().map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default()
}
#[test]
fn version_6_slices_open_as_user_slices_with_their_options() {
let linked = S { origin: 1, url: "https://example.com/", target: "_blank", message: "Go", alt: "Logo", ..user("logo", [2, 4, 10, 8]) };
let plain = S { kind: 0, cell: "a < b & c", argb: [0, 0, 0, 0], ..user("note", [10, 10, 20, 20]) };
let html = S { kind: 0, html: true, cell: "<b>Hi</b>", argb: [255, 0x12, 0x34, 0x56], ..user("", [0, 12, 6, 18]) };
let matte = S { argb: [0, 1, 2, 3], cell: "ignored", ..user("matte", [12, 0, 18, 6]) };
let auto = S { origin: 0, ..user("auto", [0, 0, 20, 2]) };
let data = v6(&[linked, plain, html, matte, auto], &[]);
for layers in [true, false] {
let f = with_resource(&psd(layers), 1050, &data);
// Either conversion brings the slices in; the automatic one stays out.
for p in [json!({}), json!({"layers": false})] {
let (s, r) = open(&f, p);
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 4, "{got:?}");
assert_eq!(got[0].0, Rect::new(2.0, 4.0, 10.0, 8.0));
assert_eq!(
got[0].1,
SliceOptions {
kind: SliceKind::Image,
name: "logo".into(),
url: "https://example.com/".into(),
target: "_blank".into(),
message: "Go".into(),
alt: "Logo".into(),
..Default::default()
}
);
// Plain cell text is escaped as the HTML a No Image cell shows; HTML stays as it is.
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.background.as_str()), (SliceKind::NoImage, "a &lt; b &amp; c", ""));
assert_eq!((got[2].1.text.as_str(), got[2].1.background.as_str(), got[2].1.name.as_str()), ("<b>Hi</b>", "#123456", ""));
// An Image slice's cell text isn't kept; a background with no alpha is the matte.
assert_eq!((got[3].1.text.as_str(), got[3].1.background.as_str()), ("", "matte"));
// Web output lays them out with auto slices around them.
let layout = s.doc().unwrap().doc.slice_layout();
assert_eq!(layout.iter().filter(|a| a.source == vectorcraft_doc::SliceSource::User).count(), 4);
assert!(layout.iter().any(|a| a.source == vectorcraft_doc::SliceSource::Auto));
}
}
}
#[test]
fn photoshop_7_descriptors_after_version_6_records_are_read_past() {
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("topOutset", D::Long(0))])].concat();
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5]), user("b", [5, 5, 10, 10])], &trailing));
let (s, r) = open(&f, json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let names: Vec<String> = slices(&s).into_iter().map(|(_, o)| o.name).collect();
assert_eq!(names, ["a", "b"]);
}
#[test]
fn version_6_descriptors_share_one_budget_of_values() {
// Each record's descriptor holds 2,501 values, well under the 200,000 one descriptor may hold;
// 100 of them hold 250,100 together.
let list = D::List((0..2_500).map(D::Long).collect());
let trailing = [16u32.to_be_bytes().to_vec(), descriptor(&[("many", list)])].concat();
let records: Vec<S> = (0..100).map(|_| user("a", [0, 0, 5, 5])).collect();
// Alone, one such descriptor is read past.
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records[..1], &trailing)), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&s).len(), 1);
// Together they are refused, and the file opens without slices.
let (s, r) = open(&with_resource(&psd(false), 1050, &v6(&records, &trailing)), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains("too many values")), "{w:?}");
assert!(slices(&s).is_empty());
}
#[test]
fn version_7_and_8_descriptors_open_as_user_slices() {
let slice = |origin: &'static str, kind: &'static str, l: i32, t: i32, r: i32, b: i32| {
D::Obj(vec![
("sliceID", D::Long(1)),
("groupID", D::Long(0)),
("origin", D::Enum("ESliceOrigin", origin)),
("Type", D::Enum("ESliceType", kind)),
("bounds", bounds(l, t, r, b)),
("Nm ", D::Text("cell")),
("url", D::Text("https://example.com/")),
("null", D::Text("_top")),
("Msge", D::Text("msg")),
("altTag", D::Text("alt")),
("cellTextIsHTML", D::Bool(false)),
("cellText", D::Text("x>y")),
("bgColorType", D::Enum("ESliceBGColorType", "Clr ")),
("bgColor", D::Obj(vec![("Rd ", D::Doub(255.0)), ("Grn ", D::Doub(128.0)), ("Bl ", D::Long(0))])),
])
};
for version in [7, 8] {
let data = v7(
version,
vec![slice("userGenerated", "Img ", 1, 2, 9, 10), slice("autoGenerated", "Img ", 0, 0, 20, 1), slice("layer", "noImage", 10, 10, 15, 15)],
);
let (s, r) = open(&with_resource(&psd(true), 1050, &data), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
let got = slices(&s);
assert_eq!(got.len(), 2, "{got:?}");
assert_eq!(got[0].0, Rect::new(1.0, 2.0, 9.0, 10.0));
assert_eq!(
got[0].1,
SliceOptions {
name: "cell".into(),
url: "https://example.com/".into(),
target: "_top".into(),
message: "msg".into(),
alt: "alt".into(),
background: "#ff8000".into(),
..Default::default()
}
);
assert_eq!((got[1].1.kind, got[1].1.text.as_str(), got[1].1.url.as_str()), (SliceKind::NoImage, "x&gt;y", ""));
}
}
#[test]
fn import_slices_false_leaves_them_out_and_must_be_a_switch() {
let f = with_resource(&psd(true), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]));
let (s, _) = open(&f, json!({"importSlices": false}));
assert!(slices(&s).is_empty());
let mut s = Session::new();
let e = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": "yes"})).unwrap_err();
assert!(e.to_string().contains("importSlices must be true or false"), "{e}");
}
#[test]
fn slices_that_cant_be_read_warn_and_the_file_still_opens() {
let good = v6(&[user("a", [0, 0, 5, 5])], &[]);
let mut bad_descriptor = v7(7, vec![]);
bad_descriptor[4..8].copy_from_slice(&15u32.to_be_bytes());
let cases: Vec<(Vec<u8>, &str)> = vec![
(good[..good.len() - 3].to_vec(), "cut short"),
([9u32.to_be_bytes().to_vec(), good[4..].to_vec()].concat(), "version 9"),
(bad_descriptor, "version other than 16"),
// The count follows the version, the bounds and the group's name.
([&good[..34], &u32::MAX.to_be_bytes()[..], &good[38..]].concat(), "more than the 10000 read"),
(v7(8, vec![D::Long(3)]), "other than a slice"),
// A whole record whose name is longer than a slice's text may be.
(v6(&[user("a".repeat(65_537).leak(), [0, 0, 5, 5])], &[]), "more than the 65536 characters read"),
];
for (data, why) in cases {
for layers in [true, false] {
let (s, r) = open(&with_resource(&psd(layers), 1050, &data), json!({}));
let w = warnings(&r);
assert!(w.iter().any(|w| w.starts_with("the slices can't be read (") && w.contains(why)), "{why}: {w:?}");
assert!(slices(&s).is_empty());
// The art still came in.
assert!(s.doc().unwrap().doc.art_bounds().is_some(), "{why}");
}
}
// A name of the longest length read comes in.
let longest = v6(&[user("a".repeat(65_536).leak(), [0, 0, 5, 5])], &[]);
let (s, r) = open(&with_resource(&psd(false), 1050, &longest), json!({}));
assert!(warnings(&r).is_empty(), "{r}");
assert_eq!(slices(&s).first().map(|(_, o)| o.name.len()), Some(65_536));
// A file without slices opens without a word about them.
let (s, r) = open(&psd(true), json!({}));
assert!(warnings(&r).is_empty() && slices(&s).is_empty(), "{r}");
}
#[test]
fn slices_are_clipped_to_the_canvas_and_those_outside_it_are_left_out() {
let data = v6(&[user("over", [-5, -5, 5, 30]), user("out", [25, 0, 30, 5]), user("empty", [4, 4, 4, 9]), user("in", [1, 1, 2, 2])], &[]);
let (s, r) = open(&with_resource(&psd(false), 1050, &data), json!({}));
assert_eq!(warnings(&r), ["2 slices lie outside the canvas or have no size and were left out"]);
let got: Vec<(Rect, String)> = slices(&s).into_iter().map(|(r, o)| (r, o.name)).collect();
assert_eq!(got, [(Rect::new(0.0, 0.0, 5.0, 20.0), "over".to_string()), (Rect::new(1.0, 1.0, 2.0, 2.0), "in".to_string())]);
}
#[test]
fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
let data = v6(&[user("a", [0, 0, 10, 10]), user("b", [10, 10, 20, 20])], &[]);
for layers in [false, true] {
let f = with_resource(&psd(layers), 1050, &data);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
// Fitted into a 40 pt square at (100, 60): twice the size.
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "rect": [100, 60, 40, 40], "layers": layers})).unwrap();
assert_eq!(r["slices"].as_array().map(Vec::len), Some(2), "{r}");
let got: Vec<Rect> = slices(&s).into_iter().map(|(r, _)| r).collect();
assert_eq!(got, [Rect::new(100.0, 60.0, 120.0, 80.0), Rect::new(120.0, 80.0, 140.0, 100.0)]);
// The placed art stays selected, and one undo takes the art and the slices away.
assert_eq!(s.doc().unwrap().selection.objects.len(), 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(slices(&s).is_empty());
assert!(s.doc().unwrap().doc.art_bounds().is_none());
// Centered on `at` at 100%.
s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "at": [100, 100], "layers": layers})).unwrap();
assert_eq!(slices(&s)[0].0, Rect::new(90.0, 90.0, 100.0, 100.0));
// `importSlices: false` places the art alone.
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "importSlices": false, "layers": layers})).unwrap();
assert!(r.get("slices").is_none());
assert_eq!(slices(&s).len(), 2);
}
}
#[test]
fn linked_files_are_placed_without_their_slices() {
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("poster.psd");
std::fs::write(&path, with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 5, 5])], &[]))).unwrap();
let path = path.to_string_lossy().into_owned();
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = s.execute("file.place", &json!({ "path": path })).unwrap();
assert_eq!((&r["linked"], r.get("slices")), (&json!(true), None));
assert!(slices(&s).is_empty());
let e = s.execute("file.place", &json!({ "path": path, "importSlices": true })).unwrap_err();
assert!(e.to_string().contains("importSlices: a linked PSD file is placed as its flat image"), "{e}");
// Embedded from its path, they come in.
let r = s.execute("file.place", &json!({ "path": path, "link": false })).unwrap();
assert_eq!((&r["linked"], r["slices"].as_array().map(Vec::len)), (&json!(false), Some(1)));
// file.place.info counts what a place would bring in.
let info = s.execute("file.place.info", &json!({ "path": path, "link": false })).unwrap();
assert_eq!(info["slices"], json!(1));
let info = s.execute("file.place.info", &json!({ "path": path })).unwrap();
assert_eq!(info["slices"], json!(0));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn psd_info_counts_the_slices_that_come_in() {
let mut s = Session::new();
let info = |s: &mut Session, f: &[u8]| s.execute("document.psdInfo", &json!({"dataBase64": b64(f)})).unwrap();
let data = v6(&[user("a", [0, 0, 5, 5]), S { origin: 0, ..user("auto", [5, 5, 20, 20]) }, user("out", [30, 30, 40, 40])], &[]);
assert_eq!(info(&mut s, &with_resource(&psd(false), 1050, &data))["slices"], json!(1));
assert_eq!(info(&mut s, &with_resource(&psd(true), 1050, &data[..data.len() - 4]))["slices"], json!(0));
assert_eq!(info(&mut s, &psd(true))["slices"], json!(0));
}
#[test]
fn damaged_slices_never_panic() {
let data = v7(8, vec![D::Obj(vec![("origin", D::Enum("ESliceOrigin", "userGenerated")), ("bounds", bounds(0, 0, 5, 5))])]);
let base = with_resource(&psd(false), 1050, &data);
let start = base.windows(data.len()).position(|w| w == data).unwrap();
for at in (start - 12..start + data.len()).step_by(3) {
for v in [0u8, 0x7f, 0xff] {
let mut f = base.clone();
f[at] = v;
let mut s = Session::new();
let _ = s.execute("document.open", &json!({"name": "poster.psd", "dataBase64": b64(&f)}));
let _ = s.execute("document.psdInfo", &json!({"dataBase64": b64(&f)}));
}
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+24
View File
@@ -1652,6 +1652,30 @@ fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() {
}
}
/// A paragraph style can hold a Standard composer: it applies to its paragraphs, redefining and
/// resetting treat it like any attribute, and the style and the paragraphs keep it through a save.
#[test]
fn paragraph_styles_keep_a_standard_composer_through_a_save() {
use vectorcraft_doc::Composer;
let (mut s, id) = session_with_text("One\nTwo");
s.execute("paraStyle.new", &json!({"name": "Legacy", "attrs": {"composer": "standardSingleLine"}})).unwrap();
s.execute("paraStyle.apply", &json!({"name": "Legacy", "id": id, "start": 0, "end": 0})).unwrap();
assert_eq!(paras(&s, id).iter().map(|p| p.composer).collect::<Vec<_>>(), [Composer::StandardSingleLine, Composer::EveryLine]);
let doc = s.doc().unwrap().doc.clone();
let saved = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
let style = saved.para_styles.iter().find(|d| d.name == "Legacy").unwrap();
assert_eq!(style.attrs["composer"], json!("standardSingleLine"));
let mut composers = vec![];
saved.walk(|n| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
composers.extend(t.paragraph_styles().iter().map(|p| p.composer));
}
});
assert_eq!(composers, [Composer::StandardSingleLine, Composer::EveryLine]);
s.execute("paraStyle.setAttrs", &json!({"name": "Legacy", "attrs": {"composer": "standardEveryLine"}})).unwrap();
assert_eq!(paras(&s, id)[0].composer, Composer::StandardEveryLine, "an edited style reaches its paragraphs");
}
/// A changed paragraph attribute outside the range `text.setFormat` keeps it to is an error for
/// `paraStyle.edit`, `paraStyle.setAttrs` and `paraStyle.new`, with no change to the document; the
/// ends of each range are accepted, and an out-of-range value the style already has can be kept.
+17 -2
View File
@@ -59,8 +59,23 @@ fn rect_in_range(r: vectorcraft_geom::Rect) -> bool {
/// margin passes without being measured: its curves stay inside their control points. Any other
/// object, and a path with a point outside that margin, is measured.
pub(crate) fn objects_in_range(d: &Document, ids: &[NodeId]) -> bool {
let paths = d.index_paths(ids.iter().copied());
ids.iter().all(|id| paths.get(id).and_then(|p| d.node_at(p)).is_none_or(|n| points_in_range(n) || n.geometric_bounds().is_none_or(rect_in_range)))
if ids.is_empty() {
return true;
}
let node_ok = |n: &vectorcraft_doc::Node| points_in_range(n) || n.geometric_bounds().is_none_or(rect_in_range);
// A cached document or a few ids: look each one up. Otherwise one walk of the tree, with no
// path vectors allocated.
if d.has_lookup_cache() || ids.len() <= 16 {
return ids.iter().all(|id| d.node(*id).is_none_or(node_ok));
}
let want: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let mut ok = true;
d.walk(|n| {
if ok && want.contains(&n.id) && !node_ok(n) {
ok = false;
}
});
ok
}
/// Coordinates at most this far from 0 keep a curve's measured bounds within [`MAX_COORD`]
+370
View File
@@ -3908,6 +3908,266 @@ fn live_paint_bucket_triple_click_fills_every_face_of_the_same_fill() {
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green, red.clone(), red]);
}
/// A triple-click whose first click is released across an edge, in the face it then clicks twice,
/// matches that face's fill from before the first click: the release painted it too.
#[test]
fn live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
assert_eq!([a, b].map(|f| fill_of(&s, f)), [green.clone(), green.clone()], "the release across x = 50 fills both faces");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A triple-click whose third press lands in another face and is released in the face its first
/// two clicks painted still matches that face's fill from before the first click.
#[test]
fn live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::TripleClick, 55.0, 25.0), v).unwrap();
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A triple-click whose first click makes the Live Paint group and is released across an edge, in
/// the face it then clicks twice, matches the fill that face was made with.
#[test]
fn live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill() {
let mut s = session();
let ids: Vec<NodeId> = [0.0, 50.0, 200.0, 300.0].iter().map(|&x| rect(&mut s, x, 0.0, 50.0, 50.0)).collect();
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
for (id, c) in ids.iter().zip([red, red, blue, red]) {
set_fill(&mut s, *id, c);
}
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 55.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click made a group");
let faces = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]);
assert_eq!(faces[..2].iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green.clone()], "the release fills both faces");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 55.0, 25.0), v).unwrap();
}
assert_eq!(faces.iter().map(|f| fill_of(&s, *f)).collect::<Vec<_>>(), [green.clone(), green.clone(), Paint::solid(blue), green]);
}
/// When the first click makes the Live Paint group and is released in a face covered by a source
/// path with no fill in front of a filled one, the face was made with the filled source's fill, as
/// Make gives it, so the triple-click there matches that fill and not none.
#[test]
fn live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill() {
let mut s = session();
let red = Color::rgb(1.0, 0.0, 0.0);
let (a, b, d) = (rect(&mut s, 0.0, 0.0, 50.0, 50.0), rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
for id in [a, b, d] {
set_fill(&mut s, id, red);
}
let (c, e) = (rect(&mut s, 60.0, 10.0, 30.0, 30.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
s.edit("t", |doc, _| {
for id in [c, e] {
doc.node_mut(id).unwrap().appearance.set_fill(Paint::None);
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [a.0, b.0, d.0, c.0, e.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 45.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 75.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click made a group");
let faces = faces_at(&s, g, &[(75.0, 25.0), (225.0, 25.0), (325.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the face under the unfilled path");
assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [Paint::solid(red), Paint::None], "Make gave the far faces red and none");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 75.0, 25.0), v).unwrap();
}
assert_eq!([faces[1], faces[2]].map(|f| fill_of(&s, f)), [green, Paint::None], "the triple-click matches the red the face was made with");
}
/// A triple-click whose first click adds paths to a selected Live Paint group and is released in a
/// face of that group matches the face's fill, not the edge around it.
#[test]
fn live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill() {
let mut s = session();
let g = live_squares(&mut s, &[0.0]);
let [a] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 51.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone())]);
let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(0.0, 0.0, 1.0));
set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(25.0, 25.0)).expect("the click merged the paths");
let faces = faces_at(&s, g, &[(25.0, 25.0), (225.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the group's face");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the face had");
}
/// When the first click merges two selected Live Paint groups, a face of the group in front takes
/// its source path's fill, so a triple-click there after a release across an edge matches that fill
/// and not the paint the face had before the merge.
#[test]
fn live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill() {
let mut s = session();
let back = live_squares(&mut s, &[0.0]);
let source = rect(&mut s, 100.0, 0.0, 50.0, 50.0);
set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [source.0]})).unwrap();
let front = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let [f] = faces_at(&s, front, &[(125.0, 25.0)])[..] else { panic!("one face") };
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
paint_parts(&mut s, &[], &Paint::None, &[(f, blue.clone())]);
let (next, far) = (rect(&mut s, 150.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
set_fill(&mut s, far, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let [m] = faces_at(&s, merged, &[(125.0, 25.0)])[..] else { panic!("one face") };
assert_eq!(fill_of(&s, m), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), "Merge gives the front group's face its source's fill");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [back.0, front.0, next.0, far.0]})).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 155.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 145.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(125.0, 25.0)).expect("the click merged the groups");
let faces = faces_at(&s, g, &[(125.0, 25.0), (325.0, 25.0)]);
assert_eq!(fill_of(&s, faces[0]), green, "the release fills the front group's face");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 145.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, faces[1]), green, "the far face had the red the merge gave the face");
}
/// When the first click merges paths into a selected Live Paint group whose face has an unplaced
/// gradient, Merge fixes the gradient to the face's fit, so a triple-click there after a release
/// across an edge matches the fixed gradient: a far face whose source has that same fixed gradient
/// takes the bucket's paint.
#[test]
fn live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)];
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
let mut s = session();
let g = live_squares(&mut s, &[0.0]);
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
paint_parts(&mut s, &[], &Paint::None, &[(f, gradient.clone())]);
let (next, far) = (rect(&mut s, 50.0, 0.0, 50.0, 50.0), rect(&mut s, 200.0, 0.0, 50.0, 50.0));
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
s.execute("select.set", &json!({"ids": [g.0, next.0]})).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let [m] = faces_at(&s, merged, &[(25.0, 25.0)])[..] else { panic!("one face") };
let fixed = fill_of(&s, m);
assert_ne!(fixed, gradient, "Merge fixes the face's gradient to its fit");
s.execute("edit.undo", &json!({})).unwrap();
s.edit("t", |d, _| {
d.node_mut(far).unwrap().appearance.set_fill(fixed.clone());
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g.0, next.0, far.0]})).unwrap();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths");
let [far_face] = faces_at(&s, g, &[(225.0, 25.0)])[..] else { panic!("the far face") };
assert_eq!(fill_of(&s, far_face), fixed, "the far face keeps its source's fixed gradient");
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
assert_eq!(fill_of(&s, far_face), green, "the far face had the fixed gradient the merge gave the face");
}
/// When the first click merges a line that splits a painted face of the selected Live Paint group,
/// Merge keeps the face's paint in one part only and the other part takes its source path's fill;
/// a triple-click in that other part after a release across an edge matches the source's fill.
#[test]
fn live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill() {
let mut s = session();
let source = rect(&mut s, 0.0, 0.0, 50.0, 50.0);
set_fill(&mut s, source, Color::rgb(1.0, 0.0, 0.0));
s.execute("select.set", &json!({"ids": [source.0]})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let [f] = faces_at(&s, g, &[(25.0, 25.0)])[..] else { panic!("one face") };
paint_parts(&mut s, &[], &Paint::None, &[(f, Paint::solid(Color::rgb(0.0, 0.0, 1.0)))]);
let line = NodeId(s.execute("shape.line", &json!({"x1": 40, "y1": -10, "x2": 40, "y2": 60})).unwrap()["id"].as_u64().unwrap());
let next = rect(&mut s, 50.0, 0.0, 50.0, 50.0);
set_fill(&mut s, next, Color::rgb(1.0, 1.0, 0.0));
let (red_far, blue_far) = (rect(&mut s, 200.0, 0.0, 50.0, 50.0), rect(&mut s, 300.0, 0.0, 50.0, 50.0));
set_fill(&mut s, red_far, Color::rgb(1.0, 0.0, 0.0));
set_fill(&mut s, blue_far, Color::rgb(0.0, 0.0, 1.0));
let ids = json!({"ids": [g.0, line.0, next.0, red_far.0, blue_far.0]});
s.execute("select.set", &ids).unwrap();
let merged = NodeId(s.execute("livePaint.merge", &json!({})).unwrap()["id"].as_u64().unwrap());
let parts = faces_at(&s, merged, &[(20.0, 25.0), (45.0, 25.0)]);
assert_eq!(
parts.iter().map(|p| fill_of(&s, *p)).collect::<Vec<_>>(),
[Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0))],
"Merge keeps the paint in the part that holds the face's inside point"
);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("select.set", &ids).unwrap();
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
s.pointer(&PointerEvent::new(PointerKind::Down, 55.0, 25.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 45.0, 25.0), v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick, PointerKind::Down, PointerKind::Up, PointerKind::TripleClick] {
s.pointer(&PointerEvent::new(kind, 45.0, 25.0), v).unwrap();
}
let g = vectorcraft_tools::builder::live_paint_at(&s.doc().unwrap().doc, Point::new(45.0, 25.0)).expect("the click merged the paths");
let far = faces_at(&s, g, &[(225.0, 25.0), (325.0, 25.0)]);
assert_eq!(far.iter().map(|p| fill_of(&s, *p)).collect::<Vec<_>>(), [green, Paint::solid(Color::rgb(0.0, 0.0, 1.0))]);
}
/// A triple-click whose first click makes the Live Paint group from the selected paths matches the
/// fill the face was made with.
#[test]
@@ -3978,6 +4238,116 @@ fn live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges(
assert_eq!(node(&s, apart[0]).appearance.stroke_paint(), black);
}
/// A double-click whose two clicks land on two joined edges paints every edge joined to them that
/// had their stroke: the edge the first click painted still joins the others.
#[test]
fn live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges() {
// A square with a line across its middle, cut at x = 30 and x = 70 by two lines from the top: the
// middle line's three edges join end to end.
let mut s = session();
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
for anchors in [
json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]),
json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}]),
json!([{"x": 70, "y": 0}, {"x": 70, "y": 70}]),
] {
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
}
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
paint_parts(&mut s, &all, &red, &[]);
let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0));
assert_eq!(middle.len(), 3, "the middle line's three edges");
paint_parts(&mut s, &middle, &black, &[]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
let shift = Mods { shift: true, ..Default::default() };
for (kind, x) in
[(PointerKind::Down, 50.0), (PointerKind::Up, 50.0), (PointerKind::Down, 85.0), (PointerKind::Up, 85.0), (PointerKind::DoubleClick, 85.0)]
{
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
}
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
// `through` takes edge ids, with scope "connected" only.
for p in [
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": "x"}),
json!({"group": g.0, "point": [15, 50], "scope": "connected", "through": [-1]}),
json!({"group": g.0, "point": [15, 50], "scope": "samePaint", "through": []}),
json!({"group": g.0, "point": [15, 50], "through": []}),
] {
assert!(s.execute("livePaint.strokeEdge", &p).is_err(), "{p}");
}
}
/// A double-click whose second press lands on the next joined edge and is released back on the
/// edge the first click painted (at the end of the line) matches that edge's stroke paint from
/// before the first click, and the edge the second press painted still joins the edge past it.
#[test]
fn live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges() {
let mut s = session();
let mut ids = vec![rect(&mut s, 0.0, 0.0, 100.0, 100.0).0];
for anchors in [
json!([{"x": 0, "y": 50}, {"x": 100, "y": 50}]),
json!([{"x": 30, "y": 0}, {"x": 30, "y": 70}]),
json!([{"x": 70, "y": 0}, {"x": 70, "y": 70}]),
] {
ids.push(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap());
}
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let (black, red) = (Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 101.0));
paint_parts(&mut s, &all, &red, &[]);
let middle = edges_in(&s, g, Rect::new(-1.0, 49.0, 101.0, 51.0));
assert_eq!(middle.len(), 3, "the middle line's three edges");
paint_parts(&mut s, &middle, &black, &[]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
let shift = Mods { shift: true, ..Default::default() };
for (kind, x) in
[(PointerKind::Down, 15.0), (PointerKind::Up, 15.0), (PointerKind::Down, 50.0), (PointerKind::Up, 15.0), (PointerKind::DoubleClick, 15.0)]
{
s.pointer(&PointerEvent::new(kind, x, 50.0).with_mods(shift), v).unwrap();
}
assert_eq!(middle.iter().map(|e| node(&s, *e).appearance.stroke_paint()).collect::<Vec<_>>(), [green.clone(), green.clone(), green]);
}
/// A triple-click whose second press holds Cmd (it goes to the selection tool Cmd lends) matches
/// the fill the face had before the first click: the lent press counts as one that paints nothing.
#[test]
fn live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0]);
let [a, b, c, d] = faces_at(&s, g, &[(25.0, 25.0), (75.0, 25.0), (125.0, 25.0), (175.0, 25.0)])[..] else { panic!("four faces") };
let (red, blue) = (Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 51.0));
paint_parts(&mut s, &all, &Paint::solid(Color::rgb(0.0, 0.0, 0.0)), &[(a, red.clone()), (b, red.clone()), (c, blue.clone()), (d, red.clone())]);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.fill = green.clone();
let cmd = Mods { cmd: true, ..Default::default() };
for (kind, m) in [
(PointerKind::Down, Mods::default()),
(PointerKind::Up, Mods::default()),
(PointerKind::Down, cmd),
(PointerKind::Up, cmd),
(PointerKind::Down, Mods::default()),
(PointerKind::Up, Mods::default()),
(PointerKind::TripleClick, Mods::default()),
] {
s.pointer(&PointerEvent::new(kind, 25.0, 25.0).with_mods(m), v).unwrap();
}
assert_eq!(s.tool_id(), "livePaintBucket");
assert_eq!([a, b, c, d].map(|f| fill_of(&s, f)), [green.clone(), green.clone(), blue, green]);
}
/// A `scope` that is not one of the three, a `match` that is not a paint or is given with a scope
/// that compares none, and a scope with a drag's points are refused; nothing changes.
#[test]
+29
View File
@@ -1722,6 +1722,35 @@ fn text_set_format() {
assert_eq!(t.para.composer, vectorcraft_doc::Composer::EveryLine);
}
/// `text.setFormat {composer}` takes the two Middle Eastern & South Asian and the two Standard
/// composers, each per paragraph and one undo step; any other value is refused and names them all.
#[test]
fn text_set_format_takes_the_four_composers() {
use vectorcraft_doc::Composer;
let mut s = session();
let r = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "One\nTwo"})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let composers = |s: &Session| {
let NodeKind::Text(t) = node(s, id).kind else { panic!() };
[t.para_at(0).composer, t.para_at(1).composer]
};
assert_eq!(composers(&s), [Composer::EveryLine; 2], "new type is ME&SA Every-line");
for (value, want) in [
("singleLine", Composer::SingleLine),
("standardSingleLine", Composer::StandardSingleLine),
("standardEveryLine", Composer::StandardEveryLine),
("everyLine", Composer::EveryLine),
] {
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": value, "start": 4, "end": 4})).unwrap();
assert_eq!(composers(&s), [Composer::EveryLine, want], "{value}: only the second paragraph");
}
s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standardEveryLine"})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(composers(&s), [Composer::EveryLine; 2], "one undo step");
let e = s.execute("text.setFormat", &json!({"ids": [id.0], "composer": "standard"})).unwrap_err().to_string();
assert!(e.contains("standardSingleLine") && e.contains("standardEveryLine"), "{e}");
}
#[test]
fn stroke_advanced_scale_swap_flip() {
let mut s = session();
+9
View File
@@ -255,6 +255,9 @@ impl Session {
}
// The Selection and Group Selection tools act on the instance whole.
self.select_whole_instance(id);
// The tool lent to does not see the press: it counts as a press elsewhere for the clicks a
// double-click or triple-click compares.
self.tool.press_elsewhere();
let lent = self.make_tool(id);
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
@@ -1086,6 +1089,12 @@ impl Session {
self.with_tool_cx(view, |t, cx| t.hover_ended(cx));
}
/// A press on the canvas went to the view tools and not to the active tool
/// ([`vectorcraft_tools::Tool::press_elsewhere`]).
pub fn tool_press_elsewhere(&mut self) {
self.tool.press_elsewhere();
}
/// Whether the active tool's hover depends on what lies under a still pointer
/// ([`vectorcraft_tools::Tool::wants_rehover`]).
pub fn tool_wants_rehover(&self) -> bool {
+5
View File
@@ -1841,6 +1841,7 @@ proptest! {
/// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden
/// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count.
/// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.)
/// Neither does `document.psdInfo`, nor placing them with their layers as objects.
#[test]
fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::<u8>()), 0..12)) {
let (name, mut bytes) = raster_samples().swap_remove(which);
@@ -1855,6 +1856,10 @@ proptest! {
let mut s = vectorcraft_engine::Session::new();
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "hiddenLayers": true});
let _ = no_panic(s.execute("document.open", &p));
let _ = no_panic(s.execute("document.psdInfo", &p));
let _ = no_panic(s.execute("file.new", &json!({})));
let p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(&bytes), "layers": true, "hiddenLayers": true});
let _ = no_panic(s.execute("file.place", &p));
});
prop_assert!(r.is_ok(), "{name}: panicked: {:?}", r.err());
}
+419 -15
View File
@@ -1038,7 +1038,8 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() {
/// The documents [`the_writer_counts_objects_as_the_reader_reads_them`] writes: groups, compound
/// paths, guides, sublayers, clipping groups and layers, painted clipping paths, opacity masks,
/// gradients, pattern definitions and tiles, images, type, symbol definitions and instances,
/// objects with art styles, objects bound to variables and live envelopes.
/// objects with art styles, objects bound to variables, live envelopes, and the rectangles of the
/// bounds of wrapped objects written as their art.
fn counted() -> Vec<(&'static str, Document)> {
vec![
("sample", sample()),
@@ -1054,9 +1055,28 @@ fn counted() -> Vec<(&'static str, Document)> {
("blend", blend_doc()),
("brushes", brushes_document()),
("envelopes", envelopes_document()),
("wrap bounds", wrap_bounds_doc()),
]
}
/// Area type below a wrapped symbol instance written as its art and wrapped type written as its
/// outlines, each with the rectangle of its bounds.
fn wrap_bounds_doc() -> Document {
let mut doc = over_area_type(|doc| {
two_leaves(doc);
let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0]));
n.isolate = true;
wrapped(n, 4.5, false)
});
let mut label = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::ZERO, "Ill", style(60.0, Color::BLACK));
// Mirrored, so written as its outlines.
label.xf = Affine::new([-1.0, 0.0, 0.0, 1.0, 150.0, 120.0]);
let label = wrapped(text_node(&mut doc, label), -2.0, true);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, label).unwrap();
doc
}
/// A blend of two squares 20 pt apart with a step every 10 pt, written as its steps.
fn blend_doc() -> Document {
let mut doc = Document::new(200.0, 100.0);
@@ -4088,20 +4108,21 @@ fn predefined_mojikumi_sets_are_reported_as_left_out() {
}
}
/// The text document has no Bunri-Kinshi: a paragraph with it on and an inseparable pair in it is
/// reported as left out, and comes back off; with it off, or with no pair, nothing is reported.
/// Bunri-Kinshi comes back on or off, with or without an inseparable pair in the paragraph, and
/// nothing is reported.
#[test]
fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() {
fn bunri_kinshi_comes_back_with_or_without_a_pair() {
use vectorcraft_doc::TextObject;
for (text, on, reported) in [
("Wait——now", true, true),
("Wait——now", false, false),
("Wait—now", true, false),
("Wait……now", true, true),
("Wait‥‥now", true, true),
("あ〳〵い", true, true),
("あ〴〵い", true, true),
("あ〵〳い", true, false),
for (text, on) in [
("Wait——now", true),
("Wait——now", false),
("Wait—now", true),
("Wait……now", true),
("Wait‥‥now", true),
("あ〳〵い", true),
("あ〴〵い", true),
("あ〵〳い", true),
("あ〵〳い", false),
] {
let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), text, style(14.0, Color::BLACK));
t.para.bunri_kinshi = on;
@@ -4110,7 +4131,7 @@ fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() {
let n = text_node(&mut doc, t);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert_eq!(!out.warnings.is_empty(), reported, "{text} {on}: {:?}", out.warnings);
assert!(out.warnings.is_empty(), "{text} {on}: {:?}", out.warnings);
let mut all = vec![];
paths(&read_back(&doc).layers, &mut all);
let paras: Vec<bool> = all
@@ -4120,10 +4141,87 @@ fn bunri_kinshi_is_reported_only_for_paragraphs_with_a_pair() {
_ => None,
})
.collect();
assert_eq!(paras, [false], "{text} {on}");
assert_eq!(paras, [on], "{text} {on}");
}
}
/// Each paragraph's Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi come back, and
/// nothing is reported: every value of each, mixed across the paragraphs of one object, Burasagari
/// and Bunri-Kinshi kept under Kinsoku None. The text document lists the Hard and Soft sets, and
/// every paragraph, the normal paragraph style and the document's defaults write all four keys.
/// Another attribute the text document leaves out is still reported.
#[test]
fn kinsoku_settings_come_back_on_each_paragraph() {
use vectorcraft_doc::{Burasagari, Kinsoku, KinsokuShoriType, ParaStyle, TextObject};
let cases = [
(Kinsoku::None, KinsokuShoriType::PushInFirst, Burasagari::Forced, true),
(Kinsoku::Soft, KinsokuShoriType::PushOutFirst, Burasagari::Standard, false),
(Kinsoku::Hard, KinsokuShoriType::PushOutOnly, Burasagari::None, true),
(Kinsoku::Hard, KinsokuShoriType::PushInFirst, Burasagari::Standard, false),
(Kinsoku::Soft, KinsokuShoriType::PushOutOnly, Burasagari::Forced, true),
];
let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "かな。\n「かな」、\nあ——い\nかな\nかな。", style(14.0, Color::BLACK));
t.set_paragraph_styles(
cases
.iter()
.map(|&(kinsoku, kinsoku_type, burasagari, bunri_kinshi)| ParaStyle {
kinsoku,
kinsoku_type,
burasagari,
bunri_kinshi,
..ParaStyle::default()
})
.collect(),
);
let mut doc = Document::new(200.0, 200.0);
let layer = doc.layers[0].id;
let n = text_node(&mut doc, t);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let back = read_back(&doc);
same_lines(&type_lines(&back), &type_lines(&doc));
let mut all = vec![];
paths(&back.layers, &mut all);
let read: Vec<_> = all
.iter()
.filter_map(|n| match &n.kind {
NodeKind::Text(t) => {
Some(t.paragraph_styles().iter().map(|p| (p.kinsoku, p.kinsoku_type, p.burasagari, p.bunri_kinshi)).collect::<Vec<_>>())
}
_ => None,
})
.collect();
assert_eq!(read, [cases.to_vec()]);
let decoded = text_document(&program(&doc));
let hard = decoded.find("PhotoshopKinsokuHard").unwrap_or_else(|| panic!("{decoded}"));
let soft = decoded.find("PhotoshopKinsokuSoft").unwrap_or_else(|| panic!("{decoded}"));
assert!(hard < soft, "{decoded}");
// Five paragraphs, then the normal paragraph style and the document's defaults (Hard, Push Out
// Only, no Burasagari, Bunri-Kinshi off).
for (key, count) in [
("/27 /nil", 1),
("/27 0", 4),
("/27 1", 2),
("/25 0", 2),
("/25 1", 1),
("/25 2", 4),
("/24 0", 3),
("/24 1", 2),
("/24 2", 2),
("/23 true", 3),
("/23 false", 4),
] {
assert_eq!(decoded.matches(key).count(), count, "{key}: {decoded}");
}
let mut lossy = doc.clone();
let id = lossy.layers[0].children().unwrap()[0].id;
if let Some(NodeKind::Text(t)) = lossy.node_mut(id).map(|n| &mut n.kind) {
t.runs[0].style.underline = true;
}
assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]);
}
#[test]
fn type_is_written_again_as_the_same_bytes() {
let doc = typed();
@@ -11374,6 +11472,42 @@ fn text_wrap_options_of_type_and_envelopes_are_read_back() {
same_wraps(&wraps(top), &[(Some("Bent".into()), 2.5, true)]);
}
/// The wrap shapes that `doc`'s first area type on its first layer takes from the objects above it,
/// in the type's own space: the bounds of each one's subpaths, and its options.
fn area_wrap_region(doc: &Document) -> Vec<(Vec<[f64; 4]>, f64, bool)> {
use vectorcraft_doc::TextKind;
let mut doc = doc.clone();
vectorcraft_doc::text::resolve_wrap(None, &mut doc);
let top = doc.layers[0].children().unwrap();
let Some(NodeKind::Text(t)) = top.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(t) if matches!(t.kind, TextKind::Area { .. })))
else {
panic!("no area type");
};
t.wrap
.iter()
.map(|s| {
let parts = s
.path
.subpaths
.iter()
.map(|sp| {
let b = PathData::new(vec![sp.clone()]).bounds().unwrap_or_default();
[b.x0, b.y0, b.x1, b.y1]
})
.collect();
(parts, s.wrap.offset, s.wrap.invert)
})
.collect()
}
/// `before` and `after` hold as many wrap shapes, each with as many subpaths, with bounds within
/// `1e-3`, and the same options.
fn same_region(before: &[(Vec<[f64; 4]>, f64, bool)], after: &[(Vec<[f64; 4]>, f64, bool)]) -> bool {
let close =
|b: &[[f64; 4]], a: &[[f64; 4]]| b.len() == a.len() && b.iter().zip(a).all(|(b, a)| b.iter().zip(a).all(|(x, y)| (x - y).abs() < 1e-3));
before.len() == after.len() && before.iter().zip(after).all(|(b, a)| close(&b.0, &a.0) && (b.1 - a.1).abs() < 1e-6 && b.2 == a.2)
}
/// Type written as its outlines wraps area type below it by its bounds, as it did before saving,
/// not by its glyphs: its text wrap options go on an unpainted rectangle of its bounds, the last
/// member of the outlines' group, which keeps the type's name and has no options of its own.
@@ -11464,6 +11598,276 @@ fn type_written_as_outlines_keeps_wrapping_by_its_bounds() {
assert_eq!(top[1].name.as_deref(), Some("Label"), "{text_out}");
}
/// A 300 × 200 document of area type "Body" filling the page, with `top` above it.
fn over_area_type(make: impl FnOnce(&mut Document) -> Node) -> Document {
use vectorcraft_doc::{TextKind, TextObject, TextRun};
let mut doc = Document::new(300.0, 200.0);
let layer = doc.layers[0].id;
let mut body = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK));
body.runs = vec![TextRun::new("one two three four five six seven eight nine ten eleven twelve", style(10.0, Color::BLACK))];
body.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 290.0, 190.0)) };
body.xf = Affine::IDENTITY;
let body = named(text_node(&mut doc, body), "Body");
let top = make(&mut doc);
for n in [body, top] {
doc.insert(Some(layer), usize::MAX, n).unwrap();
}
doc
}
/// Symbol "Leaf": two squares in opposite corners of the 20 × 20 square around the origin, apart.
fn two_leaves(doc: &mut Document) {
let a = square(doc, Rect::new(-10.0, -10.0, -6.0, -6.0), LEAF);
let b = square(doc, Rect::new(6.0, 6.0, 10.0, 10.0), LEAF);
let art = group(doc, vec![a, b], false);
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
}
/// A symbol instance written as its art (its isolation is a group's), a blend and an intertwine,
/// each written as a group of its art, wrap area type below them by their bounds after reopening,
/// as they did before saving, not by the members of that art: the text wrap options go on an
/// unpainted rectangle of the bounds, the group's first member, and the group, which keeps the
/// object's name, isolation, lock and visibility, has none. A positive offset, a negative offset
/// with Invert Wrap, and hidden and locked.
#[test]
fn live_art_written_as_a_group_keeps_wrapping_by_its_bounds() {
let instance_of = |offset: f64, invert: bool, visible: bool, locked: bool| {
move |doc: &mut Document| {
two_leaves(doc);
let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0]));
n.isolate = true;
(n.visible, n.locked) = (visible, locked);
wrapped(named(n, "Thing"), offset, invert)
}
};
let blend = |doc: &mut Document| {
let keys = vec![
Arc::new(square(doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))),
Arc::new(square(doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))),
];
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() };
wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false)
};
let intertwine = |doc: &mut Document| {
let a = Arc::new(square(doc, Rect::new(60.0, 60.0, 80.0, 80.0), Color::gray(0.5)));
let b = Arc::new(square(doc, Rect::new(200.0, 120.0, 220.0, 140.0), Color::gray(0.5)));
wrapped(named(Node::new(doc.alloc_id(), NodeKind::Intertwine { children: vec![a, b] }), "Thing"), 2.0, true)
};
let repeat = |doc: &mut Document| {
let a = Arc::new(square(doc, Rect::new(100.0, 80.0, 110.0, 90.0), Color::gray(0.5)));
let spec = vectorcraft_doc::RepeatSpec::grid(vec![a], 8.0, 12.0);
wrapped(named(Node::new(doc.alloc_id(), NodeKind::Repeat(spec)), "Thing"), 1.5, false)
};
// A Fidelity that isn't a whole number: written as its distorted art.
let envelope = |doc: &mut Document| {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
wrapped(named(envelope_node(doc, kind, 50.5, false, EnvelopeOptions::NEW), "Thing"), -3.0, true)
};
let docs = [
("instance", over_area_type(instance_of(4.5, false, true, false)), 4.5, false, true, false),
("instance, inverted", over_area_type(instance_of(-2.0, true, true, false)), -2.0, true, true, false),
("instance, hidden and locked", over_area_type(instance_of(3.0, false, false, true)), 3.0, false, false, true),
("blend", over_area_type(blend), 4.5, false, true, false),
("intertwine", over_area_type(intertwine), 2.0, true, true, false),
("repeat", over_area_type(repeat), 1.5, false, true, false),
("envelope", over_area_type(envelope), -3.0, true, true, false),
];
for (name, doc, offset, invert, visible, locked) in docs {
let thing = &doc.layers[0].children().unwrap()[1];
let want = thing.geometric_bounds().unwrap();
let text_out = program(&doc);
let back = read_back(&doc);
let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back));
assert_eq!(before.len(), usize::from(visible), "{name}");
assert!(same_region(&before, &after), "{name}\n{before:?}\n{after:?}\n{text_out}");
assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{name}: {text_out}");
let top = back.layers[0].children().unwrap();
same_wraps(&wraps(top), &[(None, offset, invert)]);
let g = &top[1];
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{name}: {text_out}");
assert_eq!(
(g.name.as_deref(), g.extras().wrap, g.visible, g.locked, g.isolate),
(Some("Thing"), None, visible, locked, thing.isolate),
"{name}"
);
let first = &g.children().unwrap()[0];
assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{name}: {text_out}");
assert_eq!((first.visible, first.locked), (visible, locked), "{name}");
let b = first.geometric_bounds().unwrap();
assert!([b.x0 - want.x0, b.y0 - want.y0, b.x1 - want.x1, b.y1 - want.y1].iter().all(|d| d.abs() < 1e-3), "{name}: {b:?} {want:?}");
}
// An envelope written live opens live and wraps by its bounds, its options its own.
let live = |doc: &mut Document| {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
wrapped(named(envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW), "Thing"), -3.0, true)
};
let doc = over_area_type(live);
let text_out = program(&doc);
let back = read_back(&doc);
let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back));
assert_eq!(before.len(), 1);
assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}");
let top = back.layers[0].children().unwrap();
assert!(matches!(top[1].kind, NodeKind::Envelope { .. }), "{text_out}");
same_wraps(&wraps(top), &[(Some("Thing".into()), -3.0, true)]);
}
/// The rectangle that keeps a blend written as its art wrapping by its bounds counts toward the
/// object limit, ahead of the art: one object short, the last step is left out with the limit's
/// warning; without room for the rectangle, the options are left out with the warning, and the
/// group does not take them. In an instance whose art holds area type, shown, hidden, in a hidden
/// group or written as its outlines, the rectangle is the group's first member, below that type:
/// area type below the instance wraps by its bounds after reopening, and the type in its art is not
/// wrapped by them.
#[test]
fn wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped() {
use vectorcraft_doc::{TextKind, TextObject, TextRun};
// A blend alone, without a symbol definition, so the objects are the group, the rectangle and
// the steps.
let mut doc = Document::new(300.0, 200.0);
let keys = vec![
Arc::new(square(&mut doc, Rect::new(60.0, 80.0, 70.0, 90.0), Color::gray(0.5))),
Arc::new(square(&mut doc, Rect::new(220.0, 110.0, 230.0, 120.0), Color::gray(0.5))),
];
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(60.0), ..Default::default() };
let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), "Thing"), 4.5, false);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, thing).unwrap();
let steps = export_ai_editing(&doc, &opts()).unwrap();
let steps = crate::ai_alone(&steps.program).unwrap().0.layers[0].children().unwrap()[0].children().unwrap().len() - 1;
let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
let all = export_within(&doc, &opts(), read).unwrap();
assert!(!all.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", all.warnings);
let out = export_within(&doc, &opts(), read - 1).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings);
let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}");
let (back, _) = crate::ai_alone(&out.program).unwrap();
let top = back.layers[0].children().unwrap();
same_wraps(&wraps(top), &[(None, 4.5, false)]);
assert_eq!((top[0].name.as_deref(), top[0].extras().wrap), (Some("Thing"), None), "{text_out}");
let members = top[0].children().unwrap();
assert_eq!(members.len(), steps, "the rectangle and all but the last step: {text_out}");
assert!(matches!(members[0].kind, NodeKind::Path { guide: false, .. }) && members[0].appearance.items.is_empty(), "{text_out}");
let out = export_within(&doc, &opts(), read - steps - 1).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", out.warnings);
let text_out = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
assert!(!text_out.contains("(AI11TextWrapOffset)"), "{text_out}");
let (back, _) = crate::ai_alone(&out.program).unwrap();
assert!(wraps(back.layers[0].children().unwrap()).is_empty(), "{text_out}");
// Area type in the symbol's art, shown or hidden, of `words`, in a hidden group with `in_hidden`.
let make = |shown: bool, words: &'static str, in_hidden: bool| {
move |doc: &mut Document| {
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(2.0, Color::BLACK));
t.runs = vec![TextRun::new(words, style(2.0, Color::BLACK))];
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(-10.0, -10.0, -6.0, -6.0)) };
t.xf = Affine::IDENTITY;
let mut t = text_node(doc, t);
t.visible = shown;
if in_hidden {
t = group(doc, vec![t], false);
t.visible = false;
}
let s = square(doc, Rect::new(6.0, 6.0, 10.0, 10.0), LEAF);
let art = group(doc, vec![t, s], false);
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
let mut n = instance(doc, "Leaf", Affine::new([3.0, 0.0, 0.0, 3.0, 150.0, 100.0]));
n.isolate = true;
wrapped(named(n, "Thing"), 4.5, false)
}
};
// Type of spaces alone is written as its outlines, which are not type.
for (what, shown, words, in_hidden) in
[("shown", true, "leaf", false), ("hidden", false, "leaf", false), ("in a hidden group", true, "leaf", true), ("spaces", true, " ", false)]
{
let doc = over_area_type(make(shown, words, in_hidden));
let text_out = program(&doc);
assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{what}: {text_out}");
let back = read_back(&doc);
let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back));
assert_eq!(before.len(), 1, "{what}");
assert!(same_region(&before, &after), "{what}\n{before:?}\n{after:?}\n{text_out}");
let g = &back.layers[0].children().unwrap()[1];
assert!(matches!(g.kind, NodeKind::Group { clip: false, .. }), "{what}: {text_out}");
assert_eq!(g.extras().wrap, None, "{what}: {text_out}");
let first = &g.children().unwrap()[0];
assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{what}: {text_out}");
let mut resolved = back.clone();
vectorcraft_doc::text::resolve_wrap(None, &mut resolved);
let mut inner = vec![];
resolved.layers[0].children().unwrap()[1].walk(&mut |m| {
if let NodeKind::Text(t) = &m.kind {
inner.push((matches!(t.kind, TextKind::Area { .. }), m.visible, t.wrap.len()));
}
});
let want: &[(bool, bool, usize)] = match what {
"shown" | "in a hidden group" => &[(true, true, 0)],
"hidden" => &[(true, false, 0)],
_ => &[],
};
assert_eq!(inner, want, "{what}: {text_out}");
}
}
/// A blend with no keys, written as an empty group, has no bounds for a rectangle: its group keeps
/// the text wrap options, and they read back.
#[test]
fn live_art_without_bounds_keeps_its_text_wrap_on_the_group() {
let mut doc = Document::new(300.0, 200.0);
let spec = vectorcraft_doc::BlendSpec::default();
let thing = wrapped(named(Node::new(doc.alloc_id(), NodeKind::Blend { children: vec![], spec: Box::new(spec) }), "Thing"), 4.5, true);
assert_eq!(thing.geometric_bounds(), None);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, thing).unwrap();
let text_out = program(&doc);
assert_eq!(text_out.matches("(AI11TextWrapOffset)").count(), 1, "{text_out}");
let back = read_back(&doc);
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(Some("Thing".into()), 4.5, true)]);
}
/// A symbol instance written as its art, whose art holds an envelope of area type beside a square,
/// wraps area type below it by its bounds after reopening. The envelope there is written as its art,
/// after the type written for it as a live envelope is taken back: the group has no text wrap
/// options, and its first member is the rectangle of the bounds.
#[test]
fn an_envelope_of_area_type_in_written_art_leaves_the_wrap_on_the_bounds() {
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
use vectorcraft_doc::{TextKind, TextObject, TextRun};
let doc = over_area_type(|doc| {
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
let mut envelope = envelope_node(doc, kind, 50.0, false, EnvelopeOptions::NEW);
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "", style(10.0, Color::BLACK));
t.runs = vec![TextRun::new("bent", style(10.0, Color::BLACK))];
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(60.0, 30.0, 140.0, 70.0)) };
t.xf = Affine::IDENTITY;
let t = text_node(doc, t);
let NodeKind::Envelope { content, .. } = &mut envelope.kind else { unreachable_envelope() };
content.push(Arc::new(t));
let s = square(doc, Rect::new(250.0, 150.0, 260.0, 160.0), LEAF);
let art = group(doc, vec![envelope, s], false);
doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) });
let mut n = instance(doc, "Bent", Affine::IDENTITY);
n.isolate = true;
wrapped(named(n, "Thing"), 4.5, false)
});
let text_out = program(&doc);
let back = read_back(&doc);
let (before, after) = (area_wrap_region(&doc), area_wrap_region(&back));
assert_eq!(before.len(), 1);
assert!(same_region(&before, &after), "{before:?}\n{after:?}\n{text_out}");
let g = &back.layers[0].children().unwrap()[1];
assert_eq!(g.extras().wrap, None, "{text_out}");
let mut live = 0;
g.walk(&mut |m| live += usize::from(matches!(m.kind, NodeKind::Envelope { .. })));
assert_eq!(live, 0, "{text_out}");
let first = &g.children().unwrap()[0];
assert!(matches!(first.kind, NodeKind::Path { guide: false, .. }) && first.appearance.items.is_empty(), "{text_out}");
}
/// A clipping path inside art cut to a clipping object is written as its fills and its strokes,
/// two objects: its text wrap options are written once, whether it has both or only strokes, and
/// with its strokes when the region outside leaves nothing of its fills.
+43 -13
View File
@@ -289,7 +289,8 @@ pub(super) struct Writer<'a> {
/// brushed stroke's pieces) the art being written is in. Text wrap options are written only
/// outside them, since only the document's own objects wrap type.
drawn: u32,
/// The type just written as outlines has its text wrap options on the rectangle of its bounds
/// The type just written as outlines, or the symbol instance or live object just written as a
/// group of its art, has its text wrap options on the rectangle of its bounds
/// ([`Self::wrap_bounds`]), not in the group's dictionary.
wrap_moved: bool,
/// The brushes written ([`brushes`]).
@@ -773,6 +774,8 @@ impl<'a> Writer<'a> {
if !self.open_group("u") {
return;
}
let state = self.state;
let moved = self.wrap_on_bounds(n, state);
// The canvas places an instance inside a symbol's art where the outer instance puts
// it (9-slice guides, stains and patterns included), and this art doesn't move with it.
self.wrote_fixed |= self.in_symbol;
@@ -817,12 +820,13 @@ impl<'a> Writer<'a> {
self.warn(SYMBOL_LIMIT);
}
}
self.wrap_moved = moved;
self.end_group("U", xy);
}
NodeKind::Envelope { .. } if self.envelope(n, xy) => {}
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES)),
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true),
NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
self.drawn_art(n, xy, Some(LIVE));
self.drawn_art(n, xy, Some(LIVE), true);
}
// Ruler guides are kept in the document's native copy only.
NodeKind::RulerGuide { .. } => {}
@@ -889,13 +893,17 @@ impl<'a> Writer<'a> {
}
/// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given.
fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>) {
/// With `bounds`, `n`'s text wrap options go on the rectangle of its bounds, the group's first
/// member ([`Self::wrap_on_bounds`]); without it, in the group's dictionary.
fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>, bounds: bool) {
if !self.open_group("u") {
return;
}
let state = self.state;
if let Some(w) = warning {
self.warn(w);
}
let moved = bounds && self.wrap_on_bounds(n, state);
if self.nest < MAX_NEST {
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
self.nest += 1;
@@ -906,9 +914,29 @@ impl<'a> Writer<'a> {
self.drawn -= 1;
self.nest -= 1;
}
self.wrap_moved = moved;
self.end_group("U", xy);
}
/// In the group that object `n` is written as, when the group's dictionary would hold `n`'s text
/// wrap options: the rectangle of `n`'s bounds with them ([`Self::wrap_bounds`]), then lock and
/// hidden state `state` again. True when the group's dictionary is to leave the options out
/// ([`Self::wrap_moved`]), so the group wraps type by `n`'s bounds, as `n` does
/// ([`vectorcraft_doc::text::resolve_wrap`]), not by its members. Written before the group's
/// members, the rectangle is below any area type among them and does not wrap it. False,
/// writing nothing, when `n` has no finite bounds, and the group's dictionary keeps the options.
fn wrap_on_bounds(&mut self, n: &Node, state: Option<(bool, bool)>) -> bool {
let Some(w) = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return false };
if finite_bounds(n).is_none() {
return false;
}
self.wrap_bounds(n, w);
if let Some((locked, hidden)) = state {
self.state(locked, hidden);
}
true
}
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
/// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an
/// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask
@@ -1555,23 +1583,20 @@ impl<'a> Writer<'a> {
for c in over {
self.node(c);
}
// Type wraps by its bounds: its text wrap options go on a rectangle of its bounds, the
// group's last member, and the group's dictionary leaves them out.
if let Some(w) = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) {
self.wrap_bounds(n, w);
self.wrap_moved = true;
}
// Type wraps by its bounds.
self.wrap_moved = self.wrap_on_bounds(n, state);
if let Some((locked, hidden)) = state {
self.state(locked, hidden);
}
self.end_group("U", xy);
}
/// An unpainted closed rectangle at the geometric bounds of type `n`, the region its text wraps
/// around, with `n`'s lock and hidden state and text wrap options `w` in its dictionary. Nothing
/// An unpainted closed rectangle at the geometric bounds of type, a symbol instance or a live
/// object `n`, the region its text wraps around ([`vectorcraft_doc::text::resolve_wrap`]), with
/// `n`'s lock and hidden state and text wrap options `w` in its dictionary. Nothing
/// when `n` has no finite bounds, or without room for it ([`Self::take_objects`]).
fn wrap_bounds(&mut self, n: &Node, w: TextWrap) {
let Some(b) = n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return };
let Some(b) = finite_bounds(n) else { return };
self.state(n.locked, !n.visible);
let objects = self.objects;
self.plain_object(&shapes::rectangle(b), FillRule::NonZero, None, None, Xy::PLAIN);
@@ -1760,6 +1785,11 @@ impl<'a> Writer<'a> {
}
}
/// `n`'s geometric bounds, when they are finite.
fn finite_bounds(n: &Node) -> Option<vectorcraft_geom::Rect> {
n.geometric_bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()))
}
/// The gradient of paint `p`, when it has one.
fn gradient(p: Option<&Paint>) -> Option<&vectorcraft_color::GradientPaint> {
match p {
@@ -411,9 +411,10 @@ impl Writer<'_> {
self.hidden -= 1;
self.nest -= 1;
// The distorted art, which takes the envelope's lock, visibility, transparency, name and
// opacity mask.
// opacity mask. The reader opens the envelope live, wrapping type by its bounds, so its text
// wrap options stay in the art's dictionary.
self.state(n.locked, !n.visible);
self.drawn_art(n, xy, None);
self.drawn_art(n, xy, None, false);
if !opened || outlines || self.left_out_since(charges) {
let lines = self.body.split_off(start);
self.give_back(charges, &lines);
+40 -11
View File
@@ -22,15 +22,15 @@ use kurbo::{ParamCurveArclen, PathSeg};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::text::MAX_AKI;
use vectorcraft_doc::{
AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, LineCap, LineJoin, Mojikumi, Node, NodeId, NodeKind, ParaDirection,
ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign,
AreaOptions, Burasagari, CharStyle, Document, FirstBaseline, Justify, Kinsoku, KinsokuShoriType, LineCap, LineJoin, Mojikumi, Node, NodeId,
NodeKind, ParaDirection, ParaStyle, PathAlign, PathEffect, TextKind, TextObject, VerticalAlign,
};
use vectorcraft_geom::{Affine, PathData, Point};
use crate::ps;
/// What the text document holds of type, and what it leaves out.
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off and right-to-left direction (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
/// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it.
const STREAM_VERSION: u32 = 14;
@@ -161,6 +161,10 @@ fn dict(pairs: Vec<(u32, V)>) -> V {
V::Dict(pairs)
}
/// The document's Kinsoku sets, in order, each by its name: a paragraph's key 27 is its set's index
/// here (0 Hard, 1 Soft), as the reader's `kinsoku_sets` reads them.
const KINSOKU_SETS: [&str; 2] = ["PhotoshopKinsokuHard", "PhotoshopKinsokuSoft"];
/// A resource set: its resources, each `<< /0 resource >>`, and its display list.
fn set(resources: Vec<V>, display: bool) -> V {
let mut d = vec![(0, V::List(resources.into_iter().map(|r| dict(vec![(0, r)])).collect()))];
@@ -401,7 +405,6 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool {
}
let hangul =
text.chars().any(|c| matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}' | '\u{FFA0}'..='\u{FFDC}'));
let pairs = text.chars().zip(text.chars().skip(1)).any(|(a, b)| vectorcraft_text::inseparable(a, b));
let held = ParaStyle {
justify: p.justify,
left_indent: p.left_indent,
@@ -411,16 +414,16 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool {
space_after: p.space_after,
hyphenate: p.hyphenate,
direction: p.direction.filter(|d| *d == ParaDirection::RightToLeft),
// The composition of Japanese punctuation new type gets (Line-end Punctuation Half
// Width, Standard burasagari) isn't reported: it changes no other script's lines.
// The Mojikumi set new type gets (Line-end Punctuation Half Width) isn't reported: it
// changes no other script's lines.
mojikumi: if p.mojikumi == Mojikumi::LineEndHalf { p.mojikumi } else { ParaStyle::default().mojikumi },
burasagari: if p.burasagari == Burasagari::Standard { p.burasagari } else { ParaStyle::default().burasagari },
kinsoku: p.kinsoku,
kinsoku_type: p.kinsoku_type,
burasagari: p.burasagari,
bunri_kinshi: p.bunri_kinshi,
// The text document has no Korean Line Break Anywhere: it reads back off, which
// changes only the lines of a paragraph with Hangul in it.
korean_line_break_anywhere: p.korean_line_break_anywhere && !hangul,
// Nor Bunri-Kinshi: it reads back off, which changes only the lines of a paragraph
// with an inseparable pair in it.
bunri_kinshi: p.bunri_kinshi && !pairs,
..ParaStyle::default()
};
*p != held
@@ -756,6 +759,32 @@ impl TextDoc {
(4, len(p.space_before)),
(5, len(p.space_after)),
(9, V::Bool(p.hyphenate)),
(23, V::Bool(p.bunri_kinshi)),
(
24,
V::Int(match p.burasagari {
Burasagari::None => 0,
Burasagari::Standard => 1,
Burasagari::Forced => 2,
}),
),
(
25,
V::Int(match p.kinsoku_type {
KinsokuShoriType::PushInFirst => 0,
KinsokuShoriType::PushOutFirst => 1,
KinsokuShoriType::PushOutOnly => 2,
}),
),
// The Kinsoku set: `/nil` for None, else its index in the document's sets ([`KINSOKU_SETS`]).
(
27,
match p.kinsoku {
Kinsoku::None => V::Name("nil"),
Kinsoku::Hard => V::Int(0),
Kinsoku::Soft => V::Int(1),
},
),
];
if rtl {
d.push((33, V::Int(1)));
@@ -1110,7 +1139,7 @@ impl TextDoc {
(1, set(fonts, true)),
(2, empty()),
(3, empty()),
(4, empty()),
(4, set(KINSOKU_SETS.iter().map(|name| dict(vec![(0, V::Str((*name).into()))])).collect(), false)),
(5, set(vec![normal_char], true)),
(6, set(vec![normal_para], true)),
(8, set(self.frames.iter().map(clone_v).collect(), false)),
+5
View File
@@ -581,6 +581,10 @@ struct Reader<'a> {
blend_budget: usize,
/// The group on `%_` lines an envelope's dictionary just took (see [`Reader::drop_envelope_art`]).
envelope_art: Option<Node>,
/// The envelope dictionaries whose `AIDeformArtKey` block (`X=` … `X+`) is being read, as how
/// many frames were open with each one innermost, innermost last. The block's art is art: a
/// dictionary in it is read as it is in a container ([`Reader::end_obj`]).
envelope_blocks: Vec<usize>,
/// Envelopes waiting for their drawn art, innermost last.
envelopes: Vec<PendingEnvelope>,
/// How many more envelopes and warped text objects this import may draw to check
@@ -813,6 +817,7 @@ impl<'a> Reader<'a> {
blend_record: None,
blend_budget: BLEND_BUDGET,
envelope_art: None,
envelope_blocks: Vec::new(),
envelopes: Vec::new(),
envelope_checks: super::envelope::MAX_CHECKED,
envelope_spent: super::envelope::Spent::default(),
+11 -1
View File
@@ -482,6 +482,13 @@ impl<'a> Reader<'a> {
return Ok(());
}
let Some(f) = self.frames.pop() else { return Ok(()) };
let depth = self.frames.len();
// A block left open ends with its dictionary, and envelopes still waiting in it keep their
// drawn art: nothing after the dictionary is theirs.
self.envelope_blocks.retain(|d| *d <= depth);
while let Some(p) = self.envelopes.pop_if(|p| p.depth > depth) {
self.warn(crate::import::ai::envelope::drawn_note(p.typed));
}
let Frame { kind, children, base, hidden, gs, pending_unread_fill, pending_unread_stroke, after, mesh_ended, state, .. } = f;
let Kind::Obj(mut o) = kind else { return Ok(()) };
obj::close(&mut o, &mut self.stack, base);
@@ -496,7 +503,10 @@ impl<'a> Reader<'a> {
}
self.after_object = after;
self.mesh_ended = mesh_ended;
if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) {
// An object's dictionary in an envelope's `AIDeformArtKey` block is about the art before it
// there, as it is in a container: an envelope there is one of the outer envelope's contents.
let in_block = o.ty == "ArtDictionary" && self.envelope_blocks.last() == Some(&depth);
if !in_block && matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) {
return self.push(V::Obj(Rc::new(*o)));
}
match o.ty.as_str() {
+29 -3
View File
@@ -41,8 +41,19 @@ impl<'a> Reader<'a> {
}
/// `X=` in a `/Mask` dictionary: the opacity mask's art starts, read until its `X+`
/// ([`Self::end_mask`]).
/// ([`Self::end_mask`]). In an envelope's dictionary, its `AIDeformArtKey` block starts
/// ([`Reader::envelope_blocks`]).
fn open_mask_object(&mut self, hidden: bool) -> Result<(), String> {
if let Some(Frame { kind: Kind::Obj(o), .. }) = self.frames.last()
&& o.ty == "ArtDictionary"
&& o.get("AIDeformOptionsKey").is_some()
{
// One entry for each open dictionary, however many `X=` it has.
if self.envelope_blocks.last() != Some(&self.frames.len()) {
self.envelope_blocks.push(self.frames.len());
}
return Ok(());
}
if !matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(o), .. }) if o.ty == "Mask") {
// `X=` also introduces legacy text frame art, read by `text_frames`.
return Ok(());
@@ -63,6 +74,22 @@ impl<'a> Reader<'a> {
self.open(Kind::Mask, hidden)
}
/// `X+`: a dictionary's art block ends. The block of a dictionary whose `X=` opened no frame (an
/// envelope's, in an opacity mask's art too) ends with the dictionary still innermost; an opacity
/// mask's ends its art ([`Self::end_mask`]).
fn end_block(&mut self) -> Result<(), String> {
if matches!(self.frames.last(), Some(Frame { kind: Kind::Obj(_), .. })) {
if self.envelope_blocks.last() == Some(&self.frames.len()) {
self.envelope_blocks.pop();
}
return Ok(());
}
if self.frames.iter().any(|f| matches!(f.kind, Kind::Mask)) {
return self.end_mask();
}
Ok(())
}
/// `LB`: a graph started in this layer that hasn't ended doesn't go on past it; the layer ends.
fn layer_end(&mut self) -> Result<(), String> {
if self.graph.as_ref().is_some_and(|g| g.frames >= self.frames.len()) {
@@ -159,8 +186,7 @@ impl<'a> Reader<'a> {
}
";" => return self.end_obj(),
"X=" => return self.open_mask_object(hidden),
"X+" if self.frames.iter().any(|f| matches!(f.kind, Kind::Mask)) => return self.end_mask(),
"X+" => return Ok(()),
"X+" => return self.end_block(),
_ => {}
}
self.state_block_continues(w);
+218
View File
@@ -8620,6 +8620,224 @@ fn an_envelope_off_the_page_opens_live_when_it_draws_close_to_its_drawn_art() {
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
/// `art` on `%_` lines, as the editing data writer hides it: a line already on one stays as it is.
fn hidden_once(art: &str) -> String {
art.lines().map(|l| if l.starts_with("%_") { format!("{l}\n") } else { format!("%_{l}\n") }).collect()
}
/// A mesh envelope of `content` shaped by the grid `shape`, with Edit Contents on (`editing`: the
/// contents in the group before the dictionary, the grid in its `AIDeformArtKey` block) or off (the
/// other way round, the contents in a plain group), then `drawn` and the plugin's `XP`. An envelope
/// record in `content` keeps its own `%_` lines.
fn mesh_envelope(shape: &str, editing: bool, content: &str, drawn: &str) -> String {
let keys = ENVELOPE_KEYS.replace("0 /Bool (AIDeformEditModeKey)", &format!("{} /Bool (AIDeformEditModeKey)", u8::from(editing)));
let (before, block) = if editing { (content.to_string(), shape.to_string()) } else { (shape.to_string(), format!("u\n{content}U\n9 () XW\n")) };
format!(
"{}%_/ArtDictionary :\n{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n",
hidden_once(&format!("u\n{before}U\n")),
commented(&keys),
hidden_once(&block),
)
}
/// The mesh envelope that maps the box 40 20 160 80 onto itself, and what it draws of
/// [`envelope_content`].
fn flat_mesh() -> (String, vectorcraft_doc::live::EnvelopeKind, String) {
let flat = vectorcraft_doc::live::EnvelopeKind::Mesh {
rows: 1,
cols: 1,
points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)],
handles: vec![],
};
let drawn = drawn_content(&flat);
(straight_mesh(1, 1, (120.0, 60.0)), flat, drawn)
}
/// An envelope inside another envelope's contents opens as a live envelope inside the live outer
/// one, with Edit Contents on or off at either level: each keeps its own kind, contents and Edit
/// Contents, and neither leaves a copy of its contents drawn beside it.
#[test]
fn an_envelope_in_an_envelope_s_contents_opens_live_inside_it() {
use vectorcraft_doc::live::EnvelopeKind;
let (shape, flat, drawn) = flat_mesh();
let EnvelopeKind::Mesh { points, .. } = &flat else { panic!("{flat:?}") };
for (outer_editing, inner_editing) in [(false, false), (false, true), (true, false), (true, true)] {
let why = format!("outer editing {outer_editing}, inner editing {inner_editing}");
let inner = mesh_envelope(&shape, inner_editing, &envelope_content(), &drawn);
let r = read_ok(&layer(&mesh_envelope(&shape, outer_editing, &hidden_once(&inner), &format!("u\n{drawn}U\n"))));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{why}: {a:#?}");
let flat_points = |kind: &EnvelopeKind| match kind {
EnvelopeKind::Mesh { rows: 1, cols: 1, points, .. } => Some(points.clone()),
_ => None,
};
let (content, kind, _, editing, _) = live_envelope(&a[0]);
assert_eq!((flat_points(kind), editing), (Some(points.clone()), outer_editing), "{why}: {kind:?}");
assert_eq!(content.len(), 1, "{why}: {content:#?}");
let (inner, kind, _, editing, _) = live_envelope(&content[0]);
assert_eq!((flat_points(kind), editing), (Some(points.clone()), inner_editing), "{why}: {kind:?}");
assert_eq!(inner.len(), 1, "{why}: {inner:#?}");
assert!(matches!(inner[0].kind, NodeKind::Path { .. }), "{why}: {inner:#?}");
assert_eq!(fill(&inner[0]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "{why}");
assert!(r.warnings.is_empty(), "{why}: {:?}", r.warnings);
}
}
/// An outer envelope, Edit Contents off, whose `AIDeformArtKey` block holds `block` as it is, with no
/// plain group around it, shaped by the grid `shape` and drawn as `drawn`.
fn bare_block_envelope(shape: &str, block: &str, drawn: &str) -> String {
format!(
"{}%_/ArtDictionary :\n{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n",
hidden_once(&format!("u\n{shape}U\n")),
commented(ENVELOPE_KEYS),
hidden_once(block),
)
}
/// An envelope record straight in another envelope's `AIDeformArtKey` block, with no group around
/// it, opens live inside the live outer envelope too. Two of them there are both its contents.
#[test]
fn an_envelope_straight_in_an_envelope_s_block_opens_live_inside_it() {
let (shape, _, drawn) = flat_mesh();
let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn));
let r = read_ok(&layer(&bare_block_envelope(&shape, &inner, &format!("u\n{drawn}U\n"))));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
let (content, ..) = live_envelope(&a[0]);
assert_eq!(content.len(), 1, "{content:#?}");
let (inner_content, ..) = live_envelope(&content[0]);
assert!(matches!(inner_content[0].kind, NodeKind::Path { .. }), "{inner_content:#?}");
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
// Two envelopes side by side in the block: both are the outer envelope's contents, each live.
let two = format!("{inner}{inner}");
let r = read_ok(&layer(&bare_block_envelope(&shape, &two, &format!("u\n{drawn}U\nu\n{drawn}U\n"))));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
let (content, ..) = live_envelope(&a[0]);
assert_eq!(content.len(), 2, "{content:#?}");
content.iter().for_each(|c| _ = live_envelope(c));
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
/// An object's own dictionary straight in an envelope's block, with no group around them, names it
/// there.
#[test]
fn an_object_s_dictionary_straight_in_an_envelope_s_block_names_it() {
let (shape, _, drawn) = flat_mesh();
let block = format!("{}/ArtDictionary :\n(Box) /String (AIArtName) ,\n;\n", envelope_content());
let r = read_ok(&layer(&bare_block_envelope(&shape, &block, &format!("u\n{drawn}U\n"))));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
let (content, ..) = live_envelope(&a[0]);
assert_eq!(content.len(), 1, "{content:#?}");
assert_eq!(content[0].name.as_deref(), Some("Box"), "{content:#?}");
}
/// An inner envelope that doesn't open live keeps its drawn art inside the live outer envelope,
/// drawn once, without its own source art: one whose drawn art differs from what it draws, and one
/// whose record doesn't read (a style number past the list). The outer envelope maps that drawn
/// art's box onto its grid. An outer envelope that doesn't match its drawn art keeps that drawn
/// art, and nothing of its record is drawn.
#[test]
fn a_nested_envelope_that_doesn_t_open_live_keeps_its_drawn_art() {
let (shape, _, drawn) = flat_mesh();
let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0));
let unread = mesh_envelope(&shape, false, &envelope_content(), &drawn).replace("%_2 /Int (AIDeformStyle)", "%_9 /Int (AIDeformStyle)");
for (why, inner) in [("drawn elsewhere", mesh_envelope(&shape, false, &envelope_content(), &shifted)), ("unread", unread)] {
for bare in [false, true] {
let inner = hidden_once(&inner);
let outer_drawn = format!("u\n{drawn}U\n");
let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) };
let r = read_ok(&layer(&body));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{why}, bare {bare}: {a:#?}");
assert!(matches!(a[0].kind, NodeKind::Envelope { .. }), "{why}, bare {bare}: {:?}", r.warnings);
let (content, ..) = live_envelope(&a[0]);
assert_eq!(content.len(), 1, "{why}, bare {bare}: {content:#?}");
// The inner envelope's drawn art: its group of one path, or, straight in the block, the
// path, as the plain group around a block's only object is the block's own.
let drawn_path = if bare {
&content[0]
} else {
let kids = content[0].children().unwrap_or_else(|| panic!("{why}: {content:#?}"));
assert_eq!(kids.len(), 1, "{why}: {content:#?}");
&kids[0]
};
assert!(matches!(drawn_path.kind, NodeKind::Path { .. }), "{why}, bare {bare}: {content:#?}");
assert_eq!(r.warnings, [super::envelope::DRAWN], "{why}, bare {bare}");
}
}
// The outer envelope's drawn art lies elsewhere: it stays, as one group, the inner record with it.
let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn));
for bare in [false, true] {
let outer_drawn = format!("u\n{shifted}U\n");
let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) };
let r = read_ok(&layer(&body));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "bare {bare}: {a:#?}");
assert!(matches!(a[0].kind, NodeKind::Group { .. }), "bare {bare}: {a:#?}");
assert_eq!(a[0].geometric_bounds(), Some(Rect::new(42.0, 20.0, 162.0, 80.0)), "bare {bare}");
assert_eq!(r.warnings, [super::envelope::DRAWN], "bare {bare}");
}
}
/// Broken nested records read without taking another record's place: an inner `X=` with no `X+`
/// (the inner envelope still opens live), an inner dictionary with no group before it (its drawn art
/// stays), and an `XP` repeated after the inner one. The outer envelope, whose own record is whole,
/// still opens live around what the inner one left.
#[test]
fn broken_nested_envelope_records_keep_the_outer_envelope() {
let (shape, _, drawn) = flat_mesh();
let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn));
let no_end = inner.replacen("%_X+\n", "", 1);
let no_group = inner.replacen(&hidden_once(&format!("u\n{shape}U\n")), "", 1);
let twice = inner.replace("%_(Adobe Deform Plugin) 1 0 0 XP\n", "%_(Adobe Deform Plugin) 1 0 0 XP\n%_(Adobe Deform Plugin) 1 0 0 XP\n");
for (why, inner, live) in [("no X+", no_end, true), ("no group", no_group, false), ("XP twice", twice, true)] {
for bare in [false, true] {
let outer_drawn = format!("u\n{drawn}U\n");
let body = if bare { bare_block_envelope(&shape, &inner, &outer_drawn) } else { mesh_envelope(&shape, false, &inner, &outer_drawn) };
let r = read_ok(&layer(&body));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{why}, bare {bare}: {a:#?}");
let (content, ..) = live_envelope(&a[0]);
assert_eq!(content.len(), 1, "{why}, bare {bare}: {content:#?}");
assert_eq!(matches!(content[0].kind, NodeKind::Envelope { .. }), live, "{why}, bare {bare}: {content:#?}");
}
}
}
/// An inner envelope whose `XP` is missing stops waiting when the outer envelope's dictionary ends:
/// a stray `XP` in a later group leaves that group's art as it is.
#[test]
fn an_inner_envelope_without_its_xp_does_not_take_later_art() {
let (shape, _, drawn) = flat_mesh();
let inner = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn)).replace("%_(Adobe Deform Plugin) 1 0 0 XP\n", "");
let later = format!("u\nu\n{drawn}U\n(Adobe Deform Plugin) 1 0 0 XP\nU\n");
let r = read_ok(&layer(&format!("{}{later}", bare_block_envelope(&shape, &inner, &format!("u\n{drawn}U\n")))));
let a = art(&r.doc);
assert_eq!(a.len(), 2, "{a:#?}");
live_envelope(&a[0]);
let kids = a[1].children().unwrap_or_else(|| panic!("{a:#?}"));
assert!(matches!(kids[0].kind, NodeKind::Group { .. }), "{a:#?}");
assert_eq!(r.warnings, [super::envelope::DRAWN], "{:?}", r.warnings);
}
/// An envelope in an opacity mask's art reads: its block's `X+` ends the block, not the mask's art.
#[test]
fn an_envelope_in_an_opacity_mask_s_art_reads() {
let (shape, _, drawn) = flat_mesh();
let owner = format!("{RED}{}f\n", rect_path(10.0, 20.0, 170.0, 90.0));
let envelope = hidden_once(&mesh_envelope(&shape, false, &envelope_content(), &drawn));
let mask = format!(
"%_/ArtDictionary :\n%_/Mask :\n%_1 /Bool (Linked) ,\n%_X=\n%_u\n{envelope}%_U\n%_X+\n%_(Art) ,\n%_1 /Bool (Clipping) ,\n%_0 /Bool (Inverted) ,\n%_0 /Bool (Disabled) ,\n%_; (AI9_Mask) ,\n%_;\n"
);
let r = read_ok(&layer(&format!("{owner}{mask}")));
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
let m = a[0].extras().mask.as_ref().unwrap_or_else(|| panic!("{a:#?}"));
assert_eq!(m.art.geometric_bounds(), Some(Rect::new(40.0, 20.0, 160.0, 80.0)), "{:#?}", m.art);
}
#[test]
fn a_gradient_mesh_reads_as_a_patch() {
let corner = |rgb: &str, x: i32, y: i32, next: (i32, i32), prev: (i32, i32)| {
+38
View File
@@ -212,6 +212,44 @@ fn text_composer_round_trips() {
assert!(!String::from_utf8_lossy(&save(&d2, false)).contains("composer"));
}
/// Every composer reads back as it was saved (the two Standard ones as their own values), and the
/// ME&SA names are the ones files have always used: `everyLine` stays the unwritten default and
/// `singleLine` keeps its spelling, so a document that never picks a Standard composer is unchanged.
#[test]
fn all_four_composers_round_trip() {
use vectorcraft_doc::{TextKind, TextObject};
let one = |c: Composer| {
let mut d = Document::new(200.0, 200.0);
let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "ક\u{ACD}ક", Default::default());
t.para.composer = c;
t.kind = TextKind::Point;
let id = d.alloc_id();
d.insert(None, usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
d
};
for (c, written) in [
(Composer::SingleLine, Some("singleLine")),
(Composer::EveryLine, None),
(Composer::StandardSingleLine, Some("standardSingleLine")),
(Composer::StandardEveryLine, Some("standardEveryLine")),
] {
let bytes = save(&one(c), false);
let text = String::from_utf8_lossy(&bytes);
match written {
Some(w) => assert!(text.contains(&format!("\"composer\":\"{w}\"")), "{c:?}"),
None => assert!(!text.contains("\"composer\""), "{c:?}"),
}
let back = load(&bytes).unwrap();
let mut got = None;
back.walk(|n| {
if let NodeKind::Text(t) = &n.kind {
got = Some(t.para.composer);
}
});
assert_eq!(got, Some(c));
}
}
/// A document as the first version wrote it (format name `drawcraft`, anchors as maps).
const V1_FILE: &str = r#"{"format":"drawcraft","version":1,"generator":"DrawCraft 0.1.0","document":{"version":1,"title":"Old","artboards":[{"id":1,"name":"Artboard 1","rect":{"x0":0.0,"y0":0.0,"x1":100.0,"y1":80.0}}],
"layers":[{"id":1,"name":"Layer 1","visible":true,"locked":false,"opacity":1.0,"kind":{"type":"layer","children":[
+1 -1
View File
@@ -392,7 +392,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"type.lineComposer",
"Toggle Line Composer",
"Cmd+Alt+Shift+C",
"{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer (text.setFormat {composer}) → \"singleLine\" | \"everyLine\"",
"{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer; paragraphs that all use a Standard composer keep it, any other mix takes the Middle Eastern & South Asian one (text.setFormat {composer}) → \"singleLine\" | \"everyLine\" | \"standardSingleLine\" | \"standardEveryLine\"",
),
(
"type.hyphenate",
+5 -1
View File
@@ -859,7 +859,9 @@ impl Exporter<'_> {
/// Opens the blend mode and the transparency group `n` is drawn with (`container` when it is a
/// group or layer whose children `knockout` each other). Returns how many were opened, and
/// whether the children are to be drawn in an isolated group of their own: the knockout group of
/// an unclipped group's elements is its isolated group too.
/// an unclipped group's elements is its isolated group too. An opaque knockout group in Normal
/// mode that does not isolate opens no group: its elements are drawn on the art below it, in a
/// knockout group without `/I` when there are several.
fn transparency(s: &mut Surface, n: &Node, page: Rect, container: bool, knockout: bool) -> (usize, bool) {
let mut pushes = 0;
if n.blend != BlendMode::Normal {
@@ -876,6 +878,8 @@ fn transparency(s: &mut Surface, n: &Node, page: Rect, container: bool, knockout
} else if n.opacity < 1.0 {
s.push_opacity(norm(n.opacity));
pushes += 1;
} else if knockout && !n.isolate && n.blend == BlendMode::Normal {
// A knockout group that does not isolate: its elements start from the art below it.
} else if knockout && matches!(n.kind, NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. }) {
isolated_children = true;
} else {
+71
View File
@@ -151,6 +151,77 @@ fn a_knockout_group_is_written_as_one_pdf_knockout_group() {
}
}
/// A knockout group with nothing blending inside is drawn in an isolated group (`/I true`) only
/// when the group isolates, clipped or not, with opaque or translucent elements, and reads back
/// knocking out.
#[test]
fn a_knockout_group_without_blending_inside_is_isolated_only_when_it_isolates() {
for clip in [false, true] {
for opacity in [0.5, 1.0] {
for isolate in [false, true] {
let mut d = knockout_squares(3, false, isolate);
let g = d.layers[0].children().unwrap()[1].id;
let mut squares: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec();
for s in &mut squares {
std::sync::Arc::make_mut(s).opacity = opacity;
}
if clip {
let c = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(10.0, 10.0, 190.0, 190.0)),
Appearance::basic(Paint::None, Paint::None, 0.0),
);
squares.insert(0, std::sync::Arc::new(c));
}
d.node_mut(g).unwrap().kind = vectorcraft_doc::NodeKind::Group { children: squares, clip };
let case = format!("clip {clip}, opacity {opacity}, isolate {isolate}");
let t = text(&d);
assert_eq!(t.matches("/Ktrue").count(), 1, "{case}");
// Each translucent element is an isolated form with its opacity.
let elements = if opacity < 1.0 { 3 } else { 0 };
assert_eq!(t.matches("/Itrue").count(), elements + usize::from(isolate), "{case}");
let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("{case}: {e}"));
let mut found = vec![];
back.walk(|n| {
if n.knockout == vectorcraft_doc::Knockout::On {
found.push(n.isolate);
}
});
assert_eq!(found, [false], "{case}");
}
}
}
}
/// An overprinting element of a knockout group that does not isolate is drawn in a `/K` group
/// without `/I true`, so it overprints the art below the group, and its graphics state still
/// overprints (`/OP`, `/op`, `/OPM 1`). An isolated group keeps `/I true`.
#[test]
fn an_overprinting_element_of_a_knockout_group_that_does_not_isolate_overprints_the_art_below() {
for isolate in [false, true] {
let mut d = knockout_squares(3, false, isolate);
let g = d.layers[0].children().unwrap()[1].id;
let squares: Vec<_> = d.node(g).unwrap().children().unwrap().iter().map(|s| s.id).collect();
for s in &squares {
d.node_mut(*s).unwrap().opacity = 1.0;
}
d.node_mut(squares[2]).unwrap().appearance.fill_mut().unwrap().overprint = true;
let t = text(&d);
assert_eq!(t.matches("/Ktrue").count(), 1, "isolate {isolate}");
assert_eq!(t.matches("/Itrue").count(), usize::from(isolate), "isolate {isolate}");
assert!(t.contains("/OPtrue/optrue/OPM1"), "isolate {isolate}");
let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap_or_else(|e| panic!("isolate {isolate}: {e}"));
let mut overprints = vec![];
back.walk(|n| {
if let Some(f) = n.appearance.fill() {
overprints.push(f.overprint);
}
});
assert_eq!(overprints, [false, false, false, true], "isolate {isolate}");
assert_eq!(knockout_groups(&back), [3], "isolate {isolate}");
}
}
/// The knockout group of an isolated group is isolated too (`/I true` beside `/K true`), and the
/// group reads back as isolated and knocking out. (Each translucent element is a group of its own.)
#[test]
+6
View File
@@ -52,6 +52,10 @@ pub struct OtFeatures {
pub extra_values: [u16; EXTRA_FEATURES.len()],
/// The value `swsh=N` gives swashes ([`Self::swash`]), as [`Self::extra_values`] for `salt`.
pub swash_value: u16,
/// Set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its
/// characters, with none of its layout tables: the Standard composers. Set per paragraph by
/// layout from the paragraph's composer, not by a style.
pub unshaped_complex: bool,
}
/// The largest value a `tag=N` feature takes: a font's glyph ids are 16 bits, so is an alternate's
@@ -94,6 +98,7 @@ impl Default for OtFeatures {
extra: 0,
extra_values: [0; EXTRA_FEATURES.len()],
swash_value: 0,
unshaped_complex: false,
}
}
}
@@ -167,6 +172,7 @@ impl OtFeatures {
extra: u32::MAX >> (32 - EXTRA_FEATURES.len()),
extra_values: [0; EXTRA_FEATURES.len()],
swash_value: 0,
unshaped_complex: false,
};
change(&mut off);
change(&mut on);
+4 -3
View File
@@ -78,10 +78,11 @@ fn joining(c: char) -> Joining {
}
/// Is the cluster of glyph `a` joined to the cluster of glyph `b` that follows it in `text`: both
/// right to left in one face, `a`'s last character other than a mark joining the letter after it,
/// and `b` starting with a letter that joins the one before it?
/// right to left in one face and set as joining letters (not by a Standard composer), `a`'s last
/// character other than a mark joining the letter after it, and `b` starting with a letter that
/// joins the one before it?
fn joined(text: &str, a: &SGlyph, b: &SGlyph) -> bool {
if a.face.id() != b.face.id() || a.level != b.level || !a.level.is_rtl() || a.byte + a.len != b.byte {
if a.face.id() != b.face.id() || a.level != b.level || !a.level.is_rtl() || a.byte + a.len != b.byte || !(a.cursive && b.cursive) {
return false;
}
let last = text.get(a.byte..a.byte + a.len).and_then(|s| s.chars().rev().find(|&c| joining(c) != Joining::Transparent));
+9 -5
View File
@@ -22,7 +22,7 @@ use crate::shape::{
Punct, SGlyph, Tcy, cap_x_heights, hyphen_glyph, is_cjk, mark_word_ends, no_line_end, no_line_start, punct, run_face, shape_range, shape_runs,
soft_line_start, style_metrics,
};
use crate::{Composer, FirstBaseline, InlineGlyph, LayoutOptions, LineInfo, ListMarker, OtFeatures, PositionedGlyph, TextLayout, VerticalAlign};
use crate::{FirstBaseline, InlineGlyph, LayoutOptions, LineInfo, ListMarker, OtFeatures, PositionedGlyph, TextLayout, VerticalAlign};
mod bidi;
mod breaking;
@@ -229,11 +229,14 @@ impl Ctx<'_> {
out
}
/// Shape paragraph `r` (its bidi resolution `bidi`).
fn shape_para(&self, r: Range<usize>, bidi: Option<&BidiInfo<'_>>) -> Vec<SGlyph> {
/// Shape paragraph `r` (its bidi resolution `bidi`, its attributes `para`). A Standard composer
/// sets a complex script glyph by glyph ([`OtFeatures::unshaped_complex`]).
fn shape_para(&self, r: Range<usize>, bidi: Option<&BidiInfo<'_>>, para: &ParaStyle) -> Vec<SGlyph> {
let mut v = Vec::with_capacity(r.len());
let levels = bidi.map_or(&[][..], |b| &b.levels);
shape_runs(self.db, self.text, r, &self.runs, &self.inlines, &self.faces, &self.opts.features, levels, &mut v);
let standard = !self.opts.composer.unwrap_or(para.composer).shapes_complex_scripts();
let feats = OtFeatures { unshaped_complex: standard, ..self.opts.features };
shape_runs(self.db, self.text, r, &self.runs, &self.inlines, &self.faces, &feats, levels, &mut v);
self.finish_shaping(&mut v, |g| self.style_at(g.byte));
v
}
@@ -373,7 +376,8 @@ impl Ctx<'_> {
// Only the glyph right after an upright glyph can continue its cluster.
let cluster = self.upright_cluster.take();
// Control characters (tabs) and soft hyphens draw nothing (fonts map them to .notdef).
let blank = g.is_soft_hyphen() || g.ch.is_control() || g.ch == '\u{2028}';
// Joiners and direction marks are format controls: no ink either, whatever glyph the font maps.
let blank = g.is_soft_hyphen() || g.ch.is_control() || g.ch == '\u{2028}' || crate::justify::is_format_control(g.ch);
// A colour glyph draws its art (COLR layers, an SVG document) or its image (a bitmap, or
// COLR paints documents have no form for), not its outline; COLR, then SVG, then bitmaps.
// Art in the text's colours takes the run's fill (black when it isn't a colour) and
+6 -6
View File
@@ -8,9 +8,9 @@ use super::vertical::{
EM_CENTER, MojikumiRules, align_shift, compress_punctuation, dot_quarter, glyph_em, halve_punctuation, punct_half, space_japanese_and_latin,
};
use super::{
Affine, BidiInfo, Burasagari, CharStyle, Composer, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo,
ListMarker, ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line,
hyphen_glyph, is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics,
Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker,
ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph,
is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics,
};
use crate::justify::is_format_control;
use crate::shape::{keep_inseparable_pairs, keep_korean_words};
@@ -62,7 +62,7 @@ fn compose_para(
// The tab of a list marker is on the first line, with the marker, and has a fixed width.
let has_tab = sg.iter().any(|g| g.ch == '\t' && g.len > 0);
let has_soft_break = sg.iter().any(|g| g.ch == '\u{2028}');
if composer != Composer::EveryLine
if composer.is_single_line()
|| pen.regions.is_none()
|| sg.len() < 2
|| sg.len() > MAX_COMPOSE_GLYPHS
@@ -247,7 +247,7 @@ fn prepare_paragraph<'a, 'text>(
let text = cx.text;
let bidi = para_bidi_with(text.get(pr.clone()).unwrap_or_default(), para.direction, &cx.char_directions(&pr));
let rtl = is_rtl(bidi.as_ref());
let mut sg = cx.shape_para(pr.clone(), bidi.as_ref());
let mut sg = cx.shape_para(pr.clone(), bidi.as_ref(), para);
// Thai, Lao, Khmer and Myanmar break lines between words, not at spaces.
mark_word_ends(text.get(pr.clone()).unwrap_or_default(), pr.start, &mut sg);
// Korean breaks between words, unless Korean Line Break Anywhere lets it break between syllables.
@@ -321,7 +321,7 @@ fn prepare_paragraph<'a, 'text>(
let composed = compose_para(cx, &sg, &flex, &line_end, para, pen, rtl, continued);
// Hyphenation options: the Hyphenation Zone applies with the Single-line Composer, and the
// Hyphen Limit counts the lines in a row that end with a hyphen.
let zone = if cx.opts.composer.unwrap_or(para.composer) == Composer::SingleLine { para.hyphenation.zone } else { 0.0 };
let zone = if cx.opts.composer.unwrap_or(para.composer).is_single_line() { para.hyphenation.zone } else { 0.0 };
let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX);
let mirror = mirrors_indents(para, rtl, cx.vertical);
ParagraphData {
+1 -1
View File
@@ -422,7 +422,7 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject,
let text = cx.text;
let bidi = para_bidi_with(text.get(pr.clone()).unwrap_or_default(), para.direction, &cx.char_directions(pr));
rtl.get_or_insert(is_rtl(bidi.as_ref()) && !cx.vertical);
let mut glyphs = cx.shape_para(pr.clone(), bidi.as_ref());
let mut glyphs = cx.shape_para(pr.clone(), bidi.as_ref(), t.para_at(pi));
// Bullets and numbers: a list paragraph's text starts after its marker here too, unless
// the paragraph continues from the frame before in its thread.
if pi > 0 || !t.first_para_continues {
+39 -5
View File
@@ -128,6 +128,27 @@ pub(crate) fn joins(script: Script) -> bool {
)
}
/// Is `script` one a Standard composer leaves unshaped: Indic (conjuncts, half forms, marks placed
/// by the font's layout tables), the joining scripts ([`joins`]: Arabic, Syriac, N'Ko, Mongolian…)
/// and Hebrew?
fn is_complex_script(script: Script) -> bool {
joins(script)
|| matches!(
script,
Script::Hebrew
| Script::Devanagari
| Script::Bengali
| Script::Gurmukhi
| Script::Gujarati
| Script::Oriya
| Script::Tamil
| Script::Telugu
| Script::Kannada
| Script::Malayalam
| Script::Sinhala
)
}
/// How `vpal` and the vertical kerning with it move an upright glyph in vertical type and change
/// its length down the column, in points: `advance` down the column, `dx` and `dy` in glyph space
/// (y down; `dy` is down the column once the glyph stands upright). `proportional`: `vpal` itself
@@ -1394,7 +1415,13 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
let source_runs = &(source_runs.start + first..source_runs.start + last);
let text_seg = &text[range.clone()];
// The segment's script: that of its first character of a script of its own.
let cursive = text_seg.chars().map(|c| c.script()).find(|s| !matches!(s, Script::Common | Script::Inherited)).is_some_and(joins);
let first_script = text_seg.chars().map(|c| c.script()).find(|s| !matches!(s, Script::Common | Script::Inherited));
// A Standard composer sets a complex script glyph by glyph (no layout tables, nominal glyphs).
// shortcut: decided for the whole segment by its first strong script, as `cursive` is; segments
// already split where the script changes.
let unshaped = feats.unshaped_complex && first_script.is_some_and(is_complex_script);
// Unshaped letters don't join, so they are not bent along a path as joined ones are.
let cursive = first_script.is_some_and(joins) && !unshaped;
let full = st.size.max(0.0);
// Superscript/subscript and small capitals shrink the glyphs; line metrics keep the full size.
let (_, pos_shift) = st.position.scale_shift(full);
@@ -1475,7 +1502,7 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
.and_then(|l| l.parse::<harfrust::Language>().ok());
let mut shaped = Shaped::default();
let Shaped { raw, proportional, vpal, chars, unkerned } = &mut shaped;
let hb_shaped = face.hb().map(|hb| {
let hb_shaped = face.hb().filter(|_| !unshaped).map(|hb| {
let shaper = face.shaper.shaper(&hb).instance(face.instance.as_ref()).build();
// The baseline and character-level pass use exactly the same resolved features.
// Alternate positioning passes still resolve their own features, with `more` last.
@@ -1591,7 +1618,8 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
}
});
if hb_shaped.is_none() {
// Fallback: nominal glyphs and hmtx advances, no shaping.
// Fallback: nominal glyphs and hmtx advances, no shaping (also a complex script under a
// Standard composer).
if let Some(f) = face.skrifa() {
let cmap = f.charmap();
let gm = f.glyph_metrics(Size::unscaled(), face.location());
@@ -1600,8 +1628,14 @@ fn shape_segment(text: &str, context: &Range<usize>, seg: &Segment, feats: &OtFe
let c = st.digits.map(c);
let chars: Vec<char> = if upper { c.to_uppercase().collect() } else { vec![c] };
for u in chars {
let g = cmap.map(u).unwrap_or_default();
let adv = gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5);
// Format characters (joiners, direction marks) have no glyph of their own in most
// fonts, and the shaper hides them: draw the space's glyph with no advance.
let (g, adv) = if crate::justify::is_format_control(u) {
(cmap.map(' ').unwrap_or_default(), 0.0)
} else {
let g = cmap.map(u).unwrap_or_default();
(g, gm.advance_width(g).unwrap_or(face.upem as f32 * 0.5))
};
raw.push((g.to_u32(), cl, adv.round() as i32, 0, 0));
}
}
+5 -3
View File
@@ -534,7 +534,8 @@ pub fn half_form_font(half: bool) -> Option<Vec<u8>> {
pub const CONJUNCT_FAMILY: &str = "Conjuncttest Sans";
/// A test-only cmap over bundled Source Sans 3: Devanagari Ka uses K, the halant uses a period and
/// the vowel sign I (drawn before its syllable) uses i. The `GSUB` table's `dev2` script has an
/// the vowel sign I (drawn before its syllable) uses i; Gujarati Ka, virama and vowel sign I use the
/// same glyphs. The `GSUB` table's `dev2` and `gjr2` scripts have an
/// `aalt` single substitution of K by k and a `salt` one of K by i, which list k and the vowel
/// sign's glyph as alternates of Ka, and a `half` ligature of K and the period into k (Ka's half
/// form). Family [`CONJUNCT_FAMILY`]. `None` when it can't be built.
@@ -549,7 +550,7 @@ pub fn conjunct_font() -> Option<Vec<u8>> {
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
let font = skrifa::FontRef::new(BASE).ok()?;
let charmap = font.charmap();
let mapping = [('क', 'K'), ('\u{094D}', '.'), ('\u{093F}', 'i')];
let mapping = [('क', 'K'), ('\u{094D}', '.'), ('\u{093F}', 'i'), ('ક', 'K'), ('\u{0ACD}', '.'), ('\u{0ABF}', 'i')];
let mappings = mapping.into_iter().map(|(c, source)| Some((c, write_fonts::types::GlyphId::new(charmap.map(source)?.to_u32()))));
let cmap = Cmap::from_mappings(mappings.collect::<Option<Vec<_>>>()?).ok()?;
let family = CONJUNCT_FAMILY;
@@ -574,7 +575,8 @@ pub fn conjunct_font() -> Option<Vec<u8>> {
SubstitutionLookup::Ligature(Lookup::new(Default::default(), vec![half])),
SubstitutionLookup::Single(Lookup::new(Default::default(), vec![salt.into()])),
]);
let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"dev2"), Script::new(Some(LangSys::new(vec![0, 1, 2])), vec![]))]);
let langsys = || Script::new(Some(LangSys::new(vec![0, 1, 2])), vec![]);
let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"dev2"), langsys()), ScriptRecord::new(Tag::new(b"gjr2"), langsys())]);
builder.add_table(&Gsub::new(scripts, features, lookups)).ok()?;
for r in font.table_directory.table_records() {
let tag = Tag::new(&r.tag().to_be_bytes());
+1
View File
@@ -10,6 +10,7 @@ mod bidi;
mod bitmaps;
mod colr;
mod combos;
mod composers;
mod composite;
mod devanagari;
mod embed;
+113
View File
@@ -0,0 +1,113 @@
//! The four composers: the Middle Eastern & South Asian ones shape complex scripts with the font's
//! layout tables, the Standard ones set them glyph by glyph as the font maps their characters.
//! Uses a font built in code ([`conjunct_font`]): Ka K, halant a period and vowel sign I i, in
//! Devanagari and Gujarati, with a `half` ligature of K and the period into k.
use crate::test_fonts::{CONJUNCT_FAMILY, conjunct_font, source_sans_gid};
use crate::*;
use kurbo::Point;
use vectorcraft_doc::{CharStyle, Composer, TextObject};
/// Ka, halant, Ka, vowel sign I in Devanagari, then in Gujarati.
const DEVANAGARI: &str = "क\u{94D}क\u{93F}";
const GUJARATI: &str = "ક\u{ACD}ક\u{ABF}";
fn db() -> FontDb {
let db = FontDb::with_font_dirs(vec![]);
db.add_font(conjunct_font().expect("the test font builds"));
db
}
fn object(text: &str, composer: Composer) -> TextObject {
let st = CharStyle { font_family: CONJUNCT_FAMILY.into(), font_style: "Regular".into(), size: 20.0, ..CharStyle::default() };
let mut t = TextObject::point(Point::ZERO, text, st);
t.para.composer = composer;
t
}
/// The glyph ids drawn for `text` with `composer`, and each glyph's source cluster length.
fn drawn(db: &FontDb, text: &str, composer: Composer) -> Vec<(u32, usize)> {
layout(db, &object(text, composer)).glyphs.iter().map(|g| (g.gid, g.len)).collect()
}
fn g(c: char) -> u32 {
u32::from(source_sans_gid(c).expect("a Source Sans glyph"))
}
/// Under the ME&SA composers the conjunct forms (the vowel sign I drawn before its syllable and Ka's
/// half form, in Devanagari and in Gujarati); under the Standard ones each character
/// has its own glyph, in text order, as the font maps it.
#[test]
fn standard_composers_set_indic_text_glyph_by_glyph() {
let db = db();
let ids = |v: Vec<(u32, usize)>| v.into_iter().map(|(gid, _)| gid).collect::<Vec<_>>();
for composer in [Composer::SingleLine, Composer::EveryLine] {
assert_eq!(ids(drawn(&db, DEVANAGARI, composer)), [g('i'), g('k'), g('K')], "{composer:?} Devanagari");
assert_eq!(ids(drawn(&db, GUJARATI, composer)), [g('i'), g('k'), g('K')], "{composer:?} Gujarati");
}
for composer in [Composer::StandardSingleLine, Composer::StandardEveryLine] {
let plain = [g('K'), g('.'), g('K'), g('i')];
let devanagari = drawn(&db, DEVANAGARI, composer);
assert_eq!(ids(devanagari.clone()), plain, "{composer:?} Devanagari");
assert_eq!(ids(drawn(&db, GUJARATI, composer)), plain, "{composer:?} Gujarati");
assert!(devanagari.iter().all(|&(_, len)| len == 3), "each glyph is one character's own cluster: {devanagari:?}");
}
}
/// The composer is per paragraph: of two paragraphs of the same text, each is shaped by its own.
#[test]
fn each_paragraph_follows_its_own_composer() {
let db = db();
let mut t = object(&format!("{DEVANAGARI}\n{DEVANAGARI}"), Composer::EveryLine);
let standard = vectorcraft_doc::ParaStyle { composer: Composer::StandardEveryLine, ..t.para.clone() };
t.set_paragraph_styles(vec![t.para.clone(), standard]);
let l = layout(&db, &t);
let second = DEVANAGARI.len() + 1;
let of = |from: usize, to: usize| l.glyphs.iter().filter(|g| (from..to).contains(&g.byte) && g.len > 0).map(|g| g.gid).collect::<Vec<_>>();
assert_eq!(of(0, second), [g('i'), g('k'), g('K')], "ME&SA paragraph");
assert_eq!(of(second, second + DEVANAGARI.len()), [g('K'), g('.'), g('K'), g('i')], "Standard paragraph");
}
/// Layout's composer override ([`LayoutOptions::composer`]) decides the shaping too.
#[test]
fn the_layout_composer_override_decides_the_shaping() {
let db = db();
let t = object(DEVANAGARI, Composer::EveryLine);
let with = |c| layout_with(&db, &t, &LayoutOptions { composer: Some(c), ..Default::default() }).glyphs.len();
assert_eq!((with(Composer::SingleLine), with(Composer::StandardSingleLine)), (3, 4));
}
/// Standard composers break lines as the ME&SA ones do (`is_single_line`), and old files' composers
/// keep their meaning.
#[test]
fn composers_split_into_breaking_and_shaping() {
use Composer::*;
for (c, single, shapes) in
[(SingleLine, true, true), (EveryLine, false, true), (StandardSingleLine, true, false), (StandardEveryLine, false, false)]
{
assert_eq!((c.is_single_line(), c.shapes_complex_scripts()), (single, shapes), "{c:?}");
assert_eq!(c.with_breaking(single), c, "{c:?}");
assert_eq!(
(c.with_breaking(!single).is_single_line(), c.with_breaking(!single).shapes_complex_scripts()),
(!single, shapes),
"{c:?} toggled"
);
}
assert_eq!(Composer::default(), EveryLine, "new type and old documents are ME&SA Every-line");
}
/// A joiner or non-joiner has no glyph in most fonts and the shaper hides it; a Standard composer
/// draws it as no width at all, not as a missing-glyph box.
#[test]
fn standard_composers_give_format_characters_no_width() {
let db = db();
let text = "क\u{200C}क";
for composer in [Composer::StandardSingleLine, Composer::StandardEveryLine] {
let l = layout(&db, &object(text, composer));
let widths: Vec<f64> = l.glyphs.iter().map(|g| g.advance).collect();
assert_eq!(widths.len(), 3, "{composer:?}: {widths:?}");
assert_eq!(widths[1], 0.0, "{composer:?}: the non-joiner takes no room: {widths:?}");
assert!(widths[0] > 0.0 && widths[2] > 0.0, "{composer:?}: {widths:?}");
// The test font maps no space: the control must still draw nothing (not glyph 0's outline).
assert!(l.glyphs[1].outline.elements().is_empty(), "{composer:?}: the non-joiner has no ink");
}
}
+4 -3
View File
@@ -41,9 +41,10 @@ pub use live_paint::{
};
use live_paint::{check_live_paint_options, lp_color, lp_rgb_color};
pub use lookup::{
EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, LP_JOIN_TOL, SOURCES_NAME, builder_members, connected_edges, drawn_outlines,
edge_near, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_takes, lp_stroke_paint, node_outline,
outline_snap, path_contains, shape_builder_shapes, shapes_for, sources, visible_edge_near, visible_face_at,
EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, LP_JOIN_TOL, SOURCES_NAME, builder_members, connected_edges,
connected_edges_through, drawn_outlines, edge_near, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at,
live_paint_takes, lp_stroke_paint, node_outline, outline_snap, path_contains, shape_builder_shapes, shapes_for, sources, visible_edge_near,
visible_face_at,
};
pub use map::{
BuilderMap, HATCH, HIGHLIGHT_RED, Hit, MergeGeometry, MergeInput, PreparedMerge, Rest, Touched, hatch, maps_built, merge_geometry, merge_inputs,
+198 -25
View File
@@ -1,14 +1,15 @@
use super::cache::RegionCache;
use super::lookup::{
connected_edges, edges, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where, lp_stroke_paint, node_outline,
visible_edge_near, visible_face_at,
connected_edges, connected_edges_through, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where,
lp_stroke_paint, node_outline, visible_edge_near, visible_face_at,
};
use super::map::{HIGHLIGHT_RED, sorted_roots};
use super::map::{BuilderMap, HIGHLIGHT_RED, sorted_roots};
use super::{
Action, Arc, BezPath, CLICK_TOL_PX, Cursor, Document, EDGE_NAME, FACE_NAME, FillRule, Mods, Node, NodeId, Overlay, Point, PointerEvent,
PointerKind, Rect, Tool, ToolContext, ToolKey, Value, color_swatches, json, json_ids, path_contains, pick_swatch, plain, swatch_chips,
};
use vectorcraft_color::Paint;
use vectorcraft_pathops as po;
// ---------- Live Paint Bucket ----------
@@ -178,10 +179,12 @@ enum LpPaint {
///
/// A double-click on a face fills it and the faces reached from it across edges that draw no
/// stroke (`scope: "connected"`); on an edge it paints the edges joined to it that have its stroke.
/// A triple-click on a face fills every face of the group with the face's fill, and on an edge it
/// paints every edge of the group with the edge's stroke (`scope: "samePaint"`). Each click of a
/// double-click or triple-click paints as it arrives, as its own undo step, and the paint compared
/// is the one the face or edge had before the first of its clicks that painted it. A first click
/// A triple-click on a face fills every face of the group that has the face's fill, and on an edge
/// it paints every edge of the group that draws with the edge's stroke paint (`scope:
/// "samePaint"`); each of them takes the bucket's paint. Each click of a double-click or
/// triple-click paints as it arrives, as its own undo step when it changes a paint, and the paint
/// compared is the one the face or edge had before the first of its clicks that painted it,
/// including a click whose drag or release crossed it. A first click
/// that made the Live Paint group counts when the face it filled is the clicked face. Shift and the
/// options choose a face or an edge as for a click; with Alt or Cmd/Ctrl held a double-click or
/// triple-click paints nothing. With Space held for the view tools, a click, double-click or triple-click paints
@@ -201,6 +204,8 @@ pub struct LivePaintBucketTool {
at: Option<(Point, Mods)>,
/// The fill command and polyline previewed from the press's snapshot.
fill_drag: Option<(Value, Vec<Vec<Point>>)>,
/// What a fill drag paints, as it was at its press.
drag_from: LpDragFrom,
/// The last [`LP_PRESSES`] presses, oldest first: the face or edge each one painted, with its
/// paint before that press, or None for a press that painted no face or edge.
presses: Vec<Option<LpPress>>,
@@ -229,22 +234,128 @@ struct LpPress {
/// The other faces or edges the double-click that followed the press reached, each with its
/// fill or drawn stroke paint before the double-click.
also: Vec<(NodeId, Paint)>,
/// The other faces the press's drag crossed, its release included, each with its fill before
/// the press.
dragged: Vec<(NodeId, Paint)>,
/// For a press that makes the Live Paint group: what the group is made from, with the path
/// chunks of the press's drag, its release included.
dragged_made: Option<Arc<(LpMade, Vec<Vec<Point>>)>>,
}
/// The fill of the face under `p` in the Live Paint group that `roots` make: the fill of the
/// front-most of their paths whose closed subpaths hold `p`, else none. Open subpaths bound no face.
fn made_face_fill(doc: &Document, roots: &[NodeId], p: Point) -> Paint {
let mut leaves = vec![];
for n in roots.iter().filter_map(|id| doc.node(*id)) {
leaf_shapes(n, &mut leaves);
/// What a Live Paint Bucket fill drag paints, as it was at the press.
#[derive(Default)]
enum LpDragFrom {
#[default]
None,
/// The faces of an existing Live Paint group.
Faces(Vec<Arc<Node>>),
/// What the group is made from, for a drag that makes the group.
Made(LpMade),
}
/// The faces among `faces` (a Live Paint group's faces, back to front) that a drag along the path
/// chunks `chunks` crosses, as `livePaint.fill` finds them, each with its fill.
fn crossed_faces(faces: &[Arc<Node>], chunks: &[Vec<Point>]) -> Vec<(NodeId, Paint)> {
let mut hit = vec![];
let mut regions = vec![];
// Front first, as visible_face_at looks.
for f in faces.iter().rev().filter(|f| f.visible) {
if let Some(path) = f.path_data()
&& let Some(bounds) = path.bounds()
{
hit.push(f);
regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds));
}
}
let map = BuilderMap { regions, ..Default::default() };
let mut crossed: Vec<(NodeId, Paint)> = vec![];
for chunk in chunks {
for f in map.hits_along(chunk, None).regions.iter().filter_map(|i| hit.get(*i)) {
if !crossed.iter().any(|(id, _)| *id == f.id) {
crossed.push((f.id, f.appearance.fill_paint()));
}
}
}
crossed
}
/// What the Live Paint group a fill press makes from the selection is made from, as it was at the
/// press, following Live Paint Make and Merge.
#[derive(Debug, PartialEq)]
struct LpMade {
/// The paint Merge keeps from the faces of the first selected Live Paint group that draw: a
/// point inside each face with its fill, given to the made face that holds the point.
kept: Vec<(Point, Paint)>,
/// The paths the faces are made from, back to front: Merge's group's source paths first, then
/// the other objects', a Live Paint group giving its source paths.
sources: Vec<Node>,
}
/// What the Live Paint group the selected `roots` make is made from ([`LpMade`]).
fn made_leaves(doc: &Document, roots: &[NodeId]) -> LpMade {
let nodes: Vec<&Node> = roots.iter().filter_map(|id| doc.node(*id)).collect();
let target = nodes.iter().position(|n| is_live_paint(n));
let mut kept = vec![];
let mut sources = vec![];
for i in target.into_iter().chain((0..nodes.len()).filter(|i| Some(*i) != target)) {
let Some(n) = nodes.get(i) else { continue };
if !is_live_paint(n) {
leaf_shapes(n, &mut sources);
continue;
}
for s in super::lookup::sources(n).and_then(|g| g.children()).into_iter().flatten() {
leaf_shapes(s, &mut sources);
}
if Some(i) == target {
let draws = |f: &&Arc<Node>| f.visible && f.opacity > 0.0 && (f.appearance.has_drawn_fill() || f.appearance.has_drawn_stroke());
// Merge fixes a kept unplaced gradient to its fit on the face it comes from.
let kept_fill = |f: &Arc<Node>| {
let mut n = (**f).clone();
n.pin_gradients();
n.appearance.fill_paint()
};
kept.extend(faces(n).into_iter().filter(draws).filter_map(|f| Some((po::interior_point(f.path_data()?)?, kept_fill(f)))));
}
}
LpMade { kept, sources: sources.into_iter().cloned().collect() }
}
/// The fill a face made at `p` from the source paths of `made` gets: the topmost fill that draws
/// of the front-most source path whose closed subpaths hold `p` and that has such a fill, else
/// none. Open subpaths bound no face.
fn made_face_fill(made: &LpMade, p: Point) -> Paint {
let holds = |l: &Node| {
node_outline(l).is_some_and(|(path, rule)| {
let closed = vectorcraft_geom::PathData::new(path.subpaths.into_iter().filter(|sp| sp.closed && sp.anchors.len() >= 2).collect());
!closed.is_empty() && path_contains(&closed, rule, p)
})
};
leaves.iter().rev().find(|l| holds(l)).map_or(Paint::None, |l| l.appearance.fill_paint())
// As Make: the front-most covering source with a fill that draws (shown, with paint and an
// opacity above 0, on a source with an opacity above 0) gives the face its topmost such fill,
// an unplaced gradient fixed to its fit on the source.
made.sources
.iter()
.rev()
.filter(|l| l.opacity > 0.0 && l.appearance.has_drawn_fill() && holds(l))
.find_map(|l| {
let mut n = l.clone();
n.pin_gradients();
n.appearance.items.iter().rev().find_map(|i| match i {
vectorcraft_doc::AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() && f.opacity > 0.0 => Some(f.paint.clone()),
_ => None,
})
})
.unwrap_or(Paint::None)
}
/// The fill face `face` of Live Paint group `group` was made with from `made`: the kept paint
/// whose point the face holds (the last one, as Merge applies them in order), else the fill of the
/// source path at a point inside the face.
fn made_part_fill(made: &LpMade, group: &Node, face: &Node) -> Paint {
if let Some((_, paint)) = made.kept.iter().rev().find(|(p, _)| face_at(group, *p).is_some_and(|f| f.id == face.id)) {
return paint.clone();
}
face.path_data().and_then(po::interior_point).map_or(Paint::None, |p| made_face_fill(made, p))
}
/// How many presses the Live Paint Bucket keeps: the three of a triple-click.
@@ -260,6 +371,7 @@ impl Default for LivePaintBucketTool {
hover: LpHover::None,
at: None,
fill_drag: None,
drag_from: LpDragFrom::None,
presses: Vec::new(),
fills: true,
strokes: false,
@@ -336,7 +448,26 @@ impl LivePaintBucketTool {
/// Note a press at `at` that paints face or edge (`edge`) `n`.
fn note_part(&mut self, n: &Node, edge: bool, at: Point) {
let before = if edge { lp_stroke_paint(n) } else { n.appearance.fill_paint() };
self.note_press(Some(LpPress { part: Some(n.id), at, before, also: vec![] }));
self.note_press(Some(LpPress { part: Some(n.id), at, before, also: vec![], dragged: vec![], dragged_made: None }));
}
/// End the fill drag, noting on the last press the other faces its drag crossed, with their
/// fills before the press (for a press that makes the group, what the group is made from and
/// the drag, for [`Self::before`] to look the faces up in the group made). → whether a fill
/// drag was on.
fn end_fill(&mut self) -> bool {
let from = std::mem::take(&mut self.drag_from);
let Some((_, chunks)) = self.fill_drag.take() else { return false };
let Some(Some(last)) = self.presses.last_mut() else { return true };
match from {
LpDragFrom::None => {}
LpDragFrom::Faces(faces) => {
let part = last.part;
last.dragged = crossed_faces(&faces, &chunks).into_iter().filter(|(id, _)| part != Some(*id)).collect();
}
LpDragFrom::Made(made) => last.dragged_made = Some(Arc::new((made, chunks))),
}
true
}
/// Note that the double-click after the last press also reaches `parts` of group `group`, with
@@ -356,12 +487,17 @@ impl LivePaintBucketTool {
/// The paint `part` had before the first press of a click sequence of `clicks` presses that
/// painted `part`, or before the double-click after a press when that double-click reached it
/// (the sequence's first press counts when it made the group `part` is in and the face it
/// filled there is `part`); `now` when the last press did not paint it.
/// filled there is `part`), a press's drag or release crossing `part` included; `now` when the
/// last press did not paint it.
fn before(&self, cx: &ToolContext, part: NodeId, clicks: usize, now: Paint) -> Paint {
let Some(run) = self.presses.len().checked_sub(clicks).and_then(|from| self.presses.get(from..)) else { return now };
let made_part = |q: &LpPress| live_paint_at(cx.doc, q.at).and_then(|g| visible_face_at(cx.doc.node(g)?, q.at)).is_some_and(|f| f.id == part);
let on_part = |i: usize, q: &LpPress| q.part == Some(part) || (i == 0 && q.part.is_none() && made_part(q));
if !run.last().and_then(Option::as_ref).is_some_and(|q| on_part(run.len() - 1, q)) {
let made_part = |at: Point| live_paint_at(cx.doc, at).and_then(|g| visible_face_at(cx.doc.node(g)?, at)).is_some_and(|f| f.id == part);
let on_part = |i: usize, q: &LpPress| q.part == Some(part) || (i == 0 && q.part.is_none() && made_part(q.at));
let dragged = |q: &LpPress| q.dragged.iter().any(|(id, _)| *id == part);
// An earlier press of the sequence that painted `part` counts too: a press on the next edge
// released back on `part` paints that edge, and the double-click targets `part`.
let painted = run.iter().enumerate().any(|(i, q)| q.as_ref().is_some_and(|q| on_part(i, q)));
if !painted && !run.last().and_then(Option::as_ref).is_some_and(dragged) {
return now;
}
for (i, q) in run.iter().enumerate() {
@@ -369,7 +505,17 @@ impl LivePaintBucketTool {
if on_part(i, q) {
return q.before.clone();
}
if let Some((_, paint)) = q.also.iter().find(|(id, _)| *id == part) {
// A face of the group the press made (the one under the press) that its drag crossed has
// the fill it was made with.
if i == 0
&& let Some(drag) = &q.dragged_made
&& let Some(group) = live_paint_at(cx.doc, q.at).and_then(|g| cx.doc.node(g))
&& let Some(face) = faces(group).into_iter().find(|f| f.id == part)
&& !crossed_faces(std::slice::from_ref(face), &drag.1).is_empty()
{
return made_part_fill(&drag.0, group, face);
}
if let Some((_, paint)) = q.dragged.iter().chain(&q.also).find(|(id, _)| *id == part) {
return paint.clone();
}
}
@@ -395,7 +541,23 @@ impl LivePaintBucketTool {
if clicks == 2
&& let Some(group) = cx.doc.node(g)
{
self.note_reached(group, connected_edges(group, e.id, &like), true);
// The other edge either click painted joins as the stroke paint it had before.
let through: Vec<NodeId> = self
.presses
.len()
.checked_sub(2)
.and_then(|i| self.presses.get(i..))
.into_iter()
.flatten()
.flatten()
.filter(|q| q.before == like)
.filter_map(|q| q.part)
.filter(|id| *id != e.id)
.collect();
self.note_reached(group, connected_edges_through(group, e.id, &like, &through), true);
if !through.is_empty() {
v["through"] = json_ids(&through);
}
}
if let Ok(like) = serde_json::to_value(like) {
v["match"] = like;
@@ -495,7 +657,7 @@ impl Tool for LivePaintBucketTool {
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let p = ev.pos;
// A second press finishes the preceding click, including callers without a release.
if ev.kind == PointerKind::Down && self.fill_drag.take().is_some() {
if ev.kind == PointerKind::Down && self.end_fill() {
let mut acts = vec![Action::Commit];
acts.extend(self.pointer(cx, ev));
return acts;
@@ -553,11 +715,15 @@ impl Tool for LivePaintBucketTool {
Some(f) => self.note_part(f, false, p),
None => self.note_press(None),
}
self.drag_from = LpDragFrom::Faces(cx.doc.node(g).map(|n| faces(n).into_iter().cloned().collect()).unwrap_or_default());
return self.begin_fill(json!({ "group": g.0, "point": point }), p);
}
if self.cache.at(cx, p).is_some() {
let roots = sorted_roots(cx.doc, &cx.selection.objects);
self.note_press(Some(LpPress { part: None, at: p, before: made_face_fill(cx.doc, &roots, p), also: vec![] }));
let made = made_leaves(cx.doc, &roots);
let before = made_face_fill(&made, p);
self.note_press(Some(LpPress { part: None, at: p, before, also: vec![], dragged: vec![], dragged_made: None }));
self.drag_from = LpDragFrom::Made(made);
return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p);
}
self.note_press(None);
@@ -568,7 +734,7 @@ impl Tool for LivePaintBucketTool {
// The swatch preview shows again at the release point.
self.at = Some((p, ev.mods));
let mut acts = self.drag_fill(p);
if self.fill_drag.take().is_some() {
if self.end_fill() {
acts.push(Action::Commit);
}
acts
@@ -586,6 +752,7 @@ impl Tool for LivePaintBucketTool {
/// the active paint, while no drag is on.
fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape {
self.drag_from = LpDragFrom::None;
return if self.fill_drag.take().is_some() { vec![Action::Cancel] } else { vec![] };
}
if !self.claims_key_with(cx, key, mods) {
@@ -621,7 +788,7 @@ impl Tool for LivePaintBucketTool {
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.presses.clear();
if self.fill_drag.take().is_some() { vec![Action::Commit] } else { vec![] }
if self.end_fill() { vec![Action::Commit] } else { vec![] }
}
/// The pointer hovers nothing for the tool: its highlight and its swatch preview go.
@@ -630,6 +797,12 @@ impl Tool for LivePaintBucketTool {
self.at = None;
}
/// A press the view tools took counts as a press that paints no face or edge, for the clicks
/// a double-click or triple-click compares.
fn press_elsewhere(&mut self) {
self.note_press(None);
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32);
// No chips during a fill drag, or while Alt makes the tool sample with the eyedropper.
+8 -1
View File
@@ -405,8 +405,15 @@ impl LpEdgeGrid {
/// end of an edge already reached.
/// Empty when `start` is not an edge of `group` that is not hidden.
pub fn connected_edges(group: &Node, start: NodeId, paint: &Paint) -> Vec<NodeId> {
connected_edges_through(group, start, paint, &[])
}
/// [`connected_edges`], with the edges in `through` counted as drawing with stroke paint `paint`
/// whatever paint they draw with now.
pub fn connected_edges_through(group: &Node, start: NodeId, paint: &Paint, through: &[NodeId]) -> Vec<NodeId> {
use std::collections::{HashMap, HashSet};
let es: Vec<&Arc<Node>> = edges(group).into_iter().filter(|e| e.visible && (e.id == start || lp_stroke_paint(e) == *paint)).collect();
let es: Vec<&Arc<Node>> =
edges(group).into_iter().filter(|e| e.visible && (e.id == start || through.contains(&e.id) || lp_stroke_paint(e) == *paint)).collect();
// The first and last points of each subpath of each edge.
let ends: Vec<Vec<Point>> = es
.iter()
+33
View File
@@ -1386,6 +1386,39 @@ fn bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fi
);
}
/// A triple-click whose second press the view tools take (held Space) matches the fill the face had
/// before the first click: that press counts as one that paints nothing. The pointer leaving the
/// canvas between three clicks adds no press.
#[test]
fn bucket_triple_click_with_a_view_tool_press_between_matches_the_first_fill() {
use vectorcraft_color::{Color, Paint};
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let (d, gid, f2, _) = live_group_doc();
let mut painted = d.clone();
painted.node_mut(f2).unwrap().appearance.set_fill(red.clone());
let s = Selection::default();
let p = paint();
let (cx, later) = (cx(&d, &s, &p), cx(&painted, &s, &p));
let own = serde_json::to_value(d.node(f2).unwrap().appearance.fill_paint()).unwrap();
assert_ne!(own, serde_json::to_value(&red).unwrap());
let want = vec![Action::Exec("livePaint.fill".into(), json!({ "group": gid.0, "point": [75.0, 25.0], "scope": "samePaint", "match": own }))];
fn click(t: &mut LivePaintBucketTool, ctx: &ToolContext) {
t.pointer(ctx, &ev(PointerKind::Down, 75.0, 25.0));
t.pointer(ctx, &ev(PointerKind::Up, 75.0, 25.0));
}
let mut t = LivePaintBucketTool::default();
click(&mut t, &cx);
t.press_elsewhere();
click(&mut t, &later);
assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), want, "a view tool's press between");
let mut t = LivePaintBucketTool::default();
click(&mut t, &cx);
click(&mut t, &later);
t.hover_ended(&later);
click(&mut t, &later);
assert_eq!(t.pointer(&later, &ev(PointerKind::TripleClick, 75.0, 25.0)), want, "the pointer leaving between");
}
/// With Space held for the view tools, the pointer outlines no face or edge, as a press there
/// paints nothing.
#[test]
+3
View File
@@ -291,6 +291,9 @@ pub trait Tool: Send {
/// another document became active. The Blend tool drops its first pick and stops adding to the
/// blend it just made.
fn history_moved(&mut self) {}
/// A press on the canvas went to the view tools (held Space, the middle button) and not to the
/// tool. The Live Paint Bucket counts it among the clicks a triple-click compares.
fn press_elsewhere(&mut self) {}
/// Time passes while the pointer button is held (`dt` seconds since the last tick, whether or
/// not the pointer moved): tools that keep working while the brush holds still (Twirl, Pucker,
/// Bloat) act on it. The host supplies the time, so tests and agents drive it exactly.
+4
View File
@@ -121,6 +121,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo
{
// Middle-button drag pans the view whatever the tool.
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Pan { start, center: v.center, middle: true }));
app.session.tool_press_elsewhere();
app.session.tool_hover_ended(view);
} else if let Some(d) = drag {
// The pointer gone (a pen lifted with its press), the drag ends where it was last seen.
@@ -342,6 +343,9 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) {
if !space && matches!(d, Drag::ZoomBox { .. } | Drag::ZoomScrub { .. } | Drag::Pan { .. } | Drag::RotateView { .. }) {
crate::shortcuts::note_tool_use(app);
}
if !matches!(d, Drag::Tool) {
app.session.tool_press_elsewhere();
}
// Panning, zooming or turning the view takes the pointer from the tool's hover.
if !tool_holds(d) {
app.session.tool_hover_ended(view);
+2
View File
@@ -97,6 +97,7 @@ pub mod plugin;
mod png_options;
pub mod print;
pub mod print_presets;
pub mod psd_import;
mod psd_options;
pub mod raster_effects;
pub mod rearrange_artboards;
@@ -417,6 +418,7 @@ registry! {
PluginStopped: [safe_mode::STOPPED] => safe_mode::STOPPED_SPEC,
SafeMode: [safe_mode::KIND] => safe_mode::SPEC,
DxfImport: [dxf_import::KIND] => dxf_import::SPEC,
PsdImport: [psd_import::KIND] => psd_import::SPEC,
RasterFormatOptions: ["tiffOptions", "bmpOptions", "tgaOptions"] => png_options::SPEC,
SaveForWeb: [save_for_web::KIND] => save_for_web::SPEC,
PsdOptions: ["psdOptions"] => png_options::SPEC,
@@ -361,7 +361,12 @@ pub(crate) fn edited_attrs(d: &Dialog) -> Result<Map<String, Value>, String> {
}
let same = unchanged("composer", "__resetComposition");
keep_or(&mut attrs, "composer", same, choice("composer").filter(|v| matches!(v.as_str(), Some("singleLine" | "everyLine"))));
keep_or(
&mut attrs,
"composer",
same,
choice("composer").filter(|v| matches!(v.as_str(), Some("singleLine" | "everyLine" | "standardSingleLine" | "standardEveryLine"))),
);
let same = unchanged("roman_hanging", "__resetComposition");
keep_or(&mut attrs, "roman_hanging", same, switch("roman_hanging"));
@@ -637,7 +642,9 @@ fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(&str, &str)]
let shown = options.iter().find(|(value, _)| *value == selected).map_or("", |(_, label)| *label);
let labels: Vec<&str> = std::iter::once(" ").chain(options.iter().map(|(_, label)| *label)).collect();
ui.add_enabled_ui(enabled, |ui| {
if let Some(i) = crate::widgets::dropdown(ui, (KIND, key), shown, &labels, 190.0) {
// shortcut: 7 pt per character approximates the widest label; measure the text when a label wraps.
let width = (labels.iter().map(|l| l.chars().count()).max().unwrap_or(0) as f32 * 7.0).max(190.0);
if let Some(i) = crate::widgets::dropdown(ui, (KIND, key), shown, &labels, width) {
d.fields.insert(key.into(), if i == 0 { Value::Null } else { options.get(i - 1).map_or(Value::Null, |(value, _)| json!(value)) });
}
});
@@ -842,11 +849,16 @@ pub(crate) fn clear_tabs(d: &mut Dialog) {
d.fields.remove("__tabEdited");
}
/// Composition: the Single-line or Every-line Composer, and Roman Hanging Punctuation.
/// Composition: the Middle Eastern & South Asian or Standard, Single-line or Every-line Composer, and Roman Hanging Punctuation.
pub(crate) fn composition_body(ui: &mut egui::Ui, d: &mut Dialog) {
egui::Grid::new("paragraph-style-composition").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| {
let row = ui.label(tl!("Composition"));
let composers = [("singleLine", tl!("Single-line Composer")), ("everyLine", tl!("Every-line Composer"))];
let composers = [
("singleLine", tl!("Middle Eastern & South Asian Single-line Composer")),
("everyLine", tl!("Middle Eastern & South Asian Every-line Composer")),
("standardSingleLine", tl!("Standard Single-line Composer")),
("standardEveryLine", tl!("Standard Every-line Composer")),
];
ui.label_inputs_by(row.id, |ui| choice(ui, d, "composer", &composers, true));
ui.end_row();
switch(ui, d, "roman_hanging", tl!("Roman Hanging Punctuation"), true);
@@ -857,7 +869,7 @@ pub(crate) fn composition_body(ui: &mut egui::Ui, d: &mut Dialog) {
/// unset; Hyphenation Zone is also inactive with the Every-line Composer, which does not use it.
pub(crate) fn hyphenation_body(ui: &mut egui::Ui, d: &mut Dialog) {
let on = d.fields.get("hyphenate").and_then(Value::as_bool) == Some(true);
let single_line = d.fields.get("composer").and_then(Value::as_str) == Some("singleLine");
let single_line = matches!(d.fields.get("composer").and_then(Value::as_str), Some("singleLine" | "standardSingleLine"));
egui::Grid::new("paragraph-style-hyphenation").num_columns(2).spacing([18.0, 8.0]).show(ui, |ui| {
switch(ui, d, "hyphenate", tl!("Hyphenation"), true);
for (key, suffix) in [
+585
View File
@@ -0,0 +1,585 @@
//! PSD Import Options: opening a PSD or PSB file with two or more layers or with slices, or
//! placing one without Link, asks whether its layers become objects or one flat image, whether
//! hidden layers come in, and whether its slices come in (Import Slices, offered only for a file
//! with slices)
//! (<https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html>).
//! A linked file shows its flat image, so placing with Link doesn't ask. The two-layer threshold,
//! the starting choices, Import Slices applying to both conversions and remembering the choices
//! are VectorCraft's own.
//!
//! Fields: `mode` (`open` | `place`), `name`, `path?`, `width`, `height` (the canvas, px),
//! `layers`, `hidden` and `slices` (counts, from `document.psdInfo`), `convert` (`objects` |
//! `flatten`), `hiddenLayers` and `importSlices`. `__place` keeps the other `file.place` params.
//! The file's bytes stay in [`crate::state::UiState::dialog_file`]. OK opens or places the file
//! with `layers`, `hiddenLayers` and (for a file with slices) `importSlices`, and remembers the
//! choices for the next file; errors keep the dialog open.
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio;
use super::DialogSpec;
use super::import_pdf::{DialogFile, other_place_params, place_source, with_file};
use crate::state::Dialog;
use crate::{VectorcraftApp, io, widgets};
pub const KIND: &str = "psdImport";
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |d| if d.str("mode") == "place" { tl!("Place PSD") } else { tl!("PSD Import Options") }.into(),
body,
confirm,
min_width: 380.0,
..DialogSpec::FORM
};
/// The fewest layers a file has for the dialog to ask.
const MIN_LAYERS: usize = 2;
/// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when they
/// are a PSD or PSB file with [`MIN_LAYERS`] layers or more, or with slices; false when they aren't
/// (the loader then opens or places the file, or says why it can't).
pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, place: Option<&Value>) -> bool {
let Ok(info) = fileio::psd_info(bytes) else { return false };
if info.layers < MIN_LAYERS && info.slices == 0 {
return false;
}
app.ui.dialog_file = Some(DialogFile::new(bytes.to_vec()));
let (layers, hidden, slices) = last_choices(app);
let mut fields = json!({
"mode": if place.is_some() { "place" } else { "open" },
"name": name,
"width": info.width,
"height": info.height,
"layers": info.layers,
"hidden": info.hidden,
"slices": info.slices,
"convert": if layers { "objects" } else { "flatten" },
"hiddenLayers": hidden,
"importSlices": slices,
});
if let Some(p) = path {
fields["path"] = json!(p);
}
if let Some(p) = place {
fields["__place"] = other_place_params(p, &["layers", "hiddenLayers", "importSlices"]);
}
app.ui.dialog = Some(Dialog::new(KIND, fields));
true
}
/// `file.place` with params `p` asks first (true) when they embed a PSD or PSB file (`link: false`,
/// or the file's bytes) and give no `layers`.
pub fn offer_place(app: &mut VectorcraftApp, p: &Value) -> bool {
let embedded = p.get("path").is_none() || p.get("link").and_then(Value::as_bool) == Some(false);
if !embedded || p.get("layers").is_some() {
return false;
}
let Some((name, bytes, path)) = place_source(app, p, |ext| matches!(ext, "psd" | "pdd" | "psb")) else { return false };
offer(app, &name, &bytes, path, Some(p))
}
/// The PSD Import Options chosen last (layers, hidden layers, slices), at first Convert Layers to
/// Objects without hidden layers, with Import Slices.
fn last_choices(app: &VectorcraftApp) -> (bool, bool, bool) {
let last = |k: &str, default: bool| app.ui.psd_import.get(k).and_then(Value::as_bool).unwrap_or(default);
(last("layers", true), last("hiddenLayers", false), last("importSlices", true))
}
/// Several files placed without Link load the place cursor without asking: the `file.place.queue`
/// params `q` take the PSD Import Options chosen last, which apply to each PSD or PSB file among them.
pub fn queue_options(app: &VectorcraftApp, q: &mut Value) {
let (layers, hidden, slices) = last_choices(app);
q["layers"] = json!(layers);
if layers && hidden {
q["hiddenLayers"] = json!(true);
}
q["importSlices"] = json!(slices);
}
/// `file.place` params `p` placed without asking (Show Import Options off) that embed a PSD or PSB
/// file and give no `layers` take the PSD Import Options chosen last; `hiddenLayers` and
/// `importSlices` that the params give are kept.
pub fn last_options(app: &VectorcraftApp, p: &mut Value) {
let embedded = p.get("path").is_none() || p.get("link").and_then(Value::as_bool) == Some(false);
let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default();
if embedded && p.get("layers").is_none() && matches!(fileio::extension(name).as_str(), "psd" | "pdd" | "psb") {
let (layers, hidden, slices) = last_choices(app);
p["layers"] = json!(layers);
if layers && hidden && p.get("hiddenLayers").is_none() {
p["hiddenLayers"] = json!(true);
}
if p.get("importSlices").is_none() {
p["importSlices"] = json!(slices);
}
if p.get("path").is_none() {
// A file from bytes has no file to link to; it may carry the Place dialog's Link.
p["link"] = json!(false);
}
}
}
/// OK: open or place the file with the choices.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let file = app.ui.dialog_file.clone().ok_or("the file is no longer loaded")?;
let layers = d.str("convert") != "flatten";
let hidden = layers && d.bool("hiddenLayers");
// Import Slices is a choice only for a file with slices; otherwise the one made last stays.
let has_slices = d.fields.get("slices").and_then(Value::as_u64).unwrap_or(0) > 0;
let slices = if has_slices { d.bool("importSlices") } else { last_choices(app).2 };
app.ui.psd_import = json!({ "layers": layers, "hiddenLayers": d.bool("hiddenLayers"), "importSlices": slices });
let r = if d.str("mode") == "place" {
let mut p = with_file(d.fields.get("__place"), d, &file);
p["layers"] = json!(layers);
if layers || has_slices {
// Layers and slices are always embedded; a file from bytes may carry the Place dialog's
// Link.
p["link"] = json!(false);
}
if hidden {
p["hiddenLayers"] = json!(true);
}
if has_slices {
p["importSlices"] = json!(slices);
}
crate::place::run_for_user(app, &p).map(|_| ())
} else {
let path = d.fields.get("path").and_then(Value::as_str).map(str::to_string);
let mut p = json!({ "layers": layers, "hiddenLayers": hidden });
if has_slices {
p["importSlices"] = json!(slices);
}
io::open_document(app, &d.str("name"), &file.bytes, path, &p).map(|_| ())
};
match r {
Ok(()) => {
// Placing may have opened another dialog; only this one closes.
if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) {
app.ui.dialog = None;
}
Ok(Value::Null)
}
Err(e) => {
app.ui.dialog = Some(d.clone());
Err(e)
}
}
}
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0);
widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers")));
// Offered only for a file with slices, with either conversion.
let sliced = count("slices") > 0;
ui.add_space(8.0);
let convert = d.str("convert") != "flatten";
if widgets::radio(ui, tl!("Convert Layers to Objects"), convert, true) {
d.fields.insert("convert".into(), json!("objects"));
}
ui.horizontal(|ui| {
ui.add_space(22.0);
let on = d.bool("hiddenLayers");
if widgets::check(ui, tl!("Import Hidden Layers"), on && convert, convert) {
d.fields.insert("hiddenLayers".into(), json!(!on));
}
});
if widgets::radio(ui, tl!("Flatten Layers to a Single Image"), !convert, true) {
d.fields.insert("convert".into(), json!("flatten"));
}
ui.add_space(8.0);
let on = d.bool("importSlices");
if widgets::check(ui, tl!("Import Slices"), on && sliced, sliced) {
d.fields.insert("importSlices".into(), json!(!on));
}
false
}
#[cfg(test)]
mod tests {
use vectorcraft_engine::Session;
use vectorcraft_engine::doc::NodeKind;
use super::*;
/// A PSD file of three layers, the middle one hidden, written by `document.export`.
fn layered() -> Vec<u8> {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
let back = s.doc().unwrap().doc.layers[0].id.0;
s.execute("layer.setProps", &json!({"id": back, "name": "Back"})).unwrap();
for (name, color) in [("Back", "#ff0000"), ("Middle", "#00ff00"), ("Front", "#0000ff")] {
if name != "Back" {
s.execute("layer.new", &json!({ "name": name })).unwrap();
}
s.execute("paint.setFill", &json!({ "color": color })).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
}
let middle = s.doc().unwrap().doc.layers[1].id.0;
s.execute("layer.setProps", &json!({"id": middle, "visible": false})).unwrap();
let r = s.execute("document.export", &json!({"format": "psd", "hiddenLayers": true})).unwrap();
vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()
}
fn app() -> VectorcraftApp {
VectorcraftApp::new(Session::new(), Default::default())
}
fn frame(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
}
fn set(app: &mut VectorcraftApp, k: &str, v: Value) {
app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);
}
fn layer_names(app: &VectorcraftApp) -> Vec<(String, bool)> {
app.session.doc().unwrap().doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect()
}
#[test]
fn opening_a_layered_file_asks_for_the_import_options() {
let psd = layered();
let mut app = app();
io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), d.str("mode"), d.str("convert"), d.bool("hiddenLayers")), (KIND, "open".into(), "objects".into(), false));
assert_eq!((&d.fields["layers"], &d.fields["hidden"], &d.fields["width"]), (&json!(3), &json!(1), &json!(20)));
assert!(app.session.active().is_none(), "nothing opens before OK");
let text = frame(&mut app);
for label in [
"PSD Import Options",
"20 × 20 px",
"Layers: 3",
"Convert Layers to Objects",
"Import Hidden Layers",
"Flatten Layers to a Single Image",
"OK",
] {
assert!(text.contains(label), "{label} in {text}");
}
// Layers as objects, hidden ones left out.
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Front".to_string(), true)]);
// With Import Hidden Layers the hidden layer comes in hidden.
io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap();
set(&mut app, "hiddenLayers", json!(true));
frame(&mut app);
super::super::confirm(&mut app).unwrap();
assert_eq!(layer_names(&app), [("Back".to_string(), true), ("Middle".to_string(), false), ("Front".to_string(), true)]);
// Flatten opens one image, and the next file starts from the choices made last.
io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap();
assert!(app.ui.dialog.as_ref().unwrap().bool("hiddenLayers"), "remembered");
set(&mut app, "convert", json!("flatten"));
frame(&mut app);
super::super::confirm(&mut app).unwrap();
let st = app.session.doc().unwrap();
assert_eq!(st.doc.layers.len(), 1);
assert!(matches!(st.doc.layers[0].children().map(Vec::as_slice), Some([one]) if matches!(one.kind, NodeKind::Image(_))));
io::open_bytes(&mut app, "poster.psd", &psd, None).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().str("convert"), "flatten");
}
#[test]
fn files_with_fewer_than_two_layers_open_without_asking() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
let one = s.execute("document.export", &json!({"format": "psd"})).unwrap();
let flat = s.execute("document.export", &json!({"format": "psd", "layers": false})).unwrap();
for r in [one, flat] {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
let mut app = app();
io::open_bytes(&mut app, "one.psd", &bytes, None).unwrap();
assert!(app.ui.dialog.is_none());
assert!(app.session.active().is_some());
}
}
#[test]
fn placing_without_link_asks_and_places_the_layers_as_a_group() {
let b64 = vectorcraft_format::base64_encode(&layered());
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
let r = crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap();
assert_eq!(r["dialog"], KIND);
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.str("mode"), &d.fields["__place"]), ("place".into(), &json!({"at": [50, 50]})));
assert!(frame(&mut app).contains("Place PSD"));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is selected") };
let g = st.doc.node(id).unwrap();
assert!(matches!(g.kind, NodeKind::Group { .. }));
let names: Vec<&str> = g.children().unwrap().iter().filter_map(|c| c.name.as_deref()).collect();
assert_eq!(names, ["Back", "Front"]);
// Flatten places the merged image.
crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap();
set(&mut app, "convert", json!("flatten"));
super::super::confirm(&mut app).unwrap();
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is selected") };
assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Image(_)));
}
#[test]
fn several_files_placed_without_link_take_the_last_choices() {
let dir = std::env::temp_dir().join(format!("vc-psd-import-queue-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let paths: Vec<String> = ["a.psd", "b.psd"]
.iter()
.map(|n| {
let p = dir.join(n);
std::fs::write(&p, layered()).unwrap();
p.to_string_lossy().into_owned()
})
.collect();
// Place both through the Place dialog, then click the cursor once for each: what was placed.
let place_two = |app: &mut VectorcraftApp, link: bool| -> Vec<vectorcraft_engine::doc::Node> {
let files: Vec<Value> = paths.iter().map(|p| json!({ "path": p })).collect();
let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": link, "template": false}));
crate::place::confirm(app, &d).unwrap();
assert!(app.ui.dialog.is_none(), "the cursor loads without asking");
let view = vectorcraft_engine::ViewInfo::default();
(0..2)
.map(|_| {
for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] {
for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() {
if let vectorcraft_engine::UiRequest::Place(p) = r {
crate::place::place_from_cursor(app, &p);
}
}
}
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is placed") };
st.doc.node(id).unwrap().clone()
})
.collect()
};
let visible = |n: &vectorcraft_engine::doc::Node| -> Vec<bool> { n.children().unwrap().iter().map(|c| c.visible).collect() };
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// At first, Convert Layers to Objects without hidden layers.
for n in place_two(&mut app, false) {
assert!(matches!(n.kind, NodeKind::Group { .. }));
assert_eq!(visible(&n), [true, true]);
}
// Then the choices made last.
app.ui.psd_import = json!({"layers": true, "hiddenLayers": true});
for n in place_two(&mut app, false) {
assert_eq!(visible(&n), [true, false, true]);
}
app.ui.psd_import = json!({"layers": false, "hiddenLayers": true});
assert!(place_two(&mut app, false).iter().all(|n| matches!(n.kind, NodeKind::Image(_))));
// Placed with Link, the files keep their flat images.
app.ui.psd_import = json!({"layers": true, "hiddenLayers": false});
assert!(place_two(&mut app, true).iter().all(|n| matches!(n.kind, NodeKind::Image(_))));
std::fs::remove_dir_all(&dir).ok();
}
/// `psd` with a slices resource (1050, version 6) holding one user slice over its top-left
/// 10 × 10 px, named "cell".
fn sliced(psd: &[u8]) -> Vec<u8> {
let ustr = |s: &str| -> Vec<u8> {
let units: Vec<u16> = s.encode_utf16().collect();
let mut b = (units.len() as u32).to_be_bytes().to_vec();
b.extend(units.iter().flat_map(|u| u.to_be_bytes()));
b
};
let mut data = 6u32.to_be_bytes().to_vec();
data.extend([0u8; 16]);
data.extend(ustr(""));
data.extend(1u32.to_be_bytes());
// ID, group ID, origin (made by the user), name, type (Image), left, top, right, bottom.
data.extend([1u32, 0, 2].iter().flat_map(|v| v.to_be_bytes()));
data.extend(ustr("cell"));
data.extend([1u32, 0, 0, 10, 10].iter().flat_map(|v| v.to_be_bytes()));
// URL, target, message, alt text, cell text is HTML, cell text, alignments, color.
for _ in 0..4 {
data.extend(ustr(""));
}
data.push(0);
data.extend(ustr(""));
data.extend([0u8; 12]);
let u32_at = |at: usize| u32::from_be_bytes(psd[at..at + 4].try_into().unwrap()) as usize;
let colors = 26 + 4 + u32_at(26);
let len = u32_at(colors);
let mut block = b"8BIM".to_vec();
block.extend(1050u16.to_be_bytes());
block.extend([0, 0]);
block.extend((data.len() as u32).to_be_bytes());
block.extend(&data);
block.resize(block.len().next_multiple_of(2), 0);
let mut out = psd[..colors].to_vec();
out.extend(((len + block.len()) as u32).to_be_bytes());
out.extend(&psd[colors + 4..colors + 4 + len]);
out.extend(block);
out.extend(&psd[colors + 4 + len..]);
out
}
fn slice_names(app: &VectorcraftApp) -> Vec<String> {
app.session.doc().unwrap().doc.slices.iter().map(|s| s.options.name.clone()).collect()
}
#[test]
fn a_file_with_slices_asks_with_import_slices_on_either_conversion() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 20})).unwrap();
s.execute("shape.rectangle", &json!({"x": 2, "y": 2, "width": 10, "height": 10})).unwrap();
let r = s.execute("document.export", &json!({"format": "psd"})).unwrap();
// One layer: without slices it opens at once, with them it asks.
let psd = sliced(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
let mut app = app();
io::open_bytes(&mut app, "one.psd", &psd, None).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), &d.fields["slices"], d.bool("importSlices")), (KIND, &json!(1), true));
assert!(frame(&mut app).contains("Import Slices"));
// Flatten keeps Import Slices: the merged image opens with the slice.
set(&mut app, "convert", json!("flatten"));
super::super::confirm(&mut app).unwrap();
assert_eq!(slice_names(&app), ["cell"]);
// Left off, the slice stays out, and the next file starts from that choice.
io::open_bytes(&mut app, "one.psd", &psd, None).unwrap();
set(&mut app, "importSlices", json!(false));
super::super::confirm(&mut app).unwrap();
assert!(slice_names(&app).is_empty());
io::open_bytes(&mut app, "one.psd", &psd, None).unwrap();
assert!(!app.ui.dialog.as_ref().unwrap().bool("importSlices"), "remembered");
// A layered file without slices keeps the choice made last for the next sliced one.
app.ui.dialog = None;
io::open_bytes(&mut app, "poster.psd", &layered(), None).unwrap();
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["slices"], json!(0));
set(&mut app, "importSlices", json!(true));
super::super::confirm(&mut app).unwrap();
assert_eq!(app.ui.psd_import["importSlices"], json!(false));
}
#[test]
fn placing_a_sliced_file_without_link_brings_its_slices_with_the_art() {
let b64 = vectorcraft_format::base64_encode(&sliced(&layered()));
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "at": [50, 50]})).unwrap();
assert!(app.ui.dialog.as_ref().unwrap().bool("importSlices"));
super::super::confirm(&mut app).unwrap();
let st = app.session.doc().unwrap();
assert_eq!(st.doc.slices.len(), 1);
assert_eq!(st.doc.slices[0].rect, vectorcraft_geom::Rect::new(40.0, 40.0, 50.0, 50.0));
// Several files placed together take the choice made last.
let mut q = json!({});
app.ui.psd_import = json!({"layers": true, "importSlices": false});
queue_options(&app, &mut q);
assert_eq!(q["importSlices"], json!(false));
}
#[test]
fn placing_with_show_import_options_off_takes_the_last_choices() {
let b64 = vectorcraft_format::base64_encode(&sliced(&layered()));
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// The file's bytes carry the Place dialog's Link, which they have no file for.
let place = |app: &mut VectorcraftApp, slices: Option<bool>| {
let mut p = json!({"name": "poster.psd", "dataBase64": b64, "link": true, "showImportOptions": false});
if let Some(s) = slices {
p["importSlices"] = json!(s);
}
crate::place::run_for_user(app, &p).unwrap();
assert!(app.ui.dialog.is_none(), "placed without asking");
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is selected") };
(st.doc.node(id).unwrap().kind.clone(), st.doc.slices.len())
};
// At first, Convert Layers to Objects with Import Slices.
let (kind, slices) = place(&mut app, None);
assert!(matches!(kind, NodeKind::Group { .. }));
assert_eq!(slices, 1);
// An `importSlices` the params give is kept.
let (kind, slices) = place(&mut app, Some(false));
assert!(matches!(kind, NodeKind::Group { .. }));
assert_eq!(slices, 1, "no new slice");
// Then the choices made last.
app.ui.psd_import = json!({"layers": false, "importSlices": false});
let (kind, slices) = place(&mut app, None);
assert!(matches!(kind, NodeKind::Image(_)));
assert_eq!(slices, 1, "no new slice");
let (_, slices) = place(&mut app, Some(true));
assert_eq!(slices, 2, "the given importSlices brings the slice in");
}
#[test]
fn files_from_bytes_placed_with_link_take_the_last_choices() {
let files: Vec<Value> = ["a.psd", "b.psd"].iter().map(|n| json!({ "name": n })).collect();
let mut app = app();
for n in ["a.psd", "b.psd"] {
app.place.picked.push((n.to_string(), sliced(&layered())));
}
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// The dialog's Link is on, but files from bytes have no file to link to.
let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": true, "template": false, "showImportOptions": false}));
crate::place::confirm(&mut app, &d).unwrap();
assert!(app.ui.dialog.is_none(), "the cursor loads without asking");
let view = vectorcraft_engine::ViewInfo::default();
for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] {
for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() {
if let vectorcraft_engine::UiRequest::Place(p) = r {
crate::place::place_from_cursor(&mut app, &p);
}
}
}
let st = app.session.doc().unwrap();
let [id] = st.selection.objects[..] else { panic!("one object is placed") };
// At first, Convert Layers to Objects with Import Slices.
assert!(matches!(st.doc.node(id).unwrap().kind, NodeKind::Group { .. }));
assert_eq!(st.doc.slices.len(), 1);
}
#[test]
fn a_cursor_loaded_with_show_import_options_on_asks_for_each_psd_file() {
let dir = std::env::temp_dir().join(format!("vc-psd-import-asks-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let paths: Vec<String> = ["a.psd", "b.psd"]
.iter()
.map(|n| {
let p = dir.join(n);
std::fs::write(&p, layered()).unwrap();
p.to_string_lossy().into_owned()
})
.collect();
let files: Vec<Value> = paths.iter().map(|p| json!({ "path": p })).collect();
let services = crate::Services { read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), ..Default::default() };
let mut app = VectorcraftApp::new(Session::new(), services);
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// The choices made last would place the layers without asking with Show Import Options off.
app.ui.psd_import = json!({"layers": true, "importSlices": true});
let d = Dialog::new(crate::dialogs::place::KIND, json!({"files": files, "link": false, "template": false, "showImportOptions": true}));
crate::place::confirm(&mut app, &d).unwrap();
assert!(app.ui.dialog.is_none(), "the cursor loads without asking");
assert_eq!(app.session.tool_options()["count"], 2);
// A click on the canvas: the file the cursor's request names asks.
let view = vectorcraft_engine::ViewInfo::default();
for kind in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] {
for r in app.session.pointer(&vectorcraft_tools::PointerEvent::new(kind, 10.0, 10.0), view).unwrap() {
if let vectorcraft_engine::UiRequest::Place(p) = r {
crate::place::place_from_cursor(&mut app, &p);
}
}
}
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the clicked file asks");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn scripted_places_and_places_that_give_layers_dont_ask() {
let b64 = vectorcraft_format::base64_encode(&layered());
let mut app = app();
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
// `file.place` run as a command places at once, as before.
let r = crate::place::run(&mut app, &json!({"name": "poster.psd", "dataBase64": b64})).unwrap();
assert!(app.ui.dialog.is_none());
assert_eq!(r["format"], "psd");
// The user's place with `layers` given doesn't ask either.
crate::place::run_for_user(&mut app, &json!({"name": "poster.psd", "dataBase64": b64, "layers": false})).unwrap();
assert!(app.ui.dialog.is_none());
}
}
+5 -1
View File
@@ -262,7 +262,8 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) {
});
}
/// Rotation presets, rotation and perspective for Extrude & Bevel, Inflate and Rotate.
/// Rotation presets, rotation and perspective for Extrude & Bevel, Inflate and Rotate, and the
/// classic 3D effects, which have the track cube below the presets.
fn view_controls(ui: &mut egui::Ui, d: &mut Dialog) {
heading(ui, tl!("Rotation"));
let names = [
@@ -296,6 +297,9 @@ fn view_controls(ui: &mut egui::Ui, d: &mut Dialog) {
d.fields.extend([("rotationX".into(), json!(x)), ("rotationY".into(), json!(y)), ("rotationZ".into(), json!(z))]);
}
});
if vectorcraft_effects::is_classic_three_d(&d.str("__effect")) {
super::three_d_classic::track_cube(ui, d);
}
for (key, name) in [("rotationX", tl!("Rotation X")), ("rotationY", tl!("Rotation Y")), ("rotationZ", tl!("Rotation Z"))] {
number(ui, d, key, name, (-180.0, 180.0), "°", 2, None);
}
@@ -61,6 +61,11 @@ impl Harness {
self.ctx.read_response(Id::unique(id)).unwrap().rect
}
/// The open dialog's track cube.
fn cube_id(&self) -> Id {
super::super::three_d_classic::cube_id(&self.app.ui.dialog.as_ref().unwrap().kind)
}
fn click(&mut self, p: Pos2) {
self.frame(vec![Event::PointerMoved(p), button(p, true)]);
self.frame(vec![button(p, false)]);
@@ -460,6 +465,88 @@ fn classic_rotate_shows_its_options_and_applies_as_one_step() {
assert_eq!(h.app.session.doc().unwrap().doc, before);
}
/// The classic effects' track cube: a drag on its face turns the object live and the presets show
/// Custom, Escape during a drag puts the angles back, the ring turns Z alone, the arrow keys turn
/// it with the keyboard focus, and OK keeps it all as one undo step. The newer effects have no cube.
#[test]
fn the_track_cube_turns_the_classic_effects_live_in_one_undo_step() {
use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE, EXTRUDE, ROTATE};
let square = "M100 100 L200 100 L200 200 L100 200 Z";
for effect in [EXTRUDE, ROTATE] {
let mut h = Harness::with(square, effect, vec2(1400.0, 1000.0));
h.app.ui.dialog.as_mut().unwrap().fields.insert("__tab".into(), json!("rotation"));
h.settle();
assert!(!h.texts.iter().any(|(t, _)| t == "Track cube"), "{effect} has no track cube");
}
for effect in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] {
let mut h = Harness::with(square, effect, vec2(1400.0, 1000.0));
h.app.ui.dialog.as_mut().unwrap().fields.insert("__tab".into(), json!("rotation"));
h.settle();
h.rect("Track cube");
}
let mut h = Harness::with(square, CLASSIC_ROTATE, vec2(1400.0, 1000.0));
let before = h.app.session.doc().unwrap().doc.clone();
h.settle();
h.rect("Off-Axis Front");
let start = ["rotationX", "rotationY", "rotationZ"].map(|k| h.value(k));
let cube = h.ctx.read_response(h.cube_id()).unwrap().rect;
// A face, dragged right: the object turns, the document previews it, and the preset is Custom.
h.drag(cube.center(), vec2(30.0, 0.0));
let turned = ["rotationX", "rotationY", "rotationZ"].map(|k| h.value(k));
assert_ne!(turned, start, "the drag turned the object");
h.rect("Custom");
let fx = |h: &Harness| {
let state = h.app.session.doc().unwrap();
state.doc.node(state.selection.objects[0]).unwrap().appearance.effects[0].params.clone()
};
assert_eq!(fx(&h)["rotationY"].as_f64(), Some(turned[1]), "the preview follows the cube");
// Escape during a drag puts the angles back and keeps the dialog open.
let p = cube.center();
h.frame(vec![Event::PointerMoved(p), button(p, true)]);
h.frame(vec![Event::PointerMoved(p + vec2(0.0, 30.0))]);
h.frame(vec![Event::PointerMoved(p + vec2(0.0, 40.0))]);
assert_ne!(h.value("rotationX"), turned[0]);
h.frame(vec![Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]);
h.frame(vec![button(p + vec2(0.0, 40.0), false)]);
h.settle();
assert!(h.app.ui.dialog.is_some(), "Escape ends the drag, not the dialog");
assert_eq!(["rotationX", "rotationY", "rotationZ"].map(|k| h.value(k)), turned);
// The ring turns in the screen plane: Z alone.
let top = pos2(cube.center().x, cube.center().y - 53.5);
h.drag(top, vec2(12.0, 2.0));
assert_eq!((h.value("rotationX"), h.value("rotationY")), (turned[0], turned[1]));
assert!(h.value("rotationZ") > turned[2], "clockwise: {} -> {}", turned[2], h.value("rotationZ"));
// With the keyboard focus (the drags gave it), Right turns about the screen's vertical axis.
let z = h.value("rotationZ");
assert!(h.ctx.memory(|m| m.has_focus(h.cube_id())), "the drag gave the cube the keyboard focus");
h.frame(vec![Event::Key { key: egui::Key::PageUp, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]);
h.settle();
assert!((h.value("rotationZ") - (z - 1.0)).abs() < 0.011, "Page Up turns 1° counterclockwise");
let y = h.value("rotationY");
h.frame(vec![Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]);
h.settle();
assert_ne!(h.value("rotationY"), y, "Right turns the cube");
let last = h.value("rotationZ");
dialogs::confirm(&mut h.app).unwrap();
assert_eq!(fx(&h)["rotationZ"].as_f64(), Some(last));
h.app.run("edit.undo", json!({})).unwrap();
assert_eq!(h.app.session.doc().unwrap().doc, before);
}
/// A mixed rotation (the 3D and Materials panel's selected effects differ) leaves the cube off.
#[test]
fn the_track_cube_is_off_while_a_rotation_is_mixed() {
use vectorcraft_effects::CLASSIC_ROTATE;
let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", CLASSIC_ROTATE, vec2(1400.0, 1000.0));
h.app.ui.dialog.as_mut().unwrap().fields.insert("rotationX".into(), Value::Null);
h.settle();
let cube = h.ctx.read_response(h.cube_id()).unwrap().rect;
h.drag(cube.center(), vec2(30.0, 0.0));
let d = h.app.ui.dialog.as_ref().unwrap();
assert_eq!(d.fields.get("rotationX"), Some(&Value::Null));
assert!(!h.ctx.read_response(h.cube_id()).unwrap().sense.senses_drag());
}
#[test]
fn extrude_bevel_options_enable_with_a_bevel_shape() {
let mut h = Harness::with("M100 100 L200 100 L200 200 L100 200 Z", vectorcraft_effects::EXTRUDE, vec2(1400.0, 1000.0));
+3 -1
View File
@@ -42,8 +42,10 @@ fn drag_id() -> Id {
Id::unique("revolve-gizmo-drag")
}
/// Is a rotation or light gesture in progress, on the artboard or on the classic 3D effects' track
/// cube?
pub(crate) fn dragging(ctx: &egui::Context) -> bool {
ctx.data(|m| m.get_temp::<Drag>(drag_id())).is_some()
ctx.data(|m| m.get_temp::<Drag>(drag_id())).is_some() || super::three_d_classic::cube_dragging(ctx)
}
pub(super) fn clear(ctx: &egui::Context) {
@@ -0,0 +1,184 @@
//! The track cube's rotations, grips and gestures.
use super::*;
use egui::pos2;
use vectorcraft_effects::ROTATION_PRESETS;
const SAMPLES: [[f64; 3]; 6] =
[[0.0, 0.0, 0.0], [-21.88, -23.4, 9.06], [27.0, -39.0, 53.0], [170.0, 10.0, -95.5], [-120.0, 75.0, 33.0], [45.0, -35.26, 30.0]];
fn close(a: [f64; 3], b: [f64; 3]) -> bool {
a.iter().zip(b).all(|(a, b)| tidy(a - b).abs() < 0.011)
}
fn same_rotation(a: M3, b: M3) -> bool {
a.iter().flatten().zip(b.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-3)
}
/// The cube turns as the 3D effects turn the art: each object axis lands where the effects' own
/// view rotation puts it.
#[test]
fn the_cube_rotates_as_the_effects_do() {
for angles in SAMPLES {
let m = rotation(angles);
let view = vectorcraft_three_d::Revolve { rotation_x: angles[0], rotation_y: angles[1], rotation_z: angles[2], ..Default::default() };
for (axis, p) in view.view_axes().into_iter().enumerate() {
assert!((m[0][axis] - p.x).abs() < 1e-9 && (m[1][axis] - p.y).abs() < 1e-9, "{angles:?} axis {axis}");
}
}
}
/// Reading the angles back gives the same angles, presets included, Back's 180° and the gimbal
/// positions Left and Right (Y at ±90°) among them.
#[test]
fn angles_read_back_as_they_were_set() {
for angles in SAMPLES.into_iter().chain(ROTATION_PRESETS.iter().map(|(_, a)| *a)) {
let back = angles_of(rotation(angles), angles);
assert!(close(back, angles), "{angles:?} read back as {back:?}");
assert!(same_rotation(rotation(back), rotation(angles)));
}
assert_eq!(angles_of(rotation([0.0, 180.0, 0.0]), [0.0, 180.0, 0.0]), [0.0, 180.0, 0.0], "Back stays Back, not -180°");
}
#[test]
fn angles_stay_in_the_fields_range_to_a_hundredth() {
assert_eq!(tidy(180.0), 180.0);
assert_eq!(tidy(-180.0), 180.0);
assert_eq!(tidy(190.004), -170.0);
assert_eq!(tidy(-0.001), 0.0);
assert!(tidy(-0.001).is_sign_positive());
}
fn drag(grip: Grip, angles: [f64; 3], from: Pos2, to: Pos2, shift: bool) -> [f64; 3] {
let mut g =
CubeDrag { grip, matrix: rotation(angles), origin: from, last: from, lock: None, fields: Default::default(), pass: 0, owner: Id::NULL };
// In five steps, as a pointer moves.
let mut near = angles;
for k in 1..=5 {
let p = from + (to - from) * (k as f32 / 5.0);
g.matrix = drag_turn(&mut g, p, pos2(0.0, 0.0), shift);
g.last = p;
near = angles_of(g.matrix, near);
}
near
}
/// The ring turns in the screen plane, which the effects apply last: only Z changes, by the angle
/// swept, clockwise on the screen.
#[test]
fn the_ring_turns_z_only() {
for angles in SAMPLES {
let after = drag(Grip::Ring, angles, pos2(0.0, -53.0), pos2(53.0, 0.0), false);
assert!(close(after, [angles[0], angles[1], angles[2] + 90.0]), "{angles:?} -> {after:?}");
}
}
/// An edge turns about its own object axis. The effects turn X first, so an X edge changes X alone.
#[test]
fn an_x_edge_turns_x_only_and_other_edges_keep_their_axis() {
let start = [-21.88, -23.4, 9.06];
let after = drag(Grip::Edge(0), start, pos2(0.0, 0.0), pos2(0.0, -40.0), false);
assert!((after[0] - start[0]).abs() > 5.0, "X turned: {after:?}");
assert!((after[1] - start[1]).abs() < 0.02 && (after[2] - start[2]).abs() < 0.02, "Y and Z kept: {after:?}");
for axis in 0..3 {
let after = drag(Grip::Edge(axis), start, pos2(0.0, 0.0), pos2(30.0, -30.0), false);
let (m0, m1) = (rotation(start), rotation(after));
let column = |m: M3| [m[0][axis], m[1][axis], m[2][axis]];
let (a, b) = (column(m0), column(m1));
assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3), "axis {axis} stays put: {a:?} {b:?}");
assert!(!same_rotation(m0, m1), "axis {axis}: the cube turned");
}
}
/// A face drag across the screen turns about the screen's vertical axis, the front toward the
/// drag; Shift keeps a slanted drag to that axis.
#[test]
fn a_face_drag_turns_the_front_toward_the_pointer_and_shift_keeps_one_axis() {
let front = [0.0, 0.0, 0.0];
let right = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(40.0, 0.0), false);
assert!(close(right, [0.0, 20.0, 0.0]), "{right:?}");
// The front (+Z) turns toward +X.
assert!(rotation(right)[0][2] > 0.3);
let down = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(0.0, 40.0), false);
assert!(close(down, [-20.0, 0.0, 0.0]), "{down:?}");
assert!(rotation(down)[1][2] > 0.3, "the front turns down");
let slanted = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(40.0, 12.0), true);
assert!(close(slanted, [0.0, 20.0, 0.0]), "Shift across: {slanted:?}");
let steep = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(10.0, -40.0), true);
assert!(close(steep, [20.0, 0.0, 0.0]), "Shift up: {steep:?}");
let free = drag(Grip::Face, front, pos2(0.0, 0.0), pos2(40.0, 12.0), false);
assert!(free[0].abs() > 1.0, "without Shift a slanted drag also tilts: {free:?}");
}
/// A gesture ends when the cube stops being drawn during it (its dialog closed, or the Rotation tab
/// was left), so Escape is not held back for a cube that is no longer there.
#[test]
fn a_drag_ends_when_the_cube_is_no_longer_drawn() {
let ctx = egui::Context::default();
let run = |draw: &mut dyn FnMut(&mut egui::Ui)| ctx.run_ui(Default::default(), draw).textures_delta.clear();
run(&mut |ui| {
let pass = ui.ctx().cumulative_pass_nr();
let drag = CubeDrag {
grip: Grip::Face,
matrix: rotation([0.0; 3]),
origin: Pos2::ZERO,
last: Pos2::ZERO,
lock: None,
fields: Default::default(),
pass,
owner: Id::NULL,
};
ui.data_mut(|m| m.insert_temp(cube_drag_id(), drag));
assert!(cube_dragging(ui.ctx()));
});
assert!(cube_dragging(&ctx), "the next pass still sees the gesture");
for _ in 0..2 {
run(&mut |_| {});
}
assert!(!cube_dragging(&ctx), "two passes without the cube end the gesture");
}
/// With the 3D and Materials panel and a 3D dialog both showing a cube, a gesture on one cube is
/// left alone by the other: Escape there does not put the first cube's settings into it.
#[test]
fn a_cube_leaves_a_gesture_on_the_other_cube_alone() {
let ctx = egui::Context::default();
let mut d = Dialog::new("effect", json!({ "rotationX": 10.0, "rotationY": 0.0, "rotationZ": 0.0 }));
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let input = egui::RawInput { events: vec![escape], ..Default::default() };
let mut out = ctx.run_ui(input, |ui| {
let pass = ui.ctx().cumulative_pass_nr();
let other = CubeDrag {
grip: Grip::Face,
matrix: rotation([50.0, 0.0, 0.0]),
origin: Pos2::ZERO,
last: Pos2::ZERO,
lock: None,
fields: json!({ "rotationX": 50.0, "rotationY": 0.0, "rotationZ": 0.0 }).as_object().cloned().unwrap_or_default(),
pass,
owner: cube_id(crate::panels::three_d::ID),
};
assert_ne!(cube_id(crate::panels::three_d::ID), cube_id(&d.kind), "each cube has its own focus");
ui.data_mut(|m| m.insert_temp(cube_drag_id(), other));
track_cube(ui, &mut d);
});
out.textures_delta.clear();
assert_eq!(d.f64("rotationX", 0.0), 10.0, "the dialog keeps its own rotation");
// The button is up in that pass, and the other cube, drawn later, still has the release to handle.
assert!(ctx.data(|m| m.get_temp::<CubeDrag>(cube_drag_id())).is_some(), "the other cube's gesture is still there");
}
/// The centre is on the front face, the ring's band on the ring, and an edge's middle on that edge.
#[test]
fn grips_follow_what_is_under_the_pointer() {
let m = rotation([-21.88, -23.4, 9.06]);
let center = pos2(100.0, 100.0);
assert_eq!(grip_at(m, center, center), Grip::Face);
assert_eq!(grip_at(m, center, center + vec2(0.0, -(RING_IN + RING_OUT) / 2.0)), Grip::Ring);
for (i, j, axis) in edges().filter(|&(i, _, axis)| edge_visible(m, i, axis)) {
let middle = corner(m, center, i) + (corner(m, center, j) - corner(m, center, i)) * 0.5;
assert_eq!(grip_at(m, center, middle), Grip::Edge(axis), "edge {i}-{j}");
}
// Facing front: four faces are edge-on and hidden, so only the front's edges show.
let m = rotation([0.0, 0.0, 0.0]);
assert_eq!(edges().filter(|&(i, _, axis)| edge_visible(m, i, axis)).count(), 4);
}
+403 -1
View File
@@ -2,14 +2,16 @@
//! compact 3D dialog: the extrude and bevel options, or the revolve options, on the Object tab
//! (Rotate (Classic) has none), and the surface with its lights, highlight, blend steps, shading
//! color and Preserve Spot Colors on the Lighting tab. Position (presets, rotation, perspective) is the Rotation tab every 3D
//! effect shares.
//! effect shares; the classic effects add the track cube to it ([`track_cube`]).
use egui::{Color32, Id, Pos2, Rect, Sense, Stroke, Vec2, vec2};
use serde_json::{Value, json};
use vectorcraft_doc::Unit;
use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, CLASSIC_ROTATE};
use super::revolve::{c3, choice, heading, label, light_list, light_record, number, reset_dot, selected_light, store_selected, toggle};
use crate::state::Dialog;
use crate::theme::Tokens;
/// Depth and cap, then the bevel: its shape, its height and whether it is added around the shape
/// or carved into it.
@@ -113,3 +115,403 @@ fn shading_custom(ui: &mut egui::Ui, d: &mut Dialog) {
}
});
}
/// The settings the track cube turns, as every 3D effect names them.
const ROTATION_KEYS: [&str; 3] = ["rotationX", "rotationY", "rotationZ"];
/// The track cube's box side, its cube's half edge, and its ring's inner and outer radius (points).
const CUBE_BOX: f32 = 124.0;
const CUBE_HALF: f32 = 25.0;
const RING_IN: f32 = 47.0;
const RING_OUT: f32 = 60.0;
/// How far an edge reaches for the pointer (points).
const EDGE_REACH: f32 = 5.0;
/// Degrees one point of pointer movement turns the cube.
const DEGREES_PER_POINT: f64 = 0.5;
/// A 3×3 rotation, rows first.
type M3 = [[f64; 3]; 3];
/// The rotation that X, Y and Z angles in degrees make, as the 3D effects apply them: X first, then
/// Y, then Z, in view space (x right, y down, z toward the viewer).
fn rotation(angles: [f64; 3]) -> M3 {
let [(sx, cx), (sy, cy), (sz, cz)] = angles.map(|a| a.to_radians().sin_cos());
[[cz * cy, cz * sy * sx - sz * cx, cz * sy * cx + sz * sx], [sz * cy, sz * sy * sx + cz * cx, sz * sy * cx - cz * sx], [-sy, cy * sx, cy * cx]]
}
fn multiply(a: M3, b: M3) -> M3 {
std::array::from_fn(|i| std::array::from_fn(|j| (0..3).map(|k| a[i][k] * b[k][j]).sum()))
}
/// The unit vector along axis `axis` (0 X, 1 Y, 2 Z).
fn unit(axis: usize) -> [f64; 3] {
std::array::from_fn(|i| if i == axis { 1.0 } else { 0.0 })
}
/// A turn of `degrees` about the unit vector `axis`.
fn turn(axis: [f64; 3], degrees: f64) -> M3 {
let (s, c) = degrees.to_radians().sin_cos();
let t = 1.0 - c;
let [x, y, z] = axis;
[
[t * x * x + c, t * x * y - s * z, t * x * z + s * y],
[t * x * y + s * z, t * y * y + c, t * y * z - s * x],
[t * x * z - s * y, t * y * z + s * x, t * z * z + c],
]
}
/// An angle as the rotation fields hold it: above -180° up to 180°, to a hundredth of a degree.
fn tidy(degrees: f64) -> f64 {
let wrapped = 180.0 - (180.0 - degrees).rem_euclid(360.0);
(wrapped * 100.0).round() / 100.0 + 0.0
}
/// The X, Y and Z angles of rotation `m`. Of the two sets of angles that make it, the one nearest
/// `near` (so a turn moves the fields as little as it can); with Y at ±90°, where X and Z turn about
/// the same axis, X keeps its value from `near`.
fn angles_of(m: M3, near: [f64; 3]) -> [f64; 3] {
let y = (-m[2][0]).clamp(-1.0, 1.0).asin().to_degrees();
let candidates = if m[2][1].hypot(m[2][2]) < 1e-9 {
let x = near[0];
let z = if y > 0.0 { x - m[0][1].atan2(m[1][1]).to_degrees() } else { (-m[0][1]).atan2(m[1][1]).to_degrees() - x };
[Some([x, y, z]), None]
} else {
let x = m[2][1].atan2(m[2][2]).to_degrees();
let z = m[1][0].atan2(m[0][0]).to_degrees();
[Some([x, y, z]), Some([x + 180.0, 180.0 - y, z + 180.0])]
};
let distance = |a: &[f64; 3]| a.iter().zip(near).map(|(a, b)| tidy(a - b).abs()).sum::<f64>();
candidates.into_iter().flatten().min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap_or(near).map(tidy)
}
/// Where corner `i` of the cube (bit 0 for +X, bit 1 for +Y, bit 2 for +Z) is drawn.
fn corner(m: M3, center: Pos2, i: usize) -> Pos2 {
let p: [f64; 3] = std::array::from_fn(|b| if i >> b & 1 == 1 { 1.0 } else { -1.0 });
let v: [f64; 3] = std::array::from_fn(|r| (0..3).map(|k| m[r][k] * p[k]).sum());
center + vec2(v[0] as f32, v[1] as f32) * CUBE_HALF
}
/// The corners of the face square to `axis` on its positive or negative side, in order round it.
fn face_corners(axis: usize, positive: bool) -> [usize; 4] {
let (b, c) = (1 << ((axis + 1) % 3), 1 << ((axis + 2) % 3));
let side = if positive { 1 << axis } else { 0 };
[0, b, b | c, c].map(|k| side | k)
}
/// Does the face square to `axis` on that side face the viewer?
fn face_visible(m: M3, axis: usize, positive: bool) -> bool {
m[2][axis] * if positive { 1.0 } else { -1.0 } > 1e-6
}
/// The 12 edges: (from corner, to corner, the object axis it runs along).
fn edges() -> impl Iterator<Item = (usize, usize, usize)> {
(0..3).flat_map(|axis| (0..8).filter(move |i| i >> axis & 1 == 0).map(move |i| (i, i | 1 << axis, axis)))
}
/// Is the edge from corner `i` along `axis` on a face the viewer sees?
fn edge_visible(m: M3, i: usize, axis: usize) -> bool {
[(axis + 1) % 3, (axis + 2) % 3].into_iter().any(|other| face_visible(m, other, i >> other & 1 == 1))
}
/// What a press on the track cube takes hold of.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Grip {
/// A face: a free turn, or with Shift about the screen's horizontal or vertical axis.
Face,
/// An edge: a turn about the object axis the edge runs along.
Edge(usize),
/// The ring round the cube: a turn in the plane of the screen.
Ring,
}
/// The z of the cross product of two screen vectors: positive when `b` is clockwise from `a`.
fn cross(a: Vec2, b: Vec2) -> f32 {
a.x * b.y - a.y * b.x
}
fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 {
let line = b - a;
let t = ((p - a).dot(line) / line.length_sq().max(1e-6)).clamp(0.0, 1.0);
p.distance(a + line * t)
}
/// What the pointer at `p` takes hold of on a cube drawn at `m` about `center`: the nearest edge
/// within reach, else a face, else the ring, else (in the box's corners) a face's free turn.
fn grip_at(m: M3, center: Pos2, p: Pos2) -> Grip {
let edge = edges()
.filter(|&(i, _, axis)| edge_visible(m, i, axis))
.map(|(i, j, axis)| (segment_distance(p, corner(m, center, i), corner(m, center, j)), axis))
.filter(|(distance, _)| *distance <= EDGE_REACH)
.min_by(|a, b| a.0.total_cmp(&b.0));
if let Some((_, axis)) = edge {
return Grip::Edge(axis);
}
let on_face = (0..3).flat_map(|axis| [(axis, true), (axis, false)]).filter(|&(axis, side)| face_visible(m, axis, side)).any(|(axis, side)| {
let points = face_corners(axis, side).map(|i| corner(m, center, i));
let sides: [f32; 4] = std::array::from_fn(|k| cross(points[(k + 1) % 4] - points[k], p - points[k]));
sides.iter().all(|s| *s >= 0.0) || sides.iter().all(|s| *s <= 0.0)
});
let distance = p.distance(center);
if !on_face && (RING_IN - 3.0..=RING_OUT + 3.0).contains(&distance) { Grip::Ring } else { Grip::Face }
}
/// The turn in degrees, clockwise on the screen, from `from` to `to` about `center`.
fn sweep(from: Pos2, to: Pos2, center: Pos2) -> f64 {
let (a, b) = (from - center, to - center);
if a.length() < 2.0 || b.length() < 2.0 {
return 0.0;
}
f64::from(cross(a, b)).atan2(f64::from(a.dot(b))).to_degrees()
}
/// A track cube gesture in progress.
#[derive(Clone)]
struct CubeDrag {
grip: Grip,
/// The rotation so far, kept unrounded so a long drag does not drift.
matrix: M3,
origin: Pos2,
last: Pos2,
/// With Shift, the screen axis the drag keeps to (0 X, 1 Y), chosen once it has moved 3 points.
lock: Option<usize>,
/// The settings before the gesture, which Escape puts back.
fields: serde_json::Map<String, Value>,
/// The last pass that drew the cube during the gesture.
pass: u64,
/// The cube the gesture started on. The 3D and Materials panel and a 3D dialog can each show
/// a cube at the same time, and only this one follows the gesture.
owner: Id,
}
impl CubeDrag {
/// Was the cube drawn in this pass or the one before? When it was not (its dialog closed, or
/// the Rotation tab or the panel was left during the drag), the gesture is over.
fn live(&self, pass: u64) -> bool {
self.pass.saturating_add(1) >= pass
}
}
/// The track cube of the dialog or panel of kind `kind`. The 3D and Materials panel and a 3D
/// dialog can show a cube at the same time, each with its own keyboard focus.
pub(super) fn cube_id(kind: &str) -> Id {
Id::unique(("three-d-track-cube", kind))
}
fn cube_drag_id() -> Id {
Id::unique("three-d-track-cube-drag")
}
/// Is a track cube gesture in progress?
pub(super) fn cube_dragging(ctx: &egui::Context) -> bool {
let pass = ctx.cumulative_pass_nr();
ctx.data(|m| m.get_temp::<CubeDrag>(cube_drag_id())).is_some_and(|g| g.live(pass))
}
/// The rotation after the pointer moves from `drag.last` to `p` on a cube about `center`.
fn drag_turn(drag: &mut CubeDrag, p: Pos2, center: Pos2, shift: bool) -> M3 {
let m = drag.matrix;
let delta = p - drag.last;
let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y));
match drag.grip {
Grip::Face => {
if shift {
let total = p - drag.origin;
if drag.lock.is_none() && total.length() >= 3.0 {
drag.lock = Some(usize::from(total.x.abs() >= total.y.abs()));
}
match drag.lock {
// Across the screen turns about its vertical (Y) axis, up and down about X.
Some(1) => dy = 0.0,
Some(_) => dx = 0.0,
None => return m,
}
}
let length = dx.hypot(dy);
if length < 1e-9 {
return m;
}
// The front follows the pointer: right turns it toward +X, down toward +Y.
multiply(turn([-dy / length, dx / length, 0.0], length * DEGREES_PER_POINT), m)
}
Grip::Ring => multiply(turn(unit(2), sweep(drag.last, p, center)), m),
Grip::Edge(axis) => {
let w = [m[0][axis], m[1][axis], m[2][axis]];
let across = w[0].hypot(w[1]);
// An axis pointing at the viewer turns like the ring, on the side it points to.
let degrees =
if w[2].abs() > 0.9 { sweep(drag.last, p, center) * w[2].signum() } else { (dx * w[1] - dy * w[0]) / across * DEGREES_PER_POINT };
multiply(m, turn(unit(axis), degrees))
}
}
}
/// The track cube on the Rotation tab of Extrude & Bevel (Classic), Revolve (Classic) and Rotate
/// (Classic): a cube drawn at the current X, Y and Z rotation (the object's front blue, its top and
/// bottom light gray, its sides mid gray and its back dark gray) inside a ring.
///
/// Dragging a face turns the object freely; with Shift the turn keeps to the screen's vertical axis
/// (a drag across) or its horizontal axis (a drag up or down), whichever the drag follows first.
/// Dragging an edge turns it about the object axis the edge runs along (X red, Y green, Z blue; the
/// edge takes its axis's color while hovered or dragged), and dragging in the ring turns it in the
/// plane of the screen. Escape during a drag puts the angles back. With the keyboard focus, the
/// arrow keys turn it about the screen's axes and Page Up and Page Down in the screen plane, 1° a
/// press (15° with Shift). The angles go to `rotationX`, `rotationY` and `rotationZ` only when they
/// change, and the dialog's preview applies them; OK records them as one undo step. The cube is off
/// while a rotation setting is mixed (the 3D and Materials panel's selected effects differ).
pub(super) fn track_cube(ui: &mut egui::Ui, d: &mut Dialog) {
let defaults = vectorcraft_effects::default_params(&d.str("__effect")).unwrap_or(json!({}));
let mixed = ROTATION_KEYS.iter().any(|k| d.fields.get(*k).is_some_and(Value::is_null));
let now = ROTATION_KEYS.map(|k| d.f64(k, defaults.get(k).and_then(Value::as_f64).unwrap_or(0.0)));
let mut next = None;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
let name = tl!("Track cube");
label(ui, name);
let (rect, _) = ui.allocate_exact_size(Vec2::splat(CUBE_BOX), Sense::hover());
let enabled = ui.is_enabled() && !mixed;
let id = cube_id(&d.kind);
let resp = ui.interact(rect, id, if enabled { Sense::click_and_drag() } else { Sense::hover() });
let center = rect.center();
let value = format!("X {:.2}°, Y {:.2}°, Z {:.2}°", now[0], now[1], now[2]);
resp.widget_info(|| egui::WidgetInfo {
current_text_value: Some(value.clone()),
..egui::WidgetInfo::labeled(egui::Role::Slider, enabled, name)
});
if enabled
&& resp.drag_started()
&& let Some(origin) = ui.input(|i| i.pointer.press_origin())
{
// A value being typed ends first; the cube then takes the keyboard focus below.
ui.ctx().memory_mut(|m| m.stop_text_input());
let matrix = rotation(now);
let pass = ui.ctx().cumulative_pass_nr();
let drag = CubeDrag {
grip: grip_at(matrix, center, origin),
matrix,
origin,
last: origin,
lock: None,
fields: d.fields.clone(),
pass,
owner: id,
};
ui.data_mut(|m| m.insert_temp(cube_drag_id(), drag));
}
if enabled && (resp.drag_started() || resp.clicked()) {
resp.request_focus();
}
let pass = ui.ctx().cumulative_pass_nr();
// A gesture on the other cube (the panel's or the dialog's) is left to that cube.
let mut drag = ui.data(|m| m.get_temp::<CubeDrag>(cube_drag_id())).filter(|g| g.owner == id);
if drag.as_ref().is_some_and(|g| !g.live(pass)) {
ui.data_mut(|m| m.remove::<CubeDrag>(cube_drag_id()));
drag = None;
}
if let Some(current) = &mut drag {
current.pass = pass;
if ui.input_mut(|i| i.consume_key(i.modifiers, egui::Key::Escape)) {
d.fields = current.fields.clone();
d.fields.remove(super::form::PREVIEWED);
ui.data_mut(|m| m.remove::<CubeDrag>(cube_drag_id()));
drag = None;
} else {
if let Some(p) = resp.interact_pointer_pos() {
let shift = ui.input(|i| i.modifiers.shift);
current.matrix = drag_turn(current, p, center, shift);
current.last = p;
next = Some(angles_of(current.matrix, now));
}
ui.data_mut(|m| m.insert_temp(cube_drag_id(), current.clone()));
}
}
// Only this cube's gesture ends here; the other cube may still have the release to handle.
if drag.is_some() && (resp.drag_stopped() || !ui.input(|i| i.pointer.primary_down())) {
ui.data_mut(|m| m.remove::<CubeDrag>(cube_drag_id()));
}
if enabled && resp.has_focus() {
use egui::{Key, Modifiers};
ui.memory_mut(|m| {
m.set_focus_lock_filter(id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() })
});
let mut m = rotation(now);
let mut turned = false;
for (key, axis, sign) in [
(Key::ArrowRight, 1, 1.0),
(Key::ArrowLeft, 1, -1.0),
(Key::ArrowUp, 0, 1.0),
(Key::ArrowDown, 0, -1.0),
(Key::PageDown, 2, 1.0),
(Key::PageUp, 2, -1.0),
] {
// Shift first: a key without modifiers also matches the key with Shift.
for (modifiers, step) in [(Modifiers::SHIFT, 15.0), (Modifiers::NONE, 1.0)] {
while ui.input_mut(|i| i.consume_key(modifiers, key)) {
m = multiply(turn(unit(axis), sign * step), m);
turned = true;
}
}
}
if turned {
next = Some(angles_of(m, now));
}
}
let shown = next.unwrap_or(now);
let hovered = drag.as_ref().map(|g| g.grip).or_else(|| resp.hover_pos().filter(|_| enabled).map(|p| grip_at(rotation(shown), center, p)));
if enabled && (resp.hovered() || drag.is_some()) {
ui.ctx().set_cursor_icon(match (hovered, drag.is_some()) {
(Some(Grip::Edge(_)), _) => egui::CursorIcon::ResizeHorizontal,
(_, true) => egui::CursorIcon::Grabbing,
_ => egui::CursorIcon::Grab,
});
}
paint_cube(ui, rect, rotation(shown), hovered, enabled, resp.has_focus());
resp.on_hover_text(tl!("Drag a face, an edge or the ring to rotate. Shift turns about one screen axis."));
});
if let Some(angles) = next
&& angles.iter().zip(now).any(|(a, b)| (a - b).abs() > 1e-9)
{
for (key, angle) in ROTATION_KEYS.into_iter().zip(angles) {
d.fields.insert(key.into(), json!(angle));
}
}
}
/// Draws the track cube at rotation `m` in `rect`, with the grip under the pointer or in hand lit.
fn paint_cube(ui: &egui::Ui, rect: Rect, m: M3, active: Option<Grip>, enabled: bool, focused: bool) {
let t = Tokens::get(ui.ctx());
let fade = |c: Color32| if enabled { c } else { c.gamma_multiply(0.4) };
let painter = ui.painter_at(rect);
let center = rect.center();
painter.rect_filled(rect, 2.0, t.input);
let ring = if active == Some(Grip::Ring) { 0.6 } else { 0.3 };
painter.circle_stroke(center, (RING_IN + RING_OUT) / 2.0, Stroke::new(RING_OUT - RING_IN, fade(t.axis_z.gamma_multiply(ring))));
// Front blue; top and bottom light, sides mid and back dark gray. Only faces turned to the
// viewer are drawn, and on a cube those never overlap.
for (axis, side) in (0..3).flat_map(|axis| [(axis, true), (axis, false)]) {
if !face_visible(m, axis, side) {
continue;
}
let fill = match (axis, side) {
(2, true) => t.axis_z,
(2, false) => Color32::from_gray(90),
(1, _) => Color32::from_gray(205),
_ => Color32::from_gray(155),
};
let points: Vec<Pos2> = face_corners(axis, side).iter().map(|&i| corner(m, center, i)).collect();
painter.add(egui::Shape::convex_polygon(points, fade(fill), Stroke::NONE));
}
let colors = [t.axis_x, t.axis_y, t.axis_z];
for (i, j, axis) in edges() {
if !edge_visible(m, i, axis) {
continue;
}
let lit = active == Some(Grip::Edge(axis));
let stroke = if lit { Stroke::new(2.5, fade(colors[axis])) } else { Stroke::new(1.0, fade(t.text_dim)) };
painter.line_segment([corner(m, center, i), corner(m, center, j)], stroke);
}
let border = if focused { t.accent } else { t.input_border };
painter.rect_stroke(rect, 2.0, Stroke::new(1.0, border), egui::StrokeKind::Inside);
}
#[cfg(test)]
#[path = "tests_track_cube.rs"]
mod tests;
+14 -4
View File
@@ -682,14 +682,22 @@ const MESSAGE_DEPTH: usize = 5;
/// Translate a status or error message for display (see the module docs). Unknown messages, and
/// parts of them (file names, numbers, a reason with no entry, a JSON object or array such as
/// `{"objects": [...]}`, a value the message quotes in `"…"`, `“…”` or backticks, such as a
/// symbol's name), stay as they are. A part that starts with `{` or `[` is translated only
/// when it is a whole message with an exact entry, such as `[x, y] (two numbers)`.
/// symbol's name), stay as they are. A part that starts with `{` is translated only when it is a
/// whole message with an exact entry. A part that starts with `[` is translated when it has an
/// exact entry, such as `[x, y] (two numbers)`, or when it fits a template that starts with `[`
/// and an index of digits, such as an effect's refusal ``[0] `id`: {why}``.
pub fn message(lang: Lang, s: &str) -> String {
message_at(lang, s, MESSAGE_DEPTH)
}
fn message_at(lang: Lang, s: &str, depth: usize) -> String {
let Some((forms, caps)) = lang.catalog().message_forms(s) else { return s.to_string() };
fill_message(lang, s, lang.catalog().message_forms(s), depth)
}
/// `s` shown through the catalog entry `found` matched for it, its placeholder values translated
/// in turn while `depth` lasts.
fn fill_message(lang: Lang, s: &str, found: Option<(&[String], catalog::Captures<'_, '_>)>, depth: usize) -> String {
let Some((forms, caps)) = found else { return s.to_string() };
let count = caps.iter().find(|(k, _)| *k == "n").and_then(|(_, v)| v.parse::<u64>().ok());
let form = count.map_or(forms.len().saturating_sub(1), |n| (lang.0.plural)(n).min(forms.len().saturating_sub(1)));
let Some(template) = forms.get(form) else { return s.to_string() };
@@ -697,8 +705,10 @@ fn message_at(lang: Lang, s: &str, depth: usize) -> String {
let nested = |v: &str| {
if depth <= 1 || quoted(v) {
v.to_string()
} else if v.starts_with(['{', '[']) {
} else if v.starts_with('{') {
exact_translation(lang.catalog(), v).unwrap_or_else(|| v.to_string())
} else if v.starts_with('[') {
fill_message(lang, v, lang.catalog().indexed_message_forms(v), depth - 1)
} else {
message_at(lang, v, depth - 1)
}
+7 -2
View File
@@ -1054,7 +1054,10 @@ font-technology Variable Променливи
Every (minutes) На всеки (минути)
Every option is at its default. Всички опции са в състояние по подразбиране.
Every option matches {base}. Всички опции съответстват на {base}.
Every-line Composer Композитор за всеки ред
Middle Eastern & South Asian Single-line Composer Ред по ред композитор (Близък изток и Южна Азия)
Middle Eastern & South Asian Every-line Composer Композитор за всеки ред (Близък изток и Южна Азия)
Standard Single-line Composer Стандартен ред по ред композитор
Standard Every-line Composer Стандартен композитор за всеки ред
Exact dash lengths Точни дължини на тиретата
Exceptions (comma separated) Изключения (разделени със запетаи)
Exclude Изключване
@@ -3368,7 +3371,6 @@ digits Malayalam Малаялам
Single Left Quotation Mark Лява единична кавичка
Single Quotes: Единични кавички:
Single Right Quotation Mark Дясна единична кавичка
Single-line Composer Ред по ред композитор
Toggle Line Composer Превключване на композитора на редове
Sixth Space Шесто разстояние
Size Размер
@@ -5189,6 +5191,8 @@ effect Soft Меко
Step up or down Стъпка нагоре или надолу
Drag values or labels. Double-click a value to type. Плъзнете стойности или етикети. Кликнете двукратно върху стойност за въвеждане.
Drag rings to rotate. Shift snaps to 15°. Плъзнете пръстените за завъртане. Shift прилепва към 15°.
Track cube Куб за завъртане
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Плъзнете стена, ръб или пръстена за завъртане. Shift завърта около една ос на екрана.
Drag the light, or its rings. Shift snaps to 15°. Плъзнете светлината или нейните пръстени. Shift прилепва към 15°.
Keep visible surfaces only when expanding Запазване само на видимите повърхности при разширяване
Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Изрязване на закритата геометрия при разширяване на оформлението. Живият преглед запазва цялата повърхност. Прозрачните бои и повърхности, надвишаващи границите на видимост, запазват всички лица.
@@ -6993,3 +6997,4 @@ breakText Glyphs Глифи
Nest Shapes… Подреждане на форми…
Nest Shapes Подреждане на форми
Roll Ролка
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
Can't render this file because it is too large.
+7 -2
View File
@@ -1035,6 +1035,8 @@
Step up or down Korak gore ili dolje
Drag values or labels. Double-click a value to type. Prevucite vrijednosti ili oznake. Dvostruki klik na vrijednost za upis.
Drag rings to rotate. Shift snaps to 15°. Prevucite prstenove za rotaciju. Shift hvata na 15°.
Track cube Kocka za rotaciju
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Prevucite stranu, ivicu ili prsten za rotaciju. Shift rotira oko jedne ose ekrana.
Drag the light, or its rings. Shift snaps to 15°. Prevucite svjetlo ili njegove prstenove. Shift hvata na 15°.
lighting Light Svjetlo
Keep visible surfaces only when expanding Pri proširivanju zadrži samo vidljive površine
@@ -2036,7 +2038,10 @@ digits Malayalam Malajalam
Tabular Lining Tabelarne brojke
Tabular Oldstyle Tabelarne stare brojke
Titling Alternates Alternative za naslove
Every-line Composer Slagač svih redova
Middle Eastern & South Asian Single-line Composer Slagač jednog reda (Bliski istok i Južna Azija)
Middle Eastern & South Asian Every-line Composer Slagač svih redova (Bliski istok i Južna Azija)
Standard Single-line Composer Standardni slagač jednog reda
Standard Every-line Composer Standardni slagač svih redova
First-line Left Indent Lijeva uvlaka prvog reda
Hyphenation… Rastavljanje riječi…
Words Longer Than: Riječi duže od:
@@ -2076,7 +2081,6 @@ digits Malayalam Malajalam
East Asian Composition Settings Postavke istočnoazijske kompozicije
Korean Composition Settings Postavke korejske kompozicije
Select a text object to edit its paragraph attributes. Odaberite tekstualni objekat da uredite njegove atribute pasusa.
Single-line Composer Slagač jednog reda
Toggle Line Composer Uključi/isključi Line Composer
Space After Paragraph Razmak nakon pasusa
Space Before Paragraph Razmak prije pasusa
@@ -7046,3 +7050,4 @@ shape Open Otvoren
Nest Shapes… Slaganje oblika…
Nest Shapes Slaganje oblika
Roll Rolna
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+7 -2
View File
@@ -1347,6 +1347,8 @@ antiAlias Sharp Nítid
Drag out from a corner, or click two straight lines, then click to place. Arrossega cap enfora des d’una cantonada, o fes clic en dues línies rectes i després fes clic per col·locar-ho.
Drag out from a segment, or click two points, then click to place. Arrossega cap enfora des d’un segment, o fes clic en dos punts i després fes clic per col·locar-ho.
Drag rings to rotate. Shift snaps to 15°. Arrossega els anells per girar. La tecla Maj ajusta a 15°.
Track cube Cub de rotació
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Arrossega una cara, una aresta o l'anell per girar. La tecla Maj gira al voltant d'un eix de la pantalla.
Drag the art to move it on the paper Arrossega la il·lustració per moure-la sobre el paper
Drag the light, or its rings. Shift snaps to 15°. Arrossega el llum o els seus anells. La tecla Maj ajusta a 15°.
Drag to float as a toolbar Arrossega per surar com a barra d’eines
@@ -1537,7 +1539,10 @@ antiAlias Sharp Nítid
Every (minutes) Cada (minuts)
Every option is at its default. Totes les opcions són al valor predeterminat.
Every option matches {base}. Totes les opcions coincideixen amb {base}.
Every-line Composer Composició línia per línia
Middle Eastern & South Asian Single-line Composer Compositor d’una línia (Orient Pròxim i Àsia Meridional)
Middle Eastern & South Asian Every-line Composer Composició línia per línia (Orient Pròxim i Àsia Meridional)
Standard Single-line Composer Compositor estàndard d’una línia
Standard Every-line Composer Composició estàndard línia per línia
Exact Exacte
Exact dash lengths Longituds de guió exactes
Example: {name} Exemple: {name}
@@ -4403,7 +4408,6 @@ digits Malayalam Malaiàlam
Single Quotes: Cometes simples:
Single Right Quotation Mark Cometa simple dreta
Single Word Justification: Justificació d’una sola paraula:
Single-line Composer Compositor d’una línia
Sixth Space Espai de sisena part
Size Mida
Size Tile to Art Ajusta la mida del mosaic a l’art
@@ -7769,3 +7773,4 @@ breakText Glyphs Glifs
@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} píxels és massa gran per a JPEG (com a màxim 65535 píxels per costat): reduïu la resolució
@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} píxels és massa gran per a Targa (com a màxim 65535 píxels per costat): reduïu la resolució
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} píxels és massa gran per a PSD (com a màxim {MAX_SIDE} píxels per costat): reduïu la resolució
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+22
View File
@@ -262,6 +262,28 @@ impl Catalog {
self.templates.iter().find_map(|t| t.captures(s).map(|caps| (t.forms.as_slice(), caps)))
}
/// [`Catalog::message_forms`] for a part of a message that starts with `[`, which may be a JSON
/// array: an exact `@msg` entry, else only a template that starts with a literal `[` and a
/// placeholder whose value is an index of ASCII digits, such as ``[{j}] `{_1}`: {why}``. An
/// array such as ``["] `x`: b"]`` fits that template's text, but not its index.
pub fn indexed_message_forms<'a>(&self, s: &'a str) -> Option<(&[String], Captures<'_, 'a>)> {
if let Some(tr) = self.messages.get(s) {
return Some((std::slice::from_ref(tr), Vec::new()));
}
if s.len() > MAX_MESSAGE_LEN {
return None;
}
self.templates.iter().find_map(|t| {
let [Piece::Text(open), Piece::Hole(index), ..] = t.pieces.as_slice() else { return None };
if open != "[" {
return None;
}
let caps = t.captures(s)?;
let digits = caps.iter().any(|(k, v)| k == index && v.bytes().all(|b| b.is_ascii_digit()));
digits.then_some((t.forms.as_slice(), caps))
})
}
/// The translation of a status or error message that has an exact `@msg` entry, as written in
/// the catalog (`{{` and `}}` for literal braces); templates are not tried.
pub fn exact_message(&self, s: &str) -> Option<&str> {
+7 -3
View File
@@ -1057,6 +1057,8 @@
Step up or down O krok nahoru nebo dolů
Drag values or labels. Double-click a value to type. Upravte hodnoty přetažením čísel nebo popisků. Dvojím kliknutím na hodnotu ji zadáte.
Drag rings to rotate. Shift snaps to 15°. Otáčejte přetažením prstenců. Shift nastaví kroky po 15°.
Track cube Otočná krychle
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Otáčejte přetažením stěny, hrany nebo prstence. Shift otáčí kolem jedné osy obrazovky.
Drag the light, or its rings. Shift snaps to 15°. Přetáhněte světlo nebo jeho prstence. Shift nastaví kroky po 15°.
lighting Light Světlo
Keep visible surfaces only when expanding Při rozložení ponechat pouze viditelné povrchy
@@ -2109,7 +2111,8 @@ digits Malayalam Malajálamské
Tabular Lining Tabulkové verzálkové
Tabular Oldstyle Tabulkové minuskové
Titling Alternates Titulkové alternativy
Every-line Composer Sazba všech řádků
Middle Eastern & South Asian Every-line Composer Sazba všech řádků (Blízký východ a Jižní Asie)
Standard Every-line Composer Standardní sazba všech řádků
First-line Left Indent Odsazení prvního řádku zleva
Hyphenation… Dělení slov…
Words Longer Than: Slova delší než:
@@ -2149,7 +2152,8 @@ digits Malayalam Malajálamské
East Asian Composition Settings Nastavení východoasijské sazby
Korean Composition Settings Nastavení korejské sazby
Select a text object to edit its paragraph attributes. Vyberte textový objekt, abyste mohli upravit atributy jeho odstavce.
Single-line Composer Sazba jednoho řádku
Middle Eastern & South Asian Single-line Composer Sazba jednoho řádku (Blízký východ a Jižní Asie)
Standard Single-line Composer Standardní sazba jednoho řádku
Toggle Line Composer Přepnout sazbu řádků
Space After Paragraph Mezera za odstavcem
Space Before Paragraph Mezera před odstavcem
@@ -8394,7 +8398,7 @@ breakText Glyphs Glyfy
@msg column: true floats the whole column and takes no onto, above or below column: true uvolní celý sloupec jako plovoucí a nepřijímá onto, above ani below
@msg command must be a shape.* command command musí být příkaz shape.*
@msg commands[{i}]: missing `command` commands[{i}]: chybí `command`
@msg composer must be "singleLine" or "everyLine" composer musí být "singleLine" nebo "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer musí být "singleLine", "everyLine", "standardSingleLine" nebo "standardEveryLine"
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes složené tvary přijímají cesty, složené cesty, skupiny, složené tvary, text, prolnutí a obálky
@msg compound {_1} must contain exactly one open path to join složený objekt {_1} musí ke spojení obsahovat právě jednu otevřenou cestu
@msg connect needs a path other than the one extended connect vyžaduje jinou cestu než tu prodlužovanou
Can't render this file because it is too large.
+8 -2
View File
@@ -1600,6 +1600,8 @@
Reset all Revolve settings to their defaults. Nulstil alle indstillinger for omdrejning til standardværdierne.
Drag values or labels. Double-click a value to type. Træk i værdier eller etiketter. Dobbeltklik på en værdi for at indtaste.
Drag rings to rotate. Shift snaps to 15°. Træk i ringe for at rotere. Shift fastgør til 15°.
Track cube Rotationsterning
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Træk i en flade, en kant eller ringen for at rotere. Shift roterer om én skærmakse.
Drag the light, or its rings. Shift snaps to 15°. Træk i lyset eller dets ringe. Shift fastgør til 15°.
lighting Light Lys
Keep visible surfaces only when expanding Behold kun synlige flader ved udvidelse
@@ -2533,7 +2535,10 @@ digits Malayalam Malayalam
Tabular Lining Tabulære versalcifre
Tabular Oldstyle Tabulære mediævalcifre
Titling Alternates Titelalternativer
Every-line Composer Hverlinjesætter
Middle Eastern & South Asian Single-line Composer Enlinjesætter (Mellemøsten og Sydasien)
Middle Eastern & South Asian Every-line Composer Hverlinjesætter (Mellemøsten og Sydasien)
Standard Single-line Composer Standard-enlinjesætter
Standard Every-line Composer Standard-hverlinjesætter
First-line Left Indent Venstre indrykning af første linje
Hyphenation… Orddeling…
Justification… Justering…
@@ -2565,7 +2570,6 @@ digits Malayalam Malayalam
East Asian Composition Settings Indstillinger for østasiatisk komposition
Korean Composition Settings Indstillinger for koreansk komposition
Select a text object to edit its paragraph attributes. Markér et tekstobjekt for at redigere dets afsnitsattributter.
Single-line Composer Enlinjesætter
Toggle Line Composer Skift linjesætter
Space After Paragraph Mellemrum efter afsnit
Space Before Paragraph Mellemrum før afsnit
@@ -5413,6 +5417,7 @@ imageTrace Outline Kontur
@msg plug-in failed: {0} plug-in fejlede: {0}
@msg plug-in manifest: {0} plug-in-manifest: {0}
@msg plug-in output: {0} plug-in-output: {0}
@msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why}
@msg plug-in parameters: {0} plug-in-parametre: {0}
@msg plug-in trapped: {0} plug-in'et blev fanget: {0}
@msg print settings are not an object printindstillingerne er ikke et objekt
@@ -7678,3 +7683,4 @@ breakText Glyphs Glyffer
Nest Shapes… Pak figurer tæt…
Nest Shapes Pak figurer tæt
Roll Rulle
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+7 -3
View File
@@ -1056,7 +1056,8 @@ font-technology Variable Variabel
Every (minutes) Alle (Minuten)
Every option is at its default. Alle Optionen haben ihren Standardwert.
Every option matches {base}. Alle Optionen entsprechen {base}.
Every-line Composer Alle-Zeilen-Setzer
Middle Eastern & South Asian Every-line Composer Alle-Zeilen-Setzer (Naher Osten und Südasien)
Standard Every-line Composer Standard-Alle-Zeilen-Setzer
Exact dash lengths Exakte Strichlängen
Exceptions (comma separated) Ausnahmen (durch Kommas getrennt)
Exclude Schnittmenge entfernen
@@ -3429,7 +3430,8 @@ digits Malayalam Malayalam
Single Left Quotation Mark Einfaches öffnendes Anführungszeichen
Single Quotes: Einfache Anführungszeichen:
Single Right Quotation Mark Einfaches schließendes Anführungszeichen
Single-line Composer Einzeilen-Setzer
Middle Eastern & South Asian Single-line Composer Einzeilen-Setzer (Naher Osten und Südasien)
Standard Single-line Composer Standard-Einzeilen-Setzer
Toggle Line Composer Zeilensetzer umschalten
Sixth Space Sechstelgeviert-Leerzeichen
Size Größe
@@ -5529,6 +5531,8 @@ theme Appearance Erscheinungsbild
# 3D and Materials › Revolve: its options dialog and gizmos.
Axis side Achsenseite
Drag rings to rotate. Shift snaps to 15°. Ziehen Sie die Ringe, um zu drehen. Mit Shift in 15°-Schritten.
Track cube Rotationswürfel
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Ziehen Sie eine Fläche, eine Kante oder den Ring, um zu drehen. Mit Shift um eine Bildschirmachse.
Drag the light, or its rings. Shift snaps to 15°. Ziehen Sie das Licht oder seine Ringe. Mit Shift in 15°-Schritten.
lighting Light Licht
Drag values or labels. Double-click a value to type. Ziehen Sie Werte oder Beschriftungen. Doppelklicken Sie auf einen Wert, um ihn einzugeben.
@@ -8075,7 +8079,7 @@ breakText Glyphs Glyphen
@msg column: true floats the whole column and takes no onto, above or below column: true macht die ganze Spalte schwebend und nimmt kein onto, above oder below
@msg command must be a shape.* command command muss ein shape.*-Befehl sein
@msg commands[{i}]: missing `command` commands[{i}]: `command` fehlt
@msg composer must be "singleLine" or "everyLine" composer muss „singleLine“ oder „everyLine“ sein
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer muss „singleLine“, „everyLine“, „standardSingleLine“ oder „standardEveryLine“ sein
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes zusammengesetzte Formen nehmen Pfade, zusammengesetzte Pfade, Gruppen, zusammengesetzte Formen, Text, Angleichungen und Verzerrungshüllen
@msg compound {_1} must contain exactly one open path to join zusammengesetzter Pfad {_1} muss genau einen offenen Pfad zum Zusammenfügen enthalten
@msg connect end must be "start" or "end" connect end muss „start“ oder „end“ sein
Can't render this file because it is too large.
+7 -2
View File
@@ -1021,7 +1021,10 @@ font-technology Variable Μεταβλητές
Every (minutes) Κάθε (λεπτά)
Every option is at its default. Όλες οι επιλογές έχουν τις προεπιλεγμένες τιμές τους.
Every option matches {base}. Όλες οι επιλογές ταιριάζουν με το {base}.
Every-line Composer Σύνθεση όλων των γραμμών
Middle Eastern & South Asian Single-line Composer Σύνθεση μονής γραμμής (Μέση Ανατολή και Νότια Ασία)
Middle Eastern & South Asian Every-line Composer Σύνθεση όλων των γραμμών (Μέση Ανατολή και Νότια Ασία)
Standard Single-line Composer Τυπική σύνθεση μονής γραμμής
Standard Every-line Composer Τυπική σύνθεση όλων των γραμμών
Exact dash lengths Ακριβή μήκη παυλών
Exceptions (comma separated) Εξαιρέσεις (χωρισμένες με κόμμα)
Exclude Εξαίρεση
@@ -4027,7 +4030,6 @@ digits Malayalam Μαλαγιάλαμ
Single Left Quotation Mark Μονό αριστερό εισαγωγικό
Single Quotes: Μονά εισαγωγικά:
Single Right Quotation Mark Μονό δεξί εισαγωγικό
Single-line Composer Σύνθεση μονής γραμμής
Toggle Line Composer Εναλλαγή σύνθεσης γραμμών
Sixth Space Διάστημα ενός έκτου
Size Tile to Art Προσαρμογή μεγέθους πλακιδίου στο σχέδιο
@@ -5431,6 +5433,8 @@ digits Malayalam Μαλαγιάλαμ
Step up or down Ένα βήμα πάνω ή κάτω
Drag values or labels. Double-click a value to type. Σύρετε τιμές ή ετικέτες. Κάντε διπλό κλικ σε μια τιμή για πληκτρολόγηση.
Drag rings to rotate. Shift snaps to 15°. Σύρετε τους δακτυλίους για περιστροφή. Με Shift γίνεται προσκόλληση ανά 15°.
Track cube Κύβος περιστροφής
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Σύρετε μια έδρα, μια ακμή ή τον δακτύλιο για περιστροφή. Με Shift η περιστροφή γίνεται γύρω από έναν άξονα της οθόνης.
Drag the light, or its rings. Shift snaps to 15°. Σύρετε την πηγή φωτός ή τους δακτυλίους της. Με Shift γίνεται προσκόλληση ανά 15°.
Keep visible surfaces only when expanding Διατήρηση μόνο ορατών επιφανειών κατά την ανάπτυξη
Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Αποκοπή καλυμμένης γεωμετρίας κατά την Ανάπτυξη εμφάνισης. Η ζωντανή προεπισκόπηση διατηρεί ολόκληρη την επιφάνεια. Διαφανή γεμίσματα και επιφάνειες που υπερβαίνουν τα όρια ορατότητας διατηρούν όλες τις έδρες.
@@ -7743,3 +7747,4 @@ breakText Glyphs Γλύφοι
@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution τα {width} × {height} εικονοστοιχεία είναι υπερβολικό μέγεθος για JPEG (το πολύ 65535 εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση
@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution τα {width} × {height} εικονοστοιχεία είναι υπερβολικό μέγεθος για Targa (το πολύ 65535 εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution τα {w} × {h} εικονοστοιχεία είναι υπερβολικό μέγεθος για PSD (το πολύ {MAX_SIDE} εικονοστοιχεία ανά πλευρά): μειώστε την ανάλυση
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine"
Can't render this file because it is too large.
+7 -2
View File
@@ -1077,7 +1077,10 @@ font-technology Variable Variables
Every (minutes) Cada (minutos)
Every option is at its default. Todas las opciones tienen su valor predeterminado.
Every option matches {base}. Todas las opciones coinciden con {base}.
Every-line Composer Composición de todas las líneas
Middle Eastern & South Asian Single-line Composer Composición de una línea (Oriente Medio y Sur de Asia)
Middle Eastern & South Asian Every-line Composer Composición de todas las líneas (Oriente Medio y Sur de Asia)
Standard Single-line Composer Composición estándar de una línea
Standard Every-line Composer Composición estándar de todas las líneas
Exact dash lengths Longitudes exactas de guion
Exceptions (comma separated) Excepciones (separadas por comas)
Exclude Excluir
@@ -3461,7 +3464,6 @@ digits Malayalam Malayálam
Single Left Quotation Mark Comilla simple de apertura
Single Quotes: Comillas simples:
Single Right Quotation Mark Comilla simple de cierre
Single-line Composer Composición de una línea
Toggle Line Composer Alternar composición de líneas
Sixth Space Sexto de espacio
Size Tamaño
@@ -5551,6 +5553,8 @@ axis Both Ambos
Step up or down Subir o bajar un paso
Drag values or labels. Double-click a value to type. Arrastra los valores o las etiquetas. Haz doble clic en un valor para escribir.
Drag rings to rotate. Shift snaps to 15°. Arrastra los anillos para girar. Shift ajusta a pasos de 15°.
Track cube Cubo de rotación
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Arrastra una cara, una arista o el anillo para girar. Shift gira sobre un eje de la pantalla.
Drag the light, or its rings. Shift snaps to 15°. Arrastra la luz o sus anillos. Shift ajusta a pasos de 15°.
lighting Light Luz
Keep visible surfaces only when expanding Conservar solo superficies visibles al expandir
@@ -7730,3 +7734,4 @@ breakText Glyphs Glifos
Nest Shapes… Anidar formas…
Nest Shapes Anidar formas
Roll Rollo
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+7 -2
View File
@@ -1038,6 +1038,8 @@
Step up or down Askel ylös tai alas
Drag values or labels. Double-click a value to type. Vedä arvoja tai nimiöitä. Kirjoita arvo kaksoisnapsauttamalla.
Drag rings to rotate. Shift snaps to 15°. Kierrä vetämällä renkaita. Vaihto kohdistaa 15°:n välein.
Track cube Kiertokuutio
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Kierrä vetämällä tahkoa, särmää tai rengasta. Vaihto kiertää yhden näytön akselin ympäri.
Drag the light, or its rings. Shift snaps to 15°. Vedä valoa tai sen renkaita. Vaihto kohdistaa 15°:n välein.
lighting Light Valo
Keep visible surfaces only when expanding Säilytä laajennettaessa vain näkyvät pinnat
@@ -2070,7 +2072,10 @@ digits Malayalam Malajalam
Tabular Lining Taulukkonumerot
Tabular Oldstyle Vanhanaikaiset taulukkonumerot
Titling Alternates Otsikkovaihtoehdot
Every-line Composer Kaikkien rivien asettelu
Middle Eastern & South Asian Single-line Composer Yhden rivin asettelu (Lähi-itä ja Etelä-Aasia)
Middle Eastern & South Asian Every-line Composer Kaikkien rivien asettelu (Lähi-itä ja Etelä-Aasia)
Standard Single-line Composer Tavallinen yhden rivin asettelu
Standard Every-line Composer Tavallinen kaikkien rivien asettelu
First-line Left Indent Ensimmäisen rivin vasen sisennys
Hyphenation… Tavutus…
Words Longer Than: Sanat, jotka ovat pidempiä kuin:
@@ -2110,7 +2115,6 @@ digits Malayalam Malajalam
East Asian Composition Settings Itäaasialaisen ladonnan asetukset
Korean Composition Settings Korean ladonnan asetukset
Select a text object to edit its paragraph attributes. Valitse tekstiobjekti, jonka kappalemääritteitä haluat muokata.
Single-line Composer Yhden rivin asettelu
Toggle Line Composer Vaihda rivien asettelu
Space After Paragraph Väli kappaleen jälkeen
Space Before Paragraph Väli ennen kappaletta
@@ -7826,3 +7830,4 @@ breakText Glyphs Merkit
@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} pikseliä on liian suuri JPEG-kuvalle (enintään 65535 pikseliä sivua kohti): pienennä tarkkuutta
@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} pikseliä on liian suuri Targa-kuvalle (enintään 65535 pikseliä sivua kohti): pienennä tarkkuutta
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pikseliä on liian suuri PSD-kuvalle (enintään {MAX_SIDE} pikseliä sivua kohti): pienennä tarkkuutta
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2 and column 73.
+7 -3
View File
@@ -1072,7 +1072,10 @@ font-technology Variable Variables
Every (minutes) Toutes les (minutes)
Every option is at its default. Toutes les options ont leur valeur par défaut.
Every option matches {base}. Toutes les options correspondent à {base}.
Every-line Composer Compositeur multiligne
Middle Eastern & South Asian Single-line Composer Compositeur ligne par ligne (Moyen-Orient et Asie du Sud)
Middle Eastern & South Asian Every-line Composer Compositeur multiligne (Moyen-Orient et Asie du Sud)
Standard Single-line Composer Compositeur standard ligne par ligne
Standard Every-line Composer Compositeur standard multiligne
Exact dash lengths Longueurs de tirets exactes
Exceptions (comma separated) Exceptions (séparées par des virgules)
Exclude Exclusion
@@ -3453,7 +3456,6 @@ digits Malayalam Malayalam
Single Left Quotation Mark Guillemet simple ouvrant
Single Quotes: Guillemets simples :
Single Right Quotation Mark Guillemet simple fermant
Single-line Composer Compositeur ligne par ligne
Toggle Line Composer Basculer le compositeur de lignes
Sixth Space Espace d’un sixième
Size Taille
@@ -5545,6 +5547,8 @@ effect Soft Doux
Step up or down Augmenter ou diminuer d’un cran
Drag values or labels. Double-click a value to type. Faites glisser les valeurs ou les libellés. Double-cliquez sur une valeur pour la saisir.
Drag rings to rotate. Shift snaps to 15°. Faites glisser les anneaux pour tourner. Maj contraint par pas de 15°.
Track cube Cube de rotation
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Faites glisser une face, une arête ou l'anneau pour tourner. Maj fait tourner autour d'un axe de l'écran.
Drag the light, or its rings. Shift snaps to 15°. Faites glisser la lumière ou ses anneaux. Maj contraint par pas de 15°.
Keep visible surfaces only when expanding Conserver uniquement les surfaces visibles lors de la décomposition
Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Découpe la géométrie masquée lors de la décomposition de l’aspect. L’aperçu conserve toute la surface. Les peintures transparentes et les surfaces dépassant les limites de visibilité conservent toutes les faces.
@@ -8255,7 +8259,7 @@ breakText Glyphs Glyphes
@msg column: true floats the whole column and takes no onto, above or below column: true rend flottante toute la colonne et n’accepte ni onto, ni above, ni below
@msg command must be a shape.* command command doit être une commande shape.*
@msg commands[{i}]: missing `command` commands[{i}] : `command` manquant
@msg composer must be "singleLine" or "everyLine" composer doit valoir "singleLine" ou "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer doit être "singleLine", "everyLine", "standardSingleLine" ou "standardEveryLine"
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes les formes composées acceptent les tracés, tracés transparents, groupes, formes composées, textes, dégradés de formes et enveloppes
@msg compound {_1} must contain exactly one open path to join le tracé transparent {_1} doit contenir exactement un tracé ouvert à joindre
@msg connect end must be "start" or "end" l’extrémité de connect doit valoir "start" ou "end"
Can't render this file because it is too large.
+7 -2
View File
@@ -1067,6 +1067,8 @@
Drag art or swatches here, or use + to add the selection's colors and text styles. અહીં આર્ટ અથવા સ્વેચ ખેંચો, અથવા પસંદગીના રંગો અને ટેક્સ્ટ સ્ટાઇલ ઉમેરવા + વાપરો.
Drag onto art to apply this appearance આ દેખાવ લાગુ કરવા આર્ટ પર ખેંચો
Drag rings to rotate. Shift snaps to 15°. ફેરવવા રિંગ્સ ખેંચો. Shift 15° પર સ્નેપ કરે છે.
Track cube ફેરવવાનો ઘન
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. ફેરવવા ફલક, ધાર અથવા રિંગ ખેંચો. Shift સ્ક્રીનની એક અક્ષની આસપાસ ફેરવે છે.
Drag the art to move it on the paper કાગળ પર ખસેડવા આર્ટ ખેંચો
Drag the light, or its rings. Shift snaps to 15°. લાઇટ અથવા તેની રિંગ્સ ખેંચો. Shift 15° પર સ્નેપ કરે છે.
Drag to float as a toolbar ટૂલબાર તરીકે ફ્લોટ કરવા ખેંચો
@@ -1241,7 +1243,6 @@
Every (minutes) દર (મિનિટ)
Every option is at its default. દરેક વિકલ્પ ડિફૉલ્ટ પર છે.
Every option matches {base}. દરેક વિકલ્પ {base} સાથે મેળ ખાય છે.
Every-line Composer એવરી-લાઇન કમ્પોઝર
Exact dash lengths ચોક્કસ ડેશ લંબાઈ
Exceptions (comma separated) અપવાદો (અલ્પવિરામથી અલગ)
Exclude બાકાત રાખો
@@ -3590,7 +3591,6 @@
Single Quotes: એકલ અવતરણ ચિહ્નો:
Single Right Quotation Mark જમણું એકલ અવતરણ ચિહ્ન
Single Word Justification: એક શબ્દ જસ્ટિફિકેશન:
Single-line Composer સિંગલ-લાઇન કમ્પોઝર
Sixth Space છઠ્ઠી જગ્યા
Size કદ
Size Tile to Art ટાઇલનું કદ આર્ટ પ્રમાણે કરો
@@ -4773,3 +4773,8 @@ swatch [Registration] [રજિસ્ટ્રેશન]
Repeat Objects પુનરાવર્તિત ઑબ્જેક્ટ્સ
@msg `{path}` must be one of {_1}, not {got} `{path}` એ {_1}માંથી એક હોવું જોઈએ, {got} નહીં
Path Length પાથની લંબાઈ
Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા)
Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા)
Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર
Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine"
Can't render this file because it contains an unexpected character in line 72 and column 5.
+7 -3
View File
@@ -1508,6 +1508,8 @@ antiAlias Sharp शार्प
Drag out from a corner, or click two straight lines, then click to place. एक कोने से बाहर खींचें, या दो सीधी रेखाओं पर क्लिक करें, फिर जगह पर क्लिक करें।
Drag out from a segment, or click two points, then click to place. एक खंड से बाहर खींचें, या दो बिंदुओं पर क्लिक करें, फिर जगह पर क्लिक करें।
Drag rings to rotate. Shift snaps to 15°. घुमाने के लिए रिंग ड्रैग करें। Shift से 15° पर स्नैप होता है।
Track cube घुमाने का घन
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. घुमाने के लिए फलक, किनारा या रिंग ड्रैग करें। Shift से स्क्रीन के एक अक्ष के चारों ओर घूमता है।
Drag the art to move it on the paper इसे कागज पर स्थानांतरित करने के लिए कला को खींचें
Drag the light, or its rings. Shift snaps to 15°. लाइट या उसकी रिंग ड्रैग करें। Shift से 15° पर स्नैप होता है।
Drag to float as a toolbar एक टूलबार के रूप में तैरने के लिए खींचें
@@ -1718,7 +1720,8 @@ antiAlias Sharp शार्प
Every (minutes) हर (मिनट)
Every option is at its default. प्रत्येक ऑप्शन इसके डिफ़ॉल्ट रूप से होता है।
Every option matches {base}. प्रत्येक ऑप्शन {base} से मेल खाता है।
Every-line Composer हर लाइन संगीतकार
Middle Eastern & South Asian Every-line Composer हर लाइन संगीतकार (मध्य पूर्व और दक्षिण एशिया)
Standard Every-line Composer मानक हर लाइन संगीतकार
Exact सटीक
Exact dash lengths सटीक डैश लंबाई
Example: {name} उदाहरण: {name}
@@ -4748,7 +4751,8 @@ antiAlias Sharp शार्प
Single Quotes: एकल उद्धरण:
Single Right Quotation Mark सिंगल राइट कोटेशन मार्क
Single Word Justification: एकल शब्द जस्टिफ़िकेशन:
Single-line Composer एकल लाइन संगीतकार
Middle Eastern & South Asian Single-line Composer एकल लाइन संगीतकार (मध्य पूर्व और दक्षिण एशिया)
Standard Single-line Composer मानक एकल लाइन संगीतकार
Sixth Space छठे हिस्से जितना स्पेस
Size आकार
Size Tile to Art आकार टाइल कला के लिए
@@ -6712,7 +6716,7 @@ antiAlias Sharp शार्प
@msg command `{id}` is not available right now आदेश `{id}` अभी उपलब्ध नहीं है
@msg command must be a shape.* command command कोई shape.* कमांड होना चाहिए
@msg commands[{i}]: missing `command` आदेश [{i}]: लापता `command`
@msg composer must be "singleLine" or "everyLine" composer "singleLine" या "everyLine" होना चाहिए
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer "singleLine", "everyLine", "standardSingleLine" या "standardEveryLine" होना चाहिए
@msg compound {_1} must contain exactly one open path to join जोड़ने के लिए कंपाउंड {_1} में ठीक एक खुला पाथ होना चाहिए
@msg compound paths can only contain paths यौगिक पाथ में केवल पाथ हो सकते हैं
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes कंपाउंड शेप पाथ, कंपाउंड पाथ, समूह, कंपाउंड शेप, टाइप, ब्लेंड और एन्वेलप लेते हैं
Can't render this file because it is too large.
+7 -3
View File
@@ -1208,6 +1208,8 @@ font-technology Variable Változó
Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. Húzz ide grafikát, színeket és szövegstílusokat, hogy más dokumentumokban is használhasd őket. A könyvtárak ezen a gépen tárolódnak, fiók nem kell hozzájuk.
Drag onto art to apply this appearance Grafikára húzva alkalmazza ezt a megjelenést
Drag rings to rotate. Shift snaps to 15°. Forgatáshoz húzd a gyűrűket. Shift: illesztés 15°-onként.
Track cube Forgatókocka
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Forgatáshoz húzz egy lapot, egy élt vagy a gyűrűt. Shift: forgatás egy képernyőtengely körül.
Drag the art to move it on the paper Húzd a grafikát a papíron való áthelyezéshez
Drag the light, or its rings. Shift snaps to 15°. Húzd a fényt vagy a gyűrűit. Shift: illesztés 15°-onként.
Drag to float as a toolbar Húzd el, hogy önálló eszköztárként lebegjen
@@ -1368,7 +1370,10 @@ font-technology Variable Változó
Every (minutes) Gyakoriság (perc)
Every option is at its default. Minden beállítás az alapértéken áll.
Every option matches {base}. Minden beállítás egyezik: {base}.
Every-line Composer Többsoros tördelő
Middle Eastern & South Asian Single-line Composer Egysoros tördelő (Közel-Kelet és Dél-Ázsia)
Middle Eastern & South Asian Every-line Composer Többsoros tördelő (Közel-Kelet és Dél-Ázsia)
Standard Single-line Composer Normál egysoros tördelő
Standard Every-line Composer Normál többsoros tördelő
Exact Pontos
Exact dash lengths Pontos vonalhosszak
Exceptions (comma separated) Kivételek (vesszővel elválasztva)
@@ -4115,7 +4120,6 @@ mark-style Japanese Japán
Single Left Quotation Mark Bal oldali szimpla idézőjel
Single Quotes: Szimpla idézőjelek:
Single Right Quotation Mark Jobb oldali szimpla idézőjel
Single-line Composer Egysoros tördelő
Toggle Line Composer Sortördelő váltása
Sixth Space Hatodkvirt-szóköz
Size Méret
@@ -8265,7 +8269,7 @@ breakText Glyphs Glifák
@msg column: true floats the whole column and takes no onto, above or below column: true az egész oszlopot lebegővé teszi, és nem adható meg mellette onto, above vagy below
@msg command must be a shape.* command command: shape.* parancs kell
@msg commands[{i}]: missing `command` commands[{i}]: hiányzik: `command`
@msg composer must be "singleLine" or "everyLine" composer: "singleLine" vagy "everyLine" kell
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer értéke "singleLine", "everyLine", "standardSingleLine" vagy "standardEveryLine" lehet
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes összetett alakzatba útvonalak, összetett útvonalak, csoportok, összetett alakzatok, szöveg, összemosások és burkolók kerülhetnek
@msg compound {_1} must contain exactly one open path to join az összetett objektumnak ({_1}) pontosan egy összekapcsolható nyitott útvonalat kell tartalmaznia
@msg connect needs a path other than the one extended connect: a meghosszabbított útvonaltól különböző útvonal kell
Can't render this file because it is too large.
+7 -2
View File
@@ -976,6 +976,8 @@
Reset all Revolve settings to their defaults. Atur ulang semua pengaturan Revolusi ke defaultnya.
Drag values or labels. Double-click a value to type. Seret nilai atau label. Klik dua kali pada nilai untuk mengetik.
Drag rings to rotate. Shift snaps to 15°. Seret cincin untuk memutar. Shift mengunci ke kelipatan 15°.
Track cube Kubus putar
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Seret sisi, tepi, atau cincin untuk memutar. Shift memutar pada satu sumbu layar.
Drag the light, or its rings. Shift snaps to 15°. Seret cahaya atau cincinnya. Shift mengunci ke kelipatan 15°.
lighting Light Cahaya
Keep visible surfaces only when expanding Pertahankan hanya permukaan yang terlihat saat memperluas
@@ -1867,7 +1869,10 @@ digits Malayalam Malayalam
Tabular Lining Lining tabular
Tabular Oldstyle Oldstyle tabular
Titling Alternates Alternatif judul
Every-line Composer Komposer tiap baris
Middle Eastern & South Asian Single-line Composer Komposer satu baris (Timur Tengah dan Asia Selatan)
Middle Eastern & South Asian Every-line Composer Komposer tiap baris (Timur Tengah dan Asia Selatan)
Standard Single-line Composer Komposer standar satu baris
Standard Every-line Composer Komposer standar tiap baris
First-line Left Indent Indentasi kiri baris pertama
Hyphenation… Pemenggalan kata…
Justification… Justifikasi…
@@ -1899,7 +1904,6 @@ digits Malayalam Malayalam
East Asian Composition Settings Pengaturan komposisi Asia Timur
Korean Composition Settings Pengaturan komposisi Korea
Select a text object to edit its paragraph attributes. Pilih objek teks untuk mengedit atribut paragrafnya.
Single-line Composer Komposer satu baris
Toggle Line Composer Alihkan komposer baris
Space After Paragraph Spasi setelah paragraf
Space Before Paragraph Spasi sebelum paragraf
@@ -7008,3 +7012,4 @@ breakText Glyphs Glif
Nest Shapes… Susun Bentuk…
Nest Shapes Susun Bentuk
Roll Gulungan
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine"
Can't render this file because it contains an unexpected character in line 2471 and column 5.
+7 -3
View File
@@ -1086,7 +1086,8 @@ font-technology Variable Variabili
Every (minutes) Ogni (minuti)
Every option is at its default. Tutte le opzioni hanno il valore predefinito.
Every option matches {base}. Tutte le opzioni corrispondono a {base}.
Every-line Composer Composizione su tutte le righe
Middle Eastern & South Asian Every-line Composer Composizione su tutte le righe (Medio Oriente e Asia meridionale)
Standard Every-line Composer Composizione standard su tutte le righe
Exact dash lengths Lunghezze esatte dei trattini
Exceptions (comma separated) Eccezioni (separate da virgole)
Exclude Escludi
@@ -3506,7 +3507,8 @@ digits Malayalam Malayalam
Single Left Quotation Mark Virgoletta singola di apertura
Single Quotes: Virgolette singole:
Single Right Quotation Mark Virgoletta singola di chiusura
Single-line Composer Composizione su riga singola
Middle Eastern & South Asian Single-line Composer Composizione su riga singola (Medio Oriente e Asia meridionale)
Standard Single-line Composer Composizione standard su riga singola
Toggle Line Composer Alterna composizione delle righe
Sixth Space Spazio di un sesto
Size Dimensione
@@ -5592,6 +5594,8 @@ effect Regular Normale
Step up or down Aumenta o riduci di un passo
Drag values or labels. Double-click a value to type. Trascina i valori o le etichette. Fai doppio clic su un valore per digitarlo.
Drag rings to rotate. Shift snaps to 15°. Trascina gli anelli per ruotare. Shift usa incrementi di 15°.
Track cube Cubo di rotazione
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Trascina una faccia, uno spigolo o l'anello per ruotare. Shift ruota attorno a un asse dello schermo.
Drag the light, or its rings. Shift snaps to 15°. Trascina la luce o i suoi anelli. Shift usa incrementi di 15°.
lighting Light Luce
Keep visible surfaces only when expanding Mantieni solo le superfici visibili durante l’espansione
@@ -8125,7 +8129,7 @@ breakText Glyphs Glifi
@msg column: true floats the whole column and takes no onto, above or below column: true rende mobile l'intera colonna e non accetta onto, above o below
@msg command must be a shape.* command command deve essere un comando shape.*
@msg commands[{i}]: missing `command` commands[{i}]: `command` mancante
@msg composer must be "singleLine" or "everyLine" composer deve essere "singleLine" o "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer deve essere "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine"
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes le forme composte accettano tracciati, tracciati composti, gruppi, forme composte, testo, fusioni e involucri
@msg compound {_1} must contain exactly one open path to join il composto {_1} deve contenere esattamente un tracciato aperto da unire
@msg connect end must be "start" or "end" end di connect deve essere "start" o "end"
Can't render this file because it is too large.
+7 -3
View File
@@ -1688,7 +1688,10 @@ antiAlias Sharp シャープ
Every (minutes) 間隔 (分)
Every option is at its default. すべてのオプションが初期値です。
Every option matches {base}. すべてのオプションが {base} と同じです。
Every-line Composer すべての行を一括処理
Middle Eastern & South Asian Single-line Composer 1 行ずつ組む (中東・南アジア)
Middle Eastern & South Asian Every-line Composer すべての行を一括処理 (中東・南アジア)
Standard Single-line Composer 1 行ずつ組む (標準)
Standard Every-line Composer すべての行を一括処理 (標準)
Exact dash lengths 破線の長さを正確に保つ
Exceptions (comma separated) 例外 (カンマ区切り)
Exclusion 除外
@@ -3290,7 +3293,6 @@ mark-style Japanese 日本式
Simulate Colored Paper 色紙をシミュレート
Simulate Paper 紙色をシミュレート
Single Quotes: 一重引用符:
Single-line Composer 1 行ずつ組む
Toggle Line Composer 行の組版方式を切り替え
Size Tile to Art タイルをアートワークのサイズに合わせる
Move Tile with Art タイルをアートワークと一緒に移動
@@ -5635,6 +5637,8 @@ effect Vertical 垂直
Step up or down 1 段階ずつ増減
Drag values or labels. Double-click a value to type. 数値やラベルをドラッグして調整。数値をダブルクリックすると入力できます。
Drag rings to rotate. Shift snaps to 15°. リングをドラッグして回転。Shiftで15°刻みに調整。
Track cube 回転キューブ
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. 面、辺、またはリングをドラッグして回転。Shiftで画面の1つの軸を中心に回転。
Drag the light, or its rings. Shift snaps to 15°. ライトやリングをドラッグ。Shiftで15°刻みに調整。
lighting Light ライト
Keep visible surfaces only when expanding アピアランス分割時に見える面だけを保持
@@ -7326,7 +7330,7 @@ axis Y Axis Y 軸
@msg column: true floats the whole column and takes no onto, above or below column: true は列全体をフローティングにするため、onto、above、below は指定できません
@msg command must be a shape.* command command には shape.* コマンドを指定してください
@msg commands[{i}]: missing `command` commands[{i}]: `command` がありません
@msg composer must be "singleLine" or "everyLine" composer には "singleLine" または "everyLine" を指定してください
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer は "singleLine"、"everyLine"、"standardSingleLine"、"standardEveryLine" のいずれかにしてください
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 複合シェイプに含められるのは、パス、複合パス、グループ、複合シェイプ、文字、ブレンド、エンベロープです
@msg compound {_1} must contain exactly one open path to join 連結するには、複合パス {_1} にオープンパスがちょうど 1 つ含まれている必要があります
@msg connect end must be "start" or "end" connect の end には "start" または "end" を指定してください
Can't render this file because it is too large.
File diff suppressed because it is too large Load Diff
+7 -3
View File
@@ -1678,7 +1678,10 @@ antiAlias Sharp 날카롭게
Every (minutes) 간격 (분)
Every option is at its default. 모든 옵션이 기본값입니다.
Every option matches {base}. 모든 옵션이 {base}와(과) 같습니다.
Every-line Composer 전체 줄 컴포저
Middle Eastern & South Asian Single-line Composer 한 줄 조판 (중동·남아시아)
Middle Eastern & South Asian Every-line Composer 전체 줄 컴포저 (중동·남아시아)
Standard Single-line Composer 표준 한 줄 조판
Standard Every-line Composer 표준 전체 줄 컴포저
Exact dash lengths 정확한 대시 길이
Exceptions (comma separated) 예외 (쉼표로 구분)
Exclusion 제외
@@ -3279,7 +3282,6 @@ mark-style Japanese 일본식
Simulate Colored Paper 색 용지 시뮬레이션
Simulate Paper 용지 시뮬레이션
Single Quotes: 작은따옴표:
Single-line Composer 한 줄 조판
Toggle Line Composer 줄 조판 방식 전환
Size Tile to Art 타일을 아트웍 크기에 맞춤
Move Tile with Art 아트웍과 함께 타일 이동
@@ -5556,6 +5558,8 @@ effect Vertical 세로
Step up or down 한 단계 올리기 또는 내리기
Drag values or labels. Double-click a value to type. 값이나 레이블을 드래그하세요. 값을 더블클릭하면 입력할 수 있습니다.
Drag rings to rotate. Shift snaps to 15°. 링을 드래그해 회전하세요. Shift를 누르면 15°씩 스냅됩니다.
Track cube 회전 큐브
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. 면, 모서리 또는 링을 드래그해 회전하세요. Shift를 누르면 화면의 한 축을 중심으로 회전합니다.
Drag the light, or its rings. Shift snaps to 15°. 조명이나 링을 드래그하세요. Shift를 누르면 15°씩 스냅됩니다.
lighting Light 광원
Keep visible surfaces only when expanding 확장 시 보이는 표면만 유지
@@ -7990,7 +7994,7 @@ breakText Glyphs 글리프
@msg column: true floats the whole column and takes no onto, above or below column: true는 열 전체를 띄우며 onto, above, below와 함께 쓸 수 없습니다
@msg command must be a shape.* command command는 shape.* 명령이어야 합니다
@msg commands[{i}]: missing `command` commands[{i}]: `command`가 없습니다
@msg composer must be "singleLine" or "everyLine" composer는 "singleLine" 또는 "everyLine"이어야 합니다
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer는 "singleLine", "everyLine", "standardSingleLine" 또는 "standardEveryLine"이어야 합니다
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 컴파운드 모양에는 패스, 컴파운드 패스, 그룹, 컴파운드 모양, 문자, 블렌드, 엔벨로프를 넣을 수 있습니다
@msg compound {_1} must contain exactly one open path to join 컴파운드 {_1}에는 연결할 열린 패스가 정확히 하나 있어야 합니다
@msg connect needs a path other than the one extended connect에는 연장한 패스가 아닌 다른 패스가 필요합니다
Can't render this file because it is too large.
+7 -3
View File
@@ -1496,6 +1496,8 @@
Reset all Revolve settings to their defaults. Stelt alle draai-instellingen opnieuw in op de standaardwaarden.
Drag values or labels. Double-click a value to type. Sleep waarden of labels. Dubbelklik op een waarde om te typen.
Drag rings to rotate. Shift snaps to 15°. Sleep de ringen om te roteren. Shift lijnt uit op 15°.
Track cube Rotatiekubus
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Sleep een vlak, een rand of de ring om te roteren. Shift roteert om één schermas.
Drag the light, or its rings. Shift snaps to 15°. Sleep het licht of de ringen ervan. Shift lijnt uit op 15°.
lighting Light Licht
Keep visible surfaces only when expanding Alleen zichtbare oppervlakken behouden bij het uitbreiden
@@ -2429,7 +2431,10 @@ digits Malayalam Malayalam
Tabular Lining Tabulaire lining
Tabular Oldstyle Tabulaire oldstyle
Titling Alternates Titelalternatieven
Every-line Composer Compositie per alinea
Middle Eastern & South Asian Single-line Composer Compositie per regel (Midden-Oosten en Zuid-Azië)
Middle Eastern & South Asian Every-line Composer Compositie per alinea (Midden-Oosten en Zuid-Azië)
Standard Single-line Composer Standaardcompositie per regel
Standard Every-line Composer Standaardcompositie per alinea
First-line Left Indent Eerste regel links inspringen
Hyphenation… Afbreken…
Justification… Uitvullen…
@@ -2461,7 +2466,6 @@ digits Malayalam Malayalam
East Asian Composition Settings Instellingen voor Oost-Aziatische zetting
Korean Composition Settings Instellingen voor Koreaanse zetting
Select a text object to edit its paragraph attributes. Selecteer een tekstobject om de alineakenmerken ervan te bewerken.
Single-line Composer Compositie per regel
Toggle Line Composer Compositiemethode wisselen
Space After Paragraph Ruimte na alinea
Space Before Paragraph Ruimte voor alinea
@@ -6312,7 +6316,7 @@ imageTrace Outline Contour
@msg column: true floats the whole column and takes no onto, above or below column: true laat de hele kolom zweven en accepteert geen onto, above of below
@msg command must be a shape.* command command moet een shape.*-opdracht zijn
@msg commands[{i}]: missing `command` commands[{i}]: `command` ontbreekt
@msg composer must be "singleLine" or "everyLine" composer moet "singleLine" of "everyLine" zijn
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer moet "singleLine", "everyLine", "standardSingleLine" of "standardEveryLine" zijn
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes samengestelde vormen accepteren paden, samengestelde paden, groepen, samengestelde vormen, tekst, mengsels en omvormingen
@msg compound {_1} must contain exactly one open path to join samengesteld object {_1} moet precies één open pad bevatten om te verbinden
@msg connect needs a path other than the one extended connect heeft een ander pad nodig dan het pad dat wordt verlengd
Can't render this file because it is too large.
+7 -3
View File
@@ -995,6 +995,8 @@
Step up or down Zwiększ lub zmniejsz o krok
Drag values or labels. Double-click a value to type. Przeciągaj wartości lub etykiety. Kliknij dwukrotnie wartość, aby ją wpisać.
Drag rings to rotate. Shift snaps to 15°. Przeciągaj pierścienie, aby obracać. Shift przyciąga co 15°.
Track cube Kostka obrotu
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Przeciągnij ścianę, krawędź lub pierścień, aby obracać. Shift obraca wokół jednej osi ekranu.
Drag the light, or its rings. Shift snaps to 15°. Przeciągaj światło lub jego pierścienie. Shift przyciąga co 15°.
lighting Light Światło
Keep visible surfaces only when expanding Przy rozszerzaniu zachowaj tylko widoczne powierzchnie
@@ -2027,7 +2029,8 @@ digits Malayalam Malajalam
Tabular Lining Tabelaryczne nowoczesne
Tabular Oldstyle Tabelaryczne nautyczne
Titling Alternates Alternatywy tytułowe
Every-line Composer Kompozytor wielowierszowy
Middle Eastern & South Asian Every-line Composer Kompozytor wielowierszowy (Bliski Wschód i Azja Południowa)
Standard Every-line Composer Standardowy kompozytor wielowierszowy
First-line Left Indent Wcięcie pierwszego wiersza
Hyphenation… Dzielenie wyrazów…
Words Longer Than: Wyrazy dłuższe niż:
@@ -2067,7 +2070,8 @@ digits Malayalam Malajalam
East Asian Composition Settings Ustawienia składu wschodnioazjatyckiego
Korean Composition Settings Ustawienia składu koreańskiego
Select a text object to edit its paragraph attributes. Zaznacz obiekt tekstowy, aby edytować atrybuty akapitu.
Single-line Composer Kompozytor jednowierszowy
Middle Eastern & South Asian Single-line Composer Kompozytor jednowierszowy (Bliski Wschód i Azja Południowa)
Standard Single-line Composer Standardowy kompozytor jednowierszowy
Toggle Line Composer Przełącz kompozytor wierszy
Space After Paragraph Odstęp po akapicie
Space Before Paragraph Odstęp przed akapitem
@@ -8366,7 +8370,7 @@ breakText Glyphs Glify
@msg column: true floats the whole column and takes no onto, above or below column: true odłącza całą kolumnę i nie przyjmuje onto, above ani below
@msg command must be a shape.* command command musi być poleceniem shape.*
@msg commands[{i}]: missing `command` commands[{i}]: brak `command`
@msg composer must be "singleLine" or "everyLine" composer musi mieć wartość "singleLine" lub "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer musi mieć wartość "singleLine", "everyLine", "standardSingleLine" lub "standardEveryLine"
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes kształty złożone przyjmują ścieżki, ścieżki złożone, grupy, kształty złożone, tekst, przejścia i koperty
@msg compound {_1} must contain exactly one open path to join obiekt złożony {_1} musi zawierać dokładnie jedną otwartą ścieżkę do połączenia
@msg connect needs a path other than the one extended connect wymaga ścieżki innej niż przedłużana
Can't render this file because it is too large.
+7 -3
View File
@@ -966,7 +966,8 @@ antiAlias Sharp Nítido
Every (minutes) A cada (minutos)
Every option is at its default. Todas as opções estão no padrão.
Every option matches {base}. Todas as opções correspondem a {base}.
Every-line Composer Compositor de Todas as Linhas
Middle Eastern & South Asian Every-line Composer Compositor de Todas as Linhas (Oriente Médio e Sul da Ásia)
Standard Every-line Composer Compositor Padrão de Todas as Linhas
Exact dash lengths Comprimentos de tracejado exatos
Exceptions (comma separated) Exceções (separadas por vírgula)
Exclude Excluir
@@ -2898,7 +2899,8 @@ digits Malayalam Malaiala
Single Left Quotation Mark Aspa Esquerda Única
Single Quotes: Aspas Simples:
Single Right Quotation Mark Aspa Direita Única
Single-line Composer Compositor de Linha Única
Middle Eastern & South Asian Single-line Composer Compositor de Linha Única (Oriente Médio e Sul da Ásia)
Standard Single-line Composer Compositor Padrão de Linha Única
Toggle Line Composer Alternar Compositor de Linhas
Sixth Space Espaço de Sexto
Size Tamanho
@@ -3562,6 +3564,8 @@ imageTrace Outline Contorno
Step up or down Aumentar ou diminuir um passo
Drag values or labels. Double-click a value to type. Arraste os valores ou rótulos. Clique duas vezes em um valor para digitá-lo.
Drag rings to rotate. Shift snaps to 15°. Arraste os anéis para girar. Shift ajusta em incrementos de 15°.
Track cube Cubo de rotação
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Arraste uma face, uma aresta ou o anel para girar. Shift gira em torno de um eixo da tela.
Drag the light, or its rings. Shift snaps to 15°. Arraste a luz ou seus anéis. Shift ajusta em incrementos de 15°.
lighting Light Luz
Keep visible surfaces only when expanding Manter apenas as superfícies visíveis ao expandir
@@ -8456,7 +8460,7 @@ swatch Yellow Green Verde-amarelado
@msg column: true floats the whole column and takes no onto, above or below column: true torna flutuante a coluna inteira e não aceita onto, above nem below
@msg command must be a shape.* command command deve ser um comando shape.*
@msg commands[{i}]: missing `command` commands[{i}]: falta `command`
@msg composer must be "singleLine" or "everyLine" composer deve ser "singleLine" ou "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer deve ser "singleLine", "everyLine", "standardSingleLine" ou "standardEveryLine"
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes formas compostas aceitam caminhos, caminhos compostos, grupos, formas compostas, texto, mesclagens e envelopes
@msg compound {_1} must contain exactly one open path to join o composto {_1} deve conter exatamente um caminho aberto para unir
@msg connect needs a path other than the one extended connect precisa de um caminho diferente do que foi estendido
Can't render this file because it is too large.
+7 -2
View File
@@ -1075,7 +1075,10 @@ font-technology Variable Вариативные
Every (minutes) Каждые (минут)
Every option is at its default. Все параметры имеют значения по умолчанию.
Every option matches {base}. Все параметры совпадают с {base}.
Every-line Composer Компоновщик всех строк
Middle Eastern & South Asian Single-line Composer Однострочный компоновщик (Ближний Восток и Южная Азия)
Middle Eastern & South Asian Every-line Composer Компоновщик всех строк (Ближний Восток и Южная Азия)
Standard Single-line Composer Стандартный однострочный компоновщик
Standard Every-line Composer Стандартный компоновщик всех строк
Exact dash lengths Точная длина штрихов
Exceptions (comma separated) Исключения (через запятую)
Exclude Исключить
@@ -3493,7 +3496,6 @@ digits Malayalam Малаялам
Single Left Quotation Mark Одинарная открывающая кавычка
Single Quotes: Одинарные кавычки:
Single Right Quotation Mark Одинарная закрывающая кавычка
Single-line Composer Однострочный компоновщик
Toggle Line Composer Переключить компоновщик строк
Sixth Space Шестая шпация
Size Размер
@@ -5590,6 +5592,8 @@ axis Both Оба
Step up or down Шаг вверх или вниз
Drag values or labels. Double-click a value to type. Перетаскивайте значения или подписи. Для ввода дважды щёлкните значение.
Drag rings to rotate. Shift snaps to 15°. Перетаскивайте кольца для вращения. Shift задаёт шаг 15°.
Track cube Куб вращения
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Перетащите грань, ребро или кольцо для вращения. Shift вращает вокруг одной оси экрана.
Drag the light, or its rings. Shift snaps to 15°. Перетаскивайте источник света или кольца. Shift задаёт шаг 15°.
lighting Light Свет
Keep visible surfaces only when expanding При разборе сохранять только видимые поверхности
@@ -9685,3 +9689,4 @@ shape Open Открытый
@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} пикселей — слишком большой размер для JPEG (не более 65535 пикселей по стороне): уменьшите разрешение
@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} пикселей — слишком большой размер для Targa (не более 65535 пикселей по стороне): уменьшите разрешение
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine"
Can't render this file because it is too large.
+7 -3
View File
@@ -1056,7 +1056,8 @@ font-technology Variable Variabla
Every (minutes) Intervall (minuter)
Every option is at its default. Alla alternativ har standardvärden.
Every option matches {base}. Alla alternativ matchar {base}.
Every-line Composer Flerradssättning
Middle Eastern & South Asian Every-line Composer Flerradssättning (Mellanöstern och Sydasien)
Standard Every-line Composer Standard-flerradssättning
Exact dash lengths Exakta strecklängder
Exceptions (comma separated) Undantag (kommaavgränsade)
Exclude Uteslut
@@ -3383,7 +3384,8 @@ digits Malayalam Malayalam
Single Left Quotation Mark Enkelt vänster citattecken
Single Quotes: Enkla citattecken:
Single Right Quotation Mark Enkelt höger citattecken
Single-line Composer Enradssättare
Middle Eastern & South Asian Single-line Composer Enradssättare (Mellanöstern och Sydasien)
Standard Single-line Composer Standard-enradssättare
Toggle Line Composer Växla radsättare
Sixth Space Sjättedelsblanksteg
Size Storlek
@@ -5455,6 +5457,8 @@ effect Soft Mjuk
Step up or down Ett steg upp eller ned
Drag values or labels. Double-click a value to type. Dra i värden eller etiketter. Dubbelklicka på ett värde för att skriva.
Drag rings to rotate. Shift snaps to 15°. Dra i ringarna för att rotera. Shift fäster i steg om 15°.
Track cube Rotationskub
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Dra i en sida, en kant eller ringen för att rotera. Shift roterar runt en skärmaxel.
Drag the light, or its rings. Shift snaps to 15°. Dra i ljuset eller dess ringar. Shift fäster i steg om 15°.
Keep visible surfaces only when expanding Behåll endast synliga ytor vid expandering
Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Trimma dold geometri vid Expandera utseende. Live-förhandsgranskningen behåller hela ytan. Transparenta färger och ytor som överskrider synlighetsgränserna behåller alla sidoytor.
@@ -8033,7 +8037,7 @@ digits Hindi Hindi
@msg column: true floats the whole column and takes no onto, above or below column: true gör hela kolumnen flytande och tar inte onto, above eller below
@msg command must be a shape.* command command måste vara ett shape.*-kommando
@msg commands[{i}]: missing `command` commands[{i}]: `command` saknas
@msg composer must be "singleLine" or "everyLine" composer måste vara "singleLine" eller "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer måste vara "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine"
@msg compound {_1} must contain exactly one open path to join sammansatt {_1} måste innehålla exakt en öppen bana att foga samman
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammansatta former tar banor, sammansatta banor, grupper, sammansatta former, text, övergångar och kuvert
@msg connect end must be "start" or "end" connect end måste vara "start" eller "end"
Can't render this file because it is too large.
+38 -1
View File
@@ -4089,7 +4089,8 @@ fn bracketed_message_parts_translate_only_as_exact_messages() {
let point = message(lang, "[x, y] (two numbers)");
assert_ne!(point, "[x, y] (two numbers)", "{code}");
assert!(point.contains("[x, y]"), "{code}: {point}");
for got in ["[1]", "[1, 2, 3]", r#"{"objects": [1]}"#, r#"[{"a": 1}, "b: c", …"#] {
// ``["] `x`: b"]`` fits the text of the effect refusal ``[{j}] `{_1}`: {why}`` but not its index.
for got in ["[1]", "[1, 2, 3]", r#"{"objects": [1]}"#, r#"[{"a": 1}, "b: c", …"#, r#"["] `x`: b"]"#] {
let shown = message(lang, &format!("`center` must be [x, y] (two numbers), not {got}"));
assert!(shown.contains(&point) && shown.contains(got), "{code}: {shown}");
let shown = message(lang, &format!("`p` must be an object, not {got}"));
@@ -4098,6 +4099,42 @@ fn bracketed_message_parts_translate_only_as_exact_messages() {
}
}
/// An effect refusal inside another message (`plug-in output: …`, and an importer's `can't open …`)
/// is translated through its template with its reason, keeping the index and the effect id.
#[test]
fn nested_effect_refusals_translate_with_their_reason() {
for code in COMPLETE_MESSAGES {
let lang = Lang::from_code(code).expect("registered");
let refusal = "[0] `fx`: nothing selected";
let output = format!("plug-in output: objects[0].effects: {refusal}");
for shown in [message(lang, refusal), message(lang, &output), message(lang, &format!("can't open `a.svg`: {output}"))] {
assert!(!shown.contains("nothing selected") && shown.contains("[0] `fx`"), "{code}: {shown}");
}
}
let de = de();
let refusal = "[0] `fx`: `radius` must be a number";
assert_eq!(message(de, refusal), "[0] `fx`: `radius` muss eine Zahl sein");
let output = format!("plug-in output: objects[0].effects: {refusal}");
assert_eq!(message(de, &output), "Plug-in-Ausgabe: objects[0].effects: [0] `fx`: `radius` muss eine Zahl sein");
assert_eq!(
message(de, &format!("can't open `a.svg`: {output}")),
"`a.svg` kann nicht geöffnet werden: Plug-in-Ausgabe: objects[0].effects: [0] `fx`: `radius` muss eine Zahl sein"
);
assert_eq!(
message(de, "plug-in output: objects[12].effects: [3] `fx`: no row for this reason"),
"Plug-in-Ausgabe: objects[12].effects: [3] `fx`: no row for this reason"
);
let selected = "[1] `fx`: nothing selected";
assert_eq!(
message(de, &format!("plug-in output: objects[0].effects: {selected}")),
"Plug-in-Ausgabe: objects[0].effects: [1] `fx`: nichts ausgewählt"
);
// Past the depth limit the refusal stays as it is.
let deep = format!("plug-in output: plug-in output: plug-in output: plug-in output: objects[0].effects: {selected}");
let shown = message(de, &deep);
assert!(shown.ends_with(selected), "{shown}");
}
/// The warning for a PDF/X file that leaves out the document's bleed is translated in every catalog,
/// alone and in the status bar's note.
#[test]
+7 -3
View File
@@ -1048,7 +1048,10 @@ font-technology Variable Değişken
Every (minutes) Her (dakika)
Every option is at its default. Her seçenek varsayılan değerdedir.
Every option matches {base}. Her seçenek {base} ile eşleşir.
Every-line Composer Her Satır Bestecisi
Middle Eastern & South Asian Single-line Composer Tek Satır Oluşturucu (Orta Doğu ve Güney Asya)
Middle Eastern & South Asian Every-line Composer Her Satır Bestecisi (Orta Doğu ve Güney Asya)
Standard Single-line Composer Standart Tek Satır Oluşturucu
Standard Every-line Composer Standart Her Satır Bestecisi
Exact dash lengths Tam çizgi uzunlukları
Exceptions (comma separated) İstisnalar (virgülle ayrılmış)
Exclude Hariç tut
@@ -3251,7 +3254,6 @@ digits Malayalam Malayalam
Single Left Quotation Mark Tek Sol Tırnak İşareti
Single Quotes: Tek Alıntılar:
Single Right Quotation Mark Tek Sağ Tırnak İşareti
Single-line Composer Tek Satır Oluşturucu
Toggle Line Composer Satır Oluşturucuyu Değiştir
Sixth Space Altıncı Uzay
Size Boyut
@@ -5327,6 +5329,8 @@ effect Soft Yumuşak
Reset all Revolve settings to their defaults. Tüm Revolve ayarlarını varsayılan değerlerine sıfırlayın.
Drag values or labels. Double-click a value to type. Değerleri veya etiketleri sürükleyin. Yazmak için bir değeri çift tıklayın.
Drag rings to rotate. Shift snaps to 15°. Döndürmek için halkaları sürükleyin. Kaydırma 15°'ye sabitlenir.
Track cube Döndürme küpü
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Döndürmek için bir yüzü, kenarı veya halkayı sürükleyin. Shift tek bir ekran ekseni etrafında döndürür.
Drag the light, or its rings. Shift snaps to 15°. Işığı veya halkalarını sürükleyin. Kaydırma 15°'ye sabitlenir.
Keep visible surfaces only when expanding Görünür yüzeyleri yalnızca genişletirken koruyun
Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Görünümü Genişlet'te kapsanan geometriyi kırpın. Canlı önizleme tüm yüzeyi korur. Şeffaf boyalar ve görünürlük sınırlarını aşan yüzeyler tüm yüzleri korur.
@@ -7709,7 +7713,7 @@ axis Y Axis Y ekseni
@msg column: true floats the whole column and takes no onto, above or below column: true tüm sütunu yüzdürür ve onto, above veya below almaz
@msg command must be a shape.* command command bir shape.* komutu olmalıdır
@msg commands[{i}]: missing `command` commands[{i}]: `command` eksik
@msg composer must be "singleLine" or "everyLine" composer "singleLine" veya "everyLine" olmalıdır
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer "singleLine", "everyLine", "standardSingleLine" veya "standardEveryLine" olmalıdır
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes bileşik şekiller yolları, bileşik yolları, grupları, bileşik şekilleri, metni, karışımları ve zarfları alır
@msg compound {_1} must contain exactly one open path to join bileşik {_1}, birleştirilecek tam olarak bir açık yol içermelidir
@msg connect needs a path other than the one extended connect için uzatılan yoldan başka bir yol gerekir
Can't render this file because it is too large.
+7 -3
View File
@@ -1080,7 +1080,8 @@ font-technology Variable Варіативні
Every (minutes) Кожен (хвилин)
Every option is at its default. Усі параметри мають значення за промовчанням.
Every option matches {base}. Усі параметри збігаються з {base}.
Every-line Composer Компонувальник всіх рядків
Middle Eastern & South Asian Every-line Composer Компонувальник всіх рядків (Близький Схід і Південна Азія)
Standard Every-line Composer Стандартний компонувальник всіх рядків
Exact dash lengths Точна довжина штрихів
Exceptions (comma separated) Винятки (через кому)
Exclude Виключити
@@ -3498,7 +3499,8 @@ digits Malayalam Малаялам
Single Left Quotation Mark Одинарна лапка, що відкриває
Single Quotes: Одинарні лапки:
Single Right Quotation Mark Одинарна лапка, що закриває
Single-line Composer Однорядковий компонувальник
Middle Eastern & South Asian Single-line Composer Однорядковий компонувальник (Близький Схід і Південна Азія)
Standard Single-line Composer Стандартний однорядковий компонувальник
Toggle Line Composer Переключити компонувальник рядків
Sixth Space Шоста шпація
Size Розмір
@@ -5572,6 +5574,8 @@ axis Both Обидві
Step up or down Крок угору або вниз
Drag values or labels. Double-click a value to type. Перетягуйте значення або підписи. Двічі клацніть значення, щоб увести його.
Drag rings to rotate. Shift snaps to 15°. Перетягуйте кільця для обертання. Shift задає крок 15°.
Track cube Куб обертання
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Перетягніть грань, ребро або кільце для обертання. Shift обертає навколо однієї осі екрана.
Drag the light, or its rings. Shift snaps to 15°. Перетягуйте джерело світла або його кільця. Shift задає крок 15°.
Keep visible surfaces only when expanding Під час розгортання зберігати лише видимі поверхні
Trim covered geometry on Expand Appearance. Live preview keeps the full surface. Transparent paints and surfaces exceeding visibility limits retain all faces. Обрізає приховану геометрію під час розгортання оформлення. Попередній перегляд зберігає всю поверхню. Прозорі заливки та поверхні, що перевищують обмеження видимості, зберігають усі грані.
@@ -7992,7 +7996,7 @@ breakText Glyphs Гліфи
@msg column: true floats the whole column and takes no onto, above or below column: true робить плаваючим увесь стовпець і не приймає onto, above або below
@msg command must be a shape.* command command має бути командою shape.*
@msg commands[{i}]: missing `command` commands[{i}]: відсутній `command`
@msg composer must be "singleLine" or "everyLine" composer має бути "singleLine" або "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer має бути "singleLine", "everyLine", "standardSingleLine" або "standardEveryLine"
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes складені фігури приймають контури, складені контури, групи, складені фігури, текст, переходи й оболонки
@msg compound {_1} must contain exactly one open path to join складений об’єкт {_1} має містити рівно один відкритий контур для з’єднання
@msg connect needs a path other than the one extended для connect потрібен контур, відмінний від того, що продовжується
Can't render this file because it is too large.
+7 -2
View File
@@ -1100,6 +1100,8 @@ font-technology Variable Biến thiên
Drag art, colors and text styles here to reuse them across documents. Libraries are stored on this machine — no account required. Kéo tác phẩm, màu và kiểu chữ vào đây để tái sử dụng trong các tài liệu. Thư viện được lưu trên máy này — không cần tài khoản.
Drag onto art to apply this appearance Kéo lên tác phẩm để áp dụng diện mạo này
Drag rings to rotate. Shift snaps to 15°. Kéo vòng để xoay. Shift khớp ở 15°.
Track cube Khối xoay
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. Kéo một mặt, một cạnh hoặc vòng để xoay. Shift xoay quanh một trục màn hình.
Drag the art to move it on the paper Kéo tác phẩm để di chuyển trên trang
Drag the light, or its rings. Shift snaps to 15°. Kéo đèn hoặc vòng của nó. Shift khớp ở 15°.
Drag to float as a toolbar Kéo để thả nổi thanh công cụ
@@ -1257,7 +1259,10 @@ font-technology Variable Biến thiên
Every (minutes) Mỗi (phút)
Every option is at its default. Mọi tùy chọn đang ở mặc định.
Every option matches {base}. Mọi tùy chọn khớp với {base}.
Every-line Composer Soạn theo từng dòng
Middle Eastern & South Asian Single-line Composer Soạn thảo một dòng (Trung Đông và Nam Á)
Middle Eastern & South Asian Every-line Composer Soạn theo từng dòng (Trung Đông và Nam Á)
Standard Single-line Composer Soạn thảo một dòng tiêu chuẩn
Standard Every-line Composer Soạn theo từng dòng tiêu chuẩn
Exact dash lengths Độ dài nét đứt chính xác
Exceptions (comma separated) Ngoại lệ (phân cách bằng dấu phẩy)
Exclude Loại trừ
@@ -3858,7 +3863,6 @@ mark-style Japanese Kiểu Nhật
Single Left Quotation Mark Dấu nháy đơn mở
Single Quotes: Dấu nháy đơn:
Single Right Quotation Mark Dấu nháy đơn đóng
Single-line Composer Soạn thảo một dòng
Toggle Line Composer Chuyển đổi cách soạn dòng
Sixth Space Dấu cách 1/6
Size Kích thước
@@ -7400,3 +7404,4 @@ breakText Glyphs Glyph
@msg {width} × {height} pixels is too large for JPEG (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho JPEG (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải
@msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải
@msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine"
Can't render this file because it contains an unexpected character in line 205 and column 5.
+7 -3
View File
@@ -1019,7 +1019,8 @@ antiAlias Sharp 锐利
Every (minutes) 每隔 (分钟)
Every option is at its default. 所有选项皆为默认值。
Every option matches {base}. 所有选项皆与{base}相同。
Every-line Composer 逐行排版器
Middle Eastern & South Asian Every-line Composer 逐行排版器(中东和南亚)
Standard Every-line Composer 标准逐行排版器
Exact dash lengths 精确虚线长度
Exceptions (comma separated) 例外词 (逗号分隔)
Exclude 差集
@@ -3320,7 +3321,8 @@ digits Malayalam 马拉雅拉姆数字
Single Left Quotation Mark 左单引号
Single Quotes: 单引号:
Single Right Quotation Mark 右单引号
Single-line Composer 单行排版器
Middle Eastern & South Asian Single-line Composer 单行排版器(中东和南亚)
Standard Single-line Composer 标准单行排版器
Toggle Line Composer 切换行排版器
Sixth Space 六分之一空格
Size 大小
@@ -5852,6 +5854,8 @@ effect Vertical 垂直
Step up or down 逐级增减
Drag values or labels. Double-click a value to type. 拖动数值或标签。双击数值即可输入。
Drag rings to rotate. Shift snaps to 15°. 拖动圆环旋转。按住 Shift 以 15° 为步长调整。
Track cube 旋转立方体
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. 拖动面、边或圆环进行旋转。按住 Shift 绕一个屏幕轴旋转。
Drag the light, or its rings. Shift snaps to 15°. 拖动光源或圆环。按住 Shift 以 15° 为步长调整。
lighting Light 光源
Keep visible surfaces only when expanding 扩展时仅保留可见表面
@@ -8352,7 +8356,7 @@ breakText Glyphs 字形
@msg column: true floats the whole column and takes no onto, above or below column: true 会使整列浮动,不能再给出 onto、above 或 below
@msg command must be a shape.* command command 必须是 shape.* 命令
@msg commands[{i}]: missing `command` commands[{i}]:缺少 `command`
@msg composer must be "singleLine" or "everyLine" composer 必须是 "singleLine" 或 "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer 必须是 "singleLine"、"everyLine"、"standardSingleLine" 或 "standardEveryLine"
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 复合形状接受路径、复合路径、编组、复合形状、文字、混合和封套
@msg compound {_1} must contain exactly one open path to join 复合对象 {_1} 必须恰好包含一条要连接的开放路径
@msg connect needs a path other than the one extended connect 需要一条不同于被延伸路径的路径
Can't render this file because it is too large.
+7 -3
View File
@@ -1050,7 +1050,8 @@ font-technology Variable 可變
Every (minutes) 每隔 (分鐘)
Every option is at its default. 所有選項皆為預設值。
Every option matches {base}. 所有選項皆與{base}相同。
Every-line Composer 逐行排版程式
Middle Eastern & South Asian Every-line Composer 逐行排版程式(中東與南亞)
Standard Every-line Composer 標準逐行排版程式
Exact dash lengths 精確虛線長度
Exceptions (comma separated) 例外 (以逗號分隔)
Exclude 差集
@@ -4583,7 +4584,8 @@ digits Malayalam 馬來亞拉姆數字
Single Left Quotation Mark 左單引號
Single Quotes: 單引號:
Single Right Quotation Mark 右單引號
Single-line Composer 單行排版程式
Middle Eastern & South Asian Single-line Composer 單行排版程式(中東與南亞)
Standard Single-line Composer 標準單行排版程式
Toggle Line Composer 切換行排版程式
Sixth Space 六分之一空格
Size 大小
@@ -5688,6 +5690,8 @@ effect Soft 柔和
Step up or down 逐級增減
Drag values or labels. Double-click a value to type. 拖曳數值或標籤。按兩下數值即可輸入。
Drag rings to rotate. Shift snaps to 15°. 拖曳圓環旋轉。按住 Shift 以 15° 為間距調整。
Track cube 旋轉立方體
Drag a face, an edge or the ring to rotate. Shift turns about one screen axis. 拖曳面、邊或圓環進行旋轉。按住 Shift 繞一個螢幕軸旋轉。
Drag the light, or its rings. Shift snaps to 15°. 拖曳光源或圓環。按住 Shift 以 15° 為間距調整。
lighting Light 光源
Keep visible surfaces only when expanding 展開時僅保留可見表面
@@ -8280,7 +8284,7 @@ breakText Glyphs 字符
@msg column: true floats the whole column and takes no onto, above or below column: true 會讓整欄浮動,不接受 onto、above 或 below
@msg command must be a shape.* command command 必須是 shape.* 指令
@msg commands[{i}]: missing `command` commands[{i}]:未提供 `command`
@msg composer must be "singleLine" or "everyLine" composer 必須是 "singleLine" 或 "everyLine"
@msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer 必須是 "singleLine"、"everyLine"、"standardSingleLine" 或 "standardEveryLine"
@msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 複合形狀接受路徑、複合路徑、群組、複合形狀、文字、漸變物件和封套
@msg compound {_1} must contain exactly one open path to join 複合路徑 {_1} 必須剛好包含一條可連接的開放路徑
@msg connect needs a path other than the one extended connect 需要延伸路徑以外的另一條路徑
Can't render this file because it is too large.
+7 -3
View File
@@ -52,10 +52,12 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt
let load = if swatches { crate::panels::swatches::load_library } else { crate::panels::graphic_styles::load_library };
return load(app, p).map(|_| Value::Null);
}
// A PDF with several pages or a password asks first (the Import PDF dialog), and so does a
// DXF drawing (DXF Import Options).
// A PDF with several pages or a password asks first (the Import PDF dialog), and so do a DXF
// drawing (DXF Import Options) and a PSD file with several layers or with slices (PSD Import
// Options), unless `p` says how its layers come in.
if crate::dialogs::import_pdf::offer(app, name, bytes, path.clone(), None)
|| crate::dialogs::dxf_import::offer(app, name, bytes, path.clone(), None)
|| (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, name, bytes, path.clone(), None))
{
return Ok(Value::Null);
}
@@ -552,9 +554,11 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va
check_import_size(path, false)?;
let mut bytes = read(app, path)?;
if background && opens_as(path).is_none() {
// A PDF with several pages or a password, or a DXF drawing, asks first, as at once.
// A PDF with several pages or a password, a DXF drawing, or a PSD file with several layers
// or with slices asks first, as at once.
if crate::dialogs::import_pdf::offer(app, path, &bytes, Some(path.to_string()), None)
|| crate::dialogs::dxf_import::offer(app, path, &bytes, Some(path.to_string()), None)
|| (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, path, &bytes, Some(path.to_string()), None))
{
note_recent(app, path);
return Ok(Value::Null);
+1 -1
View File
@@ -393,7 +393,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"type.lineComposer",
"Toggle Line Composer",
"Cmd+Alt+Shift+C",
"{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer (text.setFormat {composer}) → \"singleLine\" | \"everyLine\"",
"{} the selected type's paragraphs (or those the Type tool's selection touches) use the Single-line Composer when they all use the Every-line Composer, else the Every-line Composer; paragraphs that all use a Standard composer keep it, any other mix takes the Middle Eastern & South Asian one (text.setFormat {composer}) → \"singleLine\" | \"everyLine\" | \"standardSingleLine\" | \"standardEveryLine\"",
),
(
"type.hyphenate",
+24 -7
View File
@@ -54,15 +54,29 @@ pub(crate) fn align(app: &mut VectorcraftApp, justify: &str) -> Result<Value, St
}
/// `type.lineComposer` (Cmd+Alt+Shift+C): the Single-line Composer for the paragraphs the panel
/// acts on when they all use the Every-line Composer, else the Every-line Composer. Returns the
/// composer set.
/// acts on when they all break their lines every-line (either shaping), else the Every-line
/// Composer. Paragraphs that all use a Standard composer keep it; any other mix takes the Middle
/// Eastern & South Asian one. Returns the composer set.
pub(crate) fn toggle_composer(app: &mut VectorcraftApp) -> Result<Value, String> {
text_style(app).ok_or("select some type first")?;
let id = if shared_composer(app) == Some(Composer::EveryLine) { "singleLine" } else { "everyLine" };
let to_single = shared_para(app, |p| p.composer.is_single_line()) == Some(false);
let standard = shared_para(app, |p| p.composer.shapes_complex_scripts()) == Some(false);
let base = if standard { Composer::StandardEveryLine } else { Composer::EveryLine };
let id = composer_id(base.with_breaking(to_single));
format(app, json!({ "composer": id }));
Ok(json!(id))
}
/// The `text.setFormat` value of `composer`.
fn composer_id(composer: Composer) -> &'static str {
match composer {
Composer::SingleLine => "singleLine",
Composer::EveryLine => "everyLine",
Composer::StandardSingleLine => "standardSingleLine",
Composer::StandardEveryLine => "standardEveryLine",
}
}
/// `type.hyphenate` (Cmd+Alt+Shift+H): what the Hyphenate checkbox does, on the paragraphs the
/// panel acts on. Returns whether they now hyphenate.
pub(crate) fn toggle_hyphenate(app: &mut VectorcraftApp) -> Result<Value, String> {
@@ -874,11 +888,14 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
ui.separator();
let composer = shared_composer(app);
for (c, label, id) in
[(Composer::SingleLine, tl!("Single-line Composer"), "singleLine"), (Composer::EveryLine, tl!("Every-line Composer"), "everyLine")]
{
for (c, label) in [
(Composer::SingleLine, tl!("Middle Eastern & South Asian Single-line Composer")),
(Composer::EveryLine, tl!("Middle Eastern & South Asian Every-line Composer")),
(Composer::StandardSingleLine, tl!("Standard Single-line Composer")),
(Composer::StandardEveryLine, tl!("Standard Every-line Composer")),
] {
if menu_item(ui, label, has, composer == Some(c)) {
format(app, json!({ "composer": id }));
format(app, json!({ "composer": composer_id(c) }));
}
}
ui.separator();
@@ -82,6 +82,83 @@ fn paragraph_mixed_composer_checks_neither_menu_item() {
assert_eq!(shared_composer(&app), Some(Composer::EveryLine));
}
/// Cmd+Alt+Shift+C switches between Single-line and Every-line and keeps what each paragraph's
/// composer does with complex scripts: a Standard composer toggles to the other Standard one.
#[test]
fn toggling_the_line_composer_keeps_the_shaping() {
let (mut app, id) = editing_text("A\nB\n");
for (from, first, second) in [
("standardEveryLine", "standardSingleLine", "standardEveryLine"),
("everyLine", "singleLine", "everyLine"),
("standardSingleLine", "standardEveryLine", "standardSingleLine"),
] {
app.run("text.setFormat", json!({"id": id, "composer": from})).unwrap();
app.session.set_tool_option("selectAll", &json!(true));
assert_eq!(toggle_composer(&mut app).unwrap(), json!(first), "{from}");
assert_eq!(toggle_composer(&mut app).unwrap(), json!(second), "{from} again");
}
// Paragraphs that break differently take Every-line, as before the Standard composers existed.
app.run("text.setFormat", json!({"id": id, "composer": "standardSingleLine"})).unwrap();
app.run("text.setFormat", json!({"id": id, "start": 2, "end": 3, "composer": "singleLine"})).unwrap();
app.session.set_tool_option("selectAll", &json!(true));
assert_eq!(toggle_composer(&mut app).unwrap(), json!("everyLine"));
// Paragraphs that both break every-line but differ in shaping: Single-line, Middle Eastern & South Asian.
app.run("text.setFormat", json!({"id": id, "composer": "everyLine"})).unwrap();
app.run("text.setFormat", json!({"id": id, "start": 2, "end": 3, "composer": "standardEveryLine"})).unwrap();
app.session.set_tool_option("selectAll", &json!(true));
assert_eq!(toggle_composer(&mut app).unwrap(), json!("singleLine"));
}
/// The Paragraph panel menu lists the four composers, and ticks the one every selected paragraph has.
#[test]
fn the_paragraph_menu_sets_each_of_the_four_composers() {
let (mut app, id) = editing_text("A\nB\n");
app.session.set_tool_option("selectAll", &json!(true));
let ctx = egui::Context::default();
let items = |app: &mut VectorcraftApp| {
let mut seen = vec![];
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| menu(app, ui));
out.textures_delta.clear();
for shape in out.shapes {
collect_texts(&shape.shape, &mut seen);
}
seen
};
fn collect_texts(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Vec(v) => v.iter().for_each(|s| collect_texts(s, out)),
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
_ => {}
}
}
let labels = [
("singleLine", "Middle Eastern & South Asian Single-line Composer"),
("everyLine", "Middle Eastern & South Asian Every-line Composer"),
("standardSingleLine", "Standard Single-line Composer"),
("standardEveryLine", "Standard Every-line Composer"),
];
// The menu lists all four, each row ticked (and only that one) when every selected paragraph has it.
for (value, _) in labels {
app.run("text.setFormat", json!({"id": id, "composer": value})).unwrap();
app.session.set_tool_option("selectAll", &json!(true));
let texts = items(&mut app);
for (v, label) in labels {
let row = if v == value { format!("✓ {label}") } else { format!(" {label}") };
assert!(texts.contains(&row), "{value}: {row:?} in {texts:?}");
}
}
// Choosing a row sets its composer: the row is a `text.setFormat {composer}` with the row's id.
for (value, want) in [
("standardEveryLine", Composer::StandardEveryLine),
("singleLine", Composer::SingleLine),
("standardSingleLine", Composer::StandardSingleLine),
] {
app.run("text.setFormat", json!({"id": id, "composer": value})).unwrap();
assert_eq!(shared_composer(&app), Some(want), "{value}");
assert_eq!(composer_id(want), value);
}
}
#[test]
fn paragraph_mixed_hyphenate_checks_off() {
let (mut app, id) = editing_text("A\nB\n");
+20 -6
View File
@@ -61,7 +61,7 @@ pub fn is_document(name: &str) -> bool {
#[derive(Default)]
pub struct PlaceState {
/// Web: the bytes of the files picked for the Place dialog, by name.
picked: Vec<(String, Vec<u8>)>,
pub(crate) picked: Vec<(String, Vec<u8>)>,
/// The loaded cursor's thumbnails by file name.
thumbs: Vec<(String, Thumb)>,
/// The Control bar's `image.info`, for (document uid, revision, image id).
@@ -125,10 +125,11 @@ fn engine(app: &mut VectorcraftApp, id: &str, p: &Value) -> Result<Value, String
/// File → Place… (`file.place`): with a file (`path` or `name` + `dataBase64`), place it, centred
/// in the view unless `at`, `rect` or `replace` say otherwise (a text file without `text` options,
/// a DXF drawing without `dxf` options and a PDF with several pages or a password and no `page`
/// ask for them first, unless `showImportOptions: false` places them with the options confirmed
/// last); with `paths`, the Place dialog for them; with neither, pick the files first. The file is
/// read and placed at once (MCP, scripts).
/// a DXF drawing without `dxf` options, a PSD file embedded without `layers` (when the user places
/// it) and a PDF with several pages or a password and no `page` ask for them first, unless
/// `showImportOptions: false` places them with the options confirmed last); with `paths`, the
/// Place dialog for them; with neither, pick the files first. The file is read and placed at once
/// (MCP, scripts).
pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
place_file(app, p, Read::AtOnce)
}
@@ -181,6 +182,7 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
if let Some(dxf) = crate::dialogs::dxf_import::last_options(app, &p) {
p["dxf"] = dxf;
}
crate::dialogs::psd_import::last_options(app, &mut p);
}
if p.get("text").is_none() && crate::dialogs::text_import::is_text(&p) {
return Ok(crate::dialogs::text_import::open(app, &p));
@@ -209,6 +211,12 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result<Valu
if ask && crate::dialogs::dxf_import::offer_place(app, &p) {
return Ok(json!({ "dialog": crate::dialogs::dxf_import::KIND }));
}
// A PSD file with several layers or with slices that the user embeds asks for its import
// options. A place run as a command (MCP, scripts) places at once and takes `layers` and
// `importSlices` itself.
if ask && matches!(read, Read::ForUser { .. }) && crate::dialogs::psd_import::offer_place(app, &p) {
return Ok(json!({ "dialog": crate::dialogs::psd_import::KIND }));
}
if ["at", "rect", "replace"].iter().all(|k| p.get(k).is_none())
&& let Some(v) = app.view()
{
@@ -409,9 +417,15 @@ pub fn confirm(app: &mut VectorcraftApp, d: &crate::state::Dialog) -> Result<Val
let files: Vec<&Value> = many.iter().filter(|s| s.get("path").is_none()).collect();
let mut q = json!({ "paths": paths, "files": files, "link": link, "template": template });
if !ask {
// Each text file and DXF drawing in the cursor takes the options confirmed last.
// Each text file, DXF drawing and embedded PSD file in the cursor takes the options
// confirmed last.
q["text"] = crate::dialogs::text_import::last_options(app);
q["dxf"] = crate::dialogs::dxf_import::remembered(app);
if !link || paths.is_empty() {
// Files from bytes have no file to link to; they may carry the dialog's Link.
q["link"] = json!(false);
crate::dialogs::psd_import::queue_options(app, &mut q);
}
}
queue_files(app, &q, Read::ForUser { dropped: false }, ask)
}
+4
View File
@@ -831,6 +831,9 @@ pub struct UiState {
/// never used).
#[serde(default)]
pub dxf_import: Value,
/// The PSD Import Options chosen last (layers, hiddenLayers, importSlices; null: never used).
#[serde(default)]
pub psd_import: Value,
/// The Home screen is shown over the open documents (`app.home`): the active document's uid
/// and the document count when it opened. Choosing a tab, or a document opening, closing or
/// becoming active, leaves it.
@@ -1260,6 +1263,7 @@ impl Default for UiState {
transform_each: Value::Null,
rearrange_artboards_spacing: Value::Null,
dxf_import: Value::Null,
psd_import: Value::Null,
home: None,
trace_hold_source: None,
layers_panel: Default::default(),

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