mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-18 02:42:47 +00:00
Merge main into feat/outline-object-image-alpha
This commit is contained in:
@@ -147,3 +147,37 @@ fn show_all_hidden_attributes() {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, id).appearance.has_hidden());
|
||||
}
|
||||
|
||||
/// A Warp applied now takes its style's Bézier net (`version` 1) unless a map is given, an edit
|
||||
/// keeps the map the effect has (one saved before the version existed keeps the earlier map), and
|
||||
/// a map this build doesn't draw is refused.
|
||||
#[test]
|
||||
fn warps_keep_the_map_their_version_names() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let version = |s: &Session| node(s, id).appearance.effects[0].params.get("version").cloned();
|
||||
run(&mut s, "effect.apply", json!({"effect": "warp.flag", "params": {"bend": 40}}));
|
||||
assert_eq!(version(&s), Some(json!(vectorcraft_doc::live::WARP_NET)));
|
||||
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"bend": 20}, "warpStyle": "arc"}));
|
||||
assert_eq!(version(&s), Some(json!(vectorcraft_doc::live::WARP_NET)));
|
||||
// As a file saved before the version existed gives it.
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let Some(Value::Object(p)) = doc.node_mut(id).and_then(|n| n.appearance.effects.first_mut()).map(|e| &mut e.params) {
|
||||
p.remove("version");
|
||||
}
|
||||
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"bend": 10, "horizontal": 20}}));
|
||||
assert_eq!(version(&s), None);
|
||||
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"version": 1}}));
|
||||
assert_eq!(version(&s), Some(json!(1)));
|
||||
run(&mut s, "effect.apply", json!({"effect": "warp.arc", "params": {"version": 0}}));
|
||||
assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(0));
|
||||
// A whole number given as a float is that version.
|
||||
run(&mut s, "effect.setParams", json!({"index": 1, "params": {"version": 1.0}}));
|
||||
assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(1));
|
||||
run(&mut s, "effect.setParams", json!({"index": 1, "params": {"version": 0.0}}));
|
||||
assert_eq!(node(&s, id).appearance.effects[1].params["version"], json!(0));
|
||||
for bad in [json!(2), json!(-1), json!(0.5), json!("1")] {
|
||||
assert!(s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"version": bad}})).is_err(), "{bad}");
|
||||
assert!(s.execute("effect.setParams", &json!({"index": 0, "params": {"version": bad}})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(node(&s, id).appearance.effects.len(), 2);
|
||||
}
|
||||
|
||||
@@ -123,6 +123,51 @@ fn reset_with_warp_and_mesh_switch_the_kind_and_keep_the_content() {
|
||||
assert!(s.execute("object.envelope.resetWithMesh", &json!({})).is_err());
|
||||
}
|
||||
|
||||
/// A new warp envelope bends with its style's Bézier net (`version` [`live::WARP_NET`]) and keeps
|
||||
/// it through Reset with Warp. One saved before the version existed keeps the earlier map when its
|
||||
/// warp or its options change.
|
||||
#[test]
|
||||
fn new_warp_envelopes_take_the_net_and_saved_ones_keep_their_map() {
|
||||
// The surface point a quarter of the way along the top edge.
|
||||
let quarter = |s: &Session, e| live::EnvelopeMap::of(&node(s, e)).unwrap().surface_mesh(4, 4, vectorcraft_color::Color::BLACK).points[1].p;
|
||||
let at = |x, y| vectorcraft_geom::Point::new(x, y);
|
||||
let mut s = session();
|
||||
let (_, e) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40}));
|
||||
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e));
|
||||
assert_eq!(s.execute("object.envelope.info", &json!({})).unwrap()["version"], json!(live::WARP_NET));
|
||||
// Flag moves the top edge 6 × bend × height × u(1 - u)(1 - 2u) down at u: 22.5 at u = 1/4.
|
||||
assert!(quarter(&s, e).distance(at(150.0, 122.5)) < 1e-9, "{:?}", quarter(&s, e));
|
||||
s.execute("object.envelope.resetWithWarp", &json!({"bend": -40})).unwrap();
|
||||
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e));
|
||||
assert!(quarter(&s, e).distance(at(150.0, 77.5)) < 1e-9, "{:?}", quarter(&s, e));
|
||||
// As a file saved before the version existed gives it.
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
if let Some(NodeKind::Envelope { kind, .. }) = doc.node_mut(e).map(|n| &mut n.kind)
|
||||
&& let EnvelopeKind::Warp { version, .. } = &mut **kind
|
||||
{
|
||||
*version = 0;
|
||||
}
|
||||
s.execute("object.envelope.options", &json!({"fidelity": 75})).unwrap();
|
||||
s.execute("object.envelope.resetWithWarp", &json!({"bend": 40})).unwrap();
|
||||
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, e));
|
||||
// The earlier map's flag: half the bend times sin(π x), x = -1/2 here, in half heights.
|
||||
assert!(quarter(&s, e).distance(at(150.0, 90.0)) < 1e-9, "{:?}", quarter(&s, e));
|
||||
// `version` moves a warp to a map, and a new warp can take the earlier one.
|
||||
s.execute("object.envelope.options", &json!({"version": 1.0})).unwrap();
|
||||
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: live::WARP_NET, .. }), "{:?}", kind(&s, e));
|
||||
assert!(quarter(&s, e).distance(at(150.0, 122.5)) < 1e-9, "{:?}", quarter(&s, e));
|
||||
s.execute("object.envelope.resetWithWarp", &json!({"version": 0})).unwrap();
|
||||
assert!(matches!(kind(&s, e), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, e));
|
||||
let (_, old) = enveloped(&mut s, "object.envelope.makeWithWarp", json!({"style": "flag", "bend": 40, "version": 0}));
|
||||
assert!(matches!(kind(&s, old), EnvelopeKind::Warp { version: 0, .. }), "{:?}", kind(&s, old));
|
||||
for bad in [json!(2), json!(-1), json!(0.5), json!("1"), json!(null)] {
|
||||
for cmd in ["object.envelope.makeWithWarp", "object.envelope.resetWithWarp", "object.envelope.options"] {
|
||||
let r = s.execute(cmd, &json!({"version": bad}));
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("`version` must be 0 or 1")), "{cmd} {bad}: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_gives_back_the_warp_shape_as_a_mesh_and_keeps_the_transparency() {
|
||||
let mut s = session();
|
||||
@@ -141,9 +186,9 @@ fn release_gives_back_the_warp_shape_as_a_mesh_and_keeps_the_transparency() {
|
||||
let content = node(&s, a);
|
||||
assert_eq!((content.opacity, content.blend, content.extras().mask.is_some()), (0.4, BlendMode::Multiply, true), "the content keeps the look");
|
||||
let NodeKind::Mesh(m) = node(&s, ids[1]).kind else { panic!("the warp's shape comes back as a mesh") };
|
||||
// The mesh follows the arc: its outline reaches below the content's bottom edge at the sides.
|
||||
// The mesh follows the arc: its top corners swing out past the content's sides and up.
|
||||
let b = m.outline().bounds().unwrap();
|
||||
assert!(b.y1 > 201.0, "{b:?}");
|
||||
assert!(b.x0 < 99.0 && b.x1 > 301.0 && b.y0 < 99.0, "{b:?}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, ids);
|
||||
}
|
||||
|
||||
|
||||
@@ -154,6 +154,35 @@ fn images_bend_as_a_raster_mesh_warp() {
|
||||
assert_eq!(svg.matches("<image").count(), 1, "the pieces share the image's pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colorized_image_keeps_its_color_in_an_envelope() {
|
||||
let mut s = session();
|
||||
let img = image::GrayImage::from_pixel(4, 4, image::Luma([0]));
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let im = s
|
||||
.edit("Place", |d, sel| {
|
||||
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png));
|
||||
let id = d.alloc_id();
|
||||
let xf = Affine::translate((100.0, 100.0)) * Affine::scale(10.0);
|
||||
let im =
|
||||
vectorcraft_doc::ImageObject { key: "gray".into(), width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [im.0]})).unwrap();
|
||||
sel(&mut s, &[im]);
|
||||
arch(&mut s, 80.0, json!({}));
|
||||
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 200.0, 200.0), 1.0, true);
|
||||
// The black pixels draw in the fill color, in the bent shape.
|
||||
let mid = img.pixel(120, 97);
|
||||
assert!(mid[0] > 200 && mid[1] < 60 && mid[2] < 60, "the middle rose, red: {mid:?}");
|
||||
let inside = img.pixel(120, 120);
|
||||
assert!(inside[0] > 200 && inside[1] < 60 && inside[2] < 60, "red inside: {inside:?}");
|
||||
}
|
||||
|
||||
/// A selected embedded 2×2 image, 80×80 pt at (100, 100): a red column left of a blue one.
|
||||
fn two_color_image(s: &mut Session) -> NodeId {
|
||||
let img = image::RgbaImage::from_fn(2, 2, |x, _| if x == 0 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) });
|
||||
@@ -286,17 +315,18 @@ fn symbols_bend_with_the_envelope() {
|
||||
let e = arch(&mut s, 60.0, json!({}));
|
||||
let pts = anchors(&evaluated(&s, e));
|
||||
assert!(pts.iter().any(|p| p.y < 90.0), "the symbol's art rose in the middle");
|
||||
// Editing the symbol redraws the envelope (the renderer's cache follows the symbol's art).
|
||||
// Editing the symbol redraws the envelope (the renderer's cache follows the symbol's art). The
|
||||
// arch lifts the middle of the 100..200 box by about 51, so (200, 120) is inside it.
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
let region = Rect::new(0.0, 0.0, 400.0, 300.0);
|
||||
assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 150)[1] < 60);
|
||||
assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 120)[1] < 60);
|
||||
s.edit("edit symbol", |d, _| {
|
||||
let art = Node::path(NodeId(0), shapes::rectangle(Rect::new(-10.0, -10.0, -8.0, -8.0)), Default::default());
|
||||
d.symbols[0].art = Arc::new(art);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 150)[1] > 200);
|
||||
assert!(r.render_region(&s.doc().unwrap().doc, region, 1.0, true).pixel(200, 120)[1] > 200);
|
||||
}
|
||||
|
||||
fn strokes(nodes: &[Node]) -> usize {
|
||||
|
||||
@@ -161,7 +161,8 @@ fn an_exported_pdf_opens_with_its_file_info() {
|
||||
assert_eq!(back["description"], "A poster\nfor the fair");
|
||||
assert_eq!(back["keywords"], json!(["fair", "Poster", "print"]));
|
||||
assert!(back["created"].as_str().is_some_and(|c| c.ends_with('Z')), "the file's creation date: {}", back["created"]);
|
||||
assert_eq!(back["title"], "poster.pdf", "the title stays the file name");
|
||||
assert_eq!(back["title"], "Poster", "File Info shows the title the PDF carries");
|
||||
assert_eq!(s.doc().unwrap().title(), "poster.pdf", "the document stays named after the file");
|
||||
assert_eq!(back["copyrightStatus"], "copyrighted");
|
||||
assert_eq!(back["copyrightNotice"], "(c) 2026 Ada");
|
||||
assert_eq!(back["copyrightUrl"], "https://example.com/rights");
|
||||
@@ -277,6 +278,192 @@ fn a_pdf_compatible_ai_opens_with_the_file_info_of_its_xmp_packet() {
|
||||
assert_eq!(m.copyright_url, "");
|
||||
}
|
||||
|
||||
/// A one-page PDF whose trailer names an information dictionary with the entries `info`, and whose
|
||||
/// catalog has a metadata stream holding an XMP `dc:title` of `xmp_title`.
|
||||
fn pdf_titled(info: Option<&str>, xmp_title: Option<&str>) -> Vec<u8> {
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with_catalog};
|
||||
let first = first_extra(1);
|
||||
let mut objects = vec![];
|
||||
let mut catalog = String::new();
|
||||
if let Some(t) = xmp_title {
|
||||
let xmp = format!(
|
||||
"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\
|
||||
<rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\
|
||||
<dc:title><rdf:Alt><rdf:li xml:lang=\"de\">Zugangswege</rdf:li><rdf:li xml:lang=\"x-default\">{t}</rdf:li></rdf:Alt></dc:title>\
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"
|
||||
);
|
||||
objects.push(format!("<< /Type /Metadata /Subtype /XML /Length {} >>\nstream\n{xmp}\nendstream", xmp.len()));
|
||||
catalog = format!("/Metadata {first} 0 R ");
|
||||
}
|
||||
let info_at = first + objects.len();
|
||||
if let Some(i) = info {
|
||||
objects.push(format!("<< {i} >>"));
|
||||
}
|
||||
let refs: Vec<&str> = objects.iter().map(String::as_str).collect();
|
||||
let bytes = pdf_with_catalog(&[PdfPage::new(100.0, 100.0, "0 0 1 rg 10 10 50 50 re f")], &refs, &catalog, None);
|
||||
if info.is_none() {
|
||||
return bytes;
|
||||
}
|
||||
// The trailer follows the cross-reference table, so a longer trailer moves no object.
|
||||
String::from_utf8(bytes).unwrap().replacen("/Root 1 0 R", &format!("/Root 1 0 R /Info {info_at} 0 R"), 1).into_bytes()
|
||||
}
|
||||
|
||||
/// A document called `name` with content `bytes` opened (as `document.open` with no path: the tab
|
||||
/// shows the document's name), `s` holding it.
|
||||
fn open_named(s: &mut Session, name: &str, bytes: &[u8]) -> Value {
|
||||
s.execute("document.open", &json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap()
|
||||
}
|
||||
|
||||
/// The document's name (its tab) and its File Info title.
|
||||
fn titles(s: &mut Session) -> [String; 2] {
|
||||
let info = s.execute("file.info", &json!({})).unwrap();
|
||||
[s.doc().unwrap().title(), info["title"].as_str().unwrap().to_string()]
|
||||
}
|
||||
|
||||
/// What opening `bytes` as a file called `name` gives: the document's name and its File Info title.
|
||||
fn opened(name: &str, bytes: &[u8]) -> [String; 2] {
|
||||
let mut s = Session::new();
|
||||
let r = open_named(&mut s, name, bytes);
|
||||
let t = titles(&mut s);
|
||||
assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some(t[0].as_str()), Some(t[1].as_str())), "the open reply");
|
||||
assert_eq!(s.doc().unwrap().doc.title, t[0], "the tab is the document's title");
|
||||
t
|
||||
}
|
||||
|
||||
fn svg_titled(inner: &str) -> String {
|
||||
format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\">{inner}<rect width=\"5\" height=\"5\"><title>Tooltip</title></rect></svg>"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_puts_the_files_own_title_in_file_info_only() {
|
||||
// SVG: the root's `<title>`, its white space made single spaces (not a shape's tooltip), is the
|
||||
// File Info title; the document keeps the file's name, with its extension.
|
||||
assert_eq!(opened("box.svg", svg_titled("<title>\n Access\n paths </title>").as_bytes()), ["box.svg", "Access paths"]);
|
||||
assert_eq!(
|
||||
opened("/work/box.svg", svg_titled("<title>Zugangswege Rechenzentrum – Prüfdiagramm</title>").as_bytes()),
|
||||
["box.svg", "Zugangswege Rechenzentrum – Prüfdiagramm"]
|
||||
);
|
||||
// PDF: the XMP `dc:title` (its `x-default` item) beats the Info `Title`; the Info `Title` stands alone.
|
||||
assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Info title)"), Some("XMP title"))), ["plan.pdf", "XMP title"]);
|
||||
assert_eq!(opened("plan.pdf", &pdf_titled(None, Some("XMP title"))), ["plan.pdf", "XMP title"]);
|
||||
assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Info title)"), None)), ["plan.pdf", "Info title"]);
|
||||
assert_eq!(opened("plan.ai", &pdf_titled(Some("/Title (Info title)"), None)), ["plan.ai", "Info title"]);
|
||||
// Compressed SVG too.
|
||||
let svgz = |inner: &str| vectorcraft_svg::compress(&svg_titled(inner));
|
||||
assert_eq!(opened("box.svgz", &svgz("<title>Access paths</title>")), ["box.svgz", "Access paths"]);
|
||||
// A file that gives none (or a blank one) gives File Info the document's name.
|
||||
assert_eq!(opened("box.svg", svg_titled("").as_bytes()), ["box.svg", "box.svg"]);
|
||||
assert_eq!(opened("box.svg", svg_titled("<title> </title>").as_bytes()), ["box.svg", "box.svg"]);
|
||||
assert_eq!(opened("plan.pdf", &pdf_titled(None, None)), ["plan.pdf", "plan.pdf"]);
|
||||
assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Author (Ada)"), None)), ["plan.pdf", "plan.pdf"]);
|
||||
// The Untitled-N name New gives is no title (a document that never had one writes it).
|
||||
assert_eq!(opened("plan.pdf", &pdf_titled(Some("/Title (Untitled-2)"), None)), ["plan.pdf", "plan.pdf"]);
|
||||
// A template opens as a new untitled document, whatever title its file gave.
|
||||
let [name, info] = opened("plan.ait", &pdf_titled(Some("/Title (Info title)"), None));
|
||||
assert!(name.starts_with("Untitled-") && info == name, "{name} / {info}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imported_svg_titles_are_filtered_and_bounded() {
|
||||
for (raw, expected) in [
|
||||
("Untitled-2".to_string(), None),
|
||||
("\u{7f}".to_string(), None),
|
||||
("Re\u{7f}lease Plan".to_string(), Some("Release Plan".to_string())),
|
||||
("λ".repeat(65_537), Some("λ".repeat(65_536))),
|
||||
] {
|
||||
let svg = svg_titled(&format!("<title>{raw}</title>"));
|
||||
for format in ["svg", "svgz"] {
|
||||
let name = format!("box.{format}");
|
||||
let bytes = if format == "svgz" { vectorcraft_svg::compress(&svg) } else { svg.as_bytes().to_vec() };
|
||||
assert_eq!(opened(&name, &bytes), [name.clone(), expected.clone().unwrap_or(name)], "{format}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_a_title_opened_from_a_path_is_named_after_the_file() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-infotitle-open-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("box.svg");
|
||||
std::fs::write(&path, svg_titled("<title>Access paths</title>")).unwrap();
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("document.open", &json!({"path": path.to_str().unwrap()})).unwrap();
|
||||
assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some("box.svg"), Some("Access paths")));
|
||||
let r = s.execute("document.inspect", &json!({"depth": 0})).unwrap();
|
||||
assert_eq!((r["title"].as_str(), r["fileInfoTitle"].as_str()), (Some("box.svg"), Some("Access paths")));
|
||||
// The default names of what the document exports are made from the file's name, not its title.
|
||||
assert_eq!(s.doc().unwrap().doc.title, "box.svg");
|
||||
assert_eq!(crate::cmd::fileio::default_name(&s.doc().unwrap().doc, "png"), "box.png");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_info_edits_a_files_own_title_and_the_document_follows() {
|
||||
let mut s = Session::new();
|
||||
open_named(&mut s, "box.svg", svg_titled("<title>Access paths</title>").as_bytes());
|
||||
// The dialog sends back the title it was given: nothing changes (no undo step).
|
||||
let before = s.doc().unwrap().revision;
|
||||
let shown = s.execute("file.info", &json!({})).unwrap();
|
||||
s.execute("file.info", &shown).unwrap();
|
||||
assert_eq!(s.doc().unwrap().revision, before, "the title it gave is no edit");
|
||||
assert_eq!(titles(&mut s), ["box.svg", "Access paths"]);
|
||||
// Another title is the document's own, as ever, and the file's is gone.
|
||||
let r = s.execute("file.info", &json!({"title": "Plan B"})).unwrap();
|
||||
assert_eq!(r["title"], "Plan B");
|
||||
assert_eq!(titles(&mut s), ["Plan B", "Plan B"]);
|
||||
assert_eq!(s.doc().unwrap().doc.metadata.title, None);
|
||||
// Undo brings the file's title back, and the name.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(titles(&mut s), ["box.svg", "Access paths"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restored_file_info_title_keeps_authored_spaces() {
|
||||
let mut s = session();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).metadata.title = Some("Release Plan".into());
|
||||
for format in ["vectorcraft", "svg", "pdf"] {
|
||||
let bytes = b64(&s.execute("document.export", &json!({"format": format, "preserveEditing": true})).unwrap());
|
||||
let mut reopened = Session::new();
|
||||
let reply = open_named(&mut reopened, &format!("again.{format}"), &bytes);
|
||||
assert_eq!(reply["restored"], format != "vectorcraft", "{format}");
|
||||
assert_eq!(reopened.doc().unwrap().doc.metadata.title.as_deref(), Some("Release Plan"), "{format}");
|
||||
assert_eq!(titles(&mut reopened)[1], "Release Plan", "{format}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_files_own_title_is_kept_by_saves_and_written_by_exports() {
|
||||
let mut s = Session::new();
|
||||
open_named(&mut s, "box.svg", svg_titled("<title>Access paths</title>").as_bytes());
|
||||
// The native file: its own title is the document's name, the File Info title survives.
|
||||
let native = b64(&s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap());
|
||||
let mut t = Session::new();
|
||||
open_named(&mut t, "other.vectorcraft", &native);
|
||||
assert_eq!(titles(&mut t), ["box.svg", "Access paths"]);
|
||||
// An SVG with the editing data it carries, reopened under another name.
|
||||
let svg = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true, "metadata": true})).unwrap()["text"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(svg.contains("<title>Access paths</title>") && svg.contains("<dc:title>Access paths</dc:title>"), "{svg}");
|
||||
let mut u = Session::new();
|
||||
let r = open_named(&mut u, "again.svg", svg.as_bytes());
|
||||
assert_eq!(r["restored"], true);
|
||||
assert_eq!(titles(&mut u), ["again.svg", "Access paths"]);
|
||||
// PDF: the Info `Title` and the XMP `dc:title`, shown by the viewer.
|
||||
for pdf in pdf_texts(&mut s) {
|
||||
assert!(pdf.contains("/Title(Access paths)") && xmp_title(&pdf).contains("Access paths"), "{}", xmp_title(&pdf));
|
||||
assert!(pdf.contains("/ViewerPreferences<</DisplayDocTitle true>>"), "{pdf}");
|
||||
}
|
||||
// PNG text.
|
||||
let png = b64(&s.execute("document.export", &json!({"format": "png"})).unwrap());
|
||||
assert!(crate::cmd::fileio::pngtext::text(&png).iter().any(|(k, v)| k == "Title" && v == "Access paths"));
|
||||
// The default file names are made from the document's name.
|
||||
assert_eq!(crate::cmd::fileio::default_name(&s.doc().unwrap().doc, "pdf"), "box.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_exports_carry_text_chunks() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -194,6 +194,43 @@ fn a_search_finds_a_missing_fonts_file_by_its_names() {
|
||||
assert!(matches!(r["state"].as_str(), Some("stopped" | "done")), "{r}");
|
||||
}
|
||||
|
||||
/// A caller confined by read roots sees, in the replies to a search another caller started, only
|
||||
/// the files found inside its read roots, and the folder searched and a failed search's path only
|
||||
/// when they are inside them.
|
||||
#[test]
|
||||
fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() {
|
||||
let root = folder("read-roots");
|
||||
let font = vectorcraft_testkit::fonts::renamed("Findme Sans 3");
|
||||
let (home, wide) = (root.join("home"), root.join("lrf-wide"));
|
||||
for dir in [&home, &wide] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("Findme.otf"), &font).unwrap();
|
||||
}
|
||||
let mut s = session_for(&root);
|
||||
let roots = |read: &[&Path]| crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap();
|
||||
let (narrow, broad) = (roots(&[&home]), roots(&[&root]));
|
||||
let ask = |s: &mut Session, r: &Arc<crate::file_access::AutomationRoots>, p: Value| {
|
||||
crate::file_access::confine(Some(r), || s.execute("text.findFontFiles", &p).unwrap())
|
||||
};
|
||||
// A font no file has keeps the search going through every folder.
|
||||
let fonts = json!([{"family": "Findme Sans 3"}, {"family": "No Such Sans"}]);
|
||||
ask(&mut s, &broad, json!({"folder": root, "fonts": fonts}));
|
||||
finished(&mut s);
|
||||
let all = ask(&mut s, &broad, json!({}));
|
||||
assert_eq!((&all["fonts"][0]["files"], &all["folder"]), (&json!([home.join("Findme.otf"), wide.join("Findme.otf")]), &json!(root)), "{all}");
|
||||
for r in [ask(&mut s, &narrow, json!({})), ask(&mut s, &narrow, json!({"stop": true}))] {
|
||||
assert!(!r.to_string().contains("lrf-wide") && r.get("folder").is_none(), "{r}");
|
||||
assert_eq!((&r["fonts"][0]["files"], &r["fonts"][0]["family"]), (&json!([home.join("Findme.otf")]), &json!("Findme Sans 3")), "{r}");
|
||||
assert_eq!((&r["state"], &r["searched"], &r["id"]), (&all["state"], &all["searched"], &all["id"]), "{r}");
|
||||
}
|
||||
// A search that failed: the reason shows without the path to a caller outside its folder.
|
||||
ask(&mut s, &broad, json!({"folder": wide.join("gone"), "fonts": fonts}));
|
||||
assert!(finished(&mut s)["error"].as_str().is_some_and(|e| e.contains("lrf-wide")));
|
||||
let r = ask(&mut s, &narrow, json!({}));
|
||||
assert_eq!((r["state"].as_str(), r["error"].as_str(), r.get("folder")), (Some("failed"), Some("the folder can't be read"), None), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junk_search_params_never_fail_internally() {
|
||||
let root = folder("junk");
|
||||
|
||||
@@ -271,7 +271,7 @@ fn stop_ends_only_the_search_it_names() {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let search = findfiles::start(root.clone(), s.search_rules.clone(), Limits::default(), 1, 2, Arc::new(Blocked(Mutex::new(rx)))).unwrap();
|
||||
let links = vec![Sought { name: "a.png".into(), path: "/gone/a.png".into(), ids: vec![], size: None, hash: None }];
|
||||
s.link_search = Some(LinkSearch { id: 7, folder: root.to_string_lossy().into_owned(), links, sizes: Arc::default(), search });
|
||||
s.link_search = Some(LinkSearch { id: 7, folder: root.to_string_lossy().into_owned(), doc: None, links, sizes: Arc::default(), search });
|
||||
let until = Instant::now() + WAIT;
|
||||
while s.execute("links.findFiles", &json!({})).unwrap()["searched"]["read"] != 1 && Instant::now() < until {
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
@@ -284,6 +284,116 @@ fn stop_ends_only_the_search_it_names() {
|
||||
drop(tx);
|
||||
}
|
||||
|
||||
/// A caller confined by read roots sees, in the replies to a search another caller started and to
|
||||
/// its own, only the paths inside its read roots: the files found outside them, a link's saved path
|
||||
/// outside them and the folder searched are left out, and the rows, ids and counts stay. Without
|
||||
/// roots, the replies are as before.
|
||||
#[test]
|
||||
fn a_search_shows_a_confined_caller_only_paths_inside_its_read_roots() {
|
||||
let root = folder("read-roots");
|
||||
let mut s = session_for(&root);
|
||||
let photo = png(40, 30, RED);
|
||||
write(&root.join("lrf-away/photo.png"), &photo);
|
||||
let id = placed(&mut s, &root.join("lrf-away/photo.png"));
|
||||
std::fs::remove_file(root.join("lrf-away/photo.png")).unwrap();
|
||||
// Files of the name with other contents: the search reads every folder.
|
||||
let other = png(40, 30, BLUE);
|
||||
let (home, wide) = (root.join("home"), root.join("lrf-wide"));
|
||||
write(&home.join("photo.png"), &other);
|
||||
write(&wide.join("photo.png"), &other);
|
||||
let roots = |read: &[&Path], write: &[&Path]| crate::file_access::AutomationRoots::new(read, write).unwrap().unwrap();
|
||||
let (narrow, write_only, broad) = (roots(&[&home], &[]), roots(&[], &[&root]), roots(&[&root], &[]));
|
||||
let ask = |s: &mut Session, r: &Arc<crate::file_access::AutomationRoots>, p: Value| {
|
||||
crate::file_access::confine(Some(r), || s.execute("links.findFiles", &p).unwrap())
|
||||
};
|
||||
let hidden = |r: &Value| {
|
||||
let text = r.to_string();
|
||||
assert!(!text.contains("lrf-away") && !text.contains("lrf-wide") && r.get("folder").is_none(), "{r}");
|
||||
let row = &r["links"][0];
|
||||
assert_eq!((row["name"].as_str(), &row["ids"], row.get("path")), (Some("photo.png"), &json!([id]), None), "{r}");
|
||||
};
|
||||
// Started with the broad roots, over the whole folder.
|
||||
let r = ask(&mut s, &broad, json!({"folder": root}));
|
||||
assert_eq!(r["folder"], json!(root), "{r}");
|
||||
finished(&mut s);
|
||||
let all = ask(&mut s, &broad, json!({}));
|
||||
assert_eq!(all["links"][0]["files"].as_array().map(Vec::len), Some(2), "{all}");
|
||||
for r in [ask(&mut s, &narrow, json!({})), ask(&mut s, &narrow, json!({"stop": true}))] {
|
||||
hidden(&r);
|
||||
assert_eq!(r["links"][0]["files"], json!([{"path": home.join("photo.png"), "size": other.len(), "match": "name"}]), "{r}");
|
||||
assert_eq!((&r["state"], &r["searched"], &r["id"]), (&all["state"], &all["searched"], &all["id"]), "{r}");
|
||||
}
|
||||
let r = ask(&mut s, &write_only, json!({}));
|
||||
hidden(&r);
|
||||
assert_eq!(r["links"][0]["files"], json!([]), "{r}");
|
||||
// Without roots, every path shows.
|
||||
let r = s.execute("links.findFiles", &json!({})).unwrap();
|
||||
assert_eq!((&r["folder"], &r["links"][0]["path"]), (&json!(root), &json!(root.join("lrf-away/photo.png"))), "{r}");
|
||||
assert_eq!(r["links"][0]["files"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
// The narrow caller's own search shows the folder it gave.
|
||||
let r = ask(&mut s, &narrow, json!({"folder": home}));
|
||||
assert_eq!(r["folder"], json!(home), "{r}");
|
||||
finished(&mut s);
|
||||
let r = ask(&mut s, &narrow, json!({}));
|
||||
assert_eq!((&r["folder"], r["links"][0].get("path")), (&json!(home), None), "{r}");
|
||||
// A search that failed: the reason shows without the path to a caller outside its folder.
|
||||
ask(&mut s, &broad, json!({"folder": root.join("lrf-wide/gone")}));
|
||||
let r = finished(&mut s);
|
||||
assert!(r["error"].as_str().is_some_and(|e| e.contains("lrf-wide")), "{r}");
|
||||
let r = ask(&mut s, &narrow, json!({}));
|
||||
assert_eq!((r["state"].as_str(), r["error"].as_str()), (Some("failed"), Some("the folder can't be read")), "{r}");
|
||||
hidden(&r);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A link's saved path relative to the document is shown to a confined caller when it leads to a
|
||||
/// file inside its read roots, and left out when `..` leads out of them.
|
||||
#[test]
|
||||
fn a_relative_link_path_is_judged_from_the_documents_folder() {
|
||||
let root = folder("read-roots-relative");
|
||||
let mut s = session_for(&root);
|
||||
let home = root.join("home");
|
||||
write(&root.join("lrf-away/photo.png"), &png(40, 30, RED));
|
||||
let id = placed(&mut s, &root.join("lrf-away/photo.png"));
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
s.execute("document.save", &json!({"path": home.join("poster.vectorcraft")})).unwrap();
|
||||
let narrow = crate::file_access::AutomationRoots::new(&[&home], &[]).unwrap().unwrap();
|
||||
for (saved, shown) in [("sub/photo.png", true), ("../lrf-away/photo.png", false)] {
|
||||
s.edit("relative path", |d, _| {
|
||||
if let NodeKind::Image(im) = &mut d.node_mut(NodeId(id)).unwrap().kind {
|
||||
im.link.as_mut().unwrap().path = saved.into();
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = crate::file_access::confine(Some(&narrow), || s.execute("links.findFiles", &json!({"folder": home, "ids": [id]})).unwrap());
|
||||
assert_eq!(r["links"][0].get("path"), shown.then(|| json!(saved)).as_ref(), "{saved}: {r}");
|
||||
finished(&mut s);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// `image.info` leaves a linked file outside the confined caller's read roots unnamed (`link`
|
||||
/// null), as `links.info` leaves it out, and keeps the other fields.
|
||||
#[test]
|
||||
fn image_info_leaves_out_a_link_outside_the_read_roots() {
|
||||
let root = folder("read-roots-info");
|
||||
let mut s = session_for(&root);
|
||||
let pic = root.join("lrf-away/photo.png");
|
||||
write(&pic, &png(40, 30, RED));
|
||||
let id = placed(&mut s, &pic);
|
||||
std::fs::create_dir_all(root.join("home")).unwrap();
|
||||
let narrow = crate::file_access::AutomationRoots::new(&[&root.join("home")], &[]).unwrap().unwrap();
|
||||
let ask = |s: &mut Session, cmd: &str| crate::file_access::confine(Some(&narrow), || s.execute(cmd, &json!({"id": id})).unwrap());
|
||||
let r = ask(&mut s, "image.info");
|
||||
assert_eq!((&r["link"], &r["linked"], &r["pixelWidth"], &r["id"]), (&Value::Null, &json!(true), &json!(40), &json!(id)), "{r}");
|
||||
assert!(!r.to_string().contains("lrf-away"), "{r}");
|
||||
let info = ask(&mut s, "links.info");
|
||||
assert!(info.get("link").is_none() && !info.to_string().contains("lrf-away"), "{info}");
|
||||
assert_eq!(s.execute("image.info", &json!({"id": id})).unwrap()["link"], json!(pic));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relinking_with_copy_puts_the_file_in_the_documents_folder() {
|
||||
let root = folder("copy");
|
||||
|
||||
@@ -570,8 +570,8 @@ fn envelope_warp_make_and_content_stays_inside_bounds() {
|
||||
let pts = all_anchors(&out);
|
||||
assert!(pts.len() > 4, "curves are subdivided");
|
||||
assert!(pts.iter().all(|p| b.contains(*p)), "{b:?}");
|
||||
// It really is bent: the sides moved down.
|
||||
assert!(pts.iter().any(|p| p.y > 201.0));
|
||||
// It really is bent: the top corners swung out past the sides.
|
||||
assert!(pts.iter().any(|p| p.x < 99.0) && pts.iter().any(|p| p.x > 301.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -184,6 +184,184 @@ fn a_flip_round_a_closed_path_keeps_the_type_in_place() {
|
||||
assert!(origins(&s, id)[0].distance(first) < 8.0);
|
||||
}
|
||||
|
||||
/// A circle of radius 100 round (200, 200), starting at 9 o'clock and running clockwise, with
|
||||
/// type on it from its start.
|
||||
fn on_circle(s: &mut Session, text: &str) -> NodeId {
|
||||
path_type(s, "M100 200 A100 100 0 1 1 300 200 A100 100 0 1 1 100 200 Z", [90.0, 200.0], text)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_on_top_and_bottom_of_a_circle() {
|
||||
let mut s = session();
|
||||
let id = on_circle(&mut s, "OOOO");
|
||||
assert!(near(brackets(&s, id).0, 0.0), "{:?}", brackets(&s, id));
|
||||
let steps = undo_len(&s);
|
||||
let r = s.execute("type.pathCenter.top", &json!({})).unwrap();
|
||||
// Once round, its middle at 12 o'clock, a quarter of the way round: the type sits on the top, centered.
|
||||
let (start, end) = brackets(&s, id);
|
||||
assert!(near(start, 0.75) && end.is_none(), "{start} {end:?}");
|
||||
assert_eq!((r["ids"].clone(), r["end"].clone()), (json!([id.0]), Value::Null));
|
||||
assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::Center);
|
||||
let top = ink(&s, id);
|
||||
assert!((top.center().x - 200.0).abs() < 0.5 && top.y1 < 101.0, "{top:?}");
|
||||
assert_eq!((undo_len(&s), last_step(&s)), (steps + 1, "Center on Top".to_string()));
|
||||
// Again: nothing moves, and no undo step is recorded.
|
||||
s.execute("type.pathCenter.top", &json!({})).unwrap();
|
||||
assert_eq!(undo_len(&s), steps + 1);
|
||||
// The bottom: 6 o'clock, outside the circle (the type is not flipped).
|
||||
s.execute("type.pathCenter.bottom", &json!({})).unwrap();
|
||||
let (start, end) = brackets(&s, id);
|
||||
assert!(near(start, 0.25) && end.is_none(), "{start} {end:?}");
|
||||
let bottom = ink(&s, id);
|
||||
assert!((bottom.center().x - 200.0).abs() < 0.5 && bottom.y0 > 299.0, "{bottom:?}");
|
||||
assert_eq!((undo_len(&s), last_step(&s)), (steps + 2, "Center on Bottom".to_string()));
|
||||
// Justify Center stays as it is.
|
||||
s.execute("text.setStyle", &json!({"justify": "justifyCenter"})).unwrap();
|
||||
s.execute("type.pathCenter.top", &json!({})).unwrap();
|
||||
assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::JustifyCenter);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(near(brackets(&s, id).0, 0.25));
|
||||
// Brackets already in place with another alignment: only the alignment changes, in one step.
|
||||
s.execute("text.setStyle", &json!({"justify": "left"})).unwrap();
|
||||
let (steps, before) = (undo_len(&s), brackets(&s, id));
|
||||
s.execute("type.pathCenter.bottom", &json!({})).unwrap();
|
||||
assert_eq!((undo_len(&s), brackets(&s, id)), (steps + 1, before));
|
||||
assert_eq!(text(&s, id).para_at(0).justify, vectorcraft_doc::Justify::Center);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_on_top_twice_records_one_step_for_any_span() {
|
||||
let mut s = session();
|
||||
let id = on_circle(&mut s, "OOOO");
|
||||
for (start, end) in [(0.0, 0.2), (0.13, 0.41), (0.37, 0.52), (0.61, 0.97), (0.89, 0.07), (0.3, 0.3001)] {
|
||||
s.execute("type.pathOptions", &json!({"start": start, "end": end})).unwrap();
|
||||
for c in ["type.pathCenter.top", "type.pathCenter.bottom"] {
|
||||
s.execute(c, &json!({})).unwrap();
|
||||
let (steps, placed) = (undo_len(&s), brackets(&s, id));
|
||||
// Again: the brackets stay exactly where they are, and no undo step is recorded.
|
||||
s.execute(c, &json!({})).unwrap();
|
||||
assert_eq!((undo_len(&s), brackets(&s, id)), (steps, placed), "{c} {start} {end}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_on_top_keeps_the_span_and_measures_the_path_as_drawn() {
|
||||
let mut s = session();
|
||||
let id = on_circle(&mut s, "OOOO");
|
||||
// A span of a fifth of the path keeps its length.
|
||||
s.execute("type.pathOptions", &json!({"end": 0.2})).unwrap();
|
||||
s.execute("type.pathCenter.top", &json!({})).unwrap();
|
||||
let (start, end) = brackets(&s, id);
|
||||
assert!(near(start, 0.15) && end.is_some_and(|e| near(e, 0.35)), "{start} {end:?}");
|
||||
// Turned a quarter turn counter-clockwise, its 3 o'clock point, halfway round, is at the top.
|
||||
s.execute("type.pathOptions", &json!({"start": 0, "end": null})).unwrap();
|
||||
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
|
||||
s.execute("type.pathCenter.top", &json!({})).unwrap();
|
||||
let (start, _) = brackets(&s, id);
|
||||
assert!(near(start.rem_euclid(1.0), 0.0) || near(start, 1.0), "{start}");
|
||||
let bounds = text(&s, id).bounds().unwrap();
|
||||
let top = ink(&s, id);
|
||||
assert!((top.center().x - bounds.center().x).abs() < 0.5 && top.y1 < bounds.y0 + 1.0, "{top:?} {bounds:?}");
|
||||
// A rectangle: the middle of its top edge.
|
||||
let id = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [90.0, 100.0], "OOOO");
|
||||
s.execute("type.pathCenter.top", &json!({})).unwrap();
|
||||
let (start, end) = brackets(&s, id);
|
||||
assert!(near(start, 0.625) && end.is_none(), "{start} {end:?}");
|
||||
assert!((ink(&s, id).center().x - 200.0).abs() < 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_on_top_moves_every_selected_type_on_a_path_in_one_step() {
|
||||
let mut s = session();
|
||||
let a = on_circle(&mut s, "OOOO");
|
||||
let b = path_type(&mut s, "M100 100 L300 100 L300 300 L100 300 Z", [90.0, 100.0], "OOOO");
|
||||
let p = s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Point"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0, p]})).unwrap();
|
||||
let steps = undo_len(&s);
|
||||
let r = s.execute("type.pathCenter.top", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"], json!([a.0, b.0]));
|
||||
assert!(near(brackets(&s, a).0, 0.75) && near(brackets(&s, b).0, 0.625));
|
||||
assert_eq!(undo_len(&s), steps + 1);
|
||||
// Dynamic Text stays on, and the layout fits the text to the span where it now runs: a fifth of
|
||||
// the circle, at its bottom.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("type.pathOptions", &json!({"start": 0, "end": 0.2})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
s.execute("type.pathCenter.bottom", &json!({})).unwrap();
|
||||
assert!(text(&s, a).dynamic_text && near(brackets(&s, a).0, 0.65), "{:?}", brackets(&s, a));
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, a));
|
||||
assert!(lay.fit_scale > 1.5 && !lay.overflow, "{}", lay.fit_scale);
|
||||
let bottom = ink(&s, a);
|
||||
assert!((bottom.center().x - 200.0).abs() < 1.0 && bottom.y1 > 300.0, "{bottom:?}");
|
||||
// Vertical type on a path moves the same way.
|
||||
s.execute("type.pathOptions", &json!({"start": 0, "end": null})).unwrap();
|
||||
s.execute("type.orientation.vertical", &json!({})).unwrap();
|
||||
s.execute("type.pathCenter.top", &json!({})).unwrap();
|
||||
assert!(near(brackets(&s, a).0, 0.75));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn center_on_top_refuses_open_compound_and_threaded_type() {
|
||||
let mut s = session();
|
||||
let circle = on_circle(&mut s, "OOOO");
|
||||
let line = on_line(&mut s);
|
||||
s.execute("select.set", &json!({"ids": [circle.0, line.0]})).unwrap();
|
||||
let steps = undo_len(&s);
|
||||
let before = brackets(&s, circle);
|
||||
let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("type on an open or compound path cannot be centered on its top or bottom") && e.ends_with(&line.0.to_string()), "{e}");
|
||||
// Nothing changes, the type on the circle included, and the same holds for an explicit list.
|
||||
assert_eq!((undo_len(&s), brackets(&s, circle)), (steps, before));
|
||||
let e = s.execute("type.pathCenter.bottom", &json!({"ids": [circle.0, line.0]})).unwrap_err().to_string();
|
||||
assert!(e.contains("open or compound path") && e.ends_with(&line.0.to_string()), "{e}");
|
||||
s.execute("select.set", &json!({"ids": [circle.0]})).unwrap();
|
||||
for bad in [json!({"ids": "all"}), json!({"ids": [999_999]})] {
|
||||
assert!(s.execute("type.pathCenter.top", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(undo_len(&s), steps);
|
||||
// Two circles side by side in one path: a compound path.
|
||||
let pair = path_type(
|
||||
&mut s,
|
||||
"M100 450 A40 40 0 1 1 180 450 A40 40 0 1 1 100 450 Z M300 450 A40 40 0 1 1 380 450 A40 40 0 1 1 300 450 Z",
|
||||
[90.0, 450.0],
|
||||
"OOOO",
|
||||
);
|
||||
let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("open or compound path") && e.ends_with(&pair.0.to_string()), "{e}");
|
||||
// A closed path that is level all round has no height.
|
||||
let flat = path_type(&mut s, "M100 400 L300 400 Z", [90.0, 400.0], "OOOO");
|
||||
let e = s.execute("type.pathCenter.top", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("type on a path with no length or no height cannot be centered") && e.ends_with(&flat.0.to_string()), "{e}");
|
||||
// A frame of a thread is refused, alone or with other type on a closed path.
|
||||
let threaded = on_circle(&mut s, "Threaded story");
|
||||
let frame = s.execute("shape.rectangle", &json!({"x": 400, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [threaded.0, frame]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [threaded.0]})).unwrap();
|
||||
let before = brackets(&s, threaded);
|
||||
for ids in [json!([threaded.0]), json!([circle.0, threaded.0])] {
|
||||
let steps = undo_len(&s);
|
||||
let e = s.execute("type.pathCenter.top", &json!({ "ids": ids })).unwrap_err().to_string();
|
||||
assert!(e.contains("type on a path in a thread cannot be centered on its top or bottom") && e.ends_with(&threaded.0.to_string()), "{e}");
|
||||
assert_eq!((undo_len(&s), brackets(&s, threaded)), (steps, before));
|
||||
}
|
||||
// Without type on one closed path selected, the commands are not available.
|
||||
let p = s.execute("text.create", &json!({"x": 40, "y": 40, "text": "Point"})).unwrap()["id"].as_u64().unwrap();
|
||||
for (ids, why) in [
|
||||
(json!([p]), "select type on a closed path"),
|
||||
(json!([line.0]), "open or compound path"),
|
||||
(json!([circle.0, line.0]), "open or compound path"),
|
||||
(json!([threaded.0]), "in a thread"),
|
||||
] {
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
for c in ["type.pathCenter.top", "type.pathCenter.bottom"] {
|
||||
let e = s.execute(c, &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains(why), "{c} {ids}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_to_path_and_spacing() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -234,3 +234,160 @@ fn a_marquee_that_touches_only_a_drop_shadow_does_not_select_its_object() {
|
||||
// From above B, over B and the shadow: B only.
|
||||
assert_eq!(press(&mut s, "selection", (105.0, 5.0), (115.0, 30.0), Mods::default()), [b]);
|
||||
}
|
||||
|
||||
/// The selection after a drag with `tool` from `from` to `to`.
|
||||
fn marquee(s: &mut Session, tool: &str, from: (f64, f64), to: (f64, f64)) -> vectorcraft_doc::Selection {
|
||||
press(s, tool, from, to, Mods::default());
|
||||
s.doc().unwrap().selection.clone()
|
||||
}
|
||||
|
||||
/// The point of anchor `(si, ai)` of path `id`.
|
||||
fn anchor_point(s: &Session, id: NodeId, (si, ai): vectorcraft_doc::AnchorRef) -> Point {
|
||||
let path = s.doc().unwrap().doc.node(id).and_then(|n| n.path_data()).unwrap();
|
||||
path.anchors().find(|(s, i, _)| (*s, *i) == (si, ai)).map(|(.., a)| a.p).unwrap()
|
||||
}
|
||||
|
||||
/// The anchors a marquee or a click picked on `id`, as points.
|
||||
fn picked_points(s: &Session, id: NodeId) -> Vec<Point> {
|
||||
let refs: Vec<_> = s.doc().unwrap().selection.partial(id).into_iter().flatten().copied().collect();
|
||||
refs.into_iter().map(|r| anchor_point(s, id, r)).collect()
|
||||
}
|
||||
|
||||
/// The anchors the tool marks as hovered.
|
||||
fn anchor_marks(s: &mut Session) -> Vec<Point> {
|
||||
s.overlays(ViewInfo::default())
|
||||
.into_iter()
|
||||
.filter_map(|o| if let vectorcraft_tools::Overlay::Anchor { p, .. } = o { Some(p) } else { None })
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hover(s: &mut Session, x: f64, y: f64) -> Cursor {
|
||||
let v = ViewInfo::default();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, x, y), v).unwrap();
|
||||
s.cursor(Point::new(x, y), Mods::default(), v)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direct_selection_marquee_leaves_out_a_drop_shadow() {
|
||||
let mut s = session();
|
||||
let (a, b) = shadow_over_b(&mut s);
|
||||
let (a_before, b_before) = (bounds(&s, a), bounds(&s, b));
|
||||
assert_ne!(pixel(&s, 90, 50), WHITE);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
// Over the shadow alone: no object, no anchor, no segment.
|
||||
let sel = marquee(&mut s, "directSelection", (85.0, 40.0), (95.0, 60.0));
|
||||
assert!(sel.objects.is_empty() && sel.anchors.is_empty() && sel.segments.is_empty(), "{sel:?}");
|
||||
// Over the shadow and B's upper left corner: that anchor of B, and nothing of A.
|
||||
let sel = marquee(&mut s, "directSelection", (90.0, 5.0), (105.0, 30.0));
|
||||
assert_eq!(sel.objects, [b]);
|
||||
assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]);
|
||||
// Across B's top edge under the shadow, with neither of its anchors inside: that segment.
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_ne!(pixel(&s, 112, 25), BLUE);
|
||||
let sel = marquee(&mut s, "directSelection", (110.0, 5.0), (115.0, 30.0));
|
||||
assert_eq!(sel.objects, [b]);
|
||||
assert!(sel.segments.contains_key(&b) && !sel.segments.contains_key(&a), "{sel:?}");
|
||||
assert_eq!((bounds(&s, a), bounds(&s, b)), (a_before, b_before));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_selection_hover_leaves_out_a_drop_shadow_and_marks_the_anchor_under_it() {
|
||||
let mut s = session();
|
||||
let (_, b) = shadow_over_b(&mut s);
|
||||
// B's upper left corner lies under the shadow.
|
||||
assert_ne!(pixel(&s, 101, 21), BLUE);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("directSelection", ViewInfo::default()).unwrap();
|
||||
for (x, y) in [(90.0, 50.0), (110.0, 50.0)] {
|
||||
assert_eq!(hover(&mut s, x, y), Cursor::ArrowHollow, "({x}, {y})");
|
||||
assert!(anchor_marks(&mut s).is_empty(), "({x}, {y})");
|
||||
}
|
||||
assert_eq!(hover(&mut s, 101.0, 21.0), Cursor::DirectAnchor);
|
||||
assert_eq!(anchor_marks(&mut s), [Point::new(100.0, 20.0)]);
|
||||
// A press there picks that anchor of B.
|
||||
assert_eq!(press(&mut s, "directSelection", (101.0, 21.0), (101.0, 21.0), Mods::default()), [b]);
|
||||
assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_selection_click_on_a_drop_shadow_selects_the_object_under_it() {
|
||||
let mut s = session();
|
||||
let (a, b) = shadow_over_b(&mut s);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]);
|
||||
assert!(press(&mut s, "groupSelection", (90.0, 50.0), (90.0, 50.0), Mods::default()).is_empty());
|
||||
assert_eq!(press(&mut s, "groupSelection", (50.0, 50.0), (50.0, 50.0), Mods::default()), [a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_selection_clicks_on_a_drop_shadow_climb_the_groups_of_the_object_under_it() {
|
||||
let mut s = session();
|
||||
// B and C in one group, A and D in another above it, and A's shadow over B.
|
||||
let b = rect(&mut s, 100.0, 20.0, 60.0, 60.0, "#0000ff");
|
||||
let c = rect(&mut s, 170.0, 20.0, 20.0, 20.0, "#0000ff");
|
||||
run(&mut s, "select.set", json!({"ids": [b.0, c.0]}));
|
||||
let gb = id_of(&run(&mut s, "object.group", json!({})));
|
||||
let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0, "#ff0000");
|
||||
let d = rect(&mut s, 20.0, 120.0, 20.0, 20.0, "#ff0000");
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, d.0]}));
|
||||
let ga = id_of(&run(&mut s, "object.group", json!({})));
|
||||
shadow(&mut s, a, 40.0);
|
||||
assert_ne!(pixel(&s, 110, 50), BLUE);
|
||||
assert_ne!(pixel(&s, 90, 50), WHITE);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let click = |s: &mut Session, x, y| {
|
||||
let mut sel = press(s, "groupSelection", (x, y), (x, y), Mods::default());
|
||||
sel.sort_by_key(|n| n.0);
|
||||
sel
|
||||
};
|
||||
assert_eq!(click(&mut s, 110.0, 50.0), [b]);
|
||||
let mut both = vec![b, gb];
|
||||
both.sort_by_key(|n| n.0);
|
||||
assert_eq!(click(&mut s, 110.0, 50.0), both);
|
||||
// With A selected, a click on its shadow over the canvas does not add A's group.
|
||||
run(&mut s, "select.set", json!({"ids": [a.0]}));
|
||||
assert!(click(&mut s, 90.0, 50.0).is_empty());
|
||||
// On A itself the second click adds it.
|
||||
assert_eq!(click(&mut s, 50.0, 50.0), [a]);
|
||||
let mut both = vec![a, ga];
|
||||
both.sort_by_key(|n| n.0);
|
||||
assert_eq!(click(&mut s, 50.0, 50.0), both);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_selection_marquee_leaves_out_a_drop_shadow() {
|
||||
let mut s = session();
|
||||
let (a, b) = shadow_over_b(&mut s);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let sel = marquee(&mut s, "groupSelection", (85.0, 40.0), (95.0, 60.0));
|
||||
assert!(sel.objects.is_empty() && sel.anchors.is_empty(), "{sel:?}");
|
||||
// Over the shadow and B's upper left corner: that anchor of B.
|
||||
let sel = marquee(&mut s, "groupSelection", (90.0, 5.0), (105.0, 30.0));
|
||||
assert_eq!(sel.objects, [b]);
|
||||
assert_eq!(picked_points(&s, b), [Point::new(100.0, 20.0)]);
|
||||
// With E, a marquee around B that crosses A's shadow selects B whole, and not A.
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("groupSelection", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 95.0, 10.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 50.0), v).unwrap();
|
||||
s.tool_key(vectorcraft_tools::ToolKey::Letter('e'), Mods::default(), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 165.0, 90.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 165.0, 90.0), v).unwrap();
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert_eq!(sel.objects, [b]);
|
||||
assert!(sel.partial(b).is_none() && sel.partial(a).is_none(), "{sel:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_selection_hover_over_a_drop_shadow_marks_nothing() {
|
||||
let mut s = session();
|
||||
let (_, b) = shadow_over_b(&mut s);
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("groupSelection", ViewInfo::default()).unwrap();
|
||||
for (x, y) in [(90.0, 50.0), (110.0, 50.0), (101.0, 21.0)] {
|
||||
assert_eq!(hover(&mut s, x, y), Cursor::GroupSelection, "({x}, {y})");
|
||||
assert!(anchor_marks(&mut s).is_empty(), "({x}, {y})");
|
||||
}
|
||||
assert_eq!(press(&mut s, "groupSelection", (110.0, 50.0), (110.0, 50.0), Mods::default()), [b]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
//! Effect › Warp on placed images: the pixels bend with the frame, in the canvas and in exports.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::live::{WarpNet, WarpStyle, uses_net, warp_version};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// The box of the image [`quarters`] places.
|
||||
const FRAME: Rect = Rect::new(100.0, 100.0, 180.0, 180.0);
|
||||
|
||||
/// The color of the quarter of the image [`quarters`] places that holds (u, v) of its box: red top
|
||||
/// left, green top right, blue bottom left, yellow bottom right.
|
||||
fn quarter(u: f64, v: f64) -> [u8; 3] {
|
||||
match (u < 0.5, v < 0.5) {
|
||||
(true, true) => [255, 0, 0],
|
||||
(false, true) => [0, 255, 0],
|
||||
(true, false) => [0, 0, 255],
|
||||
(false, false) => [255, 255, 0],
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected embedded 40×40 px image filling [`FRAME`], each quarter one color ([`quarter`]).
|
||||
fn quarters(s: &mut Session) -> NodeId {
|
||||
let img = image::RgbaImage::from_fn(40, 40, |x, y| {
|
||||
let [r, g, b] = quarter(x as f64 / 40.0, y as f64 / 40.0);
|
||||
image::Rgba([r, g, b, 255])
|
||||
});
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
s.edit("Place", |d, sel| {
|
||||
d.images.insert("quarters".into(), vectorcraft_doc::ImageBlob::png(png));
|
||||
let id = d.alloc_id();
|
||||
let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0);
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "quarters".into(),
|
||||
width: 40,
|
||||
height: 40,
|
||||
xf,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Where an Arc warp bending `bend` % takes the point at (u, v) of [`FRAME`].
|
||||
fn arced(bend: f64, u: f64, v: f64) -> Point {
|
||||
let net = WarpNet::new(WarpStyle::Arc, bend / 100.0, 0.0, 0.0, FRAME.width(), FRAME.height(), false);
|
||||
FRAME.origin() + net.at(u, v).to_vec2()
|
||||
}
|
||||
|
||||
/// Points of the image's box: near each quarter's middle and on both sides of the line between
|
||||
/// the top and bottom quarters, where a warp that moves the pixels up or down changes the color.
|
||||
const SAMPLES: [(f64, f64); 10] =
|
||||
[(0.2, 0.2), (0.8, 0.2), (0.2, 0.8), (0.8, 0.8), (0.4, 0.4), (0.6, 0.4), (0.4, 0.6), (0.6, 0.6), (0.3, 0.62), (0.7, 0.62)];
|
||||
|
||||
/// The document drawn over (0, 0)–(400, 400) at one pixel a point, on white.
|
||||
fn drawn(s: &Session) -> vectorcraft_render::Rendered {
|
||||
vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 400.0, 400.0), 1.0, true)
|
||||
}
|
||||
|
||||
/// The sample points whose color in `img` at `at(u, v)` is not the image's color at (u, v).
|
||||
fn wrong(img: &vectorcraft_render::Rendered, at: &dyn Fn(f64, f64) -> Point) -> Vec<(f64, f64, [u8; 4])> {
|
||||
SAMPLES
|
||||
.iter()
|
||||
.filter_map(|&(u, v)| {
|
||||
let p = at(u, v);
|
||||
let px = img.pixel(p.x.floor() as u32, p.y.floor() as u32);
|
||||
let want = quarter(u, v);
|
||||
let near = (0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40);
|
||||
(!near).then_some((u, v, px))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `quarters` with Effect › Warp › Arc at 50 %: the warp the effect holds, checked to be the
|
||||
/// Bézier patch [`arced`] follows.
|
||||
fn arc_image(s: &mut Session) -> NodeId {
|
||||
let id = quarters(s);
|
||||
s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let e = &n.appearance.effects[0];
|
||||
assert!(warp_version(&e.params["version"]).is_some_and(uses_net), "{}", e.params);
|
||||
id
|
||||
}
|
||||
|
||||
fn decoded(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_images_pixels_bend_with_effect_warp() {
|
||||
let mut s = session();
|
||||
let id = arc_image(&mut s);
|
||||
// The arc lifts the middle of the image: the line between the quarters rises there.
|
||||
assert!(arced(50.0, 0.5, 0.6).y < FRAME.y0 + 0.5 * FRAME.height(), "{:?}", arced(50.0, 0.5, 0.6));
|
||||
let bent = drawn(&s);
|
||||
assert_eq!(wrong(&bent, &|u, v| arced(50.0, u, v)), vec![], "each pixel is drawn where the warp takes it");
|
||||
// Drawn as pieces of the one image, each placed by the warp.
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let art = vectorcraft_render::effects::reshape(Some(d), d.node(id).unwrap(), None).unwrap();
|
||||
let mut pieces = 0;
|
||||
art.walk(&mut |c| pieces += matches!(c.kind, NodeKind::Image(_)) as usize);
|
||||
assert!(pieces >= 100, "{pieces} pieces");
|
||||
// Removing the warp draws the image as it was, in one undo step.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("effect.remove", &json!({"index": 0})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
let plain = |u: f64, v: f64| Point::new(FRAME.x0 + u * FRAME.width(), FRAME.y0 + v * FRAME.height());
|
||||
assert_eq!(wrong(&drawn(&s), &plain), vec![]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![], "undo brings the bend back");
|
||||
}
|
||||
|
||||
/// `out`, an export of [`arc_image`]'s document named `name`, opened again: it draws the image
|
||||
/// bent.
|
||||
fn opens_bent(name: &str, out: &Value) {
|
||||
let mut back = session();
|
||||
back.execute("document.open", &json!({"name": name, "dataBase64": out["dataBase64"]})).unwrap();
|
||||
assert_eq!(wrong(&drawn(&back), &|u, v| arced(50.0, u, v)), vec![], "{name}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warped_image_keeps_its_bend_in_svg() {
|
||||
let mut s = session();
|
||||
arc_image(&mut s);
|
||||
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
|
||||
let text = String::from_utf8(decoded(&svg)).unwrap();
|
||||
assert_eq!(text.matches("<image").count(), 1, "the pieces share the image's pixels");
|
||||
opens_bent("warped.svg", &svg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warped_image_keeps_its_bend_in_pdf() {
|
||||
let mut s = session();
|
||||
arc_image(&mut s);
|
||||
opens_bent("warped.pdf", &s.execute("document.export", &json!({"format": "pdf", "preserveEditing": false})).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warped_image_keeps_its_bend_in_ai() {
|
||||
let mut s = session();
|
||||
arc_image(&mut s);
|
||||
opens_bent("warped.ai", &s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warped_image_keeps_its_bend_in_eps() {
|
||||
let mut s = session();
|
||||
arc_image(&mut s);
|
||||
opens_bent("warped.eps", &s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warped_image_keeps_its_bend_in_png() {
|
||||
let mut s = session();
|
||||
arc_image(&mut s);
|
||||
let out = s.execute("document.export", &json!({"format": "png"})).unwrap();
|
||||
let png = image::load_from_memory(&decoded(&out)).unwrap().to_rgba8();
|
||||
// The artboard starts at (0, 0) and the export draws one pixel a point.
|
||||
assert_eq!((png.width(), png.height()), (800, 600));
|
||||
for &(u, v) in &SAMPLES {
|
||||
let p = arced(50.0, u, v);
|
||||
let px = png.get_pixel(p.x.floor() as u32, p.y.floor() as u32).0;
|
||||
let want = quarter(u, v);
|
||||
assert!((0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40), "({u}, {v}) at {p:?}: {px:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A group the user made of two clip groups of the same image, each clipped by a rectangle, writes
|
||||
/// the image once for each: only the pieces of a warp share one.
|
||||
#[test]
|
||||
fn svg_writes_an_image_clipped_twice_in_a_users_group_twice() {
|
||||
let mut s = session();
|
||||
let im = quarters(&mut s);
|
||||
s.edit("Clip twice", |d, _| {
|
||||
let image = d.node(im).cloned().unwrap();
|
||||
let mut clipped = vec![];
|
||||
for x in [FRAME.x0, FRAME.x0 + 40.0] {
|
||||
let mut clip =
|
||||
Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(x, FRAME.y0, x + 30.0, FRAME.y0 + 30.0)), Default::default());
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let image = Node { id: d.alloc_id(), ..image.clone() };
|
||||
let children = vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)];
|
||||
clipped.push(std::sync::Arc::new(Node::new(d.alloc_id(), NodeKind::Group { children, clip: true })));
|
||||
}
|
||||
let group = Node::group(d.alloc_id(), clipped);
|
||||
d.remove(im)?;
|
||||
d.insert(d.default_layer(), 0, group)?;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
|
||||
let text = String::from_utf8(decoded(&svg)).unwrap();
|
||||
assert_eq!(text.matches("<image").count(), 2, "{text}");
|
||||
}
|
||||
|
||||
/// Expand Appearance of a warped image gives objects that draw as the canvas did, with ids of
|
||||
/// their own, in one undo step.
|
||||
#[test]
|
||||
fn expand_appearance_of_a_warped_image_draws_as_the_canvas_did() {
|
||||
let mut s = session();
|
||||
let id = arc_image(&mut s);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
let mut images = 0;
|
||||
for layer in &d.layers {
|
||||
layer.walk(&mut |c| {
|
||||
assert!(ids.insert(c.id), "{:?} twice", c.id);
|
||||
images += matches!(c.kind, NodeKind::Image(_)) as usize;
|
||||
assert!(c.appearance.effects.iter().all(|e| !e.id.starts_with("warp.")));
|
||||
});
|
||||
}
|
||||
assert!(images >= 100, "{images} pieces");
|
||||
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
assert!(matches!(n.kind, NodeKind::Image(_)) && n.appearance.effects.len() == 1);
|
||||
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]);
|
||||
}
|
||||
|
||||
/// A selected embedded grayscale 40×40 px image filling [`FRAME`], black above white, colorized
|
||||
/// red by its fill color: red above, nothing below.
|
||||
fn red_on_clear(s: &mut Session) -> NodeId {
|
||||
let img = image::GrayImage::from_fn(40, 40, |_, y| image::Luma([if y < 20 { 0 } else { 255 }]));
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::ImageLuma8(img).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let id = s
|
||||
.edit("Place", |d, sel| {
|
||||
d.images.insert("gray".into(), vectorcraft_doc::ImageBlob::png(png));
|
||||
let id = d.alloc_id();
|
||||
let xf = Affine::translate((FRAME.x0, FRAME.y0)) * Affine::scale(2.0);
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "gray".into(),
|
||||
width: 40,
|
||||
height: 40,
|
||||
xf,
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(d.default_layer(), 0, Node::new(id, NodeKind::Image(Box::new(im))))?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000", "ids": [id.0]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colorized_image_keeps_its_color_when_warped() {
|
||||
let mut s = session();
|
||||
red_on_clear(&mut s);
|
||||
s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap();
|
||||
let img = drawn(&s);
|
||||
let (red, white) = ([255u8, 0, 0], [255u8, 255, 255]);
|
||||
for (u, v, want) in [(0.5, 0.35, red), (0.2, 0.2, red), (0.5, 0.65, white), (0.8, 0.8, white)] {
|
||||
let p = arced(50.0, u, v);
|
||||
let px = img.pixel(p.x.floor() as u32, p.y.floor() as u32);
|
||||
assert!((0..3).all(|i| (px[i] as i32 - want[i] as i32).abs() <= 40), "({u}, {v}) at {p:?}: {px:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warp_on_a_group_bends_the_image_in_it() {
|
||||
let mut s = session();
|
||||
let im = quarters(&mut s);
|
||||
// A group of the image and a line below it as wide as the image: the group's box is the image's.
|
||||
let line = s.execute("shape.line", &json!({"x1": FRAME.x0, "y1": FRAME.y1, "x2": FRAME.x1, "y2": FRAME.y1})).unwrap();
|
||||
let line = NodeId(line["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [im.0, line.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "warp.arc", "params": {"bend": 50}})).unwrap();
|
||||
assert_eq!(wrong(&drawn(&s), &|u, v| arced(50.0, u, v)), vec![]);
|
||||
}
|
||||
Reference in New Issue
Block a user