mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 16:07:33 +00:00
Merge main into fix/read-roots-document-replies
This commit is contained in:
@@ -3,7 +3,7 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, Node};
|
||||
use vectorcraft_doc::{AppearanceItem, FillLayer, LineJoin, Node};
|
||||
|
||||
use crate::*;
|
||||
|
||||
@@ -185,6 +185,48 @@ fn group_rows_are_the_groups_own_stack() {
|
||||
assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00");
|
||||
}
|
||||
|
||||
/// #6739: `stroke.set` without an item on a group with a stroke row of its own edits that row;
|
||||
/// its members, which have no stroke (as paths a PDF import brings in), are left alone instead of
|
||||
/// each getting a black 1 pt stroke. Options alone never make a stroke visible: a row created for
|
||||
/// a join has no paint, while a weight still gives the usual black stroke.
|
||||
#[test]
|
||||
fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() {
|
||||
let mut s = session();
|
||||
let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0));
|
||||
for id in [a, b] {
|
||||
run(&mut s, "appearance.removeItem", json!({"ids": [id.0], "index": 1}));
|
||||
assert!(node(&s, id).appearance.stroke().is_none(), "the member has no stroke row");
|
||||
}
|
||||
let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "appearance.addStroke", json!({"ids": [g.0]}));
|
||||
run(&mut s, "appearance.setItem", json!({"ids": [g.0], "index": 0, "color": "#ffffff", "weight": 2}));
|
||||
let r = run(&mut s, "stroke.set", json!({"ids": [g.0], "join": "round"}));
|
||||
assert_eq!(r["objects"], 1, "{r}");
|
||||
let gs = node(&s, g).appearance.stroke().unwrap().clone();
|
||||
assert_eq!((gs.join, gs.width, gs.paint.color().map(|c| c.to_hex())), (LineJoin::Round, 2.0, Some("#ffffff".to_string())));
|
||||
for id in [a, b] {
|
||||
assert!(node(&s, id).appearance.stroke().is_none(), "a member keeps no stroke");
|
||||
}
|
||||
// A group without a stroke of its own still reaches its members; for a join alone the row
|
||||
// made on each has no paint, so nothing becomes visible.
|
||||
let (c, d) = (rect(&mut s, 400.0), rect(&mut s, 550.0));
|
||||
for id in [c, d] {
|
||||
run(&mut s, "appearance.removeItem", json!({"ids": [id.0], "index": 1}));
|
||||
}
|
||||
let h = NodeId(run(&mut s, "object.group", json!({"ids": [c.0, d.0]}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "stroke.set", json!({"ids": [h.0], "join": "bevel"}));
|
||||
for id in [c, d] {
|
||||
let st = node(&s, id).appearance.stroke().cloned().expect("a stroke row for the join");
|
||||
assert_eq!((st.paint, st.join), (Paint::None, LineJoin::Bevel), "no paint for a join alone");
|
||||
}
|
||||
// A weight is a visible stroke: an object without one gets the black stroke, as before.
|
||||
let e = rect(&mut s, 700.0);
|
||||
run(&mut s, "appearance.removeItem", json!({"ids": [e.0], "index": 1}));
|
||||
run(&mut s, "stroke.set", json!({"ids": [e.0], "weight": 3}));
|
||||
let st = node(&s, e).appearance.stroke().cloned().unwrap();
|
||||
assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_items_take_item_paint() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -253,6 +253,367 @@ fn selection_art_is_the_art_new_brush_takes() {
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only brush.new is an undo step");
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn selected(s: &Session) -> Vec<NodeId> {
|
||||
s.doc().unwrap().selection.objects.clone()
|
||||
}
|
||||
|
||||
/// The JSON of object `id`, as `brush.options` params take art.
|
||||
fn art_json(s: &mut Session, id: NodeId) -> Value {
|
||||
s.execute("brush.selectionArt", &json!({"ids": [id.0]})).unwrap()["art"].clone()
|
||||
}
|
||||
|
||||
/// `brush.placeArt` places a copy of an art or scatter brush's art centered where it is dropped
|
||||
/// (by default on the first artboard's center), selected, in one undo step; brushes without art,
|
||||
/// unknown brushes and a position that is not a number are refused.
|
||||
#[test]
|
||||
fn place_art_puts_a_copy_of_the_brush_art_where_it_is_dropped() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0);
|
||||
s.execute("brush.new", &json!({"type": "art", "name": "Bar", "ids": [r.0]})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Bar", "x": 100, "y": 80})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert_eq!(selected(&s), vec![id]);
|
||||
assert_ne!(id, r, "a copy, not the art the brush was made from");
|
||||
assert!(close(bounds(&s, id), Rect::new(80.0, 76.0, 120.0, 84.0), 1e-6), "{:?}", bounds(&s, id));
|
||||
// Without a position: the first artboard's center (the document is 400 × 300).
|
||||
let scatter = NodeId(s.execute("brush.placeArt", &json!({"name": "Dots"})).unwrap()["id"].as_u64().unwrap());
|
||||
let c = bounds(&s, scatter).center();
|
||||
assert!((c.x - 200.0).abs() < 1e-6 && (c.y - 150.0).abs() < 1e-6, "{c:?}");
|
||||
let steps = undo_steps(&s);
|
||||
for (p, msg) in [
|
||||
(json!({"name": "3 pt. Round"}), "`3 pt. Round` has no art (only scatter, art and pattern brushes do)"),
|
||||
(json!({"name": "Bristle Round"}), "`Bristle Round` has no art (only scatter, art and pattern brushes do)"),
|
||||
(json!({"name": "Nope"}), "no brush named `Nope`"),
|
||||
] {
|
||||
let e = s.execute("brush.placeArt", &p).unwrap_err();
|
||||
assert!(e.to_string().contains(msg), "{p}: {e}");
|
||||
}
|
||||
assert!(s.execute("brush.placeArt", &json!({"name": "Bar", "x": "100"})).is_err());
|
||||
assert_eq!(undo_steps(&s), steps, "a refused call adds no undo step");
|
||||
}
|
||||
|
||||
/// Brush art holding an instance of a symbol whose art lies away from the symbol's origin (as
|
||||
/// imported symbols can) is centered by that art, not by the box an instance has without its
|
||||
/// document.
|
||||
#[test]
|
||||
fn placed_art_with_a_symbol_instance_is_centered_by_the_symbols_art() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 300.0, 10.0, 100.0, 40.0);
|
||||
let art = node(&s, r);
|
||||
s.execute("edit.clear", &json!({"ids": [r.0]})).unwrap();
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Off".into(), art: std::sync::Arc::new(art) });
|
||||
let layer = d.layers[0].id;
|
||||
let inst = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::translate((50.0, 50.0));
|
||||
d.insert(Some(layer), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Off".into(), xf })).unwrap();
|
||||
let inst = inst.0;
|
||||
s.execute("brush.new", &json!({"type": "art", "name": "Stamp", "ids": [inst]})).unwrap();
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": "Stamp", "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap());
|
||||
let st = s.doc().unwrap();
|
||||
let b = st.doc.bounds_of(&[id], false).unwrap();
|
||||
assert!((b.center().x - 200.0).abs() < 1e-6 && (b.center().y - 150.0).abs() < 1e-6, "{b:?}");
|
||||
assert!((b.width() - 100.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// A pattern brush with side, outer corner and start tiles, the side tile with a repeat frame
|
||||
/// wider than its art: → its name.
|
||||
fn framed_pattern_brush(s: &mut Session) -> String {
|
||||
let side = rect(s, 0.0, 0.0, 20.0, 10.0);
|
||||
let corner = rect(s, 0.0, 40.0, 10.0, 10.0);
|
||||
let start = rect(s, 0.0, 80.0, 6.0, 10.0);
|
||||
let name = s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "ids": [side.0]})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
let params = json!({
|
||||
"side": art_json(s, side),
|
||||
"side_frame": Rect::new(-2.0, 0.0, 22.0, 10.0),
|
||||
"outer_corner": art_json(s, corner),
|
||||
"start": art_json(s, start),
|
||||
});
|
||||
s.execute("brush.options", &json!({"name": name, "params": params})).unwrap();
|
||||
name
|
||||
}
|
||||
|
||||
/// `brush.placeArt` lays a pattern brush's tiles out left to right, each in a group named for its
|
||||
/// tile, with an unpainted rectangle at the back of a tile with a repeat frame marking that frame.
|
||||
#[test]
|
||||
fn pattern_brushes_place_their_tiles_in_a_row() {
|
||||
let mut s = session();
|
||||
let name = framed_pattern_brush(&mut s);
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": name, "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap());
|
||||
let placed = node(&s, id);
|
||||
let tiles: Vec<Node> = placed.children().unwrap().iter().map(|c| (**c).clone()).collect();
|
||||
let names: Vec<&str> = tiles.iter().map(|t| t.name.as_deref().unwrap_or("")).collect();
|
||||
assert_eq!(names, ["Side Tile", "Outer Corner Tile", "Start Tile"]);
|
||||
let boxes: Vec<Rect> = tiles.iter().map(|t| t.geometric_bounds().unwrap()).collect();
|
||||
assert!(boxes.windows(2).all(|w| (w[1].x0 - w[0].x1 - 10.0).abs() < 1e-6), "10 pt apart, left to right: {boxes:?}");
|
||||
// The side tile: the frame's rectangle, unpainted, behind the art.
|
||||
let side = tiles[0].children().unwrap();
|
||||
assert_eq!(side.len(), 2);
|
||||
let marker = &side[0];
|
||||
assert!(marker.appearance.items.iter().all(|i| match i {
|
||||
vectorcraft_doc::AppearanceItem::Fill(f) => f.paint.is_none(),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(st) => st.paint.is_none(),
|
||||
}));
|
||||
let frame = marker.geometric_bounds().unwrap();
|
||||
assert!((frame.width() - 24.0).abs() < 1e-6 && (frame.height() - 10.0).abs() < 1e-6, "{frame:?}");
|
||||
assert_eq!(tiles[1].children().unwrap().len(), 1, "no frame, no rectangle");
|
||||
}
|
||||
|
||||
/// `brush.replaceArt` reads the tiles `brush.placeArt` places back tile by tile, frames included:
|
||||
/// every tile and the frame keep their sizes, and the frame keeps its place around the art.
|
||||
#[test]
|
||||
fn placed_pattern_tiles_go_back_into_the_brush_tile_by_tile() {
|
||||
let mut s = session();
|
||||
let name = framed_pattern_brush(&mut s);
|
||||
let before = s.execute("brush.get", &json!({"name": name})).unwrap();
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": name, "x": 200, "y": 150})).unwrap()["id"].as_u64().unwrap());
|
||||
let steps = undo_steps(&s);
|
||||
s.execute("brush.replaceArt", &json!({"name": name, "ids": [id.0]})).unwrap();
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
let after = s.execute("brush.get", &json!({"name": name})).unwrap();
|
||||
let size = |v: &Value| {
|
||||
let n: Node = serde_json::from_value(v.clone()).unwrap();
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
(b.width(), b.height())
|
||||
};
|
||||
for key in ["side", "outer_corner", "start"] {
|
||||
let (a, b) = (size(&before[key]), size(&after[key]));
|
||||
assert!((a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6, "{key}: {a:?} → {b:?}");
|
||||
}
|
||||
assert!(after.get("end").is_none_or(Value::is_null) && after.get("inner_corner").is_none_or(Value::is_null));
|
||||
let frame: Rect = serde_json::from_value(after["side_frame"].clone()).unwrap();
|
||||
let art: Node = serde_json::from_value(after["side"].clone()).unwrap();
|
||||
let art = art.geometric_bounds().unwrap();
|
||||
assert!((frame.width() - 24.0).abs() < 1e-6 && (art.x0 - frame.x0 - 2.0).abs() < 1e-6, "{frame:?} around {art:?}");
|
||||
assert!(after["outer_corner_frame"].is_null() || after.get("outer_corner_frame").is_none());
|
||||
}
|
||||
|
||||
/// Art that is not the tiles `brush.placeArt` places becomes a pattern brush's side tile, and the
|
||||
/// other tiles stay; one tile group alone replaces only that tile.
|
||||
#[test]
|
||||
fn other_art_replaces_the_side_tile_of_a_pattern_brush() {
|
||||
let mut s = session();
|
||||
let name = framed_pattern_brush(&mut s);
|
||||
let before = s.execute("brush.get", &json!({"name": name})).unwrap();
|
||||
let r = rect(&mut s, 100.0, 100.0, 30.0, 12.0);
|
||||
s.execute("brush.replaceArt", &json!({"name": name, "ids": [r.0]})).unwrap();
|
||||
let after = s.execute("brush.get", &json!({"name": name})).unwrap();
|
||||
let side: Node = serde_json::from_value(after["side"].clone()).unwrap();
|
||||
assert!(close(side.geometric_bounds().unwrap(), Rect::new(100.0, 100.0, 130.0, 112.0), 1e-6));
|
||||
assert!(after.get("side_frame").is_none_or(Value::is_null), "the old frame goes with the old art");
|
||||
assert_eq!((&after["outer_corner"], &after["start"]), (&before["outer_corner"], &before["start"]));
|
||||
// One placed tile, its group dragged back alone: only the start tile changes.
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap());
|
||||
let start = node(&s, id).children().unwrap()[2].clone();
|
||||
assert_eq!(start.name.as_deref(), Some("Start Tile"));
|
||||
s.execute("brush.replaceArt", &json!({"name": name, "ids": [start.id.0]})).unwrap();
|
||||
let last = s.execute("brush.get", &json!({"name": name})).unwrap();
|
||||
assert_eq!((&last["side"], &last["outer_corner"]), (&after["side"], &after["outer_corner"]));
|
||||
let art: Node = serde_json::from_value(last["start"].clone()).unwrap();
|
||||
assert!(close(art.geometric_bounds().unwrap(), start.geometric_bounds().unwrap(), 1e-6), "the start tile is the placed one");
|
||||
assert!(art.name.is_none(), "the tile's name stays on the canvas");
|
||||
}
|
||||
|
||||
/// `brush.replaceArt` gives a brush new art in one undo step: strokes that use it redraw with it,
|
||||
/// or with `applyToStrokes: false` keep the brush as it was while a copy with the new art becomes
|
||||
/// the current brush. A brush no stroke uses changes in place either way.
|
||||
#[test]
|
||||
fn replace_art_applies_to_strokes_or_leaves_them_on_the_old_brush() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0, 200.0, 40.0, 8.0);
|
||||
s.execute("brush.new", &json!({"type": "art", "name": "Bar", "ids": [r.0]})).unwrap();
|
||||
let path = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Bar", "ids": [path.0]})).unwrap();
|
||||
let thin = brushed_bounds(&s, path).height();
|
||||
// A path painted with a brush made from the taller art: what the stroke should draw.
|
||||
let tall = rect(&mut s, 10.0, 220.0, 40.0, 20.0);
|
||||
s.execute("brush.new", &json!({"type": "art", "name": "Tall", "ids": [tall.0]})).unwrap();
|
||||
let reference = line(&mut s);
|
||||
s.execute("brush.apply", &json!({"name": "Tall", "ids": [reference.0]})).unwrap();
|
||||
let want = brushed_bounds(&s, reference).height();
|
||||
assert!(want > thin * 2.0, "{want} against {thin}");
|
||||
// Apply to Strokes: the stroke redraws with the taller art.
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("brush.replaceArt", &json!({"name": "Bar", "ids": [tall.0]})).unwrap();
|
||||
assert_eq!(r["name"], "Bar");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
assert!((brushed_bounds(&s, path).height() - want).abs() < 1e-6);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!((brushed_bounds(&s, path).height() - thin).abs() < 1e-9, "undo puts the old art back");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
// Leave Strokes: the stroke keeps Bar as it was; Bar copy has the new art, after Bar, current.
|
||||
let short = rect(&mut s, 10.0, 260.0, 40.0, 4.0);
|
||||
let bar = s.execute("brush.get", &json!({"name": "Bar"})).unwrap();
|
||||
let r = s.execute("brush.replaceArt", &json!({"name": "Bar", "ids": [short.0], "applyToStrokes": false})).unwrap();
|
||||
assert_eq!(r["name"], "Bar copy");
|
||||
assert_eq!(brush_of(&s, path).as_deref(), Some("Bar"));
|
||||
assert_eq!(s.execute("brush.get", &json!({"name": "Bar"})).unwrap(), bar);
|
||||
assert!((brushed_bounds(&s, path).height() - want).abs() < 1e-6);
|
||||
let copy: Node = serde_json::from_value(s.execute("brush.get", &json!({"name": "Bar copy"})).unwrap()["art"].clone()).unwrap();
|
||||
assert!((copy.geometric_bounds().unwrap().height() - 4.0).abs() < 1e-6);
|
||||
let list = s.execute("brush.list", &json!({})).unwrap();
|
||||
assert_eq!(list["current"], "Bar copy");
|
||||
let names: Vec<&str> = list["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect();
|
||||
let at = names.iter().position(|n| *n == "Bar").unwrap();
|
||||
assert_eq!(names.get(at + 1), Some(&"Bar copy"));
|
||||
// No stroke uses Bar copy: its art changes in place, with or without applying.
|
||||
s.execute("brush.replaceArt", &json!({"name": "Bar copy", "ids": [tall.0], "applyToStrokes": false})).unwrap();
|
||||
assert!(s.execute("brush.get", &json!({"name": "Bar copy 2"})).is_err());
|
||||
}
|
||||
|
||||
/// `brush.replaceArt` refuses a brush without art, an unknown brush, an empty selection, art with no
|
||||
/// width and an `applyToStrokes` that is not a boolean, and changes nothing then.
|
||||
#[test]
|
||||
fn replace_art_refuses_what_it_cannot_take() {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0);
|
||||
let flat = s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap();
|
||||
let lib = s.execute("brush.list", &json!({})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
for (p, msg) in [
|
||||
(json!({"name": "3 pt. Round", "ids": [r.0]}), "`3 pt. Round` has no art (only scatter, art and pattern brushes do)"),
|
||||
(json!({"name": "Bristle Round", "ids": [r.0]}), "`Bristle Round` has no art (only scatter, art and pattern brushes do)"),
|
||||
(json!({"name": "Nope", "ids": [r.0]}), "no brush named `Nope`"),
|
||||
(json!({"name": "Arrow", "ids": [flat]}), "the selected art has no width"),
|
||||
(json!({"name": "Chain", "ids": [flat]}), "the selected art has no width"),
|
||||
(json!({"name": "Arrow", "ids": [r.0], "applyToStrokes": "no"}), "`applyToStrokes` must be true or false"),
|
||||
] {
|
||||
let e = s.execute("brush.replaceArt", &p).unwrap_err();
|
||||
assert!(e.to_string().contains(msg), "{p}: {e}");
|
||||
}
|
||||
s.select(|_, sel| sel.clear()).unwrap();
|
||||
let e = s.execute("brush.replaceArt", &json!({"name": "Arrow"})).unwrap_err();
|
||||
assert!(e.to_string().contains("nothing selected"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(s.execute("brush.list", &json!({})).unwrap(), lib);
|
||||
}
|
||||
|
||||
/// An instance of a symbol whose art has no width is art with no width for `brush.new` and
|
||||
/// `brush.replaceArt`, although an instance's box without its document has width.
|
||||
#[test]
|
||||
fn a_symbol_whose_art_has_no_width_makes_no_brush_art() {
|
||||
let mut s = session();
|
||||
let flat = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap());
|
||||
let art = node(&s, flat);
|
||||
s.execute("edit.clear", &json!({"ids": [flat.0]})).unwrap();
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Flat".into(), art: std::sync::Arc::new(art) });
|
||||
let layer = d.layers[0].id;
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::new(inst, NodeKind::SymbolInstance { symbol: "Flat".into(), xf: vectorcraft_geom::Affine::IDENTITY }))
|
||||
.unwrap();
|
||||
assert!(node(&s, inst).geometric_bounds().is_some_and(|b| b.width() > 1.0), "the box an instance has without its document");
|
||||
for (cmd, p) in [("brush.new", json!({"type": "art", "ids": [inst.0]})), ("brush.replaceArt", json!({"name": "Arrow", "ids": [inst.0]}))] {
|
||||
let e = s.execute(cmd, &p).unwrap_err();
|
||||
assert!(e.to_string().contains("the selected art has no width"), "{cmd}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `brush.replaceArt` checks only the art it is given: a tile the pattern brush already has that
|
||||
/// has no width does not stop another tile from being replaced.
|
||||
#[test]
|
||||
fn replace_art_checks_only_the_tiles_it_is_given() {
|
||||
let mut s = session();
|
||||
let flat = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 100, "x2": 50, "y2": 160})).unwrap()["id"].as_u64().unwrap());
|
||||
let end = art_json(&mut s, flat);
|
||||
s.execute("brush.options", &json!({"name": "Chain", "params": {"end": end}})).unwrap();
|
||||
let r = rect(&mut s, 10.0, 20.0, 40.0, 8.0);
|
||||
s.execute("brush.replaceArt", &json!({"name": "Chain", "ids": [r.0]})).unwrap();
|
||||
let side: Node = serde_json::from_value(s.execute("brush.get", &json!({"name": "Chain"})).unwrap()["side"].clone()).unwrap();
|
||||
assert!(close(side.geometric_bounds().unwrap(), bounds(&s, r), 1e-6));
|
||||
}
|
||||
|
||||
/// Tile `key` (`side`, `start`…) of pattern brush `name`.
|
||||
fn tile_art(s: &mut Session, name: &str, key: &str) -> Node {
|
||||
serde_json::from_value(s.execute("brush.get", &json!({"name": name})).unwrap()[key].clone()).unwrap()
|
||||
}
|
||||
|
||||
/// A pattern brush tile placed with `brush.placeArt` and given back with `brush.replaceArt` is the
|
||||
/// art it was, not that art inside the tile's group, however many times it goes out and back.
|
||||
#[test]
|
||||
fn pattern_tiles_go_out_and_back_without_gaining_a_group() {
|
||||
let mut s = session();
|
||||
let name = framed_pattern_brush(&mut s);
|
||||
let size = |n: &Node| {
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
(b.width(), b.height())
|
||||
};
|
||||
let first = tile_art(&mut s, &name, "side");
|
||||
assert!(matches!(first.kind, NodeKind::Path { .. }), "{:?}", first.kind);
|
||||
for round in 1..=2 {
|
||||
let id = s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("brush.replaceArt", &json!({"name": name, "ids": [id]})).unwrap();
|
||||
let side = tile_art(&mut s, &name, "side");
|
||||
assert!(matches!(side.kind, NodeKind::Path { .. }), "round {round}: {:?}", side.kind);
|
||||
let (a, b) = (size(&first), size(&side));
|
||||
assert!((a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6, "round {round}: {a:?} → {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A tile group whose art was deleted, leaving only the rectangle that marks its frame, is art with
|
||||
/// no width: the brush keeps its tile.
|
||||
#[test]
|
||||
fn a_tile_group_holding_only_its_frame_is_refused() {
|
||||
let mut s = session();
|
||||
let name = framed_pattern_brush(&mut s);
|
||||
let before = s.execute("brush.get", &json!({"name": name})).unwrap();
|
||||
let id = NodeId(s.execute("brush.placeArt", &json!({"name": name})).unwrap()["id"].as_u64().unwrap());
|
||||
let side = node(&s, id).children().unwrap()[0].clone();
|
||||
assert_eq!(side.name.as_deref(), Some("Side Tile"));
|
||||
let art = side.children().unwrap()[1].id;
|
||||
s.execute("edit.clear", &json!({"ids": [art.0]})).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = s.execute("brush.replaceArt", &json!({"name": name, "ids": [side.id.0]})).unwrap_err();
|
||||
assert!(e.to_string().contains("the selected art has no width"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(s.execute("brush.get", &json!({"name": name})).unwrap(), before);
|
||||
}
|
||||
|
||||
/// Two groups named for the same tile: the frontmost one is the tile's art.
|
||||
#[test]
|
||||
fn the_frontmost_group_named_for_a_tile_is_that_tile() {
|
||||
let mut s = session();
|
||||
let name = framed_pattern_brush(&mut s);
|
||||
let back = rect(&mut s, 10.0, 10.0, 20.0, 10.0);
|
||||
let front = rect(&mut s, 10.0, 40.0, 30.0, 10.0);
|
||||
let (back, front) = (node(&s, back), node(&s, front));
|
||||
s.execute("edit.clear", &json!({"ids": [back.id.0, front.id.0]})).unwrap();
|
||||
let st = s.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
let tile = |d: &mut Document, n: Node| {
|
||||
let mut g = Node::group(d.alloc_id(), vec![std::sync::Arc::new(n)]);
|
||||
g.name = Some("Start Tile".into());
|
||||
std::sync::Arc::new(g)
|
||||
};
|
||||
let tiles = vec![tile(d, back), tile(d, front)];
|
||||
let both = Node::group(d.alloc_id(), tiles);
|
||||
let both_id = both.id;
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), usize::MAX, both).unwrap();
|
||||
s.execute("brush.replaceArt", &json!({"name": name, "ids": [both_id.0]})).unwrap();
|
||||
let start = tile_art(&mut s, &name, "start");
|
||||
assert!((start.geometric_bounds().unwrap().width() - 30.0).abs() < 1e-6, "{:?}", start.geometric_bounds());
|
||||
}
|
||||
|
||||
/// Type is art for `brush.replaceArt` as it is for `brush.new`: taken as it is.
|
||||
#[test]
|
||||
fn replace_art_takes_type_as_brush_new_does() {
|
||||
let mut s = session();
|
||||
let t = s.execute("text.create", &json!({"x": 20, "y": 60, "text": "Hi", "size": 24})).unwrap()["id"].as_u64().unwrap();
|
||||
let want = art_json(&mut s, NodeId(t));
|
||||
s.execute("brush.replaceArt", &json!({"name": "Arrow", "ids": [t]})).unwrap();
|
||||
assert_eq!(s.execute("brush.get", &json!({"name": "Arrow"})).unwrap()["art"], want);
|
||||
let made = s.execute("brush.new", &json!({"type": "art", "ids": [t]})).unwrap()["name"].as_str().unwrap().to_string();
|
||||
assert_eq!(s.execute("brush.get", &json!({"name": made})).unwrap()["art"], want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_options_rename_duplicate_and_delete_update_strokes() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -234,6 +234,26 @@ fn svg_export_writes_the_drawn_size() {
|
||||
assert!(!sizes.iter().any(|v| (v - 12.0).abs() < 1e-3), "the stored size is not written: {sizes:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_type_on_a_path_keeps_the_drawn_size() {
|
||||
let mut s = session();
|
||||
let id = on_line(&mut s, "Release");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let size = 12.0 * fit(&s, id);
|
||||
assert!(size > 24.0, "the text grows on the long line: {size}");
|
||||
let r = s.execute("addon.type.releasePath", &json!({"ids": [id.0], "mode": "text"})).unwrap();
|
||||
let released = NodeId(r["texts"][0].as_u64().unwrap());
|
||||
let t = text(&s, released);
|
||||
assert!(!t.dynamic_text, "point type does not keep Dynamic Text");
|
||||
assert!((t.runs[0].style.size - size).abs() < 1e-9, "{} vs the drawn {size}", t.runs[0].style.size);
|
||||
assert_eq!(fit(&s, released), 1.0);
|
||||
// Type on a path without Dynamic Text keeps its stored size.
|
||||
let plain = on_line(&mut s, "Plain");
|
||||
let r = s.execute("addon.type.releasePath", &json!({"ids": [plain.0], "mode": "text"})).unwrap();
|
||||
let t = text(&s, NodeId(r["texts"][0].as_u64().unwrap()));
|
||||
assert!(!t.dynamic_text && t.runs[0].style.size == 12.0);
|
||||
}
|
||||
|
||||
/// 12 pt point type at (100, 100), selected, with its layout bounds.
|
||||
fn point(s: &mut Session, content: &str) -> (NodeId, vectorcraft_geom::Rect) {
|
||||
let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": content, "size": 12})).unwrap();
|
||||
|
||||
@@ -94,10 +94,49 @@ fn run_fresh(
|
||||
params: &serde_json::Value,
|
||||
) -> (std::result::Result<serde_json::Value, String>, Option<std::sync::Arc<vectorcraft_doc::Document>>) {
|
||||
let (mut s, ..) = doc_with_type();
|
||||
let r = s.execute(cmd, params).map_err(|e| e.to_string());
|
||||
let r = s.execute(cmd, params).map(|v| without_plugin_effects(cmd, v)).map_err(|e| e.to_string());
|
||||
(r, s.doc().ok().map(|d| d.doc.clone()))
|
||||
}
|
||||
|
||||
/// `cmd`'s result with the plug-in effects (`plugin.<id>`) taken out of `effect.list`'s catalog.
|
||||
/// The plug-in tests install and remove plug-ins in the process-wide registry while these
|
||||
/// comparisons run, so two runs of `effect.list` can list different plug-ins.
|
||||
fn without_plugin_effects(cmd: &str, mut r: serde_json::Value) -> serde_json::Value {
|
||||
if cmd == "effect.list"
|
||||
&& let Some(catalog) = r.get_mut("catalog").and_then(serde_json::Value::as_array_mut)
|
||||
{
|
||||
catalog.retain(|e| !e["id"].as_str().is_some_and(|id| id.starts_with(vectorcraft_plugins::PREFIX)));
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Whether two results of `cmd` are the same, apart from the plug-in effects in `effect.list`'s
|
||||
/// catalog ([`without_plugin_effects`]).
|
||||
fn same_without_plugin_effects(cmd: &str, x: &serde_json::Value, y: &serde_json::Value) -> bool {
|
||||
if cmd == "effect.list" { without_plugin_effects(cmd, x.clone()) == without_plugin_effects(cmd, y.clone()) } else { x == y }
|
||||
}
|
||||
|
||||
/// Two `effect.list` results that differ only in a plug-in effect in the catalog compare the same;
|
||||
/// a difference in a built-in effect, in `applied` or in `activeItem`, or in another command's
|
||||
/// result, does not.
|
||||
#[test]
|
||||
fn plugin_effects_are_left_out_of_the_effect_list_comparison() {
|
||||
let list = |catalog: &[&str], applied: serde_json::Value, active: serde_json::Value| {
|
||||
let catalog: Vec<_> = catalog.iter().map(|id| json!({"id": id, "label": id})).collect();
|
||||
json!({"catalog": catalog, "applied": applied, "activeItem": active})
|
||||
};
|
||||
let base = list(&["stylize.dropShadow"], json!([]), json!(null));
|
||||
let with_plugin = list(&["stylize.dropShadow", "plugin.test.glow"], json!([]), json!(null));
|
||||
assert!(same_without_plugin_effects("effect.list", &base, &with_plugin));
|
||||
assert!(same_without_plugin_effects("effect.list", &with_plugin, &base));
|
||||
assert_eq!(without_plugin_effects("effect.list", with_plugin.clone()), base);
|
||||
assert!(!same_without_plugin_effects("effect.list", &base, &list(&[], json!([]), json!(null))), "a built-in effect");
|
||||
assert!(!same_without_plugin_effects("effect.list", &base, &list(&["stylize.dropShadow"], json!([{"id": 3}]), json!(null))), "applied");
|
||||
assert!(!same_without_plugin_effects("effect.list", &base, &list(&["stylize.dropShadow"], json!([]), json!(0))), "activeItem");
|
||||
assert!(!same_without_plugin_effects("object.transform", &base, &with_plugin), "another command");
|
||||
assert_eq!(without_plugin_effects("object.transform", with_plugin.clone()), with_plugin);
|
||||
}
|
||||
|
||||
/// Every command whose params description names both `id` and `ids` (`{ids?|id?}`, `{id?, ids?:
|
||||
/// … (instead of id)}`), with nothing selected: `id` does what `ids` of that one object does (the
|
||||
/// same result or the same error, and the same document), for objects of the document and for an
|
||||
@@ -265,7 +304,7 @@ fn ids_and_selection(cmd: &str, picks: &[usize]) -> std::result::Result<bool, St
|
||||
with_ids["ids"] = json!(list);
|
||||
let (a, b) = (given.execute(cmd, &with_ids), selected.execute(cmd, ¶ms));
|
||||
let same_result = match (&a, &b) {
|
||||
(Ok(x), Ok(y)) => x == y,
|
||||
(Ok(x), Ok(y)) => same_without_plugin_effects(cmd, x, y),
|
||||
(Err(x), Err(y)) => x.to_string() == y.to_string(),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
@@ -214,26 +214,72 @@ fn swatch_library_replies_leave_out_paths_outside_the_read_root() {
|
||||
let mine = format!("loaded/{}", text(&inside));
|
||||
let copied = confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": mine})));
|
||||
assert_eq!((copied["library"].as_str(), copied["copied"].as_bool()), (Some("user/Kit.vcswatches"), Some(true)), "{copied}");
|
||||
assert_eq!(copied["path"], Value::Null, "{copied}");
|
||||
assert_eq!(copied.get("path"), None, "{copied}");
|
||||
let saved = confine(roots.as_ref(), || run(&mut s, "swatch.library.save", json!({"user": true, "name": "Mine"})));
|
||||
assert_eq!((saved["library"].as_str(), saved.get("path")), (Some("user/Mine.vcswatches"), None), "{saved}");
|
||||
for reply in [&added, &copied, &saved] {
|
||||
assert!(!holds(reply, &base.join("a")) && !holds(reply, &base.join("user")), "{reply}");
|
||||
}
|
||||
// A library loaded from data under the file name keeps its id; each concealed one takes the next
|
||||
// free one, so no two rows share an id.
|
||||
// A library loaded from data under the file name keeps its id; the concealed one shown under that
|
||||
// id takes the next free one, the other keeps its id, and no two rows share an id.
|
||||
let data = run(&mut s, "swatch.library.save", json!({}))["data"].as_str().unwrap().to_string();
|
||||
run(&mut s, "swatch.library.load", json!({"data": data, "name": "Kit.vcswatches"}));
|
||||
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
|
||||
let ids: Vec<Value> = loaded(&list).into_iter().map(|(id, ..)| id).collect();
|
||||
assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches")], "{list}");
|
||||
assert_eq!(ids, [json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches")], "{list}");
|
||||
// Copied into the user library folder, it is still found by that id, which no other library takes.
|
||||
confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": "loaded/Kit.vcswatches"})));
|
||||
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
|
||||
let ids: Vec<Value> = loaded(&list).into_iter().map(|(id, ..)| id).collect();
|
||||
assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)")], "{list}");
|
||||
assert_eq!(ids, [json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches (2)")], "{list}");
|
||||
// The person sees the folder.
|
||||
let saved = run(&mut s, "swatch.library.save", json!({"user": true, "name": "Theirs"}));
|
||||
assert_eq!(saved["path"], json!(text(&base.join("user").join("Theirs.vcswatches"))));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Outside Windows a `\` is part of a file name: a concealed library saved at `<folder>/weird\name.gpl`
|
||||
/// is shown under its whole file name. Another platform's absolute path is still named by the part
|
||||
/// after its last `\`.
|
||||
#[cfg(not(windows))]
|
||||
#[test]
|
||||
fn a_concealed_library_keeps_a_backslash_in_its_file_name() {
|
||||
let base = folder("backslash-name");
|
||||
let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap();
|
||||
let native = format!("loaded/{}/weird\\name.gpl", text(&base.join("a")));
|
||||
let foreign = r"loaded/C:\Users\someone\other.gpl".to_string();
|
||||
let s = Session::new();
|
||||
let mut hidden = confine(roots.as_ref(), || cmd::swatchlib::concealed_library_ids(&s, [native.clone(), foreign.clone()]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
hidden.sort();
|
||||
let mut want = vec![(foreign, "loaded/other.gpl".to_string()), (native, "loaded/weird\\name.gpl".to_string())];
|
||||
want.sort();
|
||||
assert_eq!(hidden, want);
|
||||
}
|
||||
|
||||
/// A concealed library keeps the id a client was shown when another library with the same file name,
|
||||
/// whose full id sorts before it, is loaded later: the id still finds the first library.
|
||||
#[test]
|
||||
fn a_concealed_library_keeps_its_id_after_another_with_its_file_name_loads() {
|
||||
let base = folder("keeps-id");
|
||||
let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap();
|
||||
let (first, later) = (base.join("b").join("Kit.vcswatches"), base.join("a").join("Kit.vcswatches"));
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
(SWATCHES.add)(&mut s, "First");
|
||||
run(&mut s, "swatch.library.save", json!({"path": text(&first), "name": "Kit"}));
|
||||
(SWATCHES.add)(&mut s, "Second");
|
||||
run(&mut s, "swatch.library.save", json!({"path": text(&later), "name": "Kit"}));
|
||||
let shown = "loaded/Kit.vcswatches";
|
||||
let count = run(&mut s, "swatch.library.load", json!({"path": text(&first)}))["count"].clone();
|
||||
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
|
||||
assert_eq!(loaded(&list), [(json!(shown), Value::Null, count)], "{list}");
|
||||
run(&mut s, "swatch.library.load", json!({"path": text(&later)}));
|
||||
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
|
||||
let ids: Vec<Value> = loaded(&list).into_iter().map(|(id, ..)| id).collect();
|
||||
assert_eq!(ids, [json!(shown), json!("loaded/Kit.vcswatches (2)")], "{list}");
|
||||
let theirs = run(&mut s, "swatch.library.get", json!({"library": format!("loaded/{}", text(&first))}));
|
||||
let got = confine(roots.as_ref(), || run(&mut s, "swatch.library.get", json!({"library": shown})));
|
||||
assert_eq!((&got["id"], &got["swatches"]), (&json!(shown), &theirs["swatches"]), "the first library: {got}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
@@ -4489,6 +4489,41 @@ fn cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on(
|
||||
assert_eq!(owners(&mut s)[4..], [Value::Null, json!(1)]);
|
||||
}
|
||||
|
||||
/// The rulers' origin dragged out of their corner snaps as a drawn point does: onto a shape's
|
||||
/// corner and edge, the artboard's centre, and with Snap to Point along a ruler guide; with
|
||||
/// nothing on it stays at the pointer. The drag changes nothing, and its guides go when it ends.
|
||||
#[test]
|
||||
fn the_ruler_origin_dragged_from_the_corner_snaps_as_a_drawn_point() {
|
||||
use vectorcraft_geom::Point;
|
||||
let mut s = session();
|
||||
rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
|
||||
let (n, doc) = (undo_len(&s), s.doc().unwrap().doc.clone());
|
||||
let v = ViewInfo::default();
|
||||
let at = |s: &mut Session, x, y| s.ruler_origin_drag(Some(Point::new(x, y)), v).unwrap();
|
||||
assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0), "the corner");
|
||||
assert!(!s.overlays(v).is_empty(), "the guide showing it");
|
||||
assert_eq!(at(&mut s, 130.0, 202.0), Point::new(130.0, 200.0), "the bottom edge");
|
||||
assert_eq!(at(&mut s, 398.0, 301.5), Point::new(400.0, 300.0), "the artboard's centre");
|
||||
assert_eq!(at(&mut s, 302.0, 50.0).x, 300.0, "along the ruler guide");
|
||||
assert_eq!(s.ruler_origin_drag(None, v), None, "off the canvas");
|
||||
assert!(s.overlays(v).is_empty());
|
||||
assert_eq!(at(&mut s, 101.5, 98.5), Point::new(100.0, 100.0));
|
||||
s.end_ruler_origin_drag();
|
||||
assert!(s.overlays(v).is_empty());
|
||||
assert_eq!((undo_len(&s), &*s.doc().unwrap().doc), (n, &*doc), "nothing changed");
|
||||
// Nothing on: it stays at the pointer.
|
||||
let off = ViewInfo { smart_guides: false, snap_to_point: false, ..v };
|
||||
assert_eq!(s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), off), Some(Point::new(101.5, 98.5)));
|
||||
s.end_ruler_origin_drag();
|
||||
// Snap to Grid: onto a gridline crossing.
|
||||
let grid = ViewInfo { snap_to_grid: true, ..v };
|
||||
let p = s.ruler_origin_drag(Some(Point::new(101.5, 98.5)), grid).unwrap();
|
||||
s.end_ruler_origin_drag();
|
||||
assert_eq!(p, Point::new(p.x.round(), p.y.round()), "{p:?}");
|
||||
assert_ne!(p, Point::new(101.5, 98.5));
|
||||
}
|
||||
|
||||
/// Guides saved before guides had layers are put on a layer when the document opens.
|
||||
#[test]
|
||||
fn guides_from_older_files_are_put_on_a_layer() {
|
||||
|
||||
@@ -280,6 +280,103 @@ fn a_missing_link_is_reported_not_copied() {
|
||||
assert!(report.contains("blue.png: not found"), "{report}");
|
||||
}
|
||||
|
||||
/// Packaged for a client whose read root holds neither the document's file nor its links: the report,
|
||||
/// its Document Info part included, names them by their file names, and `document.info` gives no
|
||||
/// link. The person's report names them whole.
|
||||
#[test]
|
||||
fn a_confined_package_names_files_outside_the_read_root_by_name() {
|
||||
let dir = Folder::new("package-roots");
|
||||
let mut s = poster(&dir);
|
||||
std::fs::create_dir_all(dir.file("in")).unwrap();
|
||||
std::fs::remove_file(dir.file("art/blue.png")).unwrap();
|
||||
open(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let report = |r: &Value| {
|
||||
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap()
|
||||
};
|
||||
let person = report(&run(&mut s, "file.package", json!({})));
|
||||
assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}");
|
||||
assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}");
|
||||
assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}");
|
||||
|
||||
let in_root = dir.0.join("in");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap();
|
||||
let client = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
|
||||
let text = report(&client);
|
||||
assert!(text.contains("From: poster.vectorcraft\n"), "{text}");
|
||||
assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}");
|
||||
let base = dir.0.to_string_lossy().into_owned();
|
||||
assert!(!text.contains(&base), "{text}");
|
||||
for key in ["missingLinks", "warnings", "files"] {
|
||||
assert!(!client[key].to_string().contains(&base), "{key}: {client}");
|
||||
}
|
||||
// Document Info, whose report the package holds, gives no link either.
|
||||
for p in [json!({}), json!({"format": "text"})] {
|
||||
let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone()));
|
||||
assert!(!info.to_string().contains(&base), "{p}: {info}");
|
||||
}
|
||||
let info = run(&mut s, "document.info", json!({"format": "text"}));
|
||||
assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}");
|
||||
}
|
||||
|
||||
/// A missing link stored as a path relative to the document names a file inside a confined
|
||||
/// request's read root: the package report and Document Info give its stored path.
|
||||
#[test]
|
||||
fn a_relative_link_inside_the_read_root_keeps_its_path() {
|
||||
let dir = Folder::new("package-roots-relative");
|
||||
write(&dir.file("art/near.png"), &png(8, 8, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &dir.file("art/near.png"));
|
||||
let mut doc = (*s.doc().unwrap().doc).clone();
|
||||
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") };
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new("art/near.png"));
|
||||
write(&dir.file("near.vectorcraft"), &vectorcraft_format::save(&doc, false));
|
||||
// Missing, the link keeps its stored path when the document opens (the package copies the
|
||||
// image the document holds).
|
||||
std::fs::remove_file(dir.file("art/near.png")).unwrap();
|
||||
open(&mut s, &dir.file("near.vectorcraft"));
|
||||
let roots = crate::file_access::AutomationRoots::new(&[dir.0.as_path()], &[]).unwrap();
|
||||
let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
|
||||
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap();
|
||||
assert!(text.contains("\nart/near.png → Links/near.png\n"), "{text}");
|
||||
let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({})));
|
||||
let links: Vec<&Value> = info["images"].as_object().unwrap().values().map(|i| &i["link"]).collect();
|
||||
assert_eq!(links, [&json!("art/near.png")], "{info}");
|
||||
let text = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", json!({"format": "text"})));
|
||||
assert!(text.to_string().contains("art/near.png"), "{text}");
|
||||
}
|
||||
|
||||
/// A link whose stored path names a place outside a confined request's read root, with its file
|
||||
/// found by name beside the document inside the root: the package report and reply give the file
|
||||
/// name, not the stored path.
|
||||
#[test]
|
||||
fn a_stored_path_outside_the_read_root_is_left_out_when_its_file_is_found_inside() {
|
||||
let dir = Folder::new("package-roots-stale");
|
||||
write(&dir.file("in/near.png"), &png(8, 8, RED));
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &dir.file("in/near.png"));
|
||||
let mut doc = (*s.doc().unwrap().doc).clone();
|
||||
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node_mut(id).map(|n| &mut n.kind) else { panic!("not an image") };
|
||||
let stale = dir.file("out/near.png");
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new(&stale));
|
||||
write(&dir.file("in/near.vectorcraft"), &vectorcraft_format::save(&doc, false));
|
||||
// Missing when the document opens, the link keeps its stored path; the file then appears beside it.
|
||||
std::fs::remove_file(dir.file("in/near.png")).unwrap();
|
||||
open(&mut s, &dir.file("in/near.vectorcraft"));
|
||||
write(&dir.file("in/near.png"), &png(8, 8, RED));
|
||||
let in_root = dir.0.join("in");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[in_root.as_path()], &[]).unwrap();
|
||||
let r = crate::file_access::confine(roots.as_ref(), || run(&mut s, "file.package", json!({})));
|
||||
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
let text = String::from_utf8(zip["near Folder/near Report.txt"].clone()).unwrap();
|
||||
assert!(text.contains("\nnear.png → Links/near.png\n"), "{text}");
|
||||
assert!(!text.contains(&stale), "{text}");
|
||||
for key in ["missingLinks", "warnings", "files"] {
|
||||
assert!(!r[key].to_string().contains(&stale), "{key}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file missing from a document that moved keeps the place its relative path names from the
|
||||
/// document's folder: the packaged document writes its relative path from there.
|
||||
#[test]
|
||||
|
||||
@@ -1153,6 +1153,98 @@ fn deferred_stages_in_symbol_art_are_listed_and_refreshed() {
|
||||
assert_eq!(run(&mut s, "effect.deferredStatus", json!({}))["effects"], json!([]));
|
||||
}
|
||||
|
||||
/// `effect.refreshDeferred` takes the id of an object in the art of a symbol, pattern, brush or
|
||||
/// opacity mask, as `effect.deferredStatus` lists it: one with a deferred stage is refreshed, and
|
||||
/// one without (or whose stage is gone) adds nothing to the counts. The id of art that is no
|
||||
/// longer in the document is an error.
|
||||
#[test]
|
||||
fn refresh_takes_objects_in_definition_art() {
|
||||
let mut s = session();
|
||||
const FX: &str = "plugin.test.engine.deferred.nested";
|
||||
let out = json!({"objects": [{"path": square_at(110.0)}]}).to_string();
|
||||
install_wat(&mut s, &tpl::returning(&tpl::manifest("test.engine.deferred.nested", "effect", "{}"), &out));
|
||||
// A symbol whose art holds an object with the effect and one without.
|
||||
let staged = rect(&mut s, 10.0, "#ff0000");
|
||||
let plain = rect(&mut s, 30.0, "#ff0000");
|
||||
run(&mut s, "effect.apply", json!({"ids": [staged.0], "effect": FX}));
|
||||
run(&mut s, "select.set", json!({"ids": [staged.0, plain.0]}));
|
||||
run(&mut s, "symbol.new", json!({"name": "Nested"}));
|
||||
// A pattern, an art brush (its source deleted) and an opacity mask, none with a stage.
|
||||
let tile = rect(&mut s, 50.0, "#00ff00");
|
||||
run(&mut s, "select.set", json!({"ids": [tile.0]}));
|
||||
run(&mut s, "object.pattern.make", json!({"name": "Tile", "width": 20, "height": 20}));
|
||||
run(&mut s, "object.pattern.done", json!({}));
|
||||
let bar = rect(&mut s, 70.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [bar.0]}));
|
||||
run(&mut s, "brush.new", json!({"type": "art", "name": "Bar"}));
|
||||
run(&mut s, "edit.clear", json!({"ids": [bar.0]}));
|
||||
let masked = rect(&mut s, 90.0, "#ff0000");
|
||||
let mask = rect(&mut s, 90.0, "#ffffff");
|
||||
run(&mut s, "select.set", json!({"ids": [masked.0, mask.0]}));
|
||||
run(&mut s, "transparency.makeOpacityMask", json!({}));
|
||||
// A layer object with a stage that stays deferred, and one without.
|
||||
let kept = rect(&mut s, 130.0, "#ff0000");
|
||||
run(&mut s, "effect.apply", json!({"ids": [kept.0], "effect": FX}));
|
||||
let bare = rect(&mut s, 150.0, "#ff0000");
|
||||
|
||||
// The ids of the objects of `art` that are not in the layers.
|
||||
let nested = |s: &Session, art: &vectorcraft_doc::Node| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut ids = Vec::new();
|
||||
vectorcraft_doc::swatches::walk_with_masks(art, &mut |n| {
|
||||
if d.node(n.id).is_none() {
|
||||
ids.push(n.id.0);
|
||||
}
|
||||
});
|
||||
ids
|
||||
};
|
||||
let d = s.doc().unwrap().doc.clone();
|
||||
let in_symbol = nested(&s, &d.symbols[0].art);
|
||||
let in_pattern = d.patterns.iter().flat_map(|p| p.art.iter().flat_map(|a| nested(&s, a))).collect::<Vec<_>>();
|
||||
let brushes = vectorcraft_brush::library(&d);
|
||||
let in_brush = brushes.iter().flat_map(|b| b.art().into_iter().flat_map(|a| nested(&s, a)).collect::<Vec<_>>()).collect::<Vec<_>>();
|
||||
let in_mask = d.node(masked).and_then(|n| n.extras().mask.as_ref()).map(|m| nested(&s, &m.art)).unwrap_or_default();
|
||||
for (what, ids) in [("symbol", &in_symbol), ("pattern", &in_pattern), ("brush", &in_brush), ("opacity mask", &in_mask)] {
|
||||
assert!(!ids.is_empty(), "the {what} art has an object outside the layers");
|
||||
}
|
||||
|
||||
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
|
||||
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
|
||||
s.doc_mut().unwrap().plugin_effects = fx.clone();
|
||||
fx.view(|| drawn(&s));
|
||||
fx.first_view_done();
|
||||
let listed = |s: &mut Session| {
|
||||
run(s, "effect.deferredStatus", json!({}))["effects"].as_array().unwrap().iter().map(|e| e["objectId"].as_u64().unwrap()).collect::<Vec<_>>()
|
||||
};
|
||||
let deferred = listed(&mut s);
|
||||
let [nested_staged, last] = deferred[..] else { panic!("two stages: {deferred:?}") };
|
||||
assert!(in_symbol.contains(&nested_staged) && last == kept.0, "{deferred:?} {in_symbol:?}");
|
||||
let Some(&nested_plain) = in_symbol.iter().find(|i| **i != nested_staged) else { panic!("{in_symbol:?}") };
|
||||
|
||||
// Objects without a stage, each on its own and together: nothing to refresh.
|
||||
let none = json!({"refreshed": 0, "stillDeferred": 0, "failed": 0});
|
||||
let mut plain_ids = vec![nested_plain, in_pattern[0], in_brush[0], in_mask[0], bare.0];
|
||||
for id in &plain_ids {
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": id})), none, "object {id}");
|
||||
}
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), none);
|
||||
assert_eq!(listed(&mut s), [nested_staged, kept.0]);
|
||||
|
||||
// The staged object of the symbol's art, by its id, with the others.
|
||||
step.store(0, std::sync::atomic::Ordering::Relaxed);
|
||||
plain_ids.push(nested_staged);
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": plain_ids})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0}));
|
||||
assert_eq!(listed(&mut s), [kept.0]);
|
||||
// Its stage is gone; the object is still there.
|
||||
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"id": nested_staged})), none);
|
||||
|
||||
// Art no longer in the document, and an id of no object.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).patterns.clear();
|
||||
assert!(s.execute("effect.refreshDeferred", &json!({"id": in_pattern[0]})).is_err(), "the pattern is gone");
|
||||
assert!(s.execute("effect.refreshDeferred", &json!({"ids": [nested_plain, 999_999]})).is_err(), "not an object of the document");
|
||||
assert_eq!(listed(&mut s), [kept.0]);
|
||||
}
|
||||
|
||||
/// `CRAFT_PLUGIN_PAINTS_WASM=<folder>` saves a test live effect to try in the app
|
||||
/// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its
|
||||
/// object's stroke is 5 pt wide, and hands the geometry back otherwise.
|
||||
|
||||
@@ -483,6 +483,105 @@ fn the_folder_store_reads_no_linked_entries() {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// A file where a folder of the store's path should be: the error names that file, not the area
|
||||
/// folder or the copy below it, for a write, a lock, a read, a listing, a removal and a recovery
|
||||
/// save.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folder_errors_name_a_file_in_the_way() {
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-file-in-way-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let file = base.join("file");
|
||||
std::fs::write(&file, b"").unwrap();
|
||||
let folder = file.join("recovery");
|
||||
let store = FolderStore::new(&folder);
|
||||
let mut s = Session::new();
|
||||
s.prefs.recovery_folder = folder.to_string_lossy().to_string();
|
||||
s.execute("file.new", &json!({"width": 50, "height": 50})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
|
||||
let errors = [
|
||||
("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err()),
|
||||
("lock", store.lock("1-2").err()),
|
||||
("read", store.read("1-1/Untitled-1-1.vectorcraft").err()),
|
||||
("list", store.list().err()),
|
||||
("remove", store.remove("1-1/Untitled-1-1.vectorcraft").err()),
|
||||
("save", s.execute("file.recovery.save", &json!({})).err().map(|e| e.to_string())),
|
||||
];
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let named = format!("{} is not a folder: ", file.display());
|
||||
let wrong: Vec<_> = errors.iter().filter(|(_, e)| !e.as_deref().is_some_and(|e| e.contains(&named))).collect();
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
/// A removal that finds the copy missing because a file is on the way to it (how Windows reports a
|
||||
/// file in the way) names that file. A copy that is just not there still counts as removed.
|
||||
#[test]
|
||||
fn a_removal_reported_missing_names_a_file_in_the_way() {
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-remove-in-way-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let file = base.join("file");
|
||||
std::fs::write(&file, b"").unwrap();
|
||||
let missing = || std::io::Error::from(std::io::ErrorKind::NotFound);
|
||||
let behind = FolderStore::removed(&file.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing()));
|
||||
let gone = FolderStore::removed(&base.join("recovery").join("1-1").join("Untitled-1-1.vectorcraft"), Err(missing()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let named = format!("{} is not a folder: ", file.display());
|
||||
assert!(behind.as_ref().is_err_and(|e| e.starts_with(&named)), "{behind:?}");
|
||||
assert_eq!(gone, Ok(()));
|
||||
}
|
||||
|
||||
/// A folder of the store's path that is missing and can't be made: a write or a lock names it as
|
||||
/// the folder it couldn't make, and a read names it as missing. An area folder that can't be made
|
||||
/// in a store folder that is there is named the same way.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folder_errors_name_a_missing_folder_that_cannot_be_made() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-missing-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let closed = base.join("closed");
|
||||
std::fs::create_dir_all(&closed).unwrap();
|
||||
std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o500)).unwrap();
|
||||
let gone = closed.join("gone");
|
||||
let store = FolderStore::new(gone.join("recovery"));
|
||||
let unmade = format!("couldn't make {}: ", gone.display());
|
||||
let area = FolderStore::new(&closed).write("1-1/Untitled-1-1.vectorcraft", b"copy").err();
|
||||
let errors = [
|
||||
("write", store.write("1-1/Untitled-1-1.vectorcraft", b"copy").err(), unmade.clone()),
|
||||
("lock", store.lock("1-2").err(), unmade),
|
||||
("read", store.read("1-1/Untitled-1-1.vectorcraft").err(), format!("{} is missing", gone.display())),
|
||||
("area", area, format!("couldn't make {}: ", closed.join("1-1").display())),
|
||||
];
|
||||
std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
// An account that can write anywhere (root) makes the folders, so the test has nothing to check.
|
||||
if errors[0].1.is_none() {
|
||||
return;
|
||||
}
|
||||
let wrong: Vec<_> = errors.iter().filter(|(_, e, named)| !e.as_deref().is_some_and(|e| e.starts_with(named.as_str()))).collect();
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
/// When every folder on the way is there, an error names the folder it happened on.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folder_errors_name_the_folder_when_every_folder_is_there() {
|
||||
use std::os::unix::fs::PermissionsExt as _;
|
||||
let base = std::env::temp_dir().join(format!("vc-recovery-unreadable-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let unreadable = base.join("unreadable");
|
||||
std::fs::create_dir_all(&unreadable).unwrap();
|
||||
std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o300)).unwrap();
|
||||
let listed = FolderStore::new(&unreadable).list();
|
||||
std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
// An account that can read any folder (root) lists it, so the test has nothing to check.
|
||||
let Err(err) = listed else { return };
|
||||
assert!(err.starts_with(&format!("{}: ", unreadable.display())), "{err}");
|
||||
}
|
||||
|
||||
/// A store in memory that notes each removal of an area (its lock file and folder, then its empty
|
||||
/// folder) and whether the area was still held then.
|
||||
#[derive(Default)]
|
||||
@@ -958,6 +1057,142 @@ fn a_copy_left_behind_is_not_offered_by_its_own_app() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A copy left in an area the session had to leave is not another app's to offer, restore or
|
||||
/// discard while the session runs, even after the app that locked that area let it go: an entry in
|
||||
/// the session's new area says it keeps it. Once the copy is written again in the new area, the
|
||||
/// entry goes; after a crash before that, the copy is offered.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_copy_left_behind_is_not_offered_by_another_app_while_its_app_runs() {
|
||||
use cmd::recovery::Lock;
|
||||
let dir = std::env::temp_dir().join(format!("vc-recovery-leftother-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let left_behind = |area: &str| dir.join(area).join("Untitled-1-1.vectorcraft");
|
||||
let leave = |a: &mut Session, area: &str| {
|
||||
std::fs::remove_file(dir.join(area).join(".lock")).unwrap();
|
||||
let Ok(Lock::Held(other)) = FolderStore::new(&dir).lock(area) else { panic!("the other app locks the area") };
|
||||
cmd::recovery::heartbeat(a);
|
||||
drop(other);
|
||||
a.recovery.own_area().unwrap().to_string()
|
||||
};
|
||||
let (mut a, area) = saved_in(&dir);
|
||||
let mine = leave(&mut a, &area);
|
||||
assert_ne!(mine, area);
|
||||
assert!(dir.join(&mine).join(format!("keeps-{area}")).is_file());
|
||||
// Removed meanwhile: the next heartbeat writes it again.
|
||||
std::fs::remove_file(dir.join(&mine).join(format!("keeps-{area}"))).unwrap();
|
||||
cmd::recovery::heartbeat(&mut a);
|
||||
assert!(dir.join(&mine).join(format!("keeps-{area}")).is_file());
|
||||
let mut b = other_app(&dir);
|
||||
assert!(offered(&mut b).is_empty());
|
||||
assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 0);
|
||||
assert!(b.execute("file.recovery.discard", &json!({})).unwrap()["discarded"].as_array().unwrap().is_empty());
|
||||
assert!(b.execute("file.recovery.discard", &json!({"file": format!("{area}/Untitled-1-1")})).is_err());
|
||||
assert!(left_behind(&area).is_file());
|
||||
// Written again in the new area: the copy left behind and the entry go.
|
||||
a.execute("file.recovery.save", &json!({})).unwrap();
|
||||
assert!(!left_behind(&area).exists());
|
||||
assert!(!dir.join(&mine).join(format!("keeps-{area}")).exists());
|
||||
assert!(offered(&mut b).is_empty());
|
||||
drop(a);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
// A crash before the copy is written again: the copy left behind is offered.
|
||||
let (mut a, area) = saved_in(&dir);
|
||||
leave(&mut a, &area);
|
||||
drop(a);
|
||||
assert_eq!(offered(&mut other_app(&dir)).len(), 1);
|
||||
assert!(left_behind(&area).is_file());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A store in memory whose areas named `foreign-…` can't be locked by this account (as another
|
||||
/// account's folder in a shared recovery folder).
|
||||
#[derive(Default)]
|
||||
struct ForeignAreas(MemoryStore);
|
||||
|
||||
impl RecoveryStore for ForeignAreas {
|
||||
fn list(&self) -> std::result::Result<Vec<String>, String> {
|
||||
self.0.list()
|
||||
}
|
||||
fn read(&self, name: &str) -> std::result::Result<Vec<u8>, String> {
|
||||
self.0.read(name)
|
||||
}
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> {
|
||||
self.0.write(name, bytes)
|
||||
}
|
||||
fn remove(&self, name: &str) -> std::result::Result<(), String> {
|
||||
self.0.remove(name)
|
||||
}
|
||||
fn location(&self) -> String {
|
||||
self.0.location()
|
||||
}
|
||||
fn lock(&self, area: &str) -> std::result::Result<cmd::recovery::Lock, String> {
|
||||
if area.starts_with("foreign-") {
|
||||
return Err(format!("{area}: belongs to another account"));
|
||||
}
|
||||
self.0.lock(area)
|
||||
}
|
||||
fn now(&self) -> Option<i64> {
|
||||
self.0.now()
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry `<area>/keeps-<left area>` in an area this account can't lock keeps nothing: a crashed
|
||||
/// app's copies in the left area are still offered.
|
||||
#[test]
|
||||
fn a_keeps_entry_in_an_area_that_cannot_be_locked_keeps_nothing() {
|
||||
let store = Arc::new(ForeignAreas::default());
|
||||
let app = || {
|
||||
let mut s = Session::new();
|
||||
s.recovery.set_store(store.clone());
|
||||
s
|
||||
};
|
||||
let mut a = app();
|
||||
a.execute("file.new", &json!({"width": 50, "height": 50})).unwrap();
|
||||
a.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 5, "height": 5})).unwrap();
|
||||
a.execute("file.recovery.save", &json!({})).unwrap();
|
||||
let area = a.recovery.own_area().unwrap().to_string();
|
||||
drop(a);
|
||||
store.write(&format!("foreign-1/keeps-{area}"), b"").unwrap();
|
||||
let mut b = app();
|
||||
assert_eq!(offered(&mut b).len(), 1);
|
||||
assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 1);
|
||||
}
|
||||
|
||||
/// An entry `<area>/keeps-<left area>` in a running app's area keeps a crashed app's copies in the
|
||||
/// left area until that app is gone too.
|
||||
#[test]
|
||||
fn a_keeps_entry_in_a_running_apps_area_keeps_the_copies() {
|
||||
let store = Arc::new(MemoryStore::default());
|
||||
let mut a = session_in(&store);
|
||||
a.execute("file.recovery.save", &json!({})).unwrap();
|
||||
let area = a.recovery.own_area().unwrap().to_string();
|
||||
drop(a);
|
||||
let mut c = session_in(&store);
|
||||
c.execute("file.recovery.save", &json!({})).unwrap();
|
||||
let keeper = c.recovery.own_area().unwrap().to_string();
|
||||
store.write(&format!("{keeper}/keeps-{area}"), b"").unwrap();
|
||||
let mut b = relaunch(&store);
|
||||
assert!(offered(&mut b).is_empty());
|
||||
assert_eq!(restored(b.execute("file.recovery.restore", &json!({})).unwrap()), 0);
|
||||
drop(c);
|
||||
assert_eq!(offered(&mut b).len(), 2);
|
||||
}
|
||||
|
||||
/// An entry `<area>/keeps-<left area>` in a folder whose lock file can't be opened keeps nothing.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_keeps_entry_in_a_folder_whose_lock_cannot_be_checked_keeps_nothing() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-recovery-keepsunlocked-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let (a, area) = saved_in(&dir);
|
||||
drop(a);
|
||||
std::fs::create_dir_all(dir.join("keeper").join(".lock")).unwrap();
|
||||
std::fs::write(dir.join("keeper").join(format!("keeps-{area}")), b"").unwrap();
|
||||
assert_eq!(offered(&mut other_app(&dir)).len(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A complex document (Data Recovery off for those) gets no new copy after the session left its
|
||||
/// area: it keeps the copy it left there, and the heartbeat asks for it only once.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -40,6 +40,50 @@ fn objects(s: &Session) -> usize {
|
||||
s.doc().unwrap().doc.node_count()
|
||||
}
|
||||
|
||||
/// A client confined by automation roots: a save without a path writes the document's own file, and
|
||||
/// when that file is outside the read roots the reply leaves out its `path` and names the files
|
||||
/// written beside it by their file names. A reply without a path leaves out a suggested `folder`
|
||||
/// outside them. A path inside the read roots, and one the client gives, stay whole.
|
||||
#[test]
|
||||
fn a_confined_save_leaves_out_paths_outside_the_read_root() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let d = dir("roots");
|
||||
let (inside, outside) = (d.join("in"), d.join("out"));
|
||||
for f in [&inside, &outside] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
rect(&mut s);
|
||||
let own = path(&outside, "doc.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": own})).unwrap();
|
||||
let person = s.execute("document.save", &json!({"separateArtboards": true})).unwrap();
|
||||
let files: Vec<String> = person["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect();
|
||||
assert_eq!((files.len(), files[0].as_str()), (3, own.as_str()), "{person}");
|
||||
|
||||
let write_only = AutomationRoots::new(&[inside.as_path()], &[outside.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), outside.as_path()], &[outside.as_path()]).unwrap();
|
||||
let run = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, id: &str, p: Value| {
|
||||
confine(roots.as_ref(), || s.execute(id, &p)).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
};
|
||||
let hidden = outside.to_string_lossy().into_owned();
|
||||
let r = run(&mut s, &write_only, "document.save", json!({}));
|
||||
assert!(r.get("path").is_none() && r["bytes"].as_u64().is_some_and(|n| n > 0), "{r}");
|
||||
assert!(!r.to_string().contains(&hidden), "{r}");
|
||||
let r = run(&mut s, &write_only, "document.save", json!({"separateArtboards": true}));
|
||||
let names: Vec<Value> = files.iter().map(|f| json!(std::path::Path::new(f).file_name().unwrap().to_string_lossy())).collect();
|
||||
assert_eq!((r.get("path"), r["files"].as_array()), (None, Some(&names)), "{r}");
|
||||
// Inside the read roots, or given by the client: whole.
|
||||
assert_eq!(run(&mut s, &both, "document.save", json!({}))["path"], json!(own));
|
||||
assert_eq!(run(&mut s, &write_only, "document.save", json!({"path": own}))["path"], json!(own));
|
||||
// A save without a path known suggests the document's folder.
|
||||
let r = run(&mut s, &write_only, "file.saveCopy", json!({}));
|
||||
assert!(r.get("folder").is_none() && r["name"] == "doc copy.vectorcraft" && r.get("dataBase64").is_some(), "{r}");
|
||||
assert_eq!(run(&mut s, &both, "file.saveCopy", json!({}))["folder"], json!(hidden));
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_svg_path_writes_svg_and_save_writes_it_back() {
|
||||
let d = dir("svg");
|
||||
|
||||
@@ -87,6 +87,87 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects()
|
||||
assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painted_and_sketched_styles_set_every_effect_setting_and_reopen_applied() {
|
||||
let mut s = session();
|
||||
let list = run(&mut s, "graphicStyle.libraries", json!({}));
|
||||
let libs = list["libraries"].as_array().unwrap();
|
||||
let at = libs.iter().position(|l| l["id"] == "painted-sketched").expect("listed");
|
||||
assert_eq!((libs[at]["name"].as_str(), libs[at]["count"].as_u64()), (Some("Painted and Sketched"), Some(7)));
|
||||
assert_eq!(libs[at - 1]["id"], "textures");
|
||||
let g = run(&mut s, "graphicStyle.library", json!({"library": "Painted and Sketched"}));
|
||||
let listed: Vec<(&str, &str, Vec<&str>)> =
|
||||
g["styles"].as_array().unwrap().iter().map(|x| (x["name"].as_str().unwrap(), x["fill"].as_str().unwrap(), names(&x["effects"]))).collect();
|
||||
let want = [
|
||||
("Washed Blue", "#8ab9c9", "artistic.watercolor"),
|
||||
("Bristle Ochre", "#c4975a", "artistic.dryBrush"),
|
||||
("Pastel Heather", "#a78ca5", "artistic.roughPastels"),
|
||||
("Charcoal Shade", "#666666", "sketch.charcoal"),
|
||||
("Ink Contour", "#d9e2df", "brushStrokes.inkOutlines"),
|
||||
("Wet Ink", "#637b85", "brushStrokes.sumiE"),
|
||||
("Fine Pen", "#d8d4c6", "sketch.graphicPen"),
|
||||
];
|
||||
assert_eq!(listed, want.iter().map(|&(n, f, e)| (n, f, vec![e])).collect::<Vec<_>>());
|
||||
// Every setting of each effect is given, with the catalog's key and kind of value.
|
||||
let (_, lib) = cmd::stylelib::library(&s, "painted-sketched").unwrap();
|
||||
for st in &lib.styles {
|
||||
let e = &st.appearance.effects[0];
|
||||
let defaults = vectorcraft_render::effects::effect_info(&e.id).unwrap().defaults;
|
||||
let (set, all) = (e.params.as_object().unwrap(), defaults.as_object().unwrap());
|
||||
let keys = |m: &serde_json::Map<String, Value>| m.keys().cloned().collect::<Vec<_>>();
|
||||
assert_eq!(keys(set), keys(all), "{}", st.name);
|
||||
for (k, v) in set {
|
||||
let kind = |v: &Value| (v.is_number(), v.is_string(), v.is_boolean());
|
||||
assert_eq!(kind(v), kind(&all[k]), "{} / {k}", st.name);
|
||||
}
|
||||
}
|
||||
let strokes: Vec<(&str, f64)> =
|
||||
lib.styles.iter().filter(|g| g.appearance.stroke_paint() != Paint::None).map(|g| (g.name.as_str(), g.appearance.stroke_width())).collect();
|
||||
assert_eq!(strokes, [("Bristle Ochre", 1.0), ("Ink Contour", 1.0)]);
|
||||
|
||||
// Each one adds and applies to a rectangle in one undo step.
|
||||
let mut ids = vec![];
|
||||
for (i, (name, fill, effect)) in want.iter().enumerate() {
|
||||
let id = rect(&mut s, 10.0 + 25.0 * i as f64, 20.0, 20.0, 30.0);
|
||||
let before = undo_len(&s);
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": name, "apply": true, "ids": [id.0]}));
|
||||
assert_eq!((names(&r["added"]), r["applied"].as_str()), (vec![*name], Some(*name)));
|
||||
assert_eq!(undo_len(&s), before + 1, "{name}");
|
||||
let node = doc(&s).node(id).unwrap();
|
||||
assert_eq!(node.appearance.fill_paint(), Paint::solid(vectorcraft_color::Color::from_hex(fill).unwrap()), "{name}");
|
||||
assert_eq!(node.appearance.effects.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), [*effect]);
|
||||
assert_eq!(node.appearance.effects[0].params, lib.style(name).unwrap().appearance.effects[0].params, "{name}");
|
||||
ids.push((id, *name));
|
||||
}
|
||||
// Adding one again reuses it: no new style, no undo step.
|
||||
let before = (undo_len(&s), doc(&s).graphic_styles.len());
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Wet Ink"}));
|
||||
assert_eq!((names(&r["added"]), names(&r["existing"])), (vec![], vec!["Wet Ink"]));
|
||||
assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before);
|
||||
// An unknown style or library changes nothing.
|
||||
assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-sketched", "names": ["Wet Ink", "Nope"]})).is_err());
|
||||
assert!(s.execute("graphicStyle.addFromLibrary", &json!({"library": "painted-and-sketched", "name": "Wet Ink"})).is_err());
|
||||
assert_eq!((undo_len(&s), doc(&s).graphic_styles.len()), before);
|
||||
|
||||
// Saved and opened again, the styles keep their effects and the rectangles stay linked to them.
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
run(&mut s, "document.open", json!({"name": "painted.vectorcraft", "dataBase64": b64}));
|
||||
for (id, name) in &ids {
|
||||
let d = doc(&s);
|
||||
let style = d.graphic_style(name).unwrap();
|
||||
assert!(style.same_look(lib.style(name).unwrap()), "{name}");
|
||||
let node = d.node(*id).unwrap();
|
||||
assert_eq!((node.extras().graphic_style, &node.appearance.effects), (Some(style.id), &style.appearance.effects), "{name}");
|
||||
}
|
||||
|
||||
// With nothing selected, `apply` only adds; empty `names` adds the whole library in order.
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Fine Pen", "apply": true}));
|
||||
assert!(r.get("applied").is_none() && doc(&s).graphic_style("Fine Pen").is_some());
|
||||
let r = run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "names": []}));
|
||||
assert_eq!((names(&r["added"]), names(&r["existing"])), (want[..6].iter().map(|w| w.0).collect::<Vec<_>>(), vec!["Fine Pen"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_dedupes_names_as_one_undo_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -798,6 +798,39 @@ fn a_pattern_library_adds_only_the_picked_pattern_and_it_undoes_and_saves() {
|
||||
assert_eq!(back.swatch("Checkerboard").map(|w| &w.paint), doc(&s).swatch("Checkerboard").map(|w| &w.paint));
|
||||
}
|
||||
|
||||
/// Grit Textures is listed after Geometric Patterns. One of its patterns comes in with its swatch
|
||||
/// once, as one undo step that also takes both away, and both stay after a save and reopen.
|
||||
#[test]
|
||||
fn a_grit_texture_adds_once_undoes_and_saves() {
|
||||
let mut s = session();
|
||||
let list = run(&mut s, "swatch.library.list", json!({}));
|
||||
let ids: Vec<&str> =
|
||||
list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "patterns").map(|l| l["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["geometric-patterns", "grit-textures"]);
|
||||
let got = run(&mut s, "swatch.library.get", json!({"library": "Grit Textures"}));
|
||||
let names: Vec<&str> = got["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["Fine Grain", "Coarse Grit", "Sand", "Speckle", "Stipple", "Scratches", "Sparse Flecks", "Dense Flecks"]);
|
||||
let counts = |d: &vectorcraft_doc::Document| (d.patterns.len(), d.swatches_iter().count());
|
||||
let empty = counts(doc(&s));
|
||||
let undo = undo_len(&s);
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]}));
|
||||
assert_eq!(r["added"], json!(["Stipple"]));
|
||||
assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1));
|
||||
let def = doc(&s).pattern("Stipple").expect("the pattern comes with its swatch").clone();
|
||||
assert!(def.art.len() >= 144, "{} marks", def.art.len());
|
||||
assert!(matches!(doc(&s).swatch("Stipple").map(|w| &w.paint), Some(Paint::Pattern { pattern, .. }) if pattern == "Stipple"));
|
||||
let r = run(&mut s, "swatch.library.add", json!({"library": "grit-textures", "names": ["Stipple"]}));
|
||||
assert_eq!((r["added"].clone(), r["existing"].clone()), (json!([]), json!(["Stipple"])));
|
||||
assert_eq!((counts(doc(&s)), undo_len(&s)), ((empty.0 + 1, empty.1 + 1), undo + 1), "added once");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(counts(doc(&s)), empty);
|
||||
assert!(doc(&s).pattern("Stipple").is_none() && doc(&s).swatch("Stipple").is_none());
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(doc(&s), false)).unwrap();
|
||||
assert_eq!(back.pattern("Stipple"), Some(&def));
|
||||
assert_eq!(back.swatch("Stipple").map(|w| &w.paint), doc(&s).swatch("Stipple").map(|w| &w.paint));
|
||||
}
|
||||
|
||||
/// A device name is saved with a `-` after it, which can be another library's own name: neither
|
||||
/// library replaces the other, and saving either again replaces only itself.
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user