mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 07:17:00 +00:00
Merge remote-tracking branch 'origin/main' into fix/6969-rasterize-gray
# Conflicts: # docs/target-app-parity.md
This commit is contained in:
@@ -106,6 +106,7 @@ mod variablecmds;
|
||||
pub(crate) mod views;
|
||||
pub mod wand;
|
||||
pub mod webexport;
|
||||
mod wireframe;
|
||||
mod xform;
|
||||
|
||||
use serde::Serialize;
|
||||
@@ -310,6 +311,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(draw2::specs());
|
||||
v.extend(xform::specs());
|
||||
v.extend(effectcmd::specs());
|
||||
v.extend(wireframe::specs());
|
||||
v.extend(pathops::specs());
|
||||
v.extend(compoundshape::specs());
|
||||
v.extend(typecmd::specs());
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_svg::{CssOptions, CssSheet, css_rules};
|
||||
|
||||
use super::fileio::{default_name, encode_with_warnings, isolated, write_file};
|
||||
use super::fileio::{Note, default_name, encode_with_notes, isolated, note_texts, write_file};
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, named_ids, targets};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -118,20 +118,22 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let css = format!("{}\n", sheet.text());
|
||||
let doc = &s.doc()?.doc;
|
||||
// Encode the pictures of rasterized art, and add each of their warnings once.
|
||||
// Encode the pictures of rasterized art, and add each of their warnings once. What CSS can't
|
||||
// describe is a loss.
|
||||
let mut images = Vec::new();
|
||||
let mut warnings = sheet.warnings.clone();
|
||||
let mut notes: Vec<Note> = sheet.warnings.iter().cloned().map(Note::loss).collect();
|
||||
for r in &sheet.rules {
|
||||
let Some(name) = &r.image else { continue };
|
||||
let (d, _) = isolated(doc, &[r.id], name).ok_or_else(|| bad(C, format!("{} paints nothing to rasterize", r.selector)))?;
|
||||
let (png, notes) = encode_with_warnings(&d, "png", &json!({}))?;
|
||||
let (png, given) = encode_with_notes(&d, "png", &json!({}))?;
|
||||
images.push((name, png));
|
||||
for w in notes {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
for n in given {
|
||||
if !notes.iter().any(|x| x.text == n.text) {
|
||||
notes.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
let warnings = note_texts(¬es);
|
||||
let n = sheet.rules.len();
|
||||
match path {
|
||||
Some(path) => {
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -131,14 +131,16 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
|
||||
/// rows of its objects filled or stroked with a spot color, with a pattern and with a gradient.
|
||||
/// `document.info` reports), its fonts, its image objects, the rows of the brushes its art uses, the
|
||||
/// rows of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
|
||||
/// pattern and with a gradient.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn sections(
|
||||
d: &Document,
|
||||
info: &Value,
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
images: &[ImageRow],
|
||||
brushes: &[(String, String)],
|
||||
repeats: &[(String, String)],
|
||||
spot_objects: &[(String, String)],
|
||||
pattern_objects: &[(String, String)],
|
||||
@@ -184,7 +186,7 @@ fn sections(
|
||||
rows
|
||||
}
|
||||
"graphicStyles" => names("graphicStyleNames"),
|
||||
"brushes" => names("brushNames"),
|
||||
"brushes" => brushes.to_vec(),
|
||||
"spotColors" => spot_objects.to_vec(),
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => gradient_objects.to_vec(),
|
||||
@@ -326,12 +328,18 @@ fn painted_runs<'a>(d: &Document, spots: &HashSet<&str>, n: &'a Node) -> Option<
|
||||
if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) {
|
||||
return None;
|
||||
}
|
||||
Some((t, drawn_runs(d, t)))
|
||||
}
|
||||
|
||||
/// The runs of type `t` that its layout draws: those with a glyph outline (list markers and ruby
|
||||
/// included) or an underline or strikethrough bar, laid out as the renderer lays it out.
|
||||
fn drawn_runs(d: &Document, t: &vectorcraft_doc::TextObject) -> BTreeSet<usize> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let resolved = d.inline_resolved(t);
|
||||
let lay = vectorcraft_text::layout(db, &resolved);
|
||||
let mut painted: BTreeSet<usize> = lay.glyphs.iter().chain(&lay.ruby).filter(|g| !g.outline.elements().is_empty()).map(|g| g.run).collect();
|
||||
painted.extend(vectorcraft_text::decorations(&lay, db, &resolved).into_iter().map(|(run, _)| run));
|
||||
Some((t, painted))
|
||||
painted
|
||||
}
|
||||
|
||||
/// The names a paint is listed by in a Document Info category: its spot colors, its pattern or its
|
||||
@@ -340,7 +348,8 @@ type PaintNames<'a> = dyn Fn(&Paint) -> Vec<String> + 'a;
|
||||
|
||||
/// The spot colors, patterns or gradients (`label`: [`spot_labels`], [`pattern_label`] or
|
||||
/// [`gradient_label`], each paint's names) that `n`'s own fills and strokes paint, each once. A
|
||||
/// hidden fill or stroke and a stroke with no width paint nothing, and neither does any fill or
|
||||
/// hidden fill or stroke, a fill or stroke at an opacity of 0 and a stroke with no width paint
|
||||
/// nothing, and neither does any fill or
|
||||
/// stroke of a guide (drawn in the guide color), of a compound path's member (`members`: the
|
||||
/// compound path's own fills and strokes paint it) or of type whose layout draws nothing
|
||||
/// (`painted_runs`). An image's fills and strokes paint only where an effect gives them a shape.
|
||||
@@ -364,7 +373,7 @@ fn own_paints(
|
||||
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().flat_map(|(_, _, item)| label(item.paint())).collect());
|
||||
let mut out: Vec<String> = vec![];
|
||||
for item in &n.appearance.items {
|
||||
if !item.visible() || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
|
||||
if !item.visible() || item.opacity() <= 0.0 || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
for name in label(item.paint()) {
|
||||
@@ -381,6 +390,41 @@ fn one_label(label: fn(&Paint) -> Option<String>) -> impl Fn(&Paint) -> Vec<Stri
|
||||
move |p| label(p).into_iter().collect()
|
||||
}
|
||||
|
||||
/// The brushes `n`'s own strokes draw with, in the order of its appearance. A hidden stroke, a
|
||||
/// stroke at an opacity of 0, a stroke with no paint and a stroke with no width draw nothing, and neither does any stroke of a
|
||||
/// guide (drawn in the guide color) or of a compound path's member (`members`: the compound path's
|
||||
/// own strokes draw it). An image's strokes draw only where an effect gives them a shape, and only
|
||||
/// paths, compound paths, type and images draw strokes of their own.
|
||||
fn applied_brushes(d: &Document, n: &Node, members: &HashSet<*const Node>) -> Vec<String> {
|
||||
if matches!(n.kind, NodeKind::Path { guide: true, .. }) || members.contains(&std::ptr::from_ref(n)) {
|
||||
return vec![];
|
||||
}
|
||||
let brush = |item: &vectorcraft_doc::AppearanceItem| match item {
|
||||
vectorcraft_doc::AppearanceItem::Stroke(st) if item.visible() && st.opacity > 0.0 && !st.paint.is_none() && st.width > 0.0 => {
|
||||
st.brush.clone().filter(|b| !b.is_empty())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if matches!(n.kind, NodeKind::Image(_)) {
|
||||
return vectorcraft_render::effects::image_paint(Some(d), n).iter().filter_map(|(_, _, item)| brush(item)).collect();
|
||||
}
|
||||
let used: Vec<String> = n.appearance.items.iter().filter_map(brush).collect();
|
||||
if used.is_empty() {
|
||||
return used;
|
||||
}
|
||||
// A path or compound path with no segment gives its strokes nothing to follow, and neither does
|
||||
// type whose layout draws nothing (spaces and line breaks without an underline or strikethrough).
|
||||
let segments = |pd: &vectorcraft_geom::PathData| pd.subpaths.iter().any(|sp| sp.segment_count() > 0);
|
||||
let follows = match &n.kind {
|
||||
NodeKind::Path { .. } => n.path_data().is_some_and(segments),
|
||||
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).any(segments),
|
||||
NodeKind::Text(t) => !drawn_runs(d, t).is_empty(),
|
||||
// A brush on any other kind of object (a layer, a group, a ruler guide) is not listed.
|
||||
_ => false,
|
||||
};
|
||||
if follows { used } else { vec![] }
|
||||
}
|
||||
|
||||
fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.info";
|
||||
let category = str_param(p, "category");
|
||||
@@ -425,8 +469,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut spot = BTreeSet::new();
|
||||
let (spot_label, pattern, gradient) = (|p: &Paint| spot_labels(&spot_swatches, p), one_label(pattern_label), one_label(gradient_label));
|
||||
let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() };
|
||||
// `brushes` holds the Brushes panel's brushes, or with selectionOnly it holds the brushes that the selected objects' strokes use.
|
||||
let mut brushes: Vec<String> = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() };
|
||||
// `library` holds the Brushes panel's brushes, and `brushes` the brushes the visited objects' strokes draw with, each once,
|
||||
// in walk order.
|
||||
let library = vectorcraft_brush::library(d);
|
||||
let mut brushes: Vec<String> = vec![];
|
||||
// `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order.
|
||||
let mut repeats: Vec<Value> = vec![];
|
||||
let mut repeat_rows: Vec<(String, String)> = vec![];
|
||||
@@ -569,14 +615,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
styles.push(&g.name);
|
||||
}
|
||||
if selection_only {
|
||||
for item in &n.appearance.items {
|
||||
if let vectorcraft_doc::AppearanceItem::Stroke(st) = item
|
||||
&& let Some(b) = &st.brush
|
||||
&& !brushes.contains(b)
|
||||
{
|
||||
brushes.push(b.clone());
|
||||
}
|
||||
for b in applied_brushes(d, n, &members) {
|
||||
if !brushes.contains(&b) {
|
||||
brushes.push(b);
|
||||
}
|
||||
}
|
||||
if let NodeKind::Repeat(spec) = &n.kind {
|
||||
@@ -587,6 +628,17 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
}
|
||||
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
|
||||
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two
|
||||
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type.
|
||||
let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect();
|
||||
let brush_entries: Vec<Value> =
|
||||
brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect();
|
||||
let brush_rows: Vec<(String, String)> = brushes
|
||||
.iter()
|
||||
.map(|name| {
|
||||
(name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} brush", k.label())))
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({
|
||||
"document": document_summary(d),
|
||||
"objects": counts,
|
||||
@@ -601,6 +653,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"graphicStyles": d.graphic_styles.len(),
|
||||
"graphicStyleNames": styles,
|
||||
"brushNames": brushes,
|
||||
"brushes": brush_entries,
|
||||
"panelBrushNames": library.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
|
||||
"repeatObjects": repeats,
|
||||
"characterStyles": d.char_styles.len(),
|
||||
"paragraphStyles": d.para_styles.len(),
|
||||
@@ -612,7 +666,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
// The document's name: its file's, else its title.
|
||||
out["document"]["name"] = json!(st.title());
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
|
||||
let sections = sections(d, &out, &fonts, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
|
||||
if text {
|
||||
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
|
||||
}
|
||||
@@ -725,38 +779,129 @@ mod tests {
|
||||
assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0);
|
||||
}
|
||||
|
||||
/// Document Info › Brushes lists the Brushes panel's brushes, and with Selection Only it lists
|
||||
/// the brushes the selected objects' strokes use, each once.
|
||||
/// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and
|
||||
/// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With
|
||||
/// Selection Only it lists the brushes the selected objects' strokes use.
|
||||
#[test]
|
||||
fn info_lists_the_brushes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let panel: Vec<Value> =
|
||||
s.execute("brush.list", &json!({})).unwrap()["brushes"].as_array().unwrap().iter().map(|b| b["name"].clone()).collect();
|
||||
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
|
||||
assert_eq!(i["brushNames"], json!(panel));
|
||||
let brushes = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap();
|
||||
// No art uses a brush: the category is empty.
|
||||
let i = brushes(&mut s, json!({"category": "brushes"}));
|
||||
assert_eq!((i["brushNames"].clone(), i["brushes"].clone(), i["panelBrushNames"].clone()), (json!([]), json!([]), json!(panel)));
|
||||
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("brushes"), Some("Brushes")));
|
||||
let rows: Vec<Value> = panel.iter().map(|n| json!([n, ""])).collect();
|
||||
assert_eq!(i["sections"][0]["rows"], json!(rows));
|
||||
assert_eq!(i["sections"][0]["rows"], json!([]));
|
||||
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
s.execute("brush.apply", &json!({"ids": [a], "name": "Charcoal"})).unwrap();
|
||||
s.execute("brush.apply", &json!({"ids": [b], "name": "Arrow"})).unwrap();
|
||||
s.execute("brush.apply", &json!({"ids": [b], "name": "Dots"})).unwrap();
|
||||
s.execute("brush.apply", &json!({"ids": [c], "name": "Charcoal"})).unwrap();
|
||||
let names =
|
||||
|s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true, "category": "brushes"})).unwrap()["brushNames"].clone();
|
||||
// The whole document: the two brushes the art uses, each once, with their types; "3 pt. Round" (a Calligraphic
|
||||
// brush in the panel) is left out.
|
||||
let i = brushes(&mut s, json!({"category": "brushes"}));
|
||||
assert_eq!(i["brushNames"], json!(["Charcoal", "Dots"]));
|
||||
assert_eq!(i["brushes"], json!([{"name": "Charcoal", "type": "art"}, {"name": "Dots", "type": "scatter"}]));
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art brush"], ["Dots", "Scatter brush"]]));
|
||||
assert!(panel.contains(&json!("3 pt. Round")) && i["panelBrushNames"] == json!(panel));
|
||||
let text = brushes(&mut s, json!({"category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nBRUSHES\nCharcoal: Art brush\nDots: Scatter brush\n") && !text.contains("3 pt. Round"), "{text}");
|
||||
assert!(!text.contains("OBJECTS"), "{text}");
|
||||
// Selection Only: the brushes the selected objects' strokes use.
|
||||
let selected = |s: &mut Session| brushes(s, json!({"selectionOnly": true, "category": "brushes"}));
|
||||
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
|
||||
assert_eq!(names(&mut s), json!(["Charcoal", "Arrow"]));
|
||||
assert_eq!(selected(&mut s)["brushNames"], json!(["Charcoal", "Dots"]));
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
assert_eq!(names(&mut s), json!(["Arrow"]));
|
||||
let i = selected(&mut s);
|
||||
assert_eq!(
|
||||
(i["brushes"].clone(), i["sections"][0]["rows"].clone()),
|
||||
(json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter brush"]]))
|
||||
);
|
||||
let text = brushes(&mut s, json!({"selectionOnly": true, "category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains("\nBRUSHES\nDots: Scatter brush\n") && !text.contains("Charcoal"), "{text}");
|
||||
// A stroke without a brush lists none.
|
||||
let plain = s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({"ids": [plain]})).unwrap();
|
||||
assert_eq!(names(&mut s), json!([]));
|
||||
let text = s.execute("document.info", &json!({"category": "brushes", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains(&format!("\nBRUSHES\n{}\n", panel[0].as_str().unwrap())), "{text}");
|
||||
assert!(text.contains("\nCharcoal\n") && text.contains("\nArrow\n") && !text.contains("OBJECTS"), "{text}");
|
||||
assert_eq!(selected(&mut s)["brushNames"], json!([]));
|
||||
}
|
||||
|
||||
/// Document Info › Brushes leaves out brushes on strokes that draw nothing (hidden, at an
|
||||
/// opacity of 0, with no width or paint, a guide's, a compound path member's, a path's with no segment, type's that
|
||||
/// draws no characters, a group's own), lists a brush the Brushes panel does
|
||||
/// not hold with no type, and gives a name two panel brushes share the type the renderer uses.
|
||||
#[test]
|
||||
fn info_brushes_skip_undrawn_strokes_and_name_missing_brushes() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
|
||||
let square = |s: &mut Session, x: f64| {
|
||||
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
|
||||
};
|
||||
let (hidden, thin, guide, missing) = (square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0));
|
||||
let (empty, faint) = (square(&mut s, 80.0), square(&mut s, 200.0));
|
||||
s.execute("brush.apply", &json!({"ids": [hidden, thin, guide, missing, empty, faint], "name": "Charcoal"})).unwrap();
|
||||
let (p, q) = (square(&mut s, 100.0), square(&mut s, 120.0));
|
||||
s.execute("select.set", &json!({"ids": [p, q]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
// A compound path's member: the compound path's own stroke draws it.
|
||||
let NodeKind::Compound { children, .. } = &mut d.node_mut(NodeId(compound)).unwrap().kind else { panic!("not a compound path") };
|
||||
let member = &mut std::sync::Arc::make_mut(&mut children[0]).appearance;
|
||||
member.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
|
||||
member.stroke_mut().unwrap().brush = Some("Dots".into());
|
||||
d.node_mut(NodeId(hidden)).unwrap().appearance.stroke_mut().unwrap().visible = false;
|
||||
d.node_mut(NodeId(thin)).unwrap().appearance.stroke_mut().unwrap().width = 0.0;
|
||||
// A stroke at an opacity of 0 draws nothing.
|
||||
d.node_mut(NodeId(faint)).unwrap().appearance.stroke_mut().unwrap().opacity = 0.0;
|
||||
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind {
|
||||
*g = true;
|
||||
}
|
||||
// A path with no segment: its stroke follows nothing.
|
||||
if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(empty)).unwrap().kind {
|
||||
*path = vectorcraft_geom::PathData::default();
|
||||
}
|
||||
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Gone".into());
|
||||
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
|
||||
assert_eq!(i["brushes"], json!([{"name": "Gone", "type": null}]));
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["Gone", "missing from the Brushes panel"]]));
|
||||
// A stroke with no paint draws nothing.
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().paint = Paint::None;
|
||||
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([]));
|
||||
// Two panel brushes with one name: the type is the one the renderer draws with, the last one's.
|
||||
let twin = square(&mut s, 140.0);
|
||||
s.execute("brush.apply", &json!({"ids": [twin], "name": "Charcoal"})).unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let mut lib = vectorcraft_brush::library(d);
|
||||
let kinds: Vec<vectorcraft_brush::BrushKind> =
|
||||
["Charcoal", "Dots"].iter().map(|n| lib.iter().find(|b| b.name == *n).unwrap().kind.clone()).collect();
|
||||
lib.extend(kinds.into_iter().map(|kind| vectorcraft_brush::Brush { name: "Twin".into(), kind }));
|
||||
vectorcraft_brush::store(d, &lib);
|
||||
d.node_mut(NodeId(twin)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Twin".into());
|
||||
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([{"name": "Twin", "type": "scatter"}]));
|
||||
// Type: a brushed stroke on drawn characters is listed, one on spaces alone is not.
|
||||
let blank = s.execute("text.create", &json!({"x": 10, "y": 60, "text": " "})).unwrap()["id"].as_u64().unwrap();
|
||||
let word = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
for (id, name) in [(blank, "Dots"), (word, "Arrow")] {
|
||||
let ap = &mut d.node_mut(NodeId(id)).unwrap().appearance;
|
||||
ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
|
||||
ap.stroke_mut().unwrap().brush = Some(name.into());
|
||||
}
|
||||
let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone();
|
||||
assert_eq!(names, json!(["Twin", "Arrow"]));
|
||||
// A group's own stroke: the group draws its members.
|
||||
let (m1, m2) = (square(&mut s, 160.0), square(&mut s, 180.0));
|
||||
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let ap = &mut d.node_mut(NodeId(group)).unwrap().appearance;
|
||||
ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
|
||||
ap.stroke_mut().unwrap().brush = Some("Leaves".into());
|
||||
let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone();
|
||||
assert_eq!(names, json!(["Twin", "Arrow"]));
|
||||
}
|
||||
|
||||
/// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number
|
||||
@@ -867,6 +1012,11 @@ mod tests {
|
||||
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Dots"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
|
||||
// Nor does a pattern fill at an opacity of 0.
|
||||
let clear = square(&mut s, 220.0);
|
||||
s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [clear], "swatch": "Dots"})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [clear], "index": 0, "opacity": 0})).unwrap();
|
||||
// A type object with no characters paints nothing either.
|
||||
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
|
||||
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Dots"})).unwrap();
|
||||
@@ -927,7 +1077,7 @@ mod tests {
|
||||
assert_eq!(i["patternNames"], json!(["Dots"]));
|
||||
// Objects counts the objects that Pattern Objects lists.
|
||||
assert_eq!(i["objects"]["patterns"].as_u64(), Some(5), "{}", i["objects"]);
|
||||
s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [d, e, clear, empty, blank, guide, compound, image.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
|
||||
assert!(i["objects"]["patterns"].is_null() && i["patternObjects"] == json!([]), "{}", i["objects"]);
|
||||
let i = s.execute("document.info", &json!({"category": "patterns"})).unwrap();
|
||||
|
||||
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
doc_compare
|
||||
),
|
||||
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model (with automation read roots, a linked or placed file outside them is named by its file name alone, without its relative path, size or date, in brush art too, and so is a data set's image value outside them; a relative path that leads outside them is left out; a stored brush entry that does not read as a brush is left out; a folder outside them is left out of export_settings)", has_doc, |s, _| {
|
||||
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model (with automation read roots, a linked or placed file outside them is named by its file name alone, without its relative path, size or date, in brush art too, and so are a data set's image value and a linked JavaScript file in svg_scripts outside them (a URL is kept); a relative path that leads outside them is left out; a stored brush entry that does not read as a brush is left out; a folder outside them is left out of export_settings)", has_doc, |s, _| {
|
||||
let st = s.doc()?;
|
||||
let d = super::links::with_hidden_paths_named(&st.doc, super::links::LinkBase::of(st));
|
||||
Ok(serde_json::to_value(&*d).unwrap_or(Value::Null))
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand…",
|
||||
["Object"],
|
||||
None,
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones, nested squares for diamond ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255; a gradient that repeats or reflects gets the same whole number of them in each run, at least one, so a run starts on an object's edge; one that needs more than 256 runs across the box stays a gradient)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
has_selection,
|
||||
expand
|
||||
),
|
||||
@@ -194,10 +194,12 @@ impl Expandable {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| r.style.has_stroke()),
|
||||
_ => shape && !c.appearance.stroke_paint().is_none(),
|
||||
};
|
||||
e.gradient |= match &c.kind {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
|
||||
_ => shape && c.appearance.items.iter().any(|i| gradient_fill(i).is_some()),
|
||||
};
|
||||
// Once one is found, the next path is not measured.
|
||||
e.gradient = e.gradient
|
||||
|| match &c.kind {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
|
||||
_ => shape && gradient_expands(d, c),
|
||||
};
|
||||
e.fill |= e.gradient;
|
||||
e.fill |= match &c.kind {
|
||||
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(&r.style.fill, Paint::Pattern { pattern, .. } if d.pattern(pattern).is_some())),
|
||||
@@ -222,6 +224,43 @@ fn gradient_fill(i: &AppearanceItem) -> Option<(&FillLayer, &GradientPaint)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether path `l` has a gradient fill that Fill expands ([`expand_fills`]): one that repeats or
|
||||
/// reflects stays a gradient when its box needs more runs than are written ([`padded_on`]). For a
|
||||
/// path that live-effect plug-ins paint, whether a piece of the art they paint has one
|
||||
/// ([`expand_pieces`]).
|
||||
fn gradient_expands(d: &Document, l: &Node) -> bool {
|
||||
if !l.appearance.items.iter().any(|i| gradient_fill(i).is_some()) {
|
||||
return false;
|
||||
}
|
||||
if !vectorcraft_render::effects::has_painted_effects(l) {
|
||||
return piece_gradient_expands(d, l);
|
||||
}
|
||||
let Some(art) = vectorcraft_render::effects::reshape(Some(d), l, None) else { return false };
|
||||
let mut any = false;
|
||||
art.walk(&mut |c| {
|
||||
any = any
|
||||
|| (matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
&& !c.is_ruler_guide()
|
||||
&& c.appearance.items.iter().any(|i| gradient_fill(i).is_some())
|
||||
&& piece_gradient_expands(d, c));
|
||||
});
|
||||
any
|
||||
}
|
||||
|
||||
/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]).
|
||||
fn piece_gradient_expands(d: &Document, l: &Node) -> bool {
|
||||
if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) {
|
||||
return l.appearance.items.iter().any(|i| gradient_fill(i).is_some());
|
||||
}
|
||||
let reshaped = reshaped(d, l);
|
||||
let l = reshaped.as_ref().unwrap_or(l);
|
||||
let Some((path, _)) = node_path(l) else { return false };
|
||||
let Some(bounds) = path.bounds() else { return false };
|
||||
l.appearance.items.iter().filter(|i| gradient_fill(i).is_some()).any(|item| {
|
||||
fill_shape(d, l, item, &path, bounds).is_some_and(|(_, _, b, moved)| gradient_fill(&moved).is_some_and(|(_, g)| padded_on(g, b).is_some()))
|
||||
})
|
||||
}
|
||||
|
||||
/// The definition and placement of a visible pattern fill whose pattern `d` defines.
|
||||
fn pattern_fill<'a, 'd>(d: &'d Document, i: &'a AppearanceItem) -> Option<(&'a FillLayer, &'d PatternDef, Affine)> {
|
||||
match i {
|
||||
@@ -476,8 +515,9 @@ fn gradient_art(d: &mut Document, l: &Node, path: &PathData, bounds: Rect, f: &F
|
||||
let m = GradientMesh::for_path_with(path, FREEFORM_MESH, FREEFORM_MESH, &*gradient_sampler(g, bounds, d.color_mode.model()))?;
|
||||
vec![Node::new(d.alloc_id(), NodeKind::Mesh(m))]
|
||||
} else {
|
||||
// A gradient that repeats or reflects expands as its stops repeated over the box.
|
||||
let (g, runs) = padded_on(g, bounds);
|
||||
// A gradient that repeats or reflects expands as its stops repeated over the box (and
|
||||
// stays a gradient when the box needs more runs than are written).
|
||||
let (g, runs) = padded_on(g, bounds)?;
|
||||
let g = &*g;
|
||||
let frame = Frame::new(g, bounds);
|
||||
match to {
|
||||
@@ -1244,26 +1284,32 @@ pub(crate) fn gradient_sampler(g: &GradientPaint, bounds: Rect, doc_model: Model
|
||||
Box::new(move |p| g.gradient.sample_keep_model(spread(geom.param_at(g.gradient.kind, p)) as f32))
|
||||
}
|
||||
|
||||
/// For stops repeated by [`padded_on`]: where along the vector (0 to 1) their first run starts and
|
||||
/// how many runs lie evenly from there to 1.
|
||||
type Runs = Option<(f64, usize)>;
|
||||
|
||||
/// `g` placed on box `bounds` as a gradient that pads past its ends: a linear, radial or diamond
|
||||
/// gradient that repeats or reflects with its stops repeated as many times as the box needs
|
||||
/// ([`vectorcraft_color::Gradient::padded_over`]), a conic one with its stops repeated around the
|
||||
/// turn ([`vectorcraft_color::Gradient::unrolled`]); others as they are. With it, for the repeated
|
||||
/// stops, where along the vector (0 to 1) their first run starts and how many runs lie evenly from
|
||||
/// there to 1.
|
||||
fn padded_on(g: &GradientPaint, bounds: Rect) -> (std::borrow::Cow<'_, GradientPaint>, Option<(f64, usize)>) {
|
||||
/// there to 1. `None` when the box needs more runs than are written
|
||||
/// ([`vectorcraft_color::Padded::capped`]): the gradient stays.
|
||||
fn padded_on(g: &GradientPaint, bounds: Rect) -> Option<(std::borrow::Cow<'_, GradientPaint>, Runs)> {
|
||||
use std::borrow::Cow;
|
||||
if !g.gradient.is_spread() {
|
||||
return (Cow::Borrowed(g), None);
|
||||
return Some((Cow::Borrowed(g), None));
|
||||
}
|
||||
let geom = g.resolve(bounds);
|
||||
match g.gradient.padded_over(&geom, bounds) {
|
||||
Some(p) if p.capped => None,
|
||||
Some(p) => {
|
||||
let runs = Some((p.first, p.runs));
|
||||
(Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs)
|
||||
Some((Cow::Owned(GradientPaint { gradient: p.gradient, geom: Some(p.geom), angle: p.geom.angle_deg(), ..g.clone() }), runs))
|
||||
}
|
||||
None => {
|
||||
let runs = Some((0.0, g.gradient.repeat_count() as usize));
|
||||
(Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs)
|
||||
Some((Cow::Owned(GradientPaint { gradient: g.gradient.unrolled().into_owned(), geom: Some(geom), ..g.clone() }), runs))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ use serde_json::{Value, json};
|
||||
|
||||
pub use action_batch::batch_overwrites_one_file;
|
||||
pub use dxf::{UNSUPPORTED, Unsupported, unsupported};
|
||||
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, encode, encode_all, encode_with_warnings};
|
||||
pub use encode::{ARTBOARD_PARAMS, ArtboardPick, Encoded, Note, NoteKind, encode, encode_all, encode_with_notes, encode_with_warnings, note_texts};
|
||||
pub(crate) use encode::{anti_alias, background, with_single_artboard};
|
||||
pub(crate) use export::with_artboard_fills;
|
||||
pub(crate) use export::{export_crop, isolated};
|
||||
|
||||
@@ -241,6 +241,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
enc.warnings.push(w);
|
||||
}
|
||||
}
|
||||
enc.add_setting_notes(out.setting_notes);
|
||||
for img in out.images {
|
||||
if !enc.linked.iter().any(|l| l.name == img.name) {
|
||||
enc.linked.push(vectorcraft_svg::LinkedImage { name: img.name, bytes: Arc::new(img.bytes) });
|
||||
|
||||
@@ -74,18 +74,104 @@ pub struct Encoded {
|
||||
pub linked: Vec<vectorcraft_svg::LinkedImage>,
|
||||
/// Image maps, each written beside its image under the image's name (raster `imageMap`).
|
||||
pub maps: Vec<imagemap::Map>,
|
||||
/// The encoder's warnings (features approximated or left out, options not applied yet).
|
||||
/// The encoder's warnings: what the file leaves out of the document or writes differently
|
||||
/// ([`NoteKind::Loss`]).
|
||||
pub warnings: Vec<String>,
|
||||
/// The encoder's notes on the options: options not applied yet or applied another way, and
|
||||
/// what an option turns off ([`NoteKind::Setting`]). A reply gives them after the warnings
|
||||
/// ([`Self::notes`]).
|
||||
pub setting_notes: Vec<String>,
|
||||
/// What joins the file's stem and the artboard name when there is a file per artboard
|
||||
/// (default `-`; EPS uses `_`, as the reference app names them).
|
||||
pub joiner: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// What a note an export gives with its file is about.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum NoteKind {
|
||||
/// Something of the document (its art, type, layers or artboards) that the file leaves out or
|
||||
/// that reaches it changed: the format, its version or a limit can't hold it, or the export
|
||||
/// couldn't write it.
|
||||
Loss,
|
||||
/// An option the export didn't apply or applied another way while the art reaches the file as
|
||||
/// it looks, or something left out because an option turns it off.
|
||||
Setting,
|
||||
}
|
||||
|
||||
/// A note an export gives with its file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Note {
|
||||
/// What the note is about.
|
||||
pub kind: NoteKind,
|
||||
/// The note, in English.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Note {
|
||||
/// A note about what the file loses ([`NoteKind::Loss`]).
|
||||
pub fn loss(text: impl Into<String>) -> Self {
|
||||
Self { kind: NoteKind::Loss, text: text.into() }
|
||||
}
|
||||
|
||||
/// A note on the options ([`NoteKind::Setting`]).
|
||||
pub fn setting(text: impl Into<String>) -> Self {
|
||||
Self { kind: NoteKind::Setting, text: text.into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The texts of `notes` in the order a reply gives them: the losses first, then the notes on the
|
||||
/// options, each kind in the order given (the status bar names the first).
|
||||
pub fn note_texts(notes: &[Note]) -> Vec<String> {
|
||||
let of = |kind| notes.iter().filter(move |n| n.kind == kind).map(|n| n.text.clone());
|
||||
of(NoteKind::Loss).chain(of(NoteKind::Setting)).collect()
|
||||
}
|
||||
|
||||
/// Add `note` to `notes` unless a note with its text is there already.
|
||||
pub(super) fn add_note(notes: &mut Vec<Note>, note: Note) {
|
||||
if !notes.iter().any(|n| n.text == note.text) {
|
||||
notes.push(note);
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoded {
|
||||
pub(super) fn one(bytes: Vec<u8>) -> Self {
|
||||
Self { files: vec![(None, bytes)], ..Self::default() }
|
||||
}
|
||||
|
||||
/// The file `bytes` with `notes`, each in the list of its kind, in the order given.
|
||||
pub(super) fn one_with_notes(bytes: Vec<u8>, notes: Vec<Note>) -> Self {
|
||||
let mut enc = Self::one(bytes);
|
||||
for n in notes {
|
||||
match n.kind {
|
||||
NoteKind::Loss => enc.warnings.push(n.text),
|
||||
NoteKind::Setting => enc.setting_notes.push(n.text),
|
||||
}
|
||||
}
|
||||
enc
|
||||
}
|
||||
|
||||
/// Add each of `texts` to [`Self::setting_notes`] unless a note with its text is there already.
|
||||
pub(super) fn add_setting_notes(&mut self, texts: impl IntoIterator<Item = String>) {
|
||||
for t in texts {
|
||||
if !self.warnings.contains(&t) && !self.setting_notes.contains(&t) {
|
||||
self.setting_notes.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every note with its kind: the warnings, then the notes on the options that aren't also
|
||||
/// warnings.
|
||||
pub fn kinded_notes(&self) -> Vec<Note> {
|
||||
let settings = self.setting_notes.iter().filter(|t| !self.warnings.contains(t)).map(Note::setting);
|
||||
self.warnings.iter().map(Note::loss).chain(settings).collect()
|
||||
}
|
||||
|
||||
/// The notes' texts in the order a reply gives them ([`note_texts`]): the warnings, then the
|
||||
/// notes on the options, each once.
|
||||
pub fn notes(&self) -> Vec<String> {
|
||||
note_texts(&self.kinded_notes())
|
||||
}
|
||||
|
||||
/// Every file to write for the destination `path` (a path or a file name): the file itself
|
||||
/// when there is one, else `{stem}-{artboard name}.{ext}` beside it (see `joiner`; a file of no artboard
|
||||
/// among several, as Save's master file, is the file itself), then the linked images beside it
|
||||
@@ -128,13 +214,14 @@ impl Encoded {
|
||||
out
|
||||
}
|
||||
|
||||
/// The one file and the warnings, when the export wrote nothing else.
|
||||
fn single(self, f: &Format) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
/// The one file and the notes, when the export wrote nothing else.
|
||||
fn single(self, f: &Format) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
if !self.linked.is_empty() || !self.maps.is_empty() {
|
||||
return Err(bad(C, format!("{} with linked images or an image map writes several files: use document.export", f.label)));
|
||||
}
|
||||
let notes = self.kinded_notes();
|
||||
match <[_; 1]>::try_from(self.files) {
|
||||
Ok([(_, bytes)]) => Ok((bytes, self.warnings)),
|
||||
Ok([(_, bytes)]) => Ok((bytes, notes)),
|
||||
Err(_) => Err(bad(C, format!("{} writes one file per artboard here: use document.export, or name one artboard", f.label))),
|
||||
}
|
||||
}
|
||||
@@ -419,8 +506,14 @@ pub fn encode(doc: &Document, format: &str, p: &Value) -> Result<Vec<u8>> {
|
||||
|
||||
/// Like [`encode`], also returning the encoder's warnings (PDF and SVG: options not applied yet,
|
||||
/// features approximated or left out; every format that draws type: fonts written in the fallback
|
||||
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame).
|
||||
/// font; PDF, EPS, SVG, EMF, WMF and the raster formats: type that doesn't fit its frame), what
|
||||
/// the file loses first ([`note_texts`]).
|
||||
pub fn encode_with_warnings(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
encode_with_notes(doc, format, p).map(|(bytes, notes)| (bytes, note_texts(¬es)))
|
||||
}
|
||||
|
||||
/// Like [`encode_with_warnings`], with each note's kind ([`Encoded::kinded_notes`]).
|
||||
pub fn encode_with_notes(doc: &Document, format: &str, p: &Value) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
let f = super::writable(C, Some(format), None)?;
|
||||
let enc = encode_all(doc, f.id, p)?;
|
||||
// The error for a version 7 .ai of several artboards names the legacy .ai.
|
||||
@@ -476,7 +569,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
|
||||
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
|
||||
/// one named after the document) with that path's extension when the plug-in lists it, else its
|
||||
/// first. Its warnings come back with the file.
|
||||
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
|
||||
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
use vectorcraft_plugins::{Error, export};
|
||||
let doc = &*doc.without_edit_modes();
|
||||
@@ -539,8 +632,8 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
|
||||
"ai" => return super::save::encode_ai(C, f, doc, p),
|
||||
"pdf" => {
|
||||
let (bytes, warnings) = super::pdf::encode(C, doc, p)?;
|
||||
return Ok(Encoded { warnings, ..Encoded::one(bytes) });
|
||||
let (bytes, notes) = super::pdf::encode(C, doc, p)?;
|
||||
return Ok(Encoded::one_with_notes(bytes, notes));
|
||||
}
|
||||
"png" | "jpg" | "webp" | "gif" | "png8" | "tiff" | "bmp" | "tga" | "psd" => {
|
||||
let o: RasterOptions = options(f, p)?;
|
||||
@@ -607,7 +700,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let regions: Vec<Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
if format == RasterFormat::WebP && o.lossless == Some(false) {
|
||||
enc.warnings.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
|
||||
enc.setting_notes.push("lossy WebP isn't available yet: the file is lossless (exact, but larger)".into());
|
||||
}
|
||||
return Ok(enc);
|
||||
}
|
||||
|
||||
@@ -382,6 +382,7 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
|
||||
enc.warnings.push(w);
|
||||
}
|
||||
}
|
||||
enc.add_setting_notes(out.setting_notes);
|
||||
}
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
Ok(enc)
|
||||
|
||||
@@ -42,7 +42,7 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
_ => json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }),
|
||||
};
|
||||
let mut out = merge(data(main.first().map_or(&[][..], |m| &m.1)), json!({ "warnings": enc.warnings }));
|
||||
let mut out = merge(data(main.first().map_or(&[][..], |m| &m.1)), json!({ "warnings": enc.notes() }));
|
||||
if main.len() > 1 {
|
||||
out["files"] = main.iter().map(|(name, bytes)| merge(json!({ "name": name }), data(bytes))).collect();
|
||||
}
|
||||
@@ -69,7 +69,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.insert("_displayDocTitle".into(), json!(display_doc_title));
|
||||
}
|
||||
let enc = encode_all(doc, f.id, &q)?;
|
||||
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.warnings }))
|
||||
write_encoded(path, &default_name(doc, f.extensions[0]), doc, &enc, json!({ "format": f.id, "warnings": enc.notes() }))
|
||||
}
|
||||
|
||||
/// The document an export of `st` in format `f` writes ([`export_source`]): a `.ai` or `.ait`
|
||||
|
||||
@@ -116,6 +116,7 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
enc.warnings.push(w);
|
||||
}
|
||||
}
|
||||
enc.add_setting_notes(out.setting_notes);
|
||||
}
|
||||
if enc.files.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
|
||||
@@ -136,10 +136,12 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
}
|
||||
let images = see_through_images(&d, mode);
|
||||
if !images.is_empty() {
|
||||
note(&mut enc.warnings, if mode == SeeThrough::Flatten { FLATTENED } else { OMITTED });
|
||||
if mode == SeeThrough::Flatten {
|
||||
note(&mut enc.warnings, FLATTENED);
|
||||
flatten_images(&mut d, &images)?;
|
||||
} else {
|
||||
// A note on the options: `transparentImages: omit` leaves them out.
|
||||
enc.add_setting_notes([OMITTED.to_string()]);
|
||||
for (_, id) in images {
|
||||
let _ = d.remove(id); // Inside an image left out before: gone already.
|
||||
}
|
||||
@@ -150,6 +152,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
for w in placed.iter().chain(&out.warnings) {
|
||||
note(&mut enc.warnings, w);
|
||||
}
|
||||
enc.add_setting_notes(out.setting_notes);
|
||||
enc.files.push((Some(b), out.bytes));
|
||||
}
|
||||
// Expanding raster effects and flattening images draw the art, and an image the renderer
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_pdf::{Overprint, PdfError, PdfOptions, PdfPreset, PdfSettings, S
|
||||
|
||||
use super::super::flatten::{FlattenOptions, flatten_document, see_through_images};
|
||||
use super::super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
|
||||
use super::{ArtboardPick, FormatOption, write_or_return};
|
||||
use super::{ArtboardPick, FormatOption, Note, note_texts, write_or_return};
|
||||
use crate::EngineError;
|
||||
|
||||
const C: &str = "document.exportPdf";
|
||||
@@ -284,21 +284,22 @@ pub const EDITING_NEEDS_EVERY_ARTBOARD: &str =
|
||||
/// ([`vectorcraft_pdf::PdfSettings::leaves_out_bleed`]).
|
||||
pub const BLEED_LEFT_OUT: &str = "the document sets a bleed that this PDF/X file leaves out: turn on Use document bleed settings";
|
||||
|
||||
/// Encode `doc` as PDF with the options in `p` → (bytes, warnings). Raster effects are rendered
|
||||
/// Encode `doc` as PDF with the options in `p` → (bytes, notes). Raster effects are rendered
|
||||
/// to images at the document's raster effects resolution. Preserve Editing embeds `doc` itself
|
||||
/// when the PDF has every artboard (a PDF of some reopens as just those).
|
||||
pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
pub fn encode(cmd: &str, doc: &Document, p: &Value) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
encode_at(cmd, doc, p, None)
|
||||
}
|
||||
|
||||
/// [`encode`] modified at `modified` (Unix seconds) when given, instead of the time of writing.
|
||||
pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i64>) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option<i64>) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
// Keep the editable object tree independent of preview fallbacks used by the drawn pages.
|
||||
let (full, mut warnings) = crate::cmd::place::document::full_documents(doc);
|
||||
let (bytes, drawn_warnings) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
|
||||
warnings.extend(drawn_warnings);
|
||||
warnings.extend(overflow_warning(cmd, &full, p)?);
|
||||
Ok((bytes, warnings))
|
||||
let (full, placed) = crate::cmd::place::document::full_documents(doc);
|
||||
let mut notes: Vec<Note> = placed.into_iter().map(Note::loss).collect();
|
||||
let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, || Ok(vectorcraft_format::save(doc, false)), || Ok(None))?;
|
||||
notes.extend(drawn);
|
||||
notes.extend(overflow_warning(cmd, &full, p)?.map(Note::loss));
|
||||
Ok((bytes, notes))
|
||||
}
|
||||
|
||||
/// The warning about the type that the pages of a PDF of `doc` with the options in `p` draw and
|
||||
@@ -321,7 +322,7 @@ pub(super) fn encode_carrying(
|
||||
p: &Value,
|
||||
native: impl FnOnce() -> Result<Vec<u8>>,
|
||||
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
|
||||
) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
encode_carrying_at(cmd, doc, p, None, native, private)
|
||||
}
|
||||
|
||||
@@ -334,7 +335,7 @@ fn encode_carrying_at(
|
||||
modified: Option<i64>,
|
||||
native: impl FnOnce() -> Result<Vec<u8>>,
|
||||
private: impl FnOnce() -> Result<Option<(vectorcraft_pdf::PrivateData, Vec<String>)>>,
|
||||
) -> Result<(Vec<u8>, Vec<String>)> {
|
||||
) -> Result<(Vec<u8>, Vec<Note>)> {
|
||||
let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?;
|
||||
// The pages' background colors, behind the art (the editing data keeps them as colors).
|
||||
let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect());
|
||||
@@ -345,21 +346,22 @@ fn encode_carrying_at(
|
||||
if opts.settings.thumbnails {
|
||||
opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?;
|
||||
}
|
||||
let mut warnings = vec![];
|
||||
// The status bar shows the first warning, so this one goes ahead of the flattening note.
|
||||
let mut notes = vec![];
|
||||
// A loss, ahead of the flattening note: the PDF/X pages leave out the bleed that Document
|
||||
// Setup gives.
|
||||
if opts.settings.leaves_out_bleed(doc) {
|
||||
warnings.push(BLEED_LEFT_OUT.to_string());
|
||||
notes.push(Note::loss(BLEED_LEFT_OUT));
|
||||
}
|
||||
if opts.settings.preserve_editing {
|
||||
if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) {
|
||||
opts.native = Some(native()?);
|
||||
if let Some((data, lost)) = private()? {
|
||||
opts.private_data = Some(data);
|
||||
warnings.extend(lost);
|
||||
notes.extend(lost.into_iter().map(Note::loss));
|
||||
}
|
||||
} else {
|
||||
opts.settings.preserve_editing = false;
|
||||
warnings.push(EDITING_NEEDS_EVERY_ARTBOARD.to_string());
|
||||
notes.push(Note::setting(EDITING_NEEDS_EVERY_ARTBOARD));
|
||||
}
|
||||
}
|
||||
let set = &opts.settings;
|
||||
@@ -370,12 +372,13 @@ fn encode_carrying_at(
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
if flattened {
|
||||
let kind = if set.standard.flattens() { set.standard.label() } else { set.compatibility.label() };
|
||||
warnings.push(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset"));
|
||||
notes.push(Note::loss(format!("transparency is flattened into opaque art and images ({kind} files have none): see the flattener preset")));
|
||||
}
|
||||
let r = super::super::rasterfx::export_pdf_with_report(flat.as_ref().unwrap_or(doc), &opts).map_err(|e| pdf_error(cmd, e))?;
|
||||
warnings.extend(r.warnings);
|
||||
warnings.extend(crate::cmd::fonts::substitution_warning(doc));
|
||||
Ok((r.bytes, warnings))
|
||||
notes.extend(r.warnings.into_iter().map(Note::loss));
|
||||
notes.extend(r.setting_notes.into_iter().map(Note::setting));
|
||||
notes.extend(crate::cmd::fonts::substitution_warning(doc).map(Note::loss));
|
||||
Ok((r.bytes, notes))
|
||||
}
|
||||
|
||||
/// The flattener preset of PDF 1.3 files whose `flattenerPreset` is empty.
|
||||
@@ -479,8 +482,8 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
q = json!({ "_displayDocTitle": display_doc_title });
|
||||
}
|
||||
let (bytes, warnings) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?;
|
||||
write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": warnings }))
|
||||
let (bytes, notes) = encode(C, titled.as_ref().unwrap_or(&st.doc), &q)?;
|
||||
write_or_return(str_param(p, "path"), &bytes, json!({ "warnings": note_texts(¬es) }))
|
||||
}
|
||||
|
||||
/// `(path, value)` for every leaf of `v` that differs from `default` (`compression.color.ppi`).
|
||||
@@ -512,7 +515,7 @@ fn pdf_settings(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let set = settings_with(Q, p, saved)?;
|
||||
let diff = changes(&set, &preset_settings(Q, p, saved)?);
|
||||
let warnings = match s.active() {
|
||||
Some(st) if bool_or(p, "includeDocument", false) => encode(Q, &st.doc, &*expand_preset(s, Q, p)?)?.1,
|
||||
Some(st) if bool_or(p, "includeDocument", false) => note_texts(&encode(Q, &st.doc, &*expand_preset(s, Q, p)?)?.1),
|
||||
_ => set.warnings(),
|
||||
};
|
||||
let v = serde_json::to_value(&set).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
|
||||
@@ -752,12 +752,14 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
|
||||
carries_editing.set(true);
|
||||
Ok(Some((data, resolved_warnings)))
|
||||
};
|
||||
let (bytes, mut warnings) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?;
|
||||
warnings.extend(placed_warnings);
|
||||
let (bytes, notes) = super::pdf::encode_carrying(cmd, &pages, ¶ms, native, private)?;
|
||||
let mut enc = Encoded::one_with_notes(bytes, notes);
|
||||
enc.warnings.extend(placed_warnings);
|
||||
// A note on the options: `pdfCompatible: false` writes blank pages.
|
||||
if !pdf_compatible {
|
||||
warnings.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string());
|
||||
enc.setting_notes.push(if carries_editing.get() { NOT_PDF_COMPATIBLE_EDITING } else { NOT_PDF_COMPATIBLE }.to_string());
|
||||
}
|
||||
Ok(Encoded { warnings, ..Encoded::one(bytes) })
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// Snapshot the active document for `plan` (stamping File Info's dates on the snapshot when the
|
||||
@@ -845,8 +847,8 @@ impl SaveJob {
|
||||
}
|
||||
|
||||
/// Encode the file → it (and, with `separateArtboards`, a file per artboard after it), with
|
||||
/// the warnings (what the format loses first, then the encoder's own notes: PDF options not
|
||||
/// applied yet…, then the plan's notes on its params).
|
||||
/// the notes (what the format loses first, then the encoder's own notes: PDF options not
|
||||
/// applied yet…, then the plan's notes on its params, which are notes on the options).
|
||||
pub fn encode(&self) -> Result<Encoded> {
|
||||
let mut enc = self.encode_one(&self.doc)?;
|
||||
for &b in &self.boards {
|
||||
@@ -854,7 +856,7 @@ impl SaveJob {
|
||||
enc.files.extend(one.files.into_iter().map(|(_, bytes)| (Some(b), bytes)));
|
||||
}
|
||||
enc.warnings.splice(0..0, self.format_losses());
|
||||
enc.warnings.extend(self.plan.notes.iter().cloned());
|
||||
enc.setting_notes.extend(self.plan.notes.iter().cloned());
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
@@ -905,9 +907,8 @@ impl SaveJob {
|
||||
/// order: when `stop` returns a value, nothing is written and that value is returned.
|
||||
pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let (plan, doc) = (&self.plan, &*self.doc);
|
||||
let mut enc = self.encode()?;
|
||||
let warnings = std::mem::take(&mut enc.warnings);
|
||||
let extra = json!({ "format": plan.format.id, "warnings": warnings });
|
||||
let enc = self.encode()?;
|
||||
let extra = json!({ "format": plan.format.id, "warnings": enc.notes() });
|
||||
let Some(path) = &plan.path else {
|
||||
let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?;
|
||||
out["name"] = json!(plan.name);
|
||||
|
||||
@@ -17,12 +17,12 @@ use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::super::{EngineError, NodeId, Result, Session, bad, bool_or, str_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::encode::{add_note, single_artboard};
|
||||
use super::export::{export_crop, isolated, selected_artwork, without_artboards};
|
||||
use super::naming::{self, NameParts};
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, ArtboardPick, Format, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_warnings, merge,
|
||||
unique_file_names_keeping_dots, with_black_output, writable, write_file,
|
||||
ARTBOARD_PARAMS, ArtboardPick, Format, Note, artboard_file_names_keeping_dots, create_dir, distinct_names_by, encode_with_notes, merge,
|
||||
note_texts, unique_file_names_keeping_dots, with_black_output, writable, write_file,
|
||||
};
|
||||
|
||||
const C: &str = "document.exportForScreens";
|
||||
@@ -1021,7 +1021,8 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
|
||||
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
|
||||
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
|
||||
/// so do different files that would share a name, with or without the `name` pattern. The reply's
|
||||
/// `warnings` lists every warning the encoders give for the files, each once.
|
||||
/// `warnings` lists every warning the encoders give for the files, each once, what the files lose
|
||||
/// first ([`super::note_texts`]).
|
||||
pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_passwords(p)?;
|
||||
let o = ScreenParams::of(p)?;
|
||||
@@ -1140,18 +1141,16 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
create_dir(dir)?;
|
||||
}
|
||||
let mut out = Output::default();
|
||||
// The encoders' warnings for every file, each once.
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
// The encoders' notes for every file, each once.
|
||||
let mut notes: Vec<Note> = Vec::new();
|
||||
// Include Bleed: a grown artboard already holds the bleed. Assets, layers and a selection are
|
||||
// written on a page of their own bounds, which it doesn't grow.
|
||||
let bleed_on_page = o.include_bleed && o.assets.is_none() && o.layers.is_none() && o.selection.is_none();
|
||||
let mut write = |doc: &Document, format: &str, options: &Value| -> Result<Vec<u8>> {
|
||||
// The steps are the files: an encoder's own steps (artboards, pages) are not reported.
|
||||
let (bytes, notes) = vectorcraft_doc::cancel::quiet(|| encode_with_warnings(doc, format, options))?;
|
||||
for w in notes {
|
||||
if !(bleed_on_page && w == super::pdf::BLEED_LEFT_OUT) && !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?;
|
||||
for n in given.into_iter().filter(|n| !(bleed_on_page && n.text == super::pdf::BLEED_LEFT_OUT)) {
|
||||
add_note(&mut notes, n);
|
||||
}
|
||||
Ok(bytes)
|
||||
};
|
||||
@@ -1226,6 +1225,8 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) ->
|
||||
if o.zip || folder.is_none() {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
// What the files lose first, across every file.
|
||||
let warnings = note_texts(¬es);
|
||||
let names: Vec<&str> = out.kept.iter().map(|(n, _)| n.as_str()).collect();
|
||||
if o.zip {
|
||||
let zip = super::zip::deflate(&out.kept, super::zip::FIXED_TIME, vectorcraft_doc::cancel::is_cancelled);
|
||||
|
||||
@@ -204,6 +204,7 @@ pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Enco
|
||||
enc.warnings.push(w);
|
||||
}
|
||||
}
|
||||
enc.add_setting_notes(out.setting_notes);
|
||||
enc.files.push((artboard, if compressed { vectorcraft_svg::compress_bytes(&bytes) } else { bytes }));
|
||||
}
|
||||
// Live type names its fonts; outlines and embedded fonts are the fallback font's.
|
||||
|
||||
@@ -194,6 +194,21 @@ fn placed_images_and_fill_hatches_can_be_left_out() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The reply gives what the drawings lose before a note on the options, across the files: the
|
||||
/// first artboard's drawing notes the fill hatches that `includeHatches: false` leaves out, and
|
||||
/// the second's also has a see-through rectangle that DXF 2000 writes opaque.
|
||||
#[test]
|
||||
fn what_the_drawings_lose_comes_before_what_an_option_left_out() {
|
||||
let mut s = two_boards();
|
||||
s.execute("object.setProps", &json!({"opacity": 50})).unwrap();
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "version": "2000", "includeHatches": false, "useArtboards": true})).unwrap();
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
let Some((option, losses)) = warnings.split_last() else { panic!("no notes") };
|
||||
assert!(option.starts_with("fill hatches are left out"), "{warnings:?}");
|
||||
assert!(losses.iter().any(|w| w.starts_with("transparency needs DXF 2004")), "{warnings:?}");
|
||||
assert!(!losses.iter().any(|w| w.starts_with("fill hatches")), "each note once: {warnings:?}");
|
||||
}
|
||||
|
||||
/// Two placed images whose pixel data can't be decoded are left out of the drawing and get no
|
||||
/// linked file, and `warnings` holds the note raster exports give, once, without naming either
|
||||
/// image's key.
|
||||
|
||||
@@ -117,3 +117,35 @@ fn formats_list_use_artboards() {
|
||||
}
|
||||
assert!(opts("vectorcraft").get("useArtboards").is_none());
|
||||
}
|
||||
|
||||
/// An export's reply gives what the file loses before its notes on the options, whatever order
|
||||
/// the encoder gave them: the WebP encoder notes that lossy WebP isn't applied before the export
|
||||
/// notes the type it drew in the fallback font. With only notes on the options, they keep their
|
||||
/// order.
|
||||
#[test]
|
||||
fn what_the_file_loses_comes_before_a_note_on_the_options() {
|
||||
let lossy = "lossy WebP isn't available yet: the file is lossless (exact, but larger)";
|
||||
let warnings = |s: &mut Session, p: Value| -> Vec<String> {
|
||||
let r = s.execute("document.export", &p).unwrap();
|
||||
r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).map(str::to_string).collect()
|
||||
};
|
||||
let mut s = session(60.0, 40.0, 1);
|
||||
assert_eq!(warnings(&mut s, json!({"format": "webp", "lossless": false})), [lossy]);
|
||||
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
|
||||
let w = warnings(&mut s, json!({"format": "webp", "lossless": false}));
|
||||
assert_eq!(w.len(), 2, "{w:?}");
|
||||
assert!(w[0].contains("fallback font") && w[0].contains("Nonexistent Sans Probe"), "{w:?}");
|
||||
assert_eq!(w[1], lossy);
|
||||
// document.serialize gives them in the same order.
|
||||
let r = s.execute("document.serialize", &json!({"format": "webp", "lossless": false})).unwrap();
|
||||
assert_eq!(r["warnings"], json!(w));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn note_texts_give_the_losses_first_each_kind_in_order() {
|
||||
use super::encode::{Note, note_texts};
|
||||
let notes = [Note::setting("s1"), Note::loss("l1"), Note::setting("s2"), Note::loss("l2")];
|
||||
assert_eq!(note_texts(¬es), ["l1", "l2", "s1", "s2"]);
|
||||
assert_eq!(note_texts(&[Note::setting("s1"), Note::setting("s2")]), ["s1", "s2"]);
|
||||
assert!(note_texts(&[]).is_empty());
|
||||
}
|
||||
|
||||
@@ -56,3 +56,21 @@ fn permissions_without_a_password_warn_and_a_password_applies_them() {
|
||||
let bytes = vectorcraft_format::base64_decode(locked["dataBase64"].as_str().unwrap()).unwrap();
|
||||
assert!(String::from_utf8_lossy(&bytes).contains("/Encrypt"));
|
||||
}
|
||||
|
||||
/// The writer notes the permissions it didn't apply before the export notes the type it drew in
|
||||
/// the fallback font: the reply gives what the file loses first, through both commands.
|
||||
#[test]
|
||||
fn the_fallback_font_note_comes_before_the_permissions_note() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 5, "y": 20, "text": "Ab", "font": "Nonexistent Sans Probe"})).unwrap();
|
||||
for r in [
|
||||
s.execute("document.exportPdf", &json!({"security": {"printing": "none"}})).unwrap(),
|
||||
s.execute("document.export", &json!({"format": "pdf", "security": {"printing": "none"}})).unwrap(),
|
||||
] {
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
let at = |s: &str| warnings.iter().position(|w| w.contains(s));
|
||||
let (font, permissions) = (at("Nonexistent Sans Probe"), at("permissions need a password"));
|
||||
assert!(font.is_some() && permissions.is_some() && font < permissions, "{warnings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -507,6 +507,22 @@ fn type_in_a_missing_family_is_named_once_for_every_format() {
|
||||
assert!(fallback[0].contains("Nonexistent Sans Probe"), "{fallback:?}");
|
||||
}
|
||||
|
||||
/// What a later file loses comes before a note on the options that an earlier file gave: the
|
||||
/// first artboard's WebP gives only the lossy WebP note, the second's also says its type doesn't
|
||||
/// fit.
|
||||
#[test]
|
||||
fn what_any_file_loses_comes_before_the_notes_on_the_options() {
|
||||
let mut s = session(2);
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect;
|
||||
let area = json!({"width": 30, "height": 8});
|
||||
s.execute("text.create", &json!({"x": second.x0 + 2.0, "y": second.y0 + 2.0, "size": 12, "area": area, "text": "Ab\nCd\nEf\nGh"})).unwrap();
|
||||
let r = export(&mut s, json!({"formats": [{"format": "webp", "lossless": false}]}));
|
||||
let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings[0].contains("doesn't fit its frame"), "{warnings:?}");
|
||||
assert!(warnings[1].starts_with("lossy WebP"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_document_gives_one_file_per_format() {
|
||||
let mut s = session(3);
|
||||
|
||||
@@ -1200,7 +1200,8 @@ pub(crate) fn with_found_paths(d: &mut Document, base: LinkBase) {
|
||||
/// `d`, a document saved at `doc_path`, as a reply to the caller asking now may show it: without
|
||||
/// read roots in force, `d` itself; with them, a copy in which each link [`path_shown`] does not
|
||||
/// allow names its file alone, without its relative path or the size and date kept of its file,
|
||||
/// and each data set's image value it does not allow names its file alone too. The folder Export
|
||||
/// and each data set's image value and linked JavaScript file (`svg_scripts`) it does not allow
|
||||
/// names its file alone too, while a JavaScript file given as a URL stays as it is. The folder Export
|
||||
/// for Screens last wrote to is left out of the export settings when it is outside the read roots.
|
||||
/// A link whose path is allowed but whose relative path leads outside the read roots loses its
|
||||
/// relative path. Links in the layers, symbols, graph designs, patterns, the pattern being edited
|
||||
@@ -1266,6 +1267,10 @@ pub(crate) fn with_hidden_paths_named<'a>(d: &'a Document, base: LinkBase) -> Co
|
||||
}
|
||||
}
|
||||
}
|
||||
let script_hidden = |f: &str| !path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url));
|
||||
for f in d.svg_scripts.iter_mut().filter(|f| script_hidden(f)) {
|
||||
*f = LinkInfo::new(f.as_str()).name().to_string();
|
||||
}
|
||||
Cow::Owned(d)
|
||||
}
|
||||
|
||||
|
||||
@@ -133,16 +133,16 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
// the objects differ, the members of groups and the objects in symbols' art included, and with
|
||||
// strokes that scale, when the sizes are out of proportion. The objects are then measured one
|
||||
// by one ([`Spans::measure`]), and the scales solved for. Objects with geometry effects,
|
||||
// objects with a butt-capped stroke along a segment at a slant, whose margins change with the
|
||||
// segment's direction, and type measured by its glyphs, are measured as drawn after each scale
|
||||
// tried instead ([`refit_drawn`]).
|
||||
// objects with a stroke that stops at the corners of a segment at a slant (butt caps, bevel and
|
||||
// miter joins), whose margins change with the segment's direction, and type measured by its
|
||||
// glyphs, are measured as drawn after each scale tried instead ([`refit_drawn`]).
|
||||
let to_local = frame.to_doc().inverse();
|
||||
let drawn = || {
|
||||
by_glyphs
|
||||
|| ids
|
||||
.iter()
|
||||
.filter_map(|id| d.node(*id))
|
||||
.any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_butt_stroke(&symbols, to_local))
|
||||
.any(|n| effects::preview::draws_geometry(&symbols, n) || n.has_slanted_stroke_corners(&symbols, to_local))
|
||||
};
|
||||
// Without Use Preview Bounds the box has no margins (`v`, `vs` and `g` are one box, glyph ink
|
||||
// included), so the scales above are exact and nothing is refitted.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -645,8 +645,8 @@ pub fn export_pdf(doc: &Document, opts: &vectorcraft_pdf::PdfOptions) -> std::re
|
||||
export_pdf_with_report(doc, opts).map(|r| r.bytes)
|
||||
}
|
||||
|
||||
/// Like [`export_pdf`], also returning the writer's warnings (options not applied yet, features
|
||||
/// approximated or left out).
|
||||
/// Like [`export_pdf`], also returning the writer's warnings (features approximated or left out)
|
||||
/// and its notes on the options (options not applied yet).
|
||||
pub fn export_pdf_with_report(
|
||||
doc: &Document,
|
||||
opts: &vectorcraft_pdf::PdfOptions,
|
||||
|
||||
@@ -1679,3 +1679,164 @@ fn the_frame_a_release_leaves_alone_has_the_bounds_of_the_whole_story() {
|
||||
let cached = t.cached_bounds.unwrap();
|
||||
assert!((cached.y0 - bounds.y0).abs() < 1e-6 && (cached.y1 - bounds.y1).abs() < 1e-6, "{cached:?} {bounds:?}");
|
||||
}
|
||||
|
||||
/// Twelve paragraphs that wrap, threaded through three frames, the first two of which end inside
|
||||
/// a paragraph; the last frame's paragraphs are indented 10 pt. → the session and the frames.
|
||||
fn split_story() -> (Session, [u64; 3]) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 900, "height": 1000})).unwrap();
|
||||
let words = "aaa bbb ccc ddd eee fff ggg hhh iii jjj ".repeat(3);
|
||||
let story = (1..=12).map(|i| format!("p{i} {}", words.trim_end())).collect::<Vec<_>>().join("\n");
|
||||
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 50}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let b = s.execute("text.thread.add", &json!({"from": a, "rect": [300, 10, 150, 50]})).unwrap()["id"].as_u64().unwrap();
|
||||
let c = s.execute("text.thread.add", &json!({"from": b, "rect": [600, 10, 250, 950]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [c], "leftIndent": 10})).unwrap();
|
||||
for id in [b, c] {
|
||||
assert!(text_of(&s.doc().unwrap().doc, NodeId(id)).unwrap().first_para_continues, "frame {id} starts inside a paragraph");
|
||||
}
|
||||
(s, [a, b, c])
|
||||
}
|
||||
|
||||
/// Each frame's text, paragraph styles and whether it continues a paragraph.
|
||||
fn frames_of(s: &Session, frames: &[u64]) -> Vec<(String, Vec<vectorcraft_doc::ParaStyle>, bool)> {
|
||||
frames
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let t = text_of(&s.doc().unwrap().doc, NodeId(*id)).unwrap();
|
||||
(t.plain_text(), t.paragraph_styles(), t.first_para_continues)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One entry for each paragraph of the story: a paragraph split between frames by its piece in the
|
||||
/// later frame. Each takes indents of its own, wide enough to move text between the frames.
|
||||
fn indent_entries(s: &Session, frames: &[u64]) -> Vec<Value> {
|
||||
let mut out = vec![];
|
||||
for (k, id) in frames.iter().enumerate() {
|
||||
let t = text_of(&s.doc().unwrap().doc, NodeId(*id)).unwrap();
|
||||
let next_continues = frames.get(k + 1).is_some_and(|n| text_of(&s.doc().unwrap().doc, NodeId(*n)).unwrap().first_para_continues);
|
||||
let plain = t.plain_text();
|
||||
let pieces: Vec<&str> = plain.split('\n').collect();
|
||||
let mut start = 0;
|
||||
for (i, piece) in pieces.iter().enumerate() {
|
||||
if i + 1 < pieces.len() || !next_continues {
|
||||
let n = out.len() as f64;
|
||||
out.push(json!({"id": id, "start": start, "leftIndent": 20.0 + n, "firstLineIndent": 15.0 - n}));
|
||||
}
|
||||
start += piece.len() + 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `paragraphIndents` sets each paragraph of a threaded story as one `text.setFormat` command for
|
||||
/// each paragraph would, the story's last paragraph first, with a paragraph split between frames
|
||||
/// set once; the story flows again once, and Undo and Redo take the whole change as one step.
|
||||
#[test]
|
||||
fn paragraph_indents_flow_a_threaded_story_once_as_one_command_per_paragraph_would() {
|
||||
let (mut one, frames) = split_story();
|
||||
let (mut each, _) = split_story();
|
||||
let entries = indent_entries(&one, &frames);
|
||||
assert_eq!(entries.len(), 12, "one entry for each paragraph of the story: {entries:?}");
|
||||
let commands: Vec<Value> = entries
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|e| {
|
||||
json!({"command": "text.setFormat", "params": {
|
||||
"ids": [e["id"]], "start": e["start"], "end": e["start"], "leftIndent": e["leftIndent"], "firstLineIndent": e["firstLineIndent"]
|
||||
}})
|
||||
})
|
||||
.collect();
|
||||
each.execute("command.batch", &json!({"label": "Left Indent", "commands": commands})).unwrap();
|
||||
let start = frames_of(&one, &frames);
|
||||
let undo = one.doc().unwrap().history.undo.len();
|
||||
let copied = COPIED.with(std::cell::Cell::get);
|
||||
let r = one.execute("text.setFormat", &json!({"paragraphIndents": entries})).unwrap();
|
||||
assert_eq!(COPIED.with(std::cell::Cell::get), copied + 1, "the story flows again once");
|
||||
// The first frame holds only the start of the paragraph that runs on into the second.
|
||||
assert_eq!(r, json!({"ids": frames[1..]}));
|
||||
assert_eq!(one.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let set = frames_of(&one, &frames);
|
||||
assert_ne!(set, start);
|
||||
assert_eq!(set, frames_of(&each, &frames));
|
||||
one.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(frames_of(&one, &frames), start);
|
||||
one.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(frames_of(&one, &frames), set);
|
||||
}
|
||||
|
||||
/// Thousands of paragraphs of a threaded story are set by one edit, which flows the story again
|
||||
/// once.
|
||||
#[test]
|
||||
fn paragraph_indents_over_thousands_of_paragraphs_flow_the_story_once() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 900, "height": 1000})).unwrap();
|
||||
let story = vec!["x"; 5000].join("\n");
|
||||
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 300}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let b = s.execute("text.thread.add", &json!({"from": a, "rect": [300, 10, 150, 300]})).unwrap()["id"].as_u64().unwrap();
|
||||
let entries: Vec<Value> = [a, b]
|
||||
.into_iter()
|
||||
.flat_map(|id| {
|
||||
let t = text_of(&s.doc().unwrap().doc, NodeId(id)).unwrap();
|
||||
let count = t.paragraph_count();
|
||||
(0..count).map(move |i| json!({"id": id, "start": 2 * i, "leftIndent": (i % 7) as f64}))
|
||||
})
|
||||
.collect();
|
||||
assert!(entries.len() >= 5000, "{}", entries.len());
|
||||
let (undo, copied) = (s.doc().unwrap().history.undo.len(), COPIED.with(std::cell::Cell::get));
|
||||
s.execute("text.setFormat", &json!({"paragraphIndents": entries})).unwrap();
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), COPIED.with(std::cell::Cell::get)), (undo + 1, copied + 1));
|
||||
let t = text_of(&s.doc().unwrap().doc, NodeId(a)).unwrap();
|
||||
assert_eq!((t.para_at(0).left_indent, t.para_at(1).left_indent, t.para_at(8).left_indent), (0.0, 1.0, 1.0));
|
||||
}
|
||||
|
||||
/// `paragraphIndents` that would change no paragraph leaves the document and its history alone, and
|
||||
/// a bad one is refused before anything changes.
|
||||
#[test]
|
||||
fn paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing() {
|
||||
let (mut s, [a, b, c]) = split_story();
|
||||
let start = frames_of(&s, &[a, b, c]);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let copied = COPIED.with(std::cell::Cell::get);
|
||||
let r =
|
||||
s.execute("text.setFormat", &json!({"paragraphIndents": [{"id": a, "start": 0, "leftIndent": 0}, {"id": c, "start": 0, "leftIndent": 10}]}));
|
||||
assert_eq!(r.unwrap(), json!({"ids": [a, c]}));
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), COPIED.with(std::cell::Cell::get)), (undo, copied), "nothing to change");
|
||||
let paragraph = text(&s, c).find('\n').unwrap() + 1;
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 900, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let ok = json!({"id": c, "start": paragraph, "leftIndent": 30});
|
||||
for bad in [
|
||||
json!({"paragraphIndents": []}),
|
||||
json!({"paragraphIndents": {"id": a, "start": 0, "leftIndent": 30}}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": 30}], "ids": [a]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": 30}], "leftIndent": 5}),
|
||||
json!({"paragraphIndents": [ok, 3]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": 0}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": "30"}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": 1300}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": 0, "firstLineIndent": -1297}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": 0, "leftIndent": 30, "spaceBefore": 4}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": "a", "start": 0, "leftIndent": 30}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": rect, "start": 0, "leftIndent": 30}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": 999_999, "start": 0, "leftIndent": 30}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "leftIndent": 30}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": -1, "leftIndent": 30}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": a, "start": 1, "leftIndent": 30}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": c, "start": paragraph, "leftIndent": 31}]}),
|
||||
json!({"paragraphIndents": [ok, {"id": c, "start": paragraph, "leftIndent": 30, "firstLineIndent": 0}]}),
|
||||
json!({"paragraphIndents": vec![ok.clone(); crate::cmd::panelcmds::MAX_PARAGRAPH_INDENTS + 1]}),
|
||||
] {
|
||||
assert!(s.execute("text.setFormat", &bad).is_err(), "{bad}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{bad}");
|
||||
assert_eq!(frames_of(&s, &[a, b, c]), start, "{bad}");
|
||||
}
|
||||
// The same entry twice is one change.
|
||||
s.execute("text.setFormat", &json!({"paragraphIndents": [ok, ok]})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
assert_eq!(text_of(&s.doc().unwrap().doc, NodeId(c)).unwrap().para_at(1).left_indent, 30.0);
|
||||
}
|
||||
|
||||
@@ -2209,3 +2209,127 @@ fn set_path_handle_reshapes_type_on_a_path() {
|
||||
assert!(s.execute("text.setPathHandle", &json!({"id": id.0, "anchor": 9, "which": "out", "x": 0, "y": 0})).is_err(), "no such anchor");
|
||||
assert!(s.execute("text.setPathHandle", &json!({"id": path["id"], "anchor": 0, "which": "out", "x": 0, "y": 0})).is_err(), "not type");
|
||||
}
|
||||
|
||||
/// `text.setFormat` refuses a number or switch given as another type, naming the key, and
|
||||
/// changes nothing; null leaves the attribute as it is.
|
||||
#[test]
|
||||
fn set_format_refuses_a_param_of_the_wrong_type() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let state = |s: &Session| (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let before = state(&s);
|
||||
for key in [
|
||||
"baselineShift",
|
||||
"hScale",
|
||||
"vScale",
|
||||
"rotation",
|
||||
"leftIndent",
|
||||
"rightIndent",
|
||||
"firstLineIndent",
|
||||
"spaceBefore",
|
||||
"spaceAfter",
|
||||
"wordsLongerThan",
|
||||
"afterFirst",
|
||||
"beforeLast",
|
||||
"hyphenLimit",
|
||||
"hyphenationZone",
|
||||
] {
|
||||
for wrong in [json!("30"), json!(true), json!([30])] {
|
||||
let err = s.execute("text.setFormat", &json!({ key: wrong })).unwrap_err().to_string();
|
||||
assert!(err.contains(&format!("`{key}` must be a number, not {wrong}")), "{key}: {err}");
|
||||
}
|
||||
}
|
||||
for key in ["underline", "allCaps", "hyphenate", "noBreak"] {
|
||||
let err = s.execute("text.setFormat", &json!({ key: "true" })).unwrap_err().to_string();
|
||||
assert!(err.contains(&format!("`{key}` must be true or false")), "{key}: {err}");
|
||||
}
|
||||
let err = s.execute("text.setFormat", &json!({"leftIndent": 30, "firstLineIndent": "12"})).unwrap_err().to_string();
|
||||
assert!(err.contains("`firstLineIndent` must be a number"), "{err}");
|
||||
assert!(state(&s) == before, "a refused call changes nothing and records no undo step");
|
||||
s.execute("text.setFormat", &json!({"leftIndent": 30, "firstLineIndent": null})).unwrap();
|
||||
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert_eq!((t.para_at(0).left_indent, t.para_at(0).first_line_indent), (30.0, 0.0));
|
||||
}
|
||||
|
||||
/// `text.setFormat` reads a null value as one left out: a call whose attributes are all null has
|
||||
/// nothing to change, and records no edit, no undo step and no new revision.
|
||||
#[test]
|
||||
fn set_format_with_only_null_values_changes_nothing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.clone(), st.history.undo.len(), st.revision)
|
||||
};
|
||||
let before = state(&s);
|
||||
for params in [
|
||||
json!({"leftIndent": null}),
|
||||
json!({"leftIndent": null, "firstLineIndent": null, "underline": null}),
|
||||
json!({"kerning": null, "antiAlias": null, "list": null, "wordSpacing": null}),
|
||||
json!({"mojikumi": null}),
|
||||
json!({"kinsoku": null, "kinsokuType": null, "direction": null, "leadingModel": null}),
|
||||
json!({"burasagari": null, "kashida": null, "singleWordJustification": null, "autoLeading": null}),
|
||||
json!({"ids": [id], "start": 0, "end": 3, "spaceBefore": null}),
|
||||
] {
|
||||
let err = s.execute("text.setFormat", ¶ms).unwrap_err().to_string();
|
||||
assert!(err.contains("nothing to change"), "{params}: {err}");
|
||||
assert!(state(&s) == before, "{params}: no edit, no undo step and no new revision");
|
||||
}
|
||||
// A null beside a value leaves only its own attribute.
|
||||
let para = |d: &vectorcraft_doc::Document| {
|
||||
let NodeKind::Text(t) = &d.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
(t.para_at(0).mojikumi, t.para_at(0).kinsoku)
|
||||
};
|
||||
let mojikumi = para(&before.0).0;
|
||||
s.execute("text.setFormat", &json!({"mojikumi": null, "kinsoku": "soft"})).unwrap();
|
||||
assert_eq!(para(&s.doc().unwrap().doc), (mojikumi, vectorcraft_doc::Kinsoku::Soft));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before.1 + 1, "one undo step");
|
||||
}
|
||||
|
||||
/// `text.setFormat` with the values the text already has succeeds and names its objects, but
|
||||
/// records no edit, no undo step and no new revision.
|
||||
#[test]
|
||||
fn set_format_with_the_current_values_records_nothing() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let state = |s: &Session| {
|
||||
let st = s.doc().unwrap();
|
||||
(st.doc.clone(), st.history.undo.len(), st.revision)
|
||||
};
|
||||
let before = state(&s);
|
||||
let NodeKind::Text(t) = &before.0.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
let hyphenate = t.para_at(0).hyphenate;
|
||||
for params in [
|
||||
json!({"leftIndent": 0, "firstLineIndent": 0}),
|
||||
json!({"underline": false, "strikethrough": false, "hyphenate": hyphenate}),
|
||||
json!({"ids": [id], "start": 0, "end": 3, "spaceBefore": 0, "spaceAfter": 0}),
|
||||
json!({"ids": [id], "start": 4, "end": 7, "leftIndent": null, "rightIndent": 0}),
|
||||
] {
|
||||
let out = s.execute("text.setFormat", ¶ms).unwrap();
|
||||
assert_eq!(out["ids"], json!([id]), "{params}");
|
||||
assert!(state(&s) == before, "{params}: no edit, no undo step and no new revision");
|
||||
}
|
||||
// A call that changes a value is one undo step; the same call again records nothing.
|
||||
s.execute("text.setFormat", &json!({"leftIndent": 24})).unwrap();
|
||||
let changed = state(&s);
|
||||
assert_eq!((changed.1, changed.2), (before.1 + 1, before.2 + 1), "one undo step and one revision");
|
||||
s.execute("text.setFormat", &json!({"leftIndent": 24})).unwrap();
|
||||
assert!(state(&s) == changed, "the same value again records nothing");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before.0, "one undo restores the text");
|
||||
// The anti-aliasing method is compared the same way.
|
||||
s.execute("text.setFormat", &json!({"antiAlias": "none"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"antiAlias": "strong"})).unwrap();
|
||||
let strong = state(&s);
|
||||
assert!(strong.1 > before.1, "a new method is an undo step");
|
||||
let NodeKind::Text(t) = &strong.0.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert_eq!(t.anti_alias, vectorcraft_doc::text::TypeAntiAlias::Strong);
|
||||
s.execute("text.setFormat", &json!({"antiAlias": "strong"})).unwrap();
|
||||
assert!(state(&s) == strong, "the same method again records nothing");
|
||||
}
|
||||
|
||||
@@ -47,9 +47,9 @@ fn selection_and_unlocked(s: &Session) -> std::result::Result<(), String> {
|
||||
variables_unlocked(s)
|
||||
}
|
||||
|
||||
/// Ends a typing session as [`Session::edit`] would, before a helper below compares the document,
|
||||
/// Ends a typing session as [`Session::edit`] would, before a command compares the document,
|
||||
/// so the typing is its own undo step whether or not the command then changes anything.
|
||||
fn settle_typing(s: &mut Session) -> Result<()> {
|
||||
pub(super) fn settle_typing(s: &mut Session) -> Result<()> {
|
||||
if !s.previewing && super::typing_in_progress(s) {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Window › 3D and Materials › Quick Actions › Expand as Wireframes: each object with a 3D effect
|
||||
//! becomes a group of stroked paths, the edges of the faces its effect draws.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::appearance::AppearanceItem;
|
||||
use vectorcraft_doc::{Appearance, LineJoin, Node, NodeId, NodeKind, StrokeLayer};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::{CommandSpec, Result, Session, bad, checked_ids_or_selection, cmd, has_doc};
|
||||
|
||||
const C: &str = "effect.expandAsWireframes";
|
||||
|
||||
/// The name of the undo step.
|
||||
const LABEL: &str = "Expand as Wireframes";
|
||||
|
||||
/// The weight of a wireframe edge's stroke, in points (VectorCraft's own).
|
||||
pub const WIRE_WEIGHT: f64 = 0.5;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"effect.expandAsWireframes",
|
||||
"Expand as Wireframes",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [..] (default: the selected objects)} replace each object that has a visible 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D (Classic) forms, on the object or on its fills and strokes) with a group of paths: the edges of the faces the effect draws, as the object is turned and projected now, each edge once (edges that meet end to end make one path, closed where it comes back to its start; curved edges stay curves; geometry effects after the 3D effect, on the object or on a fill or stroke, reshape them too), stroked 0.5 pt black with round joins and no fill (VectorCraft's own); the group takes the object's place, id, name, opacity, blending mode, opacity mask, attributes, slice and text wrap and is selected (a layer stays a layer holding the edges, which are selected, and its ruler guides and paths made into guides; a path inside a compound path in ids stands for the compound path); objects without a visible 3D effect are left as they are; one undo step. An error, with nothing changed, when no object is selected or given, when none has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than 1,000,000 edges → {ids}",
|
||||
has_doc,
|
||||
expand_as_wireframes
|
||||
)]
|
||||
}
|
||||
|
||||
/// A wireframe edge's appearance: a 0.5 pt black stroke with round joins and no fill.
|
||||
fn wire_appearance() -> Appearance {
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), WIRE_WEIGHT);
|
||||
stroke.join = LineJoin::Round;
|
||||
Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() }
|
||||
}
|
||||
|
||||
/// The guides (ruler guides and paths made into guides) of layer `n` and then those of the groups
|
||||
/// and sublayers inside it, in order, added to `out`. A guide from a hidden or locked sublayer, or
|
||||
/// from one inside a hidden or locked group or sublayer, is hidden or locked itself.
|
||||
fn guides(n: &Node, hidden: bool, locked: bool, out: &mut Vec<Arc<Node>>) {
|
||||
let Some(children) = n.children() else { return };
|
||||
for c in children.iter().filter(|c| c.is_guide()) {
|
||||
let mut g = c.clone();
|
||||
if hidden || locked {
|
||||
let g = Arc::make_mut(&mut g);
|
||||
g.visible &= !hidden;
|
||||
g.locked |= locked;
|
||||
}
|
||||
out.push(g);
|
||||
}
|
||||
for c in children.iter().filter(|c| !c.is_guide()) {
|
||||
guides(c, hidden || !c.visible, locked || c.locked, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn expand_as_wireframes(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = checked_ids_or_selection(s, p, C)?;
|
||||
if roots.is_empty() {
|
||||
return Err(bad(C, "select an object with a 3D effect, or give its id in ids"));
|
||||
}
|
||||
// Every wireframe is built before the edit, so a failure leaves the document and its history as
|
||||
// they are.
|
||||
let d = &s.doc()?.doc;
|
||||
let mut wires = vec![];
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for id in roots {
|
||||
// A path inside a compound path stands for the compound path, which draws it. An id given
|
||||
// twice is expanded once.
|
||||
let id = super::path::compound_or_self(d, id);
|
||||
if !seen.insert(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(n) = d.node(id) else { continue };
|
||||
if !effects::has_revolve(n) && !effects::has_solid(n) {
|
||||
continue;
|
||||
}
|
||||
let wire = effects::three_d_wireframe_in(Some(d), n).map_err(|e| bad(C, format!("object {}: {e}", id.0)))?;
|
||||
wires.push((id, wire));
|
||||
}
|
||||
if wires.is_empty() {
|
||||
return Err(bad(C, "no selected or given object has a visible 3D effect"));
|
||||
}
|
||||
let ids: Vec<NodeId> = s.edit(LABEL, |d, sel| {
|
||||
let mut out = vec![];
|
||||
let mut selected = vec![];
|
||||
for (id, wire) in wires {
|
||||
let Some(source) = d.node(id) else { continue };
|
||||
if matches!(source.kind, NodeKind::Layer { .. }) {
|
||||
// A layer stays a layer: its members become the edges, and its 3D effect is removed.
|
||||
// Its guides and those of its sublayers are not art: they stay, after the edges.
|
||||
let mut layer = source.clone();
|
||||
let mut kept = vec![];
|
||||
guides(source, false, false, &mut kept);
|
||||
let mut children: Vec<Arc<Node>> = wire.into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, wire_appearance()))).collect();
|
||||
selected.extend(children.iter().map(|c| c.id));
|
||||
children.extend(kept);
|
||||
if let Some(members) = layer.children_mut() {
|
||||
*members = children;
|
||||
}
|
||||
layer.appearance = Default::default();
|
||||
if let Some(slot) = d.node_mut(id) {
|
||||
*slot = layer;
|
||||
out.push(id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// The group keeps the object's name, visibility, lock, bounding box angle, transparency
|
||||
// (opacity, blending mode, isolation, knockout and opacity mask), attributes, slice and text
|
||||
// wrap.
|
||||
let mut group = Node::group(id, vec![]);
|
||||
group.name = source.name.clone();
|
||||
group.visible = source.visible;
|
||||
group.locked = source.locked;
|
||||
group.opacity = source.opacity;
|
||||
group.blend = source.blend;
|
||||
group.isolate = source.isolate;
|
||||
group.knockout = source.knockout;
|
||||
group.knockout_shape = source.knockout_shape;
|
||||
group.bbox_angle = source.bbox_angle;
|
||||
let extras = source.extras();
|
||||
let (mask, attrs, slice, wrap) = (extras.mask.clone(), extras.attrs.clone(), extras.slice.clone(), extras.wrap);
|
||||
if mask.is_some() || attrs.is_some() || slice.is_some() || wrap.is_some() {
|
||||
let mut e = group.extras_mut();
|
||||
e.mask = mask;
|
||||
e.attrs = attrs;
|
||||
e.slice = slice;
|
||||
e.wrap = wrap;
|
||||
}
|
||||
let children = wire.into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, wire_appearance()))).collect();
|
||||
group.kind = NodeKind::Group { children, clip: false };
|
||||
if let Some(slot) = d.node_mut(id) {
|
||||
*slot = group;
|
||||
out.push(id);
|
||||
selected.push(id);
|
||||
}
|
||||
}
|
||||
sel.set(selected);
|
||||
Ok(out)
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,240 @@
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::appearance::AppearanceItem;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// A new document with a filled 100 pt square; `effect` is applied to it when given.
|
||||
fn setup(effect: Option<&str>) -> (Session, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
|
||||
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
|
||||
if let Some(effect) = effect {
|
||||
s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{}})).unwrap();
|
||||
}
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, p: Value) -> crate::Result<Value> {
|
||||
s.execute("effect.expandAsWireframes", &p)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_3d_object_becomes_a_selected_group_of_stroked_edges_in_one_undo_step() {
|
||||
for effect in [
|
||||
"threeD.extrude",
|
||||
"threeD.classicExtrude",
|
||||
"threeD.revolve",
|
||||
"threeD.classicRevolve",
|
||||
"threeD.inflate",
|
||||
"threeD.rotate",
|
||||
"threeD.classicRotate",
|
||||
] {
|
||||
let (mut s, id) = setup(Some(effect));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().name = Some("Box".into());
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let history = undo_len(&s);
|
||||
let out = run(&mut s, json!({})).unwrap_or_else(|e| panic!("{effect}: {e}"));
|
||||
assert_eq!(out["ids"], json!([id.0]), "{effect}");
|
||||
let st = s.doc().unwrap();
|
||||
let group = st.doc.node(id).unwrap();
|
||||
let NodeKind::Group { children, clip: false } = &group.kind else { panic!("{effect}: a group") };
|
||||
assert!(!children.is_empty(), "{effect}");
|
||||
assert_eq!(group.name.as_deref(), Some("Box"), "{effect}");
|
||||
assert!(group.appearance.effects.is_empty(), "{effect}: the effect is gone");
|
||||
for c in children {
|
||||
assert!(c.path_data().is_some(), "{effect}: paths only");
|
||||
let [AppearanceItem::Stroke(stroke)] = c.appearance.items.as_slice() else { panic!("{effect}: one stroke and no fill") };
|
||||
assert_eq!(stroke.width, super::WIRE_WEIGHT);
|
||||
}
|
||||
assert_eq!(st.selection.objects, vec![id], "{effect}");
|
||||
assert_eq!(undo_len(&s), history + 1, "{effect}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before, "{effect}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_group_keeps_the_object_s_transparency() {
|
||||
let (mut s, id) = setup(Some("threeD.extrude"));
|
||||
s.execute("transparency.set", &json!({"opacity": 50, "knockout": "on"})).unwrap();
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().bbox_angle = 0.25;
|
||||
let before = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
run(&mut s, json!({})).unwrap();
|
||||
let group = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert!((group.opacity - 0.5).abs() < 1e-6, "{}", group.opacity);
|
||||
assert_eq!((group.opacity, group.blend, group.knockout), (before.opacity, before.blend, before.knockout));
|
||||
assert_eq!(group.bbox_angle, 0.25, "the bounding box keeps its angle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_with_a_3d_effect_stays_a_layer_holding_the_edges() {
|
||||
let (mut s, _) = setup(None);
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap();
|
||||
let history = undo_len(&s);
|
||||
// An id given twice is expanded once.
|
||||
let out = run(&mut s, json!({"ids":[layer.0, layer.0]})).unwrap();
|
||||
assert_eq!(out["ids"], json!([layer.0]));
|
||||
let st = s.doc().unwrap();
|
||||
let node = st.doc.node(layer).unwrap();
|
||||
assert!(matches!(node.kind, NodeKind::Layer { .. }));
|
||||
assert!(node.appearance.effects.is_empty());
|
||||
let children = node.children().unwrap();
|
||||
assert!(!children.is_empty() && children.iter().all(|c| c.path_data().is_some()));
|
||||
assert_eq!(st.selection.objects, children.iter().map(|c| c.id).collect::<Vec<_>>());
|
||||
assert_eq!(undo_len(&s), history + 1);
|
||||
}
|
||||
|
||||
/// A layer's ruler guides are not art: they stay on the layer, after the edges, and are not selected.
|
||||
#[test]
|
||||
fn a_layer_keeps_its_ruler_guides() {
|
||||
let (mut s, _) = setup(None);
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap();
|
||||
let guides = |s: &Session| -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().filter(|c| c.is_ruler_guide()).map(|c| c.id).collect()
|
||||
};
|
||||
let before = guides(&s);
|
||||
assert_eq!(before.len(), 1);
|
||||
s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap();
|
||||
run(&mut s, json!({"ids":[layer.0]})).unwrap();
|
||||
assert_eq!(guides(&s), before);
|
||||
let st = s.doc().unwrap();
|
||||
let children = st.doc.node(layer).unwrap().children().unwrap();
|
||||
assert!(children.len() > 1 && children.last().is_some_and(|c| c.is_ruler_guide()));
|
||||
assert!(!st.selection.objects.is_empty() && st.selection.objects.iter().all(|id| !before.contains(id)));
|
||||
}
|
||||
|
||||
/// A path made into a guide is not art either: it stays on the layer, after the edges, and is not
|
||||
/// selected.
|
||||
#[test]
|
||||
fn a_layer_keeps_its_path_guides() {
|
||||
let (mut s, id) = setup(None);
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("path.create", &json!({"d":"M0 300L300 300"})).unwrap();
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
let guides = |s: &Session| -> Vec<NodeId> {
|
||||
s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().filter(|c| c.is_guide()).map(|c| c.id).collect()
|
||||
};
|
||||
let before = guides(&s);
|
||||
assert_eq!(before.len(), 1);
|
||||
assert_ne!(before[0], id);
|
||||
s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap();
|
||||
run(&mut s, json!({"ids":[layer.0]})).unwrap();
|
||||
assert_eq!(guides(&s), before);
|
||||
let st = s.doc().unwrap();
|
||||
let children = st.doc.node(layer).unwrap().children().unwrap();
|
||||
assert!(children.len() > 1 && children.last().is_some_and(|c| c.is_guide()));
|
||||
assert!(!st.selection.objects.is_empty() && st.selection.objects.iter().all(|i| !before.contains(i)));
|
||||
}
|
||||
|
||||
/// The number of segments in the wireframe group `id`.
|
||||
fn segments(s: &Session, id: NodeId) -> usize {
|
||||
let st = s.doc().unwrap();
|
||||
st.doc.node(id).unwrap().children().unwrap().iter().flat_map(|c| &c.path_data().unwrap().subpaths).map(|sp| sp.segment_count()).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_box_expands_to_the_nine_edges_of_its_three_faces() {
|
||||
let (mut s, id) = setup(Some("threeD.extrude"));
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
run(&mut s, json!({"ids":[id.0]})).unwrap();
|
||||
assert_eq!(segments(&s, id), 9);
|
||||
// A stroke is outlined before the effect, so its own solid adds its edges.
|
||||
let (mut s, id) = setup(Some("threeD.extrude"));
|
||||
run(&mut s, json!({"ids":[id.0]})).unwrap();
|
||||
assert!(segments(&s, id) > 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_without_a_3d_effect_are_left_and_none_at_all_is_an_error() {
|
||||
let (mut s, plain) = setup(None);
|
||||
let history = undo_len(&s);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let e = run(&mut s, json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("no selected or given object has a visible 3D effect"), "{e}");
|
||||
assert_eq!(undo_len(&s), history, "no undo step when nothing changes");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
|
||||
// A hidden 3D effect draws nothing to expand.
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.extrude","item":null,"params":{}})).unwrap();
|
||||
s.execute("effect.setParams", &json!({"index":0,"item":null,"visible":false})).unwrap();
|
||||
assert!(run(&mut s, json!({})).is_err());
|
||||
|
||||
// With nothing selected.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let e = run(&mut s, json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("select an object with a 3D effect"), "{e}");
|
||||
|
||||
// A second object with a 3D effect expands; the plain one is left as it is.
|
||||
let other = NodeId(s.execute("path.create", &json!({"d":"M250 250L300 250L300 300Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.remove", &json!({"ids":[plain.0],"index":0,"item":null})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids":[other.0],"color":"#ff0000"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"ids":[other.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap();
|
||||
let kept = s.doc().unwrap().doc.node(plain).unwrap().clone();
|
||||
let out = run(&mut s, json!({"ids":[plain.0, other.0]})).unwrap();
|
||||
assert_eq!(out["ids"], json!([other.0]));
|
||||
assert_eq!(s.doc().unwrap().doc.node(plain).unwrap(), &kept);
|
||||
}
|
||||
|
||||
/// A live-effect plug-in after a fill's 3D effect that links its pieces to one of the document's
|
||||
/// swatches reshapes the edges, as it reshapes the drawn surface.
|
||||
#[test]
|
||||
fn a_painted_effect_after_a_fill_s_3d_effect_finds_the_document_s_swatches() {
|
||||
use vectorcraft_geom::{PathData, Point, SubPath};
|
||||
let mut leaf = serde_json::to_value(vectorcraft_color::Paint::solid(vectorcraft_color::Color::from_hex("#00ff00").unwrap())).unwrap();
|
||||
leaf["swatch"] = json!("Leaf");
|
||||
let corners = [Point::new(300.0, 300.0), Point::new(320.0, 300.0), Point::new(320.0, 320.0), Point::new(300.0, 320.0)];
|
||||
let output = json!({"objects": [{"path": PathData::single(SubPath::polyline(&corners, true)), "fills": [leaf]}]}).to_string();
|
||||
let manifest = r#"{"id":"test.engine.wireleaf","name":"Test wireleaf","version":"1","kind":"effect","api":2,"paintOutput":true,"params":{}}"#;
|
||||
let wasm = wat::parse_str(vectorcraft_plugins::wat::returning(manifest, &output)).unwrap();
|
||||
for effect in ["threeD.extrude", "threeD.revolve"] {
|
||||
let (mut s, id) = setup(None);
|
||||
s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "replace": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("swatch.new", &json!({"name": "Leaf", "color": "#00ff00", "global": true})).unwrap();
|
||||
let items = &s.doc().unwrap().doc.node(id).unwrap().appearance.items;
|
||||
let fill = items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
for e in [effect, "plugin.test.engine.wireleaf"] {
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": e, "item": fill, "params": {}})).unwrap();
|
||||
}
|
||||
run(&mut s, json!({"ids": [id.0]})).unwrap_or_else(|e| panic!("{effect}: {e}"));
|
||||
let b = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap();
|
||||
assert_eq!((b.x0, b.y0, b.x1, b.y1), (300.0, 300.0, 320.0, 320.0), "{effect}: the plug-in's square");
|
||||
assert_eq!(segments(&s, id), 4, "{effect}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A path inside a compound path in `ids` stands for the compound path: the compound path becomes
|
||||
/// the group, and no member is replaced by a group inside it.
|
||||
#[test]
|
||||
fn a_compound_path_member_in_ids_expands_the_compound_path() {
|
||||
let (mut s, a) = setup(None);
|
||||
let b = NodeId(s.execute("path.create", &json!({"d":"M250 100L350 100L350 200L250 200Z"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids":[a.0, b.0]})).unwrap();
|
||||
let c = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("effect.apply", &json!({"ids":[c.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap();
|
||||
let member = s.doc().unwrap().doc.node(c).unwrap().children().unwrap()[0].id;
|
||||
let out = run(&mut s, json!({"ids":[member.0]})).unwrap();
|
||||
assert_eq!(out["ids"], json!([c.0]));
|
||||
let st = s.doc().unwrap();
|
||||
let NodeKind::Group { children, clip: false } = &st.doc.node(c).unwrap().kind else { panic!("the compound path is a group") };
|
||||
assert!(!children.is_empty() && children.iter().all(|ch| ch.path_data().is_some()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_ids_are_errors() {
|
||||
let (mut s, _) = setup(Some("threeD.extrude"));
|
||||
for p in [json!({"ids":[9999]}), json!({"ids":"x"}), json!({"ids":[-1]})] {
|
||||
let history = undo_len(&s);
|
||||
assert!(run(&mut s, p.clone()).is_err(), "{p}");
|
||||
assert_eq!(undo_len(&s), history, "{p}");
|
||||
}
|
||||
}
|
||||
@@ -529,6 +529,42 @@ fn a_spread_gradient_expands_into_whole_bands_for_each_run() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient that repeats across a box in more runs than are written (700 runs of 0.2 pt) is not
|
||||
/// expanded into its first runs and a flat last color: the fill stays a gradient, and the rest of
|
||||
/// the object (its stroke) still expands. `object.expand.info` reports no gradient or fill to
|
||||
/// expand, and Expand with only Fill on reports nothing to expand; the same gradient in 70 runs
|
||||
/// (10 repeats) reports both.
|
||||
#[test]
|
||||
fn a_spread_gradient_with_more_runs_than_written_stays_a_gradient() {
|
||||
let gradient = |repeats: u32| {
|
||||
json!({"kind": "linear", "spread": "repeat", "repeats": repeats, "start": [30, 100], "end": [50, 100],
|
||||
"stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]})
|
||||
};
|
||||
for (repeats, expands) in [(10, true), (100, false)] {
|
||||
let mut s = session();
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gradient(repeats), true);
|
||||
let info = s.execute("object.expand.info", &json!({})).unwrap();
|
||||
assert_eq!(
|
||||
(info["gradient"].clone(), info["fill"].clone(), info["stroke"].clone()),
|
||||
(json!(expands), json!(expands), json!(true)),
|
||||
"{repeats}"
|
||||
);
|
||||
let only_fill = s.execute("object.expand", &json!({"object": false, "stroke": false}));
|
||||
assert_eq!(only_fill.is_ok(), expands, "{repeats}: {only_fill:?}");
|
||||
}
|
||||
for to in [json!({"steps": 240}), json!({"gradient": "mesh"})] {
|
||||
let mut s = session();
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gradient(100), true);
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", to.clone());
|
||||
let after = render(&s);
|
||||
assert!(mean_diff(&before, &after) < 2.0, "{to}: {}", mean_diff(&before, &after));
|
||||
let mut gradients = 0;
|
||||
s.doc().unwrap().doc.walk(|n| gradients += usize::from(matches!(n.appearance.fill_paint(), Paint::Gradient(_))));
|
||||
assert_eq!(gradients, 1, "{to}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() {
|
||||
for gradient in [
|
||||
|
||||
@@ -1102,6 +1102,13 @@ fn document_replies_leave_out_paths_outside_the_read_roots() {
|
||||
s.execute("variable.define", &json!({"name": "Photo", "kind": "image"})).unwrap();
|
||||
s.execute("dataset.new", &json!({"name": "Row", "values": {"Photo": pic}})).unwrap();
|
||||
let image = r["ids"][0].as_u64().unwrap();
|
||||
// A linked JavaScript file outside the read roots, and one given as a URL.
|
||||
let script = away.file("menu.js");
|
||||
write(&script, b"void 0;");
|
||||
let url = "https://example.com/scripts/menu.js";
|
||||
for file in [script.as_str(), url] {
|
||||
s.execute("svgInteractivity.addFile", &json!({"file": file})).unwrap();
|
||||
}
|
||||
let poster = away.file("poster.vectorcraft");
|
||||
save(&mut s, &poster);
|
||||
// The folder Export for Screens wrote to, and a pattern of the linked image being edited: its
|
||||
@@ -1124,11 +1131,13 @@ fn document_replies_leave_out_paths_outside_the_read_roots() {
|
||||
assert!(model.contains(&format!("\"path\":\"{name}\"")), "{name}: {model}");
|
||||
}
|
||||
assert!(model.contains("{\"image\":\"photo.png\"}"), "{model}");
|
||||
assert!(model.contains(&format!("\"svg_scripts\":[\"menu.js\",\"{url}\"]")), "{model}");
|
||||
// The document keeps its links, and a caller whose read roots hold the files sees every path.
|
||||
assert_eq!(placed(&s, id).link.path, src);
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [script.as_str(), url]);
|
||||
for model in [ask(&mut s, &away.0, "document.json"), s.execute("document.json", &json!({})).unwrap()] {
|
||||
let model = model.to_string();
|
||||
for path in [&src, &pic, &out] {
|
||||
for path in [&src, &pic, &out, &script] {
|
||||
assert!(model.contains(&json!(path).to_string()), "{path}: {model}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -722,6 +722,27 @@ fn expanding_a_gradient_fill_keeps_each_piece_s_own_paint() {
|
||||
}
|
||||
}
|
||||
|
||||
/// `object.expand.info` measures each piece a painted effect returns: a piece whose repeating
|
||||
/// gradient needs more runs across it than are written (1,000) reports no gradient to expand, as
|
||||
/// Expand leaves it a gradient, and the same gradient in 10 runs reports one.
|
||||
#[test]
|
||||
fn expand_info_measures_the_gradient_on_each_painted_piece() {
|
||||
for (end, expands) in [(120.0, true), (100.2, false)] {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 10.0, "#ff0000");
|
||||
let gradient = json!({"kind": "linear", "spread": "repeat", "repeats": 10, "start": [100, 50], "end": [end, 50]});
|
||||
run(&mut s, "paint.setFill", json!({"ids": [id.0], "gradient": gradient}));
|
||||
let out = json!({"objects": [{"path": square_at(100.0)}]}).to_string();
|
||||
install_wat(&mut s, &tpl::returning(&painting("test.engine.expandruns", true), &out));
|
||||
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.expandruns"}));
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
let info = s.execute("object.expand.info", &json!({})).unwrap();
|
||||
assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(expands), json!(expands)), "{end}");
|
||||
let only_fill = s.execute("object.expand", &json!({"object": false, "fill": true, "stroke": false}));
|
||||
assert_eq!(only_fill.is_ok(), expands, "{end}: {only_fill:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Object › Expand of a pattern fill works piece by piece: a piece that keeps the pattern has its
|
||||
/// tiles expanded, and a piece with a paint of its own keeps that paint.
|
||||
#[test]
|
||||
|
||||
@@ -581,11 +581,13 @@ fn set_bounds_measures_paths_turned_together_square_to_their_box() {
|
||||
fn a_size_below_what_the_kept_strokes_of_several_paths_add_gives_them_no_width() {
|
||||
// With no width, the paths have a visual box 10 pt wide, the width of the thick stroke. A width
|
||||
// of 0 or more below 10 gives both paths no width, and the left edge of the visual box stays at
|
||||
// -2. A negative width turns the paths over, as it does one path.
|
||||
// -2. With no width each path turns back at its top and bottom, where the miter join bevels,
|
||||
// so the visual box runs from y 100 to 150. A negative width turns the paths over, as it does
|
||||
// one path.
|
||||
let mut wrong = vec![];
|
||||
for (width, paths, visual) in [
|
||||
(8.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 95.0, 8.0, 155.0)),
|
||||
(0.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 95.0, 8.0, 155.0)),
|
||||
(8.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 100.0, 8.0, 150.0)),
|
||||
(0.0, [Rect::new(3.0, 100.0, 3.0, 150.0); 2], Rect::new(-2.0, 100.0, 8.0, 150.0)),
|
||||
(-37.0, [Rect::new(-44.0, 100.0, 0.0, 150.0), Rect::new(-44.0, 100.0, -13.2, 150.0)], Rect::new(-49.0, 95.0, 1.0, 155.0)),
|
||||
] {
|
||||
let (mut s, ids) = thin_and_thick();
|
||||
@@ -666,6 +668,35 @@ fn set_bounds_gives_a_butt_path_with_slanted_corners_the_size_out_of_proportion(
|
||||
assert!((v.width() - 60.0).abs() < 1e-6 && (v.height() - 20.0).abs() < 1e-6, "{v:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_closed_path_with_beveled_or_mitered_corners_the_size_out_of_proportion() {
|
||||
// The bevel at the triangle's tip, the miter the limit bevels there and the miter spikes it
|
||||
// keeps reach past the path by margins that follow the slanted segments' directions, which a
|
||||
// scale out of proportion changes. The miter spikes of a stroke whose dashes have round or
|
||||
// projecting caps reach past the path too.
|
||||
let mut wrong = vec![];
|
||||
for (join, limit, cap, dash) in [
|
||||
("bevel", 10.0, "round", Value::Null),
|
||||
("miter", 2.0, "round", Value::Null),
|
||||
("miter", 10.0, "round", Value::Null),
|
||||
("miter", 10.0, "round", json!([6, 3])),
|
||||
("miter", 10.0, "projecting", json!([6, 3])),
|
||||
] {
|
||||
let mut s = session();
|
||||
let anchors = json!([{"x": 100, "y": 150}, {"x": 110, "y": 100}, {"x": 120, "y": 150}]);
|
||||
let id = NodeId(run(&mut s, "path.create", json!({"anchors": anchors, "closed": true}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "stroke.set", json!({"weight": 2, "cap": cap, "join": join, "miterLimit": limit, "dash": dash}));
|
||||
preview(&mut s, true);
|
||||
run(&mut s, "select.set", json!({"ids": [id.0]}));
|
||||
run(&mut s, "object.setBounds", json!({"width": 60, "height": 20, "reference": 0, "strokes": false}));
|
||||
let v = s.transform_bounds(&[id]).unwrap();
|
||||
if (v.width() - 60.0).abs() > 1e-6 || (v.height() - 20.0).abs() > 1e-6 {
|
||||
wrong.push(format!("{join} {limit} {cap} {dash}: {v:?}"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_bounds_gives_a_symbol_instance_of_a_diagonal_butt_line_the_size_out_of_proportion() {
|
||||
let mut s = session();
|
||||
|
||||
Reference in New Issue
Block a user