mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 11:05:03 +00:00
Merge main into feat/proof-setup-save-load
This commit is contained in:
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush Options…",
|
||||
[],
|
||||
None,
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
"{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}",
|
||||
has_doc,
|
||||
brush_options
|
||||
),
|
||||
|
||||
@@ -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: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), 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 that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), 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, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; 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. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
"{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: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), 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 that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), 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, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; 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. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -144,6 +144,45 @@ fn font_detail(used: &super::fonts::UsedFont) -> (Value, (String, String)) {
|
||||
(entry, (label, detail))
|
||||
}
|
||||
|
||||
/// The type of a font as Fonts lists it: `truetype` or `opentype` by the outlines of the face the
|
||||
/// type is drawn in (in the version the type names), `unknown` for a font that is not installed in
|
||||
/// the family and style it names, or whose face holds neither kind of outline.
|
||||
fn font_type(used: &super::fonts::UsedFont) -> &'static str {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let (family, style, version) = used;
|
||||
match db.resolve(family, style) {
|
||||
Some((f, vectorcraft_text::FontMatch::Exact)) => match db.face_version(family, style, version.as_deref()).unwrap_or(f).outline_format() {
|
||||
Some(vectorcraft_text::OutlineFormat::TrueType) => "truetype",
|
||||
Some(vectorcraft_text::OutlineFormat::Cff) => "opentype",
|
||||
None => "unknown",
|
||||
},
|
||||
_ => "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
/// A font as Fonts lists it: its `fontUses` entry and its row, which gives the font's type and its
|
||||
/// number of uses (`uses`: the text objects set in it).
|
||||
fn font_use(used: &super::fonts::UsedFont, uses: usize) -> (Value, (String, String)) {
|
||||
let label = super::fonts::font_label(used);
|
||||
let kind = font_type(used);
|
||||
let name = match kind {
|
||||
"truetype" => "TrueType",
|
||||
"opentype" => "OpenType",
|
||||
_ => "unknown type",
|
||||
};
|
||||
let count = if uses == 1 { "1 use".to_string() } else { format!("{uses} uses") };
|
||||
(json!({ "font": label, "type": kind, "uses": uses }), (label, format!("{name}; {count}")))
|
||||
}
|
||||
|
||||
/// Counts text object `t` once for each font its runs are drawn in, a composite font's parts in
|
||||
/// place of its name ([`super::fonts::run_fonts`]).
|
||||
fn count_fonts(fonts: &mut BTreeMap<super::fonts::UsedFont, usize>, t: &vectorcraft_doc::TextObject) {
|
||||
let own: BTreeSet<super::fonts::UsedFont> = t.runs.iter().flat_map(super::fonts::run_fonts).collect();
|
||||
for font in own {
|
||||
*fonts.entry(font).or_default() += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// An image object as Document Info lists it: (name, width, height, linked file).
|
||||
type ImageRow = (String, u32, u32, Option<String>);
|
||||
|
||||
@@ -221,16 +260,16 @@ fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec
|
||||
}
|
||||
|
||||
/// The Document Info categories of `d` (only `category` when given) from `info` (what
|
||||
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, its fonts
|
||||
/// and their Font Details rows, 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.
|
||||
/// `document.info` reports), the rows of the artboards the Artboard tool has selected, the rows of
|
||||
/// its fonts and their Font Details rows, 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,
|
||||
selected_artboards: &[(String, String)],
|
||||
fonts: &BTreeSet<super::fonts::UsedFont>,
|
||||
fonts: &[(String, String)],
|
||||
font_details: &[(String, String)],
|
||||
images: &[ImageRow],
|
||||
brushes: &[(String, String)],
|
||||
@@ -296,7 +335,7 @@ fn sections(
|
||||
"patterns" => pattern_objects.to_vec(),
|
||||
"gradients" => gradient_objects.to_vec(),
|
||||
"symbols" => names("symbols"),
|
||||
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
|
||||
"fonts" => fonts.to_vec(),
|
||||
"fontDetails" => font_details.to_vec(),
|
||||
"linkedImages" => {
|
||||
images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect()
|
||||
@@ -627,7 +666,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The paths' total length, as Document Info › Objects shows it (the length of a cut line, a
|
||||
// strip of LEDs along the letters, #1958).
|
||||
let mut path_length = 0.0;
|
||||
let mut fonts = BTreeSet::new();
|
||||
// Each font with the number of text objects set in it.
|
||||
let mut fonts: BTreeMap<super::fonts::UsedFont, usize> = BTreeMap::new();
|
||||
let mut images: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let mut image_rows: Vec<ImageRow> = vec![];
|
||||
// Whether the request being served may read each linked file (a relative path read from the
|
||||
@@ -702,9 +742,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
NodeKind::Compound { .. } => Some("compoundPaths"),
|
||||
NodeKind::Text(t) => {
|
||||
for run in &t.runs {
|
||||
fonts.insert((run.style.font_family.clone(), run.style.font_style.clone(), run.style.font_version.clone()));
|
||||
}
|
||||
count_fonts(&mut fonts, t);
|
||||
Some("textObjects")
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
@@ -787,12 +825,16 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
// The document's fonts include those of the type in opacity masks and in the art of its
|
||||
// symbols and patterns, as Find Font lists them.
|
||||
// symbols and patterns, as Find Font lists them. Each of those text objects counts once, however
|
||||
// many objects show it.
|
||||
if !selection_only {
|
||||
fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style))));
|
||||
for (_, t, _) in super::fonts::art_texts_of(d) {
|
||||
count_fonts(&mut fonts, t);
|
||||
}
|
||||
}
|
||||
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
|
||||
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(font_detail).unzip();
|
||||
let font_names: Vec<String> = fonts.keys().map(super::fonts::font_label).collect();
|
||||
let (font_uses, font_use_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip();
|
||||
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip();
|
||||
// The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a
|
||||
// linked image's row value (its path, or its file name alone when the request may not read it),
|
||||
// and null for an embedded one.
|
||||
@@ -820,6 +862,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"objects": counts,
|
||||
"pathLength": path_length,
|
||||
"fonts": font_names,
|
||||
"fontUses": font_uses,
|
||||
"fontDetails": font_entries,
|
||||
"images": images,
|
||||
"imageObjects": image_objects,
|
||||
@@ -850,7 +893,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d,
|
||||
&out,
|
||||
&selected_rows,
|
||||
&fonts,
|
||||
&font_use_rows,
|
||||
&font_rows,
|
||||
&image_rows,
|
||||
&brush_rows,
|
||||
@@ -1083,6 +1126,92 @@ mod tests {
|
||||
assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"]));
|
||||
}
|
||||
|
||||
/// Fonts gives each font's type and its number of uses: the text objects set in it, each once
|
||||
/// however many of its runs use the font. The type in a symbol's art counts once however many
|
||||
/// instances show it, and the type in an opacity mask once. With Selection Only it counts the
|
||||
/// selected type alone. A font that is not installed has an unknown type. The rows, the report
|
||||
/// and `fontUses` give the same facts, in the order of `fonts`.
|
||||
#[test]
|
||||
fn info_fonts_give_each_font_s_type_and_uses() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
|
||||
let text =
|
||||
|s: &mut Session, font: &str, y: f64| id(s.execute("text.create", &json!({"x": 10, "y": y, "text": "Hello", "font": font})).unwrap());
|
||||
// Two runs in Source Sans 3 Regular in one text object, a second object in it, and one in Inter.
|
||||
let twice = text(&mut s, "Source Sans 3", 20.0);
|
||||
s.execute("text.setRangeStyle", &json!({"id": twice.0, "start": 0, "end": 2, "size": 30})).unwrap();
|
||||
assert!(matches!(&s.doc().unwrap().doc.node(twice).unwrap().kind, NodeKind::Text(t) if t.runs.len() == 2));
|
||||
let other = text(&mut s, "Source Sans 3", 50.0);
|
||||
text(&mut s, "Inter", 80.0);
|
||||
text(&mut s, "Qx Absent Family", 110.0);
|
||||
// A symbol whose art holds type in Inter, shown by two instances, and a mask holding type in Inter.
|
||||
let in_symbol = text(&mut s, "Inter", 140.0);
|
||||
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
|
||||
s.execute("symbol.place", &json!({"name": "Mark", "x": 100, "y": 100})).unwrap();
|
||||
let masked = id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap());
|
||||
let in_mask = text(&mut s, "Inter", 170.0);
|
||||
s.edit("Mask", |d, _| {
|
||||
let art = d.remove(in_mask)?;
|
||||
d.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let i = s.execute("document.info", &json!({"category": "fonts"})).unwrap();
|
||||
assert_eq!(i["fonts"], json!(["Inter Regular", "Qx Absent Family Regular", "Source Sans 3 Regular"]));
|
||||
assert_eq!(
|
||||
i["fontUses"],
|
||||
json!([
|
||||
{"font": "Inter Regular", "type": "truetype", "uses": 3},
|
||||
{"font": "Qx Absent Family Regular", "type": "unknown", "uses": 1},
|
||||
{"font": "Source Sans 3 Regular", "type": "truetype", "uses": 2},
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
i["sections"][0]["rows"],
|
||||
json!([
|
||||
["Inter Regular", "TrueType; 3 uses"],
|
||||
["Qx Absent Family Regular", "unknown type; 1 use"],
|
||||
["Source Sans 3 Regular", "TrueType; 2 uses"],
|
||||
])
|
||||
);
|
||||
let report = s.execute("document.info", &json!({"category": "fonts", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
|
||||
assert!(report.contains("\nFONTS\nInter Regular: TrueType; 3 uses\nQx Absent Family Regular: unknown type; 1 use\n"), "{report}");
|
||||
// Selection Only: the selected type's fonts and uses.
|
||||
s.execute("select.set", &json!({"ids": [other.0]})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "fonts"})).unwrap();
|
||||
assert_eq!(i["fontUses"], json!([{"font": "Source Sans 3 Regular", "type": "truetype", "uses": 1}]));
|
||||
assert_eq!(i["sections"][0]["rows"], json!([["Source Sans 3 Regular", "TrueType; 1 use"]]));
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "fonts"})).unwrap();
|
||||
assert_eq!((i["fontUses"].clone(), i["sections"][0]["rows"].clone()), (json!([]), json!([])));
|
||||
}
|
||||
|
||||
/// Type set in a composite font counts as a use of the fonts of the parts its characters fall
|
||||
/// in, as Find Font lists them, not of the composite font's name.
|
||||
#[test]
|
||||
fn info_fonts_count_the_parts_of_a_composite_font() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
let font = json!({"name": "DI Uses Composite", "parts": {
|
||||
"kanji": {"font": "Source Sans 3"},
|
||||
"roman": {"font": "JetBrains Mono"},
|
||||
"numerals": {"font": "Inter"},
|
||||
}});
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab1", "font": "DI Uses Composite"})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "12", "font": "DI Uses Composite"})).unwrap();
|
||||
let i = s.execute("document.info", &json!({"category": "fonts"})).unwrap();
|
||||
assert_eq!(i["fonts"], json!(["Inter Regular", "JetBrains Mono Regular"]));
|
||||
assert_eq!(
|
||||
i["fontUses"],
|
||||
json!([
|
||||
{"font": "Inter Regular", "type": "truetype", "uses": 2},
|
||||
{"font": "JetBrains Mono Regular", "type": "truetype", "uses": 1},
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/// Document Info › Objects gives the paths' total length in the document's units (#1958): an
|
||||
/// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't.
|
||||
#[test]
|
||||
|
||||
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Pencil",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
|
||||
has_doc,
|
||||
freehand
|
||||
),
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1, tilt −90..90°, barrel rotation 0..360° clockwise, finger wheel 0..1; pen values are checked as path.freehand checks them), size?: pt (10; from 0.1 to 1000), angle?: ° (0, −180–180: the tip's long axis counter-clockwise from level), roundness?: % (100, 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" | \"stylusWheel\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0–1000, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn; stylusWheel from less at one end of an airbrush pen's finger wheel travel to more at the other. A drag without that pen reading (a mouse) erases at the value itself. An angle or roundness outside its range, an unknown mode, or a variation below 0 or past its range is refused with an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths and filled open paths without a visible painted stroke lose its area, and other open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
|
||||
@@ -22,15 +22,17 @@ pub(super) struct Sample {
|
||||
tilt: Option<[f64; 2]>,
|
||||
/// Barrel rotation, degrees clockwise.
|
||||
rotation: Option<f64>,
|
||||
/// The airbrush finger wheel, 0..1.
|
||||
wheel: Option<f64>,
|
||||
}
|
||||
|
||||
/// The keys of a point's pen values, in the order a point given as an array holds them after its
|
||||
/// x and y.
|
||||
const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"];
|
||||
const PEN_KEYS: [&str; 5] = ["pressure", "tiltX", "tiltY", "rotation", "wheel"];
|
||||
|
||||
/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees and rotation
|
||||
/// 0..360 degrees (360 is the same direction as 0).
|
||||
const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0)];
|
||||
/// The range each of [`PEN_KEYS`] takes: pressure 0..1, each tilt −90..90 degrees, rotation
|
||||
/// 0..360 degrees (360 is the same direction as 0) and the wheel 0..1.
|
||||
const PEN_RANGES: [(f64, f64); PEN_KEYS.len()] = [(0.0, 1.0), (-90.0, 90.0), (-90.0, 90.0), (0.0, 360.0), (0.0, 1.0)];
|
||||
|
||||
/// Blob Brush and Eraser Tool Options' Size, in points.
|
||||
pub(super) const SIZES: (f64, f64) = (0.1, 1000.0);
|
||||
@@ -61,11 +63,11 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result<Point> {
|
||||
}
|
||||
|
||||
/// [`points_param`] with what a pen read at each point, as far as it is given:
|
||||
/// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure
|
||||
/// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in
|
||||
/// degrees clockwise, 0..360. A point whose x or y is not a number, whose pressure, tilt or
|
||||
/// rotation is neither a number nor null or is outside its range, or an array of more than six
|
||||
/// numbers, is an error.
|
||||
/// `[[x,y,pressure,tiltX,tiltY,rotation,wheel]…]` or `[{x,y,pressure,tiltX,tiltY,rotation,wheel}…]`.
|
||||
/// Pressure is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0);
|
||||
/// rotation in degrees clockwise, 0..360; the wheel 0..1. A point whose x or y is not a number,
|
||||
/// whose pressure, tilt, rotation or wheel is neither a number nor null or is outside its range,
|
||||
/// or an array of more than seven numbers, is an error.
|
||||
pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sample>> {
|
||||
let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?;
|
||||
let pts: Vec<Sample> = a
|
||||
@@ -79,7 +81,7 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sampl
|
||||
let key = format!("{key}[{at}]");
|
||||
return Err(bad(cmd, format!("`{key}` must be an array of at most {MAX_ITEMS} entries")));
|
||||
}
|
||||
let mut pen = [None; 4];
|
||||
let mut pen = [None; PEN_KEYS.len()];
|
||||
for (i, ((key, range), slot)) in PEN_KEYS.iter().zip(PEN_RANGES).zip(&mut pen).enumerate() {
|
||||
let given = match v {
|
||||
Value::Array(xy) => xy.get(i + 2),
|
||||
@@ -91,9 +93,9 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result<Vec<Sampl
|
||||
Some(v) => return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
};
|
||||
}
|
||||
let [pressure, tx, ty, rotation] = pen;
|
||||
let [pressure, tx, ty, rotation, wheel] = pen;
|
||||
let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0)));
|
||||
Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation })
|
||||
Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation, wheel })
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if pts.is_empty() {
|
||||
@@ -126,6 +128,15 @@ fn stroke_pressure(samples: &[Sample]) -> Option<PressureProfile> {
|
||||
PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.pressure.unwrap_or(1.0))))
|
||||
}
|
||||
|
||||
/// Where an airbrush pen's finger wheel was set along a freehand stroke, when any of its samples
|
||||
/// has it; samples without it count as the middle of its travel, which draws a brush's own value.
|
||||
fn stroke_wheel(samples: &[Sample]) -> Option<PressureProfile> {
|
||||
if samples.iter().all(|s| s.wheel.is_none()) {
|
||||
return None;
|
||||
}
|
||||
PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.wheel.unwrap_or(PressureProfile::MID))))
|
||||
}
|
||||
|
||||
/// A pen that leans less than this many degrees from upright leans no way in particular: its
|
||||
/// bearing is the one before it.
|
||||
const UPRIGHT: f64 = 1.0;
|
||||
@@ -165,24 +176,31 @@ fn stroke_pose(samples: &[Sample]) -> (Option<PressureProfile>, Option<AngleProf
|
||||
(tilt.flatten(), bearing.flatten(), rotation.flatten())
|
||||
}
|
||||
|
||||
/// What a pen recorded along a stroke ([`StrokeLayer`]'s `pressure`, `tilt`, `bearing` and
|
||||
/// `rotation`).
|
||||
/// What a pen recorded along a stroke ([`StrokeLayer`]'s `pressure`, `tilt`, `bearing`,
|
||||
/// `rotation` and `wheel`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(super) struct PenRecord {
|
||||
pressure: Option<PressureProfile>,
|
||||
tilt: Option<PressureProfile>,
|
||||
bearing: Option<AngleProfile>,
|
||||
rotation: Option<AngleProfile>,
|
||||
wheel: Option<PressureProfile>,
|
||||
}
|
||||
|
||||
impl PenRecord {
|
||||
/// What a freehand stroke's samples recorded.
|
||||
pub(super) fn of_samples(samples: &[Sample]) -> Self {
|
||||
let (tilt, bearing, rotation) = stroke_pose(samples);
|
||||
Self { pressure: stroke_pressure(samples), tilt, bearing, rotation }
|
||||
Self { pressure: stroke_pressure(samples), tilt, bearing, rotation, wheel: stroke_wheel(samples) }
|
||||
}
|
||||
pub(super) fn of(st: &StrokeLayer) -> Self {
|
||||
Self { pressure: st.pressure.clone(), tilt: st.tilt.clone(), bearing: st.bearing.clone(), rotation: st.rotation.clone() }
|
||||
Self {
|
||||
pressure: st.pressure.clone(),
|
||||
tilt: st.tilt.clone(),
|
||||
bearing: st.bearing.clone(),
|
||||
rotation: st.rotation.clone(),
|
||||
wheel: st.wheel.clone(),
|
||||
}
|
||||
}
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
*self == Self::default()
|
||||
@@ -195,6 +213,7 @@ impl PenRecord {
|
||||
tilt: PressureProfile::extended(self.tilt.as_ref(), old_len, added.tilt.as_ref(), added_len),
|
||||
bearing: AngleProfile::extended(self.bearing.as_ref(), old_len, added.bearing.as_ref(), added_len),
|
||||
rotation: AngleProfile::extended(self.rotation.as_ref(), old_len, added.rotation.as_ref(), added_len),
|
||||
wheel: PressureProfile::extended(self.wheel.as_ref(), old_len, added.wheel.as_ref(), added_len),
|
||||
}
|
||||
}
|
||||
/// The record along the path reversed.
|
||||
@@ -204,6 +223,7 @@ impl PenRecord {
|
||||
tilt: self.tilt.as_ref().map(PressureProfile::reversed),
|
||||
bearing: self.bearing.as_ref().map(AngleProfile::reversed),
|
||||
rotation: self.rotation.as_ref().map(AngleProfile::reversed),
|
||||
wheel: self.wheel.as_ref().map(PressureProfile::reversed),
|
||||
}
|
||||
}
|
||||
/// Keep the record on stroke `st`.
|
||||
@@ -212,6 +232,7 @@ impl PenRecord {
|
||||
st.tilt = self.tilt;
|
||||
st.bearing = self.bearing;
|
||||
st.rotation = self.rotation;
|
||||
st.wheel = self.wheel;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -438,7 +438,7 @@ fn erase_rect(s: &mut Session, r: Rect) -> Result<Value> {
|
||||
|
||||
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
|
||||
/// `sizeMode`.
|
||||
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
|
||||
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\", \"rotation\" or \"stylusWheel\"";
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with
|
||||
/// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation`
|
||||
|
||||
@@ -41,7 +41,7 @@ mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
pub mod hpgl;
|
||||
mod jp2read;
|
||||
mod metafile;
|
||||
mod naming;
|
||||
|
||||
@@ -878,7 +878,7 @@ fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool, changed: Optio
|
||||
/// absent; an error when it is not four finite numbers with a positive size, when the format isn't
|
||||
/// a raster one, or when it comes with an artboard choice (`rect` is the area, so those would
|
||||
/// contradict it). The image size limits are checked with the scale, as for an artboard.
|
||||
fn page_rect(f: &Format, p: &Value) -> Result<Option<Rect>> {
|
||||
pub(super) fn page_rect(f: &Format, p: &Value) -> Result<Option<Rect>> {
|
||||
let v = match p.get("rect") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(v) => v,
|
||||
|
||||
@@ -6,6 +6,7 @@ use serde_json::Value;
|
||||
use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE};
|
||||
use vectorcraft_cad::hpgl::{HpglOptions, Origin, Version};
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::Rect;
|
||||
|
||||
use super::super::{Result, bad, number_or, switch_or, text_param};
|
||||
use super::{ArtboardPick, Encoded, FormatOption};
|
||||
@@ -92,10 +93,58 @@ fn hex(v: &Value) -> Option<[u8; 3]> {
|
||||
Some([byte(0)?, byte(2)?, byte(4)?])
|
||||
}
|
||||
|
||||
/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with
|
||||
/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let opts = parse(p)?;
|
||||
/// Check the HP-GL options and the artboard choice in `p` for an export of `doc`, as the export
|
||||
/// reads them, without exporting (dialogs keep themselves open on an error).
|
||||
pub fn check(doc: &Document, p: &Value) -> std::result::Result<(), String> {
|
||||
let run = || -> Result<()> {
|
||||
parse(p)?;
|
||||
with_plotted(doc, p, |_, _| Ok(()))
|
||||
};
|
||||
run().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The pen table an export of `doc` with the options and artboard choice in `p`, and no `pens`,
|
||||
/// uses: pen 1's color first, as `#rrggbb` colors. Empty when nothing is plotted; an error when
|
||||
/// the options or the artboard choice are refused.
|
||||
pub fn automatic_pens(doc: &Document, p: &Value) -> std::result::Result<Vec<String>, String> {
|
||||
let run = || -> Result<Vec<[u8; 3]>> {
|
||||
let mut q = p.clone();
|
||||
if let Some(o) = q.as_object_mut() {
|
||||
o.remove("pens");
|
||||
}
|
||||
// The order the paths are drawn in doesn't change which pen a color gets.
|
||||
let opts = HpglOptions { sort: false, inside_first: false, ..parse(&q)? };
|
||||
with_plotted(doc, &q, |doc, regions| {
|
||||
let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
Ok(plots.first().map(|o| o.pens.clone()).unwrap_or_default())
|
||||
})
|
||||
};
|
||||
let pens = run().map_err(|e| e.to_string())?;
|
||||
Ok(pens.iter().map(|[r, g, b]| format!("#{r:02x}{g:02x}{b:02x}")).collect())
|
||||
}
|
||||
|
||||
/// Run `f` on the document an export of `doc` with `p` plots and the regions of its plots: with
|
||||
/// `useArtboards: false`, a copy of `doc` whose one artboard is the bounds of the visible art.
|
||||
/// Like the export, it refuses `rect`, leaves out an opacity-mask or symbol editing layer, and
|
||||
/// measures the bounds without the art a plot draws nothing for.
|
||||
fn with_plotted<T>(doc: &Document, p: &Value, f: impl FnOnce(&Document, Vec<Rect>) -> Result<T>) -> Result<T> {
|
||||
let format = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?;
|
||||
super::encode::page_rect(format, p)?;
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let use_artboards = super::encode::use_artboards(C, p)?;
|
||||
if use_artboards == Some(false)
|
||||
&& let Some((art, q)) = super::encode::art_page(C, doc, p, |n| vectorcraft_cad::hpgl::write::plots_nothing(doc, n))?
|
||||
{
|
||||
let (_, regions) = boards(&art, &q, None)?;
|
||||
return f(&art, regions);
|
||||
}
|
||||
let (_, regions) = boards(doc, p, use_artboards)?;
|
||||
f(doc, regions)
|
||||
}
|
||||
|
||||
/// The artboards a plot of `doc` covers and their regions: the chosen artboard (default the
|
||||
/// first), or with `use_artboards` each chosen one (default all).
|
||||
fn boards(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<(Vec<usize>, Vec<Rect>)> {
|
||||
let f = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?;
|
||||
let pick: ArtboardPick = super::encode::options(f, p)?;
|
||||
let n = doc.artboards.len();
|
||||
@@ -103,10 +152,25 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
|
||||
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
|
||||
};
|
||||
if boards.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
let regions = boards
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
// The writer's own region check, so a dialog's check refuses what the writer refuses.
|
||||
for r in ®ions {
|
||||
vectorcraft_cad::hpgl::write::check_region(*r).map_err(|e| bad(C, e))?;
|
||||
}
|
||||
Ok((boards, regions))
|
||||
}
|
||||
|
||||
/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with
|
||||
/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let opts = parse(p)?;
|
||||
let (boards, regions) = boards(doc, p, use_artboards)?;
|
||||
let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
for (b, out) in boards.into_iter().zip(plots) {
|
||||
@@ -118,9 +182,6 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) ->
|
||||
}
|
||||
enc.add_setting_notes(out.setting_notes);
|
||||
}
|
||||
if enc.files.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
let regions: Vec<vectorcraft_geom::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)));
|
||||
Ok(enc)
|
||||
|
||||
@@ -534,6 +534,104 @@ fn export_options_are_checked() {
|
||||
let p = json!({"format": "hpgl", "origin": "CENTER", "pens": ["#ff0000", "#000000"], "curveTolerance": 10, "sortPaths": true});
|
||||
let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap();
|
||||
assert_eq!(plot, "IN;PU;SP2;PU-141,141;PD-564,141,-564,564,-141,564,-141,141;PU;SP0;");
|
||||
// The check a dialog runs refuses the same options, and passes the given ones.
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
assert!(hpgl::check(&doc, &json!({"pens": ["#ff0000", "red"]})).unwrap_err().contains("`pens`"));
|
||||
assert!(hpgl::check(&doc, &json!({"curveTolerance": 11})).unwrap_err().contains("`curveTolerance`"));
|
||||
assert_eq!(hpgl::check(&doc, &p), Ok(()));
|
||||
// It checks the artboard choice as the export does: an artboard or range past the document's,
|
||||
// a `useArtboards` that isn't true or false, and the art's bounds when no art shows.
|
||||
let mut blank = Session::new();
|
||||
blank.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let blank_doc = blank.doc().unwrap().doc.clone();
|
||||
for (on_blank, p) in [
|
||||
(false, json!({"format": "hpgl", "artboard": 2})),
|
||||
(false, json!({"format": "hpgl", "useArtboards": true, "range": "1-3"})),
|
||||
(false, json!({"format": "hpgl", "artboards": [0, 1]})),
|
||||
(false, json!({"format": "hpgl", "useArtboards": "yes"})),
|
||||
(true, json!({"format": "hpgl", "useArtboards": false})),
|
||||
] {
|
||||
let (session, d) = if on_blank { (&mut blank, &blank_doc) } else { (&mut s, &doc) };
|
||||
assert!(hpgl::check(d, &p).is_err(), "{p}");
|
||||
assert!(session.execute("document.export", &p).is_err(), "{p}");
|
||||
}
|
||||
// An artboard with no width is refused before the writer refuses it.
|
||||
let mut flat = vectorcraft_doc::Document::clone(&doc);
|
||||
flat.artboards[1].rect = vectorcraft_geom::Rect::new(200.0, 0.0, 200.0, 100.0);
|
||||
assert_eq!(hpgl::check(&flat, &json!({"artboard": 1})).unwrap_err(), hpgl::check(&flat, &json!({"useArtboards": true})).unwrap_err());
|
||||
assert!(hpgl::check(&flat, &json!({"artboard": 1})).unwrap_err().contains("the export region is empty"));
|
||||
assert_eq!(hpgl::check(&flat, &json!({})), Ok(()));
|
||||
// A document with no artboard has nothing to plot on one, or on each.
|
||||
flat.artboards.clear();
|
||||
for p in [json!({}), json!({"useArtboards": true})] {
|
||||
assert!(hpgl::check(&flat, &p).unwrap_err().contains("the document has no artboard"), "{p}");
|
||||
}
|
||||
// An area of the page is a raster export's option: the export refuses it, and so does the check.
|
||||
let rect = json!({"format": "hpgl", "rect": [0, 0, 10, 10]});
|
||||
assert!(s.execute("document.export", &rect).is_err());
|
||||
assert!(hpgl::check(&doc, &rect).unwrap_err().contains("rect applies to raster formats"));
|
||||
assert_eq!(hpgl::check(&doc, &json!({"useArtboards": true, "range": "2"})), Ok(()));
|
||||
assert_eq!(hpgl::check(&doc, &json!({"useArtboards": false})), Ok(()));
|
||||
}
|
||||
|
||||
/// The pens an export without a pen table uses: one per color the plotted art draws in, in the
|
||||
/// order it first draws in each, over the artboards or the art's bounds the export plots.
|
||||
#[test]
|
||||
fn automatic_pens_list_the_plotted_art_s_colors_in_pen_order() {
|
||||
let s = two_boards();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let pens = |p: Value| hpgl::automatic_pens(doc, &p).unwrap();
|
||||
assert_eq!(pens(json!({})), ["#000000"], "the first artboard");
|
||||
assert_eq!(pens(json!({"artboard": 1})), ["#ff0000"]);
|
||||
assert_eq!(pens(json!({"useArtboards": true})), ["#000000", "#ff0000"], "one numbering for every file");
|
||||
assert_eq!(pens(json!({"useArtboards": false})), ["#000000", "#ff0000"], "the art's bounds");
|
||||
// The pens given and the path order are not the export's own pens.
|
||||
assert_eq!(pens(json!({"useArtboards": true, "pens": ["#00ff00"], "sortPaths": true})), ["#000000", "#ff0000"]);
|
||||
// A refused artboard choice or option is an error, not an empty table.
|
||||
assert!(hpgl::automatic_pens(doc, &json!({"artboard": 5})).is_err());
|
||||
assert!(hpgl::automatic_pens(doc, &json!({"curveTolerance": 20})).unwrap_err().contains("`curveTolerance`"));
|
||||
// So is an area of the page, which the export and the check refuse for HP-GL.
|
||||
assert!(hpgl::automatic_pens(doc, &json!({"rect": [0, 0, 10, 10]})).unwrap_err().contains("rect applies to raster formats"));
|
||||
|
||||
// Art outside every artboard is plotted only with the art's bounds.
|
||||
let mut off = Session::new();
|
||||
off.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
off.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
off.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
|
||||
off.execute("shape.rectangle", &json!({"x": 500, "y": 500, "width": 30, "height": 30})).unwrap();
|
||||
let doc = &off.doc().unwrap().doc;
|
||||
assert_eq!(hpgl::automatic_pens(doc, &json!({})), Ok(vec![]));
|
||||
assert_eq!(hpgl::automatic_pens(doc, &json!({"useArtboards": false})), Ok(vec!["#0000ff".to_string()]));
|
||||
}
|
||||
|
||||
/// A placed document opened with only its preview is plotted with its file's art (the plot reads
|
||||
/// the file), so the check and the pens of a dialog measure that art as the export does.
|
||||
#[test]
|
||||
fn a_placed_document_s_pens_are_those_of_its_file_s_art() {
|
||||
use crate::tests_links::{Folder, open, save, session, write};
|
||||
let dir = Folder::new("hpgl-placed");
|
||||
let src = dir.file("logo.vectorcraft");
|
||||
let mut d = vectorcraft_doc::Document::new(100.0, 50.0);
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0));
|
||||
let look = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0);
|
||||
let rect = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 50.0));
|
||||
d.insert(Some(layer), 0, vectorcraft_doc::Node::path(id, rect, look)).unwrap();
|
||||
write(&src, &vectorcraft_format::save_file(&d));
|
||||
let mut s = session();
|
||||
s.execute("file.place", &json!({"path": src, "at": [200, 150]})).unwrap();
|
||||
let poster = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &poster);
|
||||
open(&mut s, &poster);
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert!(doc.images.values().any(vectorcraft_doc::ImageBlob::is_proxy), "opened with the preview only");
|
||||
for p in [json!({}), json!({"useArtboards": false})] {
|
||||
assert_eq!(hpgl::automatic_pens(doc, &p), Ok(vec!["#ff0000".to_string()]), "{p}");
|
||||
assert_eq!(hpgl::check(doc, &p), Ok(()), "{p}");
|
||||
}
|
||||
let plot = String::from_utf8(bytes(&s.execute("document.export", &json!({"format": "hpgl"})).unwrap())).unwrap();
|
||||
assert!(plot.contains("SP1;") && plot.contains("PD"), "{plot}");
|
||||
}
|
||||
|
||||
/// `insideFirst` draws the square inside the other one first, though it was made last.
|
||||
|
||||
@@ -437,3 +437,48 @@ fn svg_darkness_uses_rendered_shadow_in_non_srgb_working_space() {
|
||||
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 8), "at {x}: {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #864 / G11: SVG export preserves the document's physical units on the root `width`/`height` so
|
||||
/// that the unit setting survives a save/open round-trip. The engine-level test covers the full
|
||||
/// stack (file.new → document.setUnits → document.serialize → document.open).
|
||||
#[test]
|
||||
fn svg_round_trip_preserves_document_units() {
|
||||
// (unit name the engine accepts, expected unit after re-import)
|
||||
let cases: &[(&str, vectorcraft_doc::Unit)] = &[
|
||||
("millimeters", vectorcraft_doc::Unit::Millimeters),
|
||||
("centimeters", vectorcraft_doc::Unit::Centimeters),
|
||||
("inches", vectorcraft_doc::Unit::Inches),
|
||||
("picas", vectorcraft_doc::Unit::Picas),
|
||||
// Points and pixels both serialise as bare user-unit numbers, so both import as Pixels.
|
||||
("pixels", vectorcraft_doc::Unit::Pixels),
|
||||
];
|
||||
for (name, expected) in cases {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap();
|
||||
s.execute("document.setUnits", &json!({"units": name})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg_text = r["text"].as_str().unwrap();
|
||||
match *expected {
|
||||
vectorcraft_doc::Unit::Millimeters => assert!(svg_text.contains("mm\""), "mm suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Centimeters => assert!(svg_text.contains("cm\""), "cm suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Inches => assert!(svg_text.contains("in\""), "in suffix missing: {svg_text}"),
|
||||
vectorcraft_doc::Unit::Picas => assert!(svg_text.contains("pc\""), "pc suffix missing: {svg_text}"),
|
||||
_ => {}
|
||||
}
|
||||
let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes());
|
||||
s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap();
|
||||
let doc_state = s.doc().unwrap();
|
||||
assert_eq!(doc_state.doc.units, *expected, "unit mismatch after round-trip for '{name}'");
|
||||
}
|
||||
|
||||
// Points serialise without suffix and re-open as Pixels (equivalent in user units).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 1})).unwrap();
|
||||
s.execute("document.setUnits", &json!({"units": "points"})).unwrap();
|
||||
let r = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
|
||||
let svg_text = r["text"].as_str().unwrap();
|
||||
assert!(svg_text.contains("width=\"200\" height=\"100\""), "{svg_text}");
|
||||
let b64 = vectorcraft_format::base64_encode(svg_text.as_bytes());
|
||||
s.execute("document.open", &json!({"name": "test.svg", "dataBase64": b64})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.units, vectorcraft_doc::Unit::Pixels);
|
||||
}
|
||||
|
||||
@@ -746,8 +746,8 @@ fn give_appearance(a: &Appearance, b: &Appearance, m: &Appearance, n: &mut Share
|
||||
}
|
||||
|
||||
/// Give the member's fill or stroke `n` the settings of the model's that changed from `a` to `b`,
|
||||
/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing and
|
||||
/// rotation stay its own.
|
||||
/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing,
|
||||
/// rotation and wheel stay its own.
|
||||
fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut AppearanceItem) {
|
||||
use AppearanceItem::{Fill, Stroke};
|
||||
match (a, b, m, n) {
|
||||
@@ -781,6 +781,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut
|
||||
tilt: _,
|
||||
bearing: _,
|
||||
rotation: _,
|
||||
wheel: _,
|
||||
} = m;
|
||||
give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, brush_options, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode);
|
||||
// A stroke's own brush settings go with the brush they set: a new brush takes the model's.
|
||||
|
||||
@@ -1572,6 +1572,79 @@ fn freehand_points_record_the_pens_tilt_bearing_and_rotation() {
|
||||
assert_eq!(tilt.unwrap().at(0.9), vectorcraft_doc::PressureProfile::MID, "half way over without one");
|
||||
}
|
||||
|
||||
/// The airbrush finger wheel recorded on the stroke `id`.
|
||||
fn wheel_of(s: &Session, id: NodeId) -> Option<PressureProfile> {
|
||||
node(s, id).appearance.stroke().and_then(|st| st.wheel.clone())
|
||||
}
|
||||
|
||||
/// `path.freehand` points carry an airbrush pen's finger wheel seventh (or as `wheel`), 0..1; the
|
||||
/// stroke keeps it, a continued or reversed stroke keeps it in step, a wheel that is not a number
|
||||
/// or is outside 0..1 is refused, and the Paintbrush records it from the pen. A Calligraphic brush with
|
||||
/// Size on Stylus Wheel draws it, and it lasts through saving, new art leaving it behind.
|
||||
#[test]
|
||||
fn freehand_points_record_the_stylus_wheel() {
|
||||
let mut s = session();
|
||||
let draw = |s: &mut Session, points: Value| {
|
||||
NodeId(s.execute("path.freehand", &json!({"points": points, "style": "brush"})).unwrap()["id"].as_u64().unwrap())
|
||||
};
|
||||
let id = draw(&mut s, json!([[0, 50, null, null, null, null, 0], [100, 50, null, null, null, null, 1]]));
|
||||
let w = wheel_of(&s, id).unwrap();
|
||||
assert!(w.at(0.0) < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}");
|
||||
assert_eq!(pose_of(&s, id), (None, None, None), "the wheel alone");
|
||||
assert_eq!(pressure_of(&s, id), None);
|
||||
// As keys; a point without one is half way.
|
||||
let id = draw(&mut s, json!([{"x": 0, "y": 150, "wheel": 0}, {"x": 50, "y": 150}, {"x": 100, "y": 150, "wheel": 1}]));
|
||||
let w = wheel_of(&s, id).unwrap();
|
||||
assert!(w.at(0.0) < 1e-6 && (w.at(0.5) - 0.5).abs() < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}");
|
||||
// No wheel given: none recorded.
|
||||
let id = draw(&mut s, json!([[0, 250, 0.5, 30, 0, 90], [100, 250, 0.5, 30, 0, 90]]));
|
||||
assert_eq!(wheel_of(&s, id), None);
|
||||
// Not a number: refused, and nothing drawn.
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("path.freehand", &json!({"points": [[0, 0, null, null, null, null, "0.5"], [10, 0]], "style": "brush"}));
|
||||
assert!(err.unwrap_err().to_string().contains("`wheel` must be a number"));
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged");
|
||||
// Outside 0..1: refused, and nothing drawn.
|
||||
for points in [json!([{"x": 0, "y": 0, "wheel": -2}, {"x": 10, "y": 0}]), json!([[0, 0], [10, 0, null, null, null, null, 9]])] {
|
||||
let err = s.execute("path.freehand", &json!({"points": points, "style": "brush"}));
|
||||
assert!(err.unwrap_err().to_string().contains("`wheel` must be from 0 to 1"));
|
||||
assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged");
|
||||
}
|
||||
// Continued at its end by a stroke without a wheel: the old part keeps it, the new one is half way.
|
||||
let id = draw(&mut s, json!([[0, 350, null, null, null, null, 1], [100, 350, null, null, null, null, 1]]));
|
||||
s.execute("path.freehand", &json!({"points": [[100, 350], [200, 350]], "style": "brush", "extend": {"id": id.0, "end": "end"}})).unwrap();
|
||||
let w = wheel_of(&s, id).unwrap();
|
||||
assert!((w.at(0.25) - 1.0).abs() < 1e-6 && (w.at(0.9) - 0.5).abs() < 1e-6, "{w:?}");
|
||||
// The Paintbrush records it, and a brush with Size on Stylus Wheel draws it.
|
||||
let params = json!({"angle": 0, "roundness": 100, "size": 6, "variation": [0, 0, 4], "modes": ["fixed", "fixed", "stylusWheel"]});
|
||||
s.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap();
|
||||
s.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("paintbrush", v).unwrap();
|
||||
let strokes = |s: &mut Session, y: f64, wheel: Option<f32>| {
|
||||
let pen = wheel.map(|w| PenPose { wheel: Some(w), ..PenPose::default() });
|
||||
for (k, x) in [(PointerKind::Down, 20.0), (PointerKind::Drag, 120.0), (PointerKind::Drag, 220.0), (PointerKind::Up, 320.0)] {
|
||||
s.pointer(&PointerEvent { pen, ..PointerEvent::new(k, x, y) }, v).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
select(s, &[]);
|
||||
id
|
||||
};
|
||||
let far = strokes(&mut s, 500.0, Some(1.0));
|
||||
let near = strokes(&mut s, 600.0, Some(0.0));
|
||||
let mouse = strokes(&mut s, 700.0, None);
|
||||
assert_eq!(wheel_of(&s, far).map(|w| w.at(0.5)), Some(1.0));
|
||||
assert_eq!(wheel_of(&s, mouse), None, "a mouse has no wheel");
|
||||
let height = |s: &Session, id| brushed_bounds(s, id).height();
|
||||
assert!((height(&s, far) - 10.0).abs() < 0.1 && (height(&s, near) - 2.0).abs() < 0.1, "{} {}", height(&s, far), height(&s, near));
|
||||
assert!((height(&s, mouse) - 6.0).abs() < 0.1, "the brush's own size: {}", height(&s, mouse));
|
||||
// Saved and reopened as it was; new art takes the look without the wheel.
|
||||
let doc: Document = (*s.doc().unwrap().doc).clone();
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
|
||||
assert_eq!(back.node(far).unwrap().appearance.stroke(), doc.node(far).unwrap().appearance.stroke());
|
||||
assert!(vectorcraft_doc::Appearance::clone(&doc.node(far).unwrap().appearance).without_pressure().stroke().is_some_and(|st| st.wheel.is_none()));
|
||||
}
|
||||
|
||||
/// #764: a stroke that connects two paths joins the pen's tilt, bearing and rotation of both, the
|
||||
/// connected path's after the stroke's.
|
||||
#[test]
|
||||
@@ -1611,7 +1684,7 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() {
|
||||
select(s, &[]);
|
||||
id
|
||||
};
|
||||
let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0) }));
|
||||
let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0), wheel: None }));
|
||||
let (tilt, bearing, rotation) = pose_of(&s, pen);
|
||||
assert_eq!(tilt.as_ref().map(|t| t.at(0.5)), Some(0.0), "upright");
|
||||
assert!(bearing.is_some() && (rotation.unwrap().at(0.5) + 30.0).abs() < 1e-6);
|
||||
|
||||
@@ -751,14 +751,14 @@ fn eraser_size_follows_the_pen_pressure() {
|
||||
assert!(err.to_string().contains("sizeMode"), "{err}");
|
||||
}
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Rotation, Bearing,
|
||||
/// Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Stylus Wheel, Rotation,
|
||||
/// Bearing, Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a
|
||||
/// drag without the reading erases at the value itself, an open path is cut where the varied tip
|
||||
/// covers it, and an unknown mode or a variation out of its range is refused with nothing erased.
|
||||
#[test]
|
||||
fn the_eraser_tip_varies_with_its_modes() {
|
||||
// Which of `probes` a level drag through the middle of a 400 by 200 rectangle erases, each of
|
||||
// its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation]).
|
||||
// its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation, wheel]).
|
||||
let erased = |tip: serde_json::Value, pen: serde_json::Value, probes: &[(f64, f64)]| -> Vec<bool> {
|
||||
let mut s = session();
|
||||
rect(&mut s, 0.0, 0.0, 400.0, 200.0);
|
||||
@@ -785,6 +785,10 @@ fn the_eraser_tip_varies_with_its_modes() {
|
||||
// The barrel turned half way round reads the most, which turns the tip upright.
|
||||
assert_eq!(erased(on_rotation.clone(), json!([none, none, none, 180]), &probes), [true, true], "Rotation");
|
||||
assert_eq!(erased(on_rotation.clone(), json!([]), &probes), [true, false], "Rotation without a reading");
|
||||
// The finger wheel at the far end of its travel reads the most; without a wheel the tip lies level.
|
||||
let on_wheel = with(&level, json!({"angleMode": "stylusWheel", "angleVariation": 90}));
|
||||
assert_eq!(erased(on_wheel.clone(), json!([none, none, none, none, 1.0]), &probes), [true, true], "Stylus Wheel");
|
||||
assert_eq!(erased(on_wheel, json!([none, none, none, none, none]), &probes), [true, false], "Stylus Wheel without a reading");
|
||||
// Leaning to the left (a bearing of 180°) reads the most too.
|
||||
let on_bearing = with(&level, json!({"angleMode": "bearing", "angleVariation": 90}));
|
||||
assert_eq!(erased(on_bearing.clone(), json!([none, -45, 0, none]), &probes), [true, true], "Bearing");
|
||||
@@ -831,11 +835,11 @@ fn the_eraser_tip_varies_with_its_modes() {
|
||||
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
let stroke = json!({"points": [[-10, 50], [110, 50]]});
|
||||
let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
|
||||
let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\", \"rotation\" or \"stylusWheel\"";
|
||||
for (extra, want) in [
|
||||
(json!({"angleMode": "wheel"}), format!("angleMode is one of {modes}, not `wheel`")),
|
||||
(json!({"roundnessMode": 3}), format!("roundnessMode is one of {modes}, not 3")),
|
||||
(json!({"sizeMode": "stylusWheel"}), format!("sizeMode is one of {modes}, not `stylusWheel`")),
|
||||
(json!({"sizeMode": "Pressure"}), format!("sizeMode is one of {modes}, not `Pressure`")),
|
||||
(json!({"angleVariation": 181}), "angleVariation must be at most 180".to_string()),
|
||||
(json!({"roundnessVariation": 101}), "roundnessVariation must be at most 100".to_string()),
|
||||
(json!({"roundnessVariation": -1}), "roundnessVariation must be 0 or more".to_string()),
|
||||
@@ -3171,8 +3175,9 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() {
|
||||
}
|
||||
|
||||
/// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90
|
||||
/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six
|
||||
/// numbers, naming the point; the document, the selection and the undo history stay as they were.
|
||||
/// to 90, a rotation outside 0 to 360 and a stylus wheel outside 0 to 1, naming the key, and a
|
||||
/// point array of more than seven numbers, naming the point; the document, the selection and the
|
||||
/// undo history stay as they were.
|
||||
/// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw.
|
||||
#[test]
|
||||
fn pen_values_outside_their_ranges_are_refused() {
|
||||
@@ -3194,7 +3199,8 @@ fn pen_values_outside_their_ranges_are_refused() {
|
||||
let tilt_x = "`tiltX` must be from -90 to 90";
|
||||
let tilt_y = "`tiltY` must be from -90 to 90";
|
||||
let rotation = "`rotation` must be from 0 to 360";
|
||||
let entries = "`points[3]` must be an array of at most 6 entries";
|
||||
let wheel = "`wheel` must be from 0 to 1";
|
||||
let entries = "`points[3]` must be an array of at most 7 entries";
|
||||
for cmd in cmds {
|
||||
for (bad, want) in [
|
||||
(json!([150, 150, -0.01]), pressure),
|
||||
@@ -3208,8 +3214,11 @@ fn pen_values_outside_their_ranges_are_refused() {
|
||||
(json!([150, 150, null, null, null, -1]), rotation),
|
||||
(json!({"x": 150, "y": 150, "rotation": 360.5}), rotation),
|
||||
(json!([150, 150, null, null, null, 720]), rotation),
|
||||
(json!([150, 150, 0.5, 0, 0, 0, 1]), entries),
|
||||
(json!([150, 150, null, null, null, null, null]), entries),
|
||||
(json!([150, 150, null, null, null, null, -0.01]), wheel),
|
||||
(json!([150, 150, 0.5, 0, 0, 0, 1.5]), wheel),
|
||||
(json!({"x": 150, "y": 150, "wheel": 1e300}), wheel),
|
||||
(json!([150, 150, 0.5, 0, 0, 0, 1, 0]), entries),
|
||||
(json!([150, 150, null, null, null, null, null, null]), entries),
|
||||
] {
|
||||
let points: Vec<_> = good.iter().cloned().chain([bad]).collect();
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
@@ -3220,8 +3229,8 @@ fn pen_values_outside_their_ranges_are_refused() {
|
||||
for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() {
|
||||
let y = 300.0 + 50.0 * row as f64;
|
||||
let points = json!([
|
||||
[100, y, 0, -90, 90, 0],
|
||||
[150, y, 1, 90, -90, 360],
|
||||
[100, y, 0, -90, 90, 0, 0],
|
||||
[150, y, 1, 90, -90, 360, 1],
|
||||
[200, y, 0.5, null, 30],
|
||||
{"x": 250, "y": y, "tiltX": -45, "pressure": null},
|
||||
[300, y],
|
||||
|
||||
@@ -747,7 +747,9 @@ fn a_font_named_by_another_of_its_names_is_copied() {
|
||||
let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
|
||||
let report = String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap();
|
||||
assert!(report.contains("SourceSans3-Semibold Regular → Fonts/"), "{report}");
|
||||
let details = report.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default();
|
||||
// The Font Details row: the Fonts rows above it start with the same label.
|
||||
let font_details = report.split("\nFONT DETAILS\n").nth(1).unwrap_or_default();
|
||||
let details = font_details.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default();
|
||||
assert!(details.contains("embedding allowed") && !details.contains("missing"), "{report}");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user