mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 09:13:34 +00:00
Merge main into feat/recolor-group-storage
This commit is contained in:
@@ -97,7 +97,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Expand Appearance",
|
||||
["Object"],
|
||||
None,
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it 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. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it 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. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}",
|
||||
can_expand,
|
||||
expand_appearance
|
||||
),
|
||||
@@ -963,16 +963,74 @@ fn is_container(n: &Node) -> bool {
|
||||
|
||||
/// The raster effects of `n` (its own, its fills' and strokes') as an embedded image rendered at
|
||||
/// the document's raster effects resolution or a Rasterize effect's finer one, with whether they
|
||||
/// all paint below it (shadows and outer glows: the image then holds just them). A group's or
|
||||
/// layer's image leaves out its members' raster effects, which are expanded with them. `None`
|
||||
/// when it has none.
|
||||
fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// all paint below it (shadows and outer glows: the image then holds just them, and paints with
|
||||
/// their blend mode when they all use one). A group's or layer's image leaves out its members'
|
||||
/// raster effects, which are expanded with them. `None` when it has none.
|
||||
/// `Err` when that image would take `budget` past its limits: the object then stays as it is.
|
||||
fn raster_image(d: &mut Document, n: &Node, budget: &mut RasterBudget) -> std::result::Result<Option<(Node, bool)>, OverBudget> {
|
||||
let fx = rasterfx::raster_fx(n);
|
||||
if fx.is_empty() {
|
||||
return None;
|
||||
return Ok(None);
|
||||
}
|
||||
let below = fx.iter().all(effects::RasterFx::is_below);
|
||||
Some((rasterfx::raster_image(d, n, below, true)?, below))
|
||||
let pixels = budget.take(rasterfx::raster_pixels(d, n, below, true))?;
|
||||
let mut image = rasterfx::raster_image(d, n, below, true);
|
||||
if image.is_none() {
|
||||
// No image was made: it takes nothing from the budget.
|
||||
budget.images += 1;
|
||||
budget.pixels += pixels;
|
||||
}
|
||||
// Rendered alone, over nothing, the shadows and glows can't blend with the art below the
|
||||
// object, so the image does, as the canvas draws them.
|
||||
let mut modes = fx.iter().filter_map(effects::RasterFx::mode);
|
||||
if below
|
||||
&& let (Some(mode), Some(image)) = (modes.next(), image.as_mut())
|
||||
&& modes.all(|m| m == mode)
|
||||
{
|
||||
image.blend = mode;
|
||||
}
|
||||
Ok(image.map(|image| (image, below)))
|
||||
}
|
||||
|
||||
/// The most images of raster effects one Expand Appearance makes.
|
||||
const MAX_RASTER_IMAGES: u32 = 1_024;
|
||||
|
||||
/// The most pixels the images of raster effects one Expand Appearance makes hold in all.
|
||||
const MAX_RASTER_PIXELS: u64 = 256_000_000;
|
||||
|
||||
/// The note when objects keep their raster effects because their images would take an Expand
|
||||
/// Appearance past [`MAX_RASTER_IMAGES`] or [`MAX_RASTER_PIXELS`].
|
||||
pub(crate) const RASTER_EFFECTS_LEFT: &str =
|
||||
"some raster effects were not made into images: they would take more than 1,024 images or 256 megapixels in all";
|
||||
|
||||
/// An image of raster effects that would take a [`RasterBudget`] past its limits.
|
||||
#[derive(Debug)]
|
||||
struct OverBudget;
|
||||
|
||||
/// What one Expand Appearance has left of [`MAX_RASTER_IMAGES`] and [`MAX_RASTER_PIXELS`], and the
|
||||
/// objects whose raster effects it left as they are because their images would go past them.
|
||||
pub(crate) struct RasterBudget {
|
||||
images: u32,
|
||||
pixels: u64,
|
||||
pub(crate) left: usize,
|
||||
}
|
||||
|
||||
impl RasterBudget {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { images: MAX_RASTER_IMAGES, pixels: MAX_RASTER_PIXELS, left: 0 }
|
||||
}
|
||||
|
||||
/// Take an image of `pixels` ([`rasterfx::raster_pixels`]) before it is made, and return
|
||||
/// them; `Err`, with its object counted in `left`, when it would go past what is left.
|
||||
fn take(&mut self, pixels: u64) -> std::result::Result<u64, OverBudget> {
|
||||
if self.images == 0 || pixels > self.pixels {
|
||||
self.left += 1;
|
||||
return Err(OverBudget);
|
||||
}
|
||||
self.images -= 1;
|
||||
self.pixels -= pixels;
|
||||
Ok(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand the pieces of `m`, art evaluated from the object of the same id (its pieces share that
|
||||
@@ -983,6 +1041,7 @@ fn raster_image(d: &mut Document, n: &Node) -> Option<(Node, bool)> {
|
||||
/// pieces with the ids they have before that. `kept` gets the new id of each object in them that
|
||||
/// had an id `skip` lists before. Returns what each of those other members' expansions lists, by
|
||||
/// the member's new id.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn expand_pieces(
|
||||
d: &mut Document,
|
||||
m: &mut Node,
|
||||
@@ -991,6 +1050,7 @@ fn expand_pieces(
|
||||
skip: &[NodeId],
|
||||
kept: &mut Vec<NodeId>,
|
||||
stroke_art: effects::StrokeArt,
|
||||
raster: &mut RasterBudget,
|
||||
) -> std::collections::HashMap<NodeId, Vec<Listed>> {
|
||||
let id = m.id;
|
||||
let mut seen = std::collections::HashSet::from([id]);
|
||||
@@ -1005,7 +1065,7 @@ fn expand_pieces(
|
||||
if all || c.id == id {
|
||||
effects::expand_art(d, c, stroke_art);
|
||||
} else if has_seeded(c) && repeats_an_id(c, &seen) {
|
||||
listed = Some(expand_in_place(d, c, brushes, skip));
|
||||
listed = Some(expand_in_place(d, c, brushes, skip, raster));
|
||||
}
|
||||
let mut was = vec![];
|
||||
if !skip.is_empty() {
|
||||
@@ -1030,37 +1090,65 @@ fn expand_pieces(
|
||||
}
|
||||
|
||||
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
|
||||
/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as
|
||||
/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so
|
||||
/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more
|
||||
/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art
|
||||
/// would take the objects placed so far past `budget`.
|
||||
fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) {
|
||||
/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`],
|
||||
/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in
|
||||
/// that art in turn, so [`expand_pieces`] bakes their effects with the rest.
|
||||
fn expand_nested_instances(d: &mut Document, m: &mut Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) {
|
||||
for c in m.children_mut().into_iter().flatten() {
|
||||
if !matches!(c.kind, NodeKind::SymbolInstance { .. }) {
|
||||
if c.children().is_some() {
|
||||
expand_nested_instances(d, Arc::make_mut(c), depth, budget);
|
||||
expand_nested_instances(d, Arc::make_mut(c), depth, budget, raster);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue };
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) {
|
||||
continue;
|
||||
}
|
||||
let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue };
|
||||
let count = sym.art.count() as u64;
|
||||
if count > *budget {
|
||||
continue;
|
||||
}
|
||||
*budget -= count;
|
||||
let art = vectorcraft_render::instance_art(&sym.art, c);
|
||||
if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) {
|
||||
expand_nested_instances(d, &mut a, depth + 1, budget);
|
||||
if let Some(a) = expanded_instance(d, c, depth, budget, raster) {
|
||||
*c = Arc::new(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Symbol instance `c`, art an instance placed (`depth` instances deep), as art: the raster
|
||||
/// effects of its active fill or stroke an embedded image ([`raster_image`]) that replaces the art
|
||||
/// (blur, feather, inner glow) or goes below it (shadows, outer glows), and its art as
|
||||
/// [`effects::expand_outlined`] makes it without them, or as [`effects::instance_as_art`] does when
|
||||
/// it has no geometry effect, with the instances in that art expanded in turn. `None`, the instance
|
||||
/// staying as it is, when its active fill and stroke have no such effect, it is more than
|
||||
/// [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art would
|
||||
/// take the objects placed so far past `budget`, or the image of its raster effects would take
|
||||
/// `raster` past its limits. When that image can't be made, they stay on the art its geometry
|
||||
/// effects make, and without one it stays as it is.
|
||||
fn expanded_instance(d: &mut Document, c: &Node, depth: usize, budget: &mut u64, raster: &mut RasterBudget) -> Option<Node> {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { return None };
|
||||
let has_raster = effects::has_instance_row_raster(c);
|
||||
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !(has_raster || effects::has_item_geometry(c)) {
|
||||
return None;
|
||||
}
|
||||
let sym = d.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let count = sym.art.count() as u64;
|
||||
if count > *budget {
|
||||
return None;
|
||||
}
|
||||
let art = vectorcraft_render::instance_art(&sym.art, c);
|
||||
let image = if has_raster { raster_image(d, c, raster).ok()? } else { None };
|
||||
*budget -= count;
|
||||
let mut v = c.clone();
|
||||
if image.is_some() {
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
}
|
||||
let below = match image {
|
||||
Some((image, false)) => return Some(rasterfx::replace_with_image(v, image)),
|
||||
Some((image, true)) => Some(image),
|
||||
None => None,
|
||||
};
|
||||
let mut a = effects::expand_outlined(Some(&*d), &v, Some(&art))
|
||||
.or_else(|| if below.is_some() { effects::instance_as_art(Some(&*d), &v, Some(&art)) } else { None })?;
|
||||
expand_nested_instances(d, &mut a, depth + 1, budget, raster);
|
||||
if let Some(image) = below {
|
||||
rasterfx::put_below(d, &mut a, image);
|
||||
}
|
||||
Some(a)
|
||||
}
|
||||
|
||||
/// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids?
|
||||
fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
@@ -1075,9 +1163,9 @@ fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
|
||||
type Listed = (NodeId, usize);
|
||||
|
||||
/// [`expanded_node`] of `c` in place. Returns what the expansion lists, by places in the walk of `c`.
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId]) -> Vec<Listed> {
|
||||
fn expand_in_place(d: &mut Document, c: &mut Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Vec<Listed> {
|
||||
let mut listed = vec![];
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed) {
|
||||
if let Some(e) = expanded_node(d, c.clone(), brushes, skip, &mut listed, raster) {
|
||||
*c = e;
|
||||
}
|
||||
listed
|
||||
@@ -1099,18 +1187,26 @@ fn fresh_ids_listed(d: &mut Document, c: &mut Node, seen: &mut std::collections:
|
||||
/// Expand Appearance of `id` (and, recursively, of a group's or layer's members): every fill and
|
||||
/// stroke becomes an object of its own (a stroke a path stroked by it alone, brushes as their art),
|
||||
/// geometry effects are baked, raster effects become an embedded image, and the object keeps its
|
||||
/// transparency.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>) {
|
||||
expand_node_except(d, id, brushes, &[], out);
|
||||
/// transparency. An object whose raster effects' image would take `raster` past its limits stays
|
||||
/// as it is, with what is inside it.
|
||||
pub(crate) fn expand_node(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], out: &mut Vec<NodeId>, raster: &mut RasterBudget) {
|
||||
expand_node_except(d, id, brushes, &[], out, raster);
|
||||
}
|
||||
|
||||
/// [`expand_node`], leaving the objects `skip` lists, and what they hold, as they are. A geometry
|
||||
/// effect of a group or layer around one still reshapes it with the rest of its members, and the
|
||||
/// copies of it that such an effect makes are left as they are too.
|
||||
fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<NodeId>) {
|
||||
fn expand_node_except(
|
||||
d: &mut Document,
|
||||
id: NodeId,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
out: &mut Vec<NodeId>,
|
||||
raster: &mut RasterBudget,
|
||||
) {
|
||||
let Some(n) = d.node(id).cloned() else { return };
|
||||
let mut listed = vec![];
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed);
|
||||
let m = expanded_node(d, n, brushes, skip, &mut listed, raster);
|
||||
out.extend(listed.into_iter().map(|(id, _)| id));
|
||||
if let Some(mut m) = m {
|
||||
// Art made from type takes its emoji's pixels into the document.
|
||||
@@ -1124,11 +1220,20 @@ fn expand_node_except(d: &mut Document, id: NodeId, brushes: &[vectorcraft_brush
|
||||
/// [`expand_node`] of `n`, which need not be in `d`: `n` with its appearance expanded, `None` when
|
||||
/// it has nothing to expand. `out` gets the objects whose appearance expands, by places in the walk
|
||||
/// of the expanded `n`, `n`'s first when its own does. The objects `skip` lists are not expanded.
|
||||
fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], out: &mut Vec<Listed>) -> Option<Node> {
|
||||
fn expanded_node(
|
||||
d: &mut Document,
|
||||
mut n: Node,
|
||||
brushes: &[vectorcraft_brush::Brush],
|
||||
skip: &[NodeId],
|
||||
out: &mut Vec<Listed>,
|
||||
raster: &mut RasterBudget,
|
||||
) -> Option<Node> {
|
||||
let id = n.id;
|
||||
if skip.contains(&id) || !expandable(&n) {
|
||||
return None;
|
||||
}
|
||||
// What `out` held before `n`: an object left by the raster budget lists nothing.
|
||||
let listed_before = out.len();
|
||||
// Colour adjustments: the colours inside become the adjusted ones (an embedded image a
|
||||
// recoloured copy), then the rest of the appearance expands.
|
||||
let mut changed = false;
|
||||
@@ -1141,6 +1246,10 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// The embedded images before the adjustment, when the raster budget may yet leave `n` as it
|
||||
// is: the recolored copies the adjustment adds then go again.
|
||||
let images_before = (effects::has_adjustment(&n) && !rasterfx::raster_fx(&n).is_empty())
|
||||
.then(|| d.images.keys().cloned().collect::<std::collections::HashSet<_>>());
|
||||
if effects::has_adjustment(&n)
|
||||
&& let Some(m) = effects::adjust_in_document(d, &n, symbol_art)
|
||||
{
|
||||
@@ -1163,7 +1272,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
for (i, c) in m.children_mut().into_iter().flatten().enumerate() {
|
||||
let c = Arc::make_mut(c);
|
||||
if i == 0 {
|
||||
expanded = expand_in_place(d, c, brushes, skip);
|
||||
expanded = expand_in_place(d, c, brushes, skip, raster);
|
||||
fresh_ids_listed(d, c, &mut seen, &mut expanded);
|
||||
} else {
|
||||
effects::fresh_ids(d, c, &mut seen);
|
||||
@@ -1186,7 +1295,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
return Some(m);
|
||||
}
|
||||
let image = raster_image(d, &n);
|
||||
// Raster effects whose image would go past the budget stay: so does the object, with what is
|
||||
// inside it and its color adjustments (a symbol instance stays an instance of its symbol).
|
||||
let Ok(image) = raster_image(d, &n, raster) else {
|
||||
out.truncate(listed_before);
|
||||
if let Some(keys) = images_before {
|
||||
d.images.retain(|k, _| keys.contains(k));
|
||||
}
|
||||
return None;
|
||||
};
|
||||
let mut v = n.clone();
|
||||
rasterfx::strip_raster(&mut v, false);
|
||||
let mut stroke_art =
|
||||
@@ -1206,7 +1323,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
} else if container {
|
||||
// A group's or layer's own fills and strokes become art among its members.
|
||||
effects::evaluate_container(Some(&*d), &v).map(|mut m| {
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art);
|
||||
members = expand_pieces(d, &mut m, false, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
} else if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })
|
||||
@@ -1224,10 +1341,15 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
|
||||
// A symbol instance whose active fill or stroke has only effects that paint below it
|
||||
// (now in the image) becomes its art as well.
|
||||
let row_raster = image.is_some() && effects::has_instance_row_raster(&n);
|
||||
let outlined = effects::expand_outlined(Some(&*d), &v, symbol.as_ref())
|
||||
.or_else(|| if row_raster { effects::instance_as_art(Some(&*d), &v, symbol.as_ref()) } else { None });
|
||||
outlined.map(|mut m| {
|
||||
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art);
|
||||
expand_nested_instances(d, &mut m, 1, &mut budget, raster);
|
||||
expand_pieces(d, &mut m, true, brushes, skip, &mut kept, &mut stroke_art, raster);
|
||||
m
|
||||
})
|
||||
};
|
||||
@@ -1262,7 +1384,7 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
|
||||
match members.remove(&c.id) {
|
||||
Some(listed) => out.extend(listed),
|
||||
None => {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out) {
|
||||
if let Some(e) = expanded_node(d, (**c).clone(), brushes, &skip, out, raster) {
|
||||
*c = Arc::new(e);
|
||||
changed = true;
|
||||
}
|
||||
@@ -1336,6 +1458,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let failed = vectorcraft_render::decode_failures();
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let mut raster = RasterBudget::new();
|
||||
let ids = s.edit("Expand Appearance", |d, _| {
|
||||
let before = d.clone();
|
||||
// The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose
|
||||
@@ -1351,7 +1474,7 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut out = vec![];
|
||||
let threaded = super::threads::frames(d);
|
||||
for id in &roots {
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out);
|
||||
expand_node_except(d, *id, &brushes, &designs, &mut out, &mut raster);
|
||||
}
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was replaced stays where it was, no longer linked.
|
||||
@@ -1360,6 +1483,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// stays type under a new id takes its frame's place.
|
||||
super::threads::leave_threads(d, &threaded);
|
||||
if out.is_empty() || (kept && d.layers == before.layers) {
|
||||
if raster.left > 0 {
|
||||
return Err(EngineError::Other(RASTER_EFFECTS_LEFT.into()));
|
||||
}
|
||||
return Err(EngineError::Other("Expand Appearance: the selection has a basic appearance".into()));
|
||||
}
|
||||
super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad("Expand Appearance", e))?;
|
||||
@@ -1367,8 +1493,12 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
let mut out = json!({ "ids": ids_json(&ids) });
|
||||
// Raster effects become images rendered from the art.
|
||||
if let Some(w) = rasterfx::undecoded_warning(failed) {
|
||||
out["warning"] = json!(w);
|
||||
let warnings: Vec<&str> = rasterfx::undecoded_warning(failed).into_iter().chain((raster.left > 0).then_some(RASTER_EFFECTS_LEFT)).collect();
|
||||
if !warnings.is_empty() {
|
||||
out["warning"] = json!(warnings.join("; "));
|
||||
}
|
||||
if raster.left > 0 {
|
||||
out["rasterLeft"] = json!(raster.left);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -1082,3 +1082,28 @@ fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
|
||||
let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
|
||||
assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
|
||||
}
|
||||
|
||||
/// The raster budget charges each image its pixels before it is made: an image past what is left
|
||||
/// is refused and counted, and the object keeps its blur.
|
||||
#[test]
|
||||
fn an_image_past_the_pixels_left_stays_unmade() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
s.execute("effect.apply", &json!({"ids": [id.0], "effect": "blur.gaussian", "params": {"radius": 3}})).unwrap();
|
||||
let mut d = s.doc().unwrap().doc.as_ref().clone();
|
||||
let n = d.node(id).cloned().unwrap();
|
||||
let pixels = super::rasterfx::raster_pixels(&d, &n, false, true);
|
||||
assert!(pixels > 10_000, "a 100 pt square at 72 ppi: {pixels}");
|
||||
|
||||
let mut budget = super::RasterBudget { images: 10, pixels: pixels - 1, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err());
|
||||
assert_eq!((budget.images, budget.pixels, budget.left), (10, pixels - 1, 1), "nothing is taken");
|
||||
|
||||
let mut budget = super::RasterBudget { images: 10, pixels, left: 0 };
|
||||
let (image, _) = super::raster_image(&mut d, &n, &mut budget).unwrap().expect("the image is made");
|
||||
let NodeKind::Image(img) = &image.kind else { panic!("not an image") };
|
||||
assert_eq!(u64::from(img.width) * u64::from(img.height), pixels, "the charge is the image's size");
|
||||
assert_eq!((budget.images, budget.pixels, budget.left), (9, 0, 0));
|
||||
|
||||
let mut budget = super::RasterBudget { images: 0, pixels, left: 0 };
|
||||
assert!(super::raster_image(&mut d, &n, &mut budget).is_err(), "no image is left");
|
||||
}
|
||||
|
||||
@@ -142,7 +142,9 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
let one = super::save::artboard_doc(doc, b);
|
||||
let (full, placed) = crate::cmd::place::document::full_documents(&one);
|
||||
let mut d = full.into_owned();
|
||||
expand_appearances(&mut d);
|
||||
if expand_appearances(&mut d) {
|
||||
note(&mut enc.warnings, super::super::effectcmd::RASTER_EFFECTS_LEFT);
|
||||
}
|
||||
if mode == SeeThrough::Flatten {
|
||||
expand_image_patterns(&mut d)?;
|
||||
}
|
||||
@@ -175,14 +177,17 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
Ok(enc)
|
||||
}
|
||||
|
||||
/// Expand Appearance of every layer's art whose appearance the format can't hold.
|
||||
fn expand_appearances(d: &mut Document) {
|
||||
/// Expand Appearance of every layer's art whose appearance the format can't hold. Returns whether
|
||||
/// objects kept raster effects whose images would go past Expand Appearance's limits.
|
||||
fn expand_appearances(d: &mut Document) -> bool {
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let layers: Vec<NodeId> = d.layers.iter().map(|l| l.id).collect();
|
||||
let mut out = vec![];
|
||||
let mut raster = super::super::effectcmd::RasterBudget::new();
|
||||
for id in layers {
|
||||
super::super::effectcmd::expand_node(d, id, &brushes, &mut out);
|
||||
super::super::effectcmd::expand_node(d, id, &brushes, &mut out, &mut raster);
|
||||
}
|
||||
raster.left > 0
|
||||
}
|
||||
|
||||
/// Expand every layer's pattern fills that paint an image with see-through pixels, a colorize paint,
|
||||
|
||||
@@ -764,7 +764,7 @@ fn leave_out_folder(r: &mut Value, folder: &str) {
|
||||
|
||||
/// Export settings kept in the document or a preset, as the request being served may see them: a
|
||||
/// `folder` outside the read roots ([`super::access::shown`]) is left out.
|
||||
fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
|
||||
pub(super) fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
|
||||
if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) {
|
||||
settings.remove("folder");
|
||||
}
|
||||
|
||||
@@ -180,12 +180,24 @@ pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) ->
|
||||
})
|
||||
}
|
||||
|
||||
/// The native document Preserve Editing embeds: `doc`, without an Export for Screens `folder`
|
||||
/// outside the read roots of the request being served (the open document keeps it).
|
||||
fn native_attachment(doc: &Document) -> Vec<u8> {
|
||||
let settings = super::screens::leave_out_unreadable_settings_folder(doc.export_settings.clone());
|
||||
if settings.len() == doc.export_settings.len() {
|
||||
return vectorcraft_format::save(doc, false);
|
||||
}
|
||||
let mut kept = doc.clone();
|
||||
kept.export_settings = settings;
|
||||
vectorcraft_format::save(&kept, false)
|
||||
}
|
||||
|
||||
/// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they
|
||||
/// link to and the writer's warnings.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result<Encoded, String> {
|
||||
let (opts, boards, chosen) = plan(doc, p)?;
|
||||
// Preserve editing embeds the native document (once, shared by every file).
|
||||
let native = opts.preserve_editing.then(|| vectorcraft_format::save(doc, false));
|
||||
let native = opts.preserve_editing.then(|| native_attachment(doc));
|
||||
// Draw linked files as vectors when available, or their previews with a warning. Keep
|
||||
// that preparation out of the native attachment so missing links remain relinkable.
|
||||
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
|
||||
|
||||
@@ -53,6 +53,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
font_list
|
||||
),
|
||||
cmd!(
|
||||
query "text.similarFonts",
|
||||
"Show Similar Fonts",
|
||||
[],
|
||||
None,
|
||||
"{family (any of its names), limit?: whole number 1..100000 (default: all)} → {family: the family's own name, families: [names]}: the families `text.fontList` lists, ordered as a font menu's Show Similar Fonts orders them: the family itself first, then those that set the same script (Japanese, Thai or neither), then the others, each group nearest first by VectorCraft's own measure of the faces nearest an upright Regular (OS/2 PANOSE digits, weight and width classes, x-height, cap height and average character width, the italic angle, and the kind); an error when the family isn't available or the font menus don't list it, or `limit` is not a whole number from 1 to 100000",
|
||||
always,
|
||||
similar_fonts
|
||||
),
|
||||
cmd!(
|
||||
query "text.glyphCategories",
|
||||
"Glyph Categories",
|
||||
@@ -1146,6 +1155,36 @@ fn font_list(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most families `text.similarFonts` takes as its `limit`.
|
||||
const MAX_SIMILAR: u64 = 100_000;
|
||||
|
||||
fn similar_fonts(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.similarFonts";
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let family = match p.get("family") {
|
||||
Some(Value::String(f)) if !f.trim().is_empty() => f.as_str(),
|
||||
Some(Value::String(_)) | None => return Err(bad(C, "`family` is required")),
|
||||
Some(_) => return Err(bad(C, "`family` must be a string")),
|
||||
};
|
||||
let limit = match p.get("limit") {
|
||||
None => None,
|
||||
Some(v) => Some(
|
||||
v.as_u64()
|
||||
.filter(|n| (1..=MAX_SIMILAR).contains(n))
|
||||
.ok_or_else(|| bad(C, format!("`limit` must be a whole number from 1 to {MAX_SIMILAR}")))?,
|
||||
),
|
||||
};
|
||||
// Any of the family's names, spelled as the font menus list it; a family they don't list is not available.
|
||||
let menu = db.menu_family_list();
|
||||
let listed = db.has_family(family).then(|| db.canonical(family, "").0).and_then(|c| menu.iter().find(|f| f.eq_ignore_ascii_case(&c)).cloned());
|
||||
let Some(family) = listed else { return Err(bad(C, format!("font family `{family}` is not available"))) };
|
||||
let mut families = db.similar_families(&family, &menu);
|
||||
if let Some(n) = limit.and_then(|n| usize::try_from(n).ok()) {
|
||||
families.truncate(n);
|
||||
}
|
||||
Ok(json!({ "family": family, "families": families }))
|
||||
}
|
||||
|
||||
/// `text.glyphCategories`: the OpenType categories of a font's glyphs
|
||||
/// ([`vectorcraft_text::FontFace::glyph_categories`]).
|
||||
fn glyph_categories(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -133,7 +133,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Crop Image",
|
||||
["Object"],
|
||||
None,
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
|
||||
"{rect?: [x, y, width, height] | trim?: true (to the pixels that aren't fully transparent, pixel for pixel; an image with none to cut is left as it is, trimmed: false), ppi?: number (without trim: the cropped image's resolution in pixels per inch, resampled from the cut pixels; 1 to 2400, at most the image's own, or 300 for a linked image; default the image's own; a rect over the whole image with a new ppi only resamples it)} crop the selected image (default: to the artboard it sits on) → {id, width, height, trimmed? (with trim), warning? (without trim: the image couldn't be decoded, as object.rasterize says)}",
|
||||
has_image,
|
||||
crop_image
|
||||
),
|
||||
@@ -967,10 +967,10 @@ fn polygon_path(pts: &[Point]) -> PathData {
|
||||
PathData::single(vectorcraft_geom::SubPath::new(pts.iter().map(|p| Anchor::corner(*p)).collect(), true))
|
||||
}
|
||||
|
||||
/// The part of an image under `r` (in document space) copied out of its pixels, as PNG bytes, with its size and
|
||||
/// placement. `None` when the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or
|
||||
/// `r` not on the pixel grid), so the caller draws it instead.
|
||||
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(Vec<u8>, u32, u32, Affine)> {
|
||||
/// The part of an image under `r` (in document space) copied out of its pixels, with its placement. `None` when
|
||||
/// the image can't be cut that way (turned or skewed, CMYK, pixels that can't be read, or `r` not on the pixel
|
||||
/// grid), so the caller draws it instead.
|
||||
fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Option<(image::RgbaImage, Affine)> {
|
||||
let blob = doc.images.get(&im.key)?;
|
||||
let [a, b, c, d, _, _] = im.xf.as_coeffs();
|
||||
if blob.is_cmyk() || b.abs() > 1e-9 || c.abs() > 1e-9 || a.abs() < 1e-9 || d.abs() < 1e-9 {
|
||||
@@ -996,9 +996,85 @@ fn crop_pixels(doc: &vectorcraft_doc::Document, im: &ImageObject, r: Rect) -> Op
|
||||
return None;
|
||||
}
|
||||
let cut = image::imageops::crop_imm(&px, x0, y0, x1 - x0, y1 - y0).to_image();
|
||||
Some((cut, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
|
||||
}
|
||||
|
||||
/// Crop Image's `ppi`: the resolution asked for, in pixels per point, and whether it keeps the image's pixels as
|
||||
/// they are (its own, with square pixels); `None` for the image's own. Refuses a resolution that isn't a positive
|
||||
/// number or is above what the image allows: its own, or 300 ppi for a linked image, within 1 to 2400 ppi as
|
||||
/// Rasterize's.
|
||||
fn crop_resolution(p: &Value, im: &ImageObject) -> Result<Option<(f64, bool)>> {
|
||||
const C: &str = "object.cropImage";
|
||||
let Some(ppi) = p.get("ppi").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let ppi = ppi.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad(C, format!("ppi must be a positive number, not {ppi}")))?;
|
||||
if !(1.0..=2400.0).contains(&ppi) {
|
||||
return Err(bad(C, "ppi must be between 1 and 2400"));
|
||||
}
|
||||
let (_, max) = vectorcraft_tools::cropimage::image_ppi(im);
|
||||
if ppi > max + 1e-6 {
|
||||
let max = (max * 100.0 + 1e-6).floor() / 100.0;
|
||||
return Err(bad(C, format!("ppi can't be more than {max} for this image")));
|
||||
}
|
||||
// An image whose pixels are not square is resampled on both sides, even at its denser side's resolution.
|
||||
Ok(Some((ppi / 72.0, vectorcraft_tools::cropimage::keeps_resolution(im, ppi, 1e-6))))
|
||||
}
|
||||
|
||||
/// A `w` × `h` image resampled at a resolution asked for, held to the size a drawing may have ([`MAX_PIXELS`], and
|
||||
/// no side past the renderer's).
|
||||
fn check_crop_size(w: f64, h: f64) -> Result<()> {
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
if w * h > MAX_PIXELS || w > side || h > side {
|
||||
let (w, h) = (w as u64, h as u64);
|
||||
return Err(bad("object.cropImage", format!("an image of {w} × {h} pixels is too large to draw")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `img` resampled to `w` × `h` with its colors weighted by their alpha, so the color of a fully
|
||||
/// transparent pixel does not show at the edges of what is opaque. The weighted colors are held in
|
||||
/// 16 bits a channel until the end, so a nearly transparent pixel keeps its color. An error when
|
||||
/// the working copies would not fit ([`check_resample_size`]).
|
||||
fn resize_premultiplied(img: &image::RgbaImage, w: u32, h: u32) -> Result<image::RgbaImage> {
|
||||
check_resample_size(img.width(), img.height(), w, h)?;
|
||||
let mut pre = image::ImageBuffer::<image::Rgba<u16>, Vec<u16>>::new(img.width(), img.height());
|
||||
for (d, s) in pre.pixels_mut().zip(img.pixels()) {
|
||||
let a = u32::from(s[3]);
|
||||
for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) {
|
||||
// c × 257 × a / 255, rounded: the color scaled to 16 bits and weighted.
|
||||
*dc = ((u32::from(*sc) * 257 * a + 127) / 255) as u16;
|
||||
}
|
||||
d.0[3] = (a * 257) as u16;
|
||||
}
|
||||
let out = image::imageops::resize(&pre, w, h, image::imageops::FilterType::Lanczos3);
|
||||
let mut res = image::RgbaImage::new(out.width(), out.height());
|
||||
for (d, s) in res.pixels_mut().zip(out.pixels()) {
|
||||
let a = u64::from(s[3]);
|
||||
for (dc, sc) in d.0[..3].iter_mut().zip(&s.0[..3]) {
|
||||
// c × 65535 / a back to 8 bits (÷ 257), rounded: c × 255 / a.
|
||||
*dc = (u64::from(*sc) * 255 + a / 2).checked_div(a).unwrap_or(0).min(255) as u8;
|
||||
}
|
||||
d.0[3] = ((a + 128) / 257).min(255) as u8;
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
/// Whether resampling a `sw` × `sh` image to `w` × `h` fits in [`MAX_RASTER_ALLOC`]: the source and
|
||||
/// its weighted 16-bit copy (12 bytes a pixel), the resampler's float rows between its two passes
|
||||
/// (16 bytes a pixel, `sw` × `h`) and the 16-bit and 8-bit results (12 bytes a pixel of `w` × `h`).
|
||||
pub(crate) fn check_resample_size(sw: u32, sh: u32, w: u32, h: u32) -> Result<()> {
|
||||
let (sw, sh, w, h) = (u64::from(sw), u64::from(sh), u64::from(w), u64::from(h));
|
||||
let bytes = (sw * sh).saturating_mul(12).saturating_add((sw * h).saturating_mul(16)).saturating_add((w * h).saturating_mul(12));
|
||||
if bytes > crate::cmd::fileio::MAX_RASTER_ALLOC {
|
||||
return Err(bad("object.cropImage", format!("an image of {sw} × {sh} pixels is too large to resample")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `img` as PNG bytes.
|
||||
fn encode_png(img: &image::RgbaImage) -> Result<Vec<u8>> {
|
||||
let mut png = Vec::new();
|
||||
cut.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
|
||||
Some((png, x1 - x0, y1 - y0, im.xf * Affine::translate((f64::from(x0), f64::from(y0)))))
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| bad("object.cropImage", e.to_string()))?;
|
||||
Ok(png)
|
||||
}
|
||||
|
||||
fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1014,9 +1090,15 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
|
||||
if switch_or(p, "trim", false, C)? {
|
||||
if p.get("ppi").is_some_and(|v| !v.is_null()) {
|
||||
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
|
||||
}
|
||||
return trim_image(s, id, (**im).clone());
|
||||
}
|
||||
let ib = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?;
|
||||
let asked = crop_resolution(p, im)?;
|
||||
// The resolution the image's pixels are resampled to when they are cut straight.
|
||||
let target = asked.and_then(|(t, keeps)| (!keeps).then_some(t));
|
||||
let rect = match p.get("rect").filter(|v| !v.is_null()) {
|
||||
Some(Value::Array(a)) if a.len() == 4 => {
|
||||
let v: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();
|
||||
@@ -1038,16 +1120,49 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return Err(bad(C, "crop rectangle doesn't overlap the image"));
|
||||
}
|
||||
if (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6 {
|
||||
// A box over the whole image still resamples it to a new resolution.
|
||||
let whole = (r.x0 - ib.x0).abs() < 1e-6 && (r.y0 - ib.y0).abs() < 1e-6 && (r.x1 - ib.x1).abs() < 1e-6 && (r.y1 - ib.y1).abs() < 1e-6;
|
||||
// A turned or skewed image is drawn, so a resolution asked for, even its own, still makes a new image.
|
||||
let [_, xb, xc, _, _, _] = im.xf.as_coeffs();
|
||||
let turned = xb.abs() > 1e-9 || xc.abs() > 1e-9;
|
||||
if whole && target.is_none() && (asked.is_none() || !turned) {
|
||||
return Err(bad(C, "nothing to crop"));
|
||||
}
|
||||
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled.
|
||||
if let Some((png, cw, ch, xf)) = crop_pixels(&st.doc, im, r) {
|
||||
put_pixels(s, id, png, cw, ch, xf)?;
|
||||
if let Some(t) = target {
|
||||
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
|
||||
}
|
||||
// A plain, axis-aligned raster is cut straight from its pixels, so nothing is resampled unless a
|
||||
// resolution is asked for.
|
||||
if let Some((cut, xf)) = crop_pixels(&st.doc, im, r) {
|
||||
let (cut, xf) = match target {
|
||||
Some(t) => {
|
||||
let (cw, ch) = cut.dimensions();
|
||||
let (w, h) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
|
||||
let resized = resize_premultiplied(&cut, w, h)?;
|
||||
(resized, xf * Affine::scale_non_uniform(f64::from(cw) / f64::from(w), f64::from(ch) / f64::from(h)))
|
||||
}
|
||||
None => (cut, xf),
|
||||
};
|
||||
let (cw, ch) = cut.dimensions();
|
||||
put_pixels(s, id, encode_png(&cut)?, cw, ch, xf)?;
|
||||
return Ok(json!({ "id": id.0, "width": cw, "height": ch }));
|
||||
}
|
||||
// Keep the image's pixel density.
|
||||
let scale = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
|
||||
// A drawn crop is made at a resolution asked for even when it is the image's own: the box of a
|
||||
// turned or skewed image holds fewer of its pixels a point than the image does.
|
||||
let target = asked.map(|(t, _)| t);
|
||||
if let Some(t) = target {
|
||||
check_crop_size((r.width() * t).round().max(1.0), (r.height() * t).round().max(1.0))?;
|
||||
}
|
||||
// Drawn at the image's pixel density, or for a resolution asked for at up to twice that (no more
|
||||
// than the image's own, measured on its pixel grid however it is turned, nor past the size a
|
||||
// drawing may have), and resampled to it.
|
||||
let native = (im.width as f64 / ib.width().max(1e-9)).max(im.height as f64 / ib.height().max(1e-9));
|
||||
let scale = target.map_or(native, |t| {
|
||||
let own = native.max(vectorcraft_tools::cropimage::image_ppi(im).0 / 72.0);
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
let budget = (MAX_PIXELS / (r.width() * r.height()).max(1e-9)).sqrt().min(side / r.width().max(1e-9)).min(side / r.height().max(1e-9));
|
||||
(2.0 * t).min(own).min(budget).max(t.min(own))
|
||||
});
|
||||
let mut bare = node.clone();
|
||||
bare.opacity = 1.0;
|
||||
bare.blend = Default::default();
|
||||
@@ -1058,23 +1173,41 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(e) = bare.extras_if_any() {
|
||||
e.color_mask = None;
|
||||
}
|
||||
let (dw, dh) = ((r.width() * scale).round().max(1.0), (r.height() * scale).round().max(1.0));
|
||||
let region = Rect::new(r.x0, r.y0, r.x0 + dw / scale, r.y0 + dh / scale);
|
||||
// At a resolution asked for, the drawing is fitted to the box below: the image is stretched
|
||||
// about the box's corner so the box fills the whole pixels drawn, and nothing past it is drawn.
|
||||
if target.is_some()
|
||||
&& let NodeKind::Image(bi) = &mut bare.kind
|
||||
{
|
||||
let o = r.origin().to_vec2();
|
||||
bi.xf = Affine::translate(o)
|
||||
* Affine::scale_non_uniform(region.width() / r.width(), region.height() / r.height())
|
||||
* Affine::translate(-o)
|
||||
* bi.xf;
|
||||
}
|
||||
let tmp = isolated_doc(&st.doc, vec![bare]);
|
||||
let region = Rect::new(r.x0, r.y0, r.x0 + (r.width() * scale).round().max(1.0) / scale, r.y0 + (r.height() * scale).round().max(1.0) / scale);
|
||||
let (png, w, h, warning) =
|
||||
render_png(&tmp, region, scale, &RasterExportOptions::default().render_options(RasterFormat::Png), RasterColorModel::Document)?;
|
||||
// At a resolution asked for, the drawing is resampled to the box's size at that resolution and
|
||||
// fitted to the box, so the image keeps its size.
|
||||
let (png, w, h, xf) = match target {
|
||||
Some(t) => {
|
||||
let drawn = image::load_from_memory(&png).map_err(|e| bad(C, e.to_string()))?.into_rgba8();
|
||||
// Only the decoded pixels are held while they are resampled.
|
||||
drop(png);
|
||||
let (tw, th) = ((r.width() * t).round().max(1.0) as u32, (r.height() * t).round().max(1.0) as u32);
|
||||
let resized = resize_premultiplied(&drawn, tw, th)?;
|
||||
let xf = Affine::translate(r.origin().to_vec2()) * Affine::scale_non_uniform(r.width() / f64::from(tw), r.height() / f64::from(th));
|
||||
(encode_png(&resized)?, tw, th, xf)
|
||||
}
|
||||
None => (png, w, h, Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale)),
|
||||
};
|
||||
s.edit("Crop Image", |d, _| {
|
||||
let key = unique_key(d, "crop");
|
||||
d.images.insert(key.clone(), vectorcraft_doc::ImageBlob::new("image/png", png));
|
||||
if let Some(n) = d.node_mut(id) {
|
||||
n.kind = NodeKind::Image(Box::new(ImageObject {
|
||||
key,
|
||||
width: w,
|
||||
height: h,
|
||||
xf: Affine::translate(region.origin().to_vec2()) * Affine::scale(1.0 / scale),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
}));
|
||||
n.kind = NodeKind::Image(Box::new(ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None }));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -166,15 +166,18 @@ const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
|
||||
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
|
||||
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
|
||||
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
|
||||
/// An instance in another symbol's art is placed by that symbol's instances and is left as it is.
|
||||
/// A document without pixel-aligned symbols is not walked.
|
||||
/// An instance in another symbol's art, the art on the symbol editing layer included, is placed by
|
||||
/// that symbol's instances and is left as it is. A document without pixel-aligned symbols is not walked.
|
||||
fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let was = before.pixel_aligned_symbols();
|
||||
// The symbol whose editing mode this edit ended, if any.
|
||||
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let edited_now = doc.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let edit_ended = edited_before.filter(|b| edited_now != Some(*b)).map(str::to_owned);
|
||||
let mut every = false;
|
||||
for name in &aligned {
|
||||
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
@@ -184,22 +187,29 @@ fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
_ => true,
|
||||
};
|
||||
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
|
||||
if !was.contains(name) || edited_before == Some(name.as_str()) || art_changed || size_changed {
|
||||
if !was.contains(name) || edit_ended.as_deref() == Some(name.as_str()) || art_changed || size_changed {
|
||||
snap_symbol_art(doc, name);
|
||||
every = true;
|
||||
}
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
// The symbol editing layer holds another symbol's art.
|
||||
let editing = doc.symbol_edit.as_ref().map(|e| e.layer);
|
||||
if every {
|
||||
for layer in doc.layers.iter_mut() {
|
||||
if holds_instance(layer, &natural) {
|
||||
if Some(layer.id) != editing && holds_instance(layer, &natural) {
|
||||
snap_instances_in(Arc::make_mut(layer), &natural);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (mut ids, mut masked) = (vec![], vec![]);
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
if let Some(layer) = editing {
|
||||
let outside = |layers: &[Arc<Node>]| layers.iter().filter(|l| l.id != layer).cloned().collect::<Vec<_>>();
|
||||
changed_instances(&outside(&before.layers), &outside(&doc.layers), &natural, &mut ids, &mut masked);
|
||||
} else {
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
}
|
||||
for id in ids {
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
snap_instance(n, &natural);
|
||||
@@ -358,9 +368,10 @@ fn snap_mask(n: &mut Node) -> bool {
|
||||
|
||||
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
|
||||
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
|
||||
/// rotated (a half turn included) or sheared instance stays where it is.
|
||||
/// rotated (a half turn included) or sheared instance stays where it is. The instance moves as any
|
||||
/// move moves it ([`Node::transform`]), so the art of a linked opacity mask moves with it.
|
||||
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &mut n.kind else { return };
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return };
|
||||
let Some(nat) = natural.get(symbol.as_str()) else { return };
|
||||
let [a, b, c, d, e, f] = xf.as_coeffs();
|
||||
let [na, _, _, nd, _, _] = nat.as_coeffs();
|
||||
@@ -373,7 +384,12 @@ fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
return;
|
||||
}
|
||||
let (x, y) = (e.round(), f.round());
|
||||
if x != e || y != f {
|
||||
if x == e && y == f {
|
||||
return;
|
||||
}
|
||||
n.transform(Affine::translate((x - e, y - f)), Scaling::default());
|
||||
// Whole points exactly, which adding the offset to the old position need not give.
|
||||
if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind {
|
||||
*xf = Affine::new([a, b, c, d, x, y]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -704,8 +704,9 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
];
|
||||
|
||||
/// Commands a plug-in may not call although no rule refuses them, in order: they change the
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, run
|
||||
/// plug-ins again, or read a file and report where it is on disk.
|
||||
/// preferences, a tool's options, a drag's state or the font names the whole app knows, list the
|
||||
/// fonts installed on the system as `text.fontList` does, run plug-ins again, or read a file and
|
||||
/// report where it is on disk.
|
||||
pub(super) const DENIED: &[&str] = &[
|
||||
"addon.cleanup.splitText",
|
||||
"addon.pathtools.movePointsTogether",
|
||||
@@ -718,5 +719,6 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"object.pathfinder.options",
|
||||
"stroke.arrowheads.edit",
|
||||
"stroke.arrowheads.list",
|
||||
"text.similarFonts",
|
||||
"type.compositeFonts.set",
|
||||
];
|
||||
|
||||
@@ -174,19 +174,14 @@ pub(crate) fn effects_scale(doc: &Document) -> f64 {
|
||||
(doc.raster_effects_ppi / 72.0).clamp(1.0 / 72.0, 2400.0 / 72.0)
|
||||
}
|
||||
|
||||
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
|
||||
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
|
||||
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
|
||||
/// of the image, which then only holds what the effects add around it (a shadow to go under the
|
||||
/// vector object). The document's raster effects settings add room around it and finish its pixels.
|
||||
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
|
||||
/// positive, or when its PNG can't be encoded.
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
/// The region [`effect_image`] renders `whole` over in `d`, and the scale it renders at (`scale`, or
|
||||
/// less for an image past 64 Mpx or a side the renderer can't address). `None` when it paints
|
||||
/// nothing, when the area it covers overflows `f64` or the scale is not positive.
|
||||
fn effect_region(d: &Document, whole: &Node, scale: f64) -> Option<(Rect, f64)> {
|
||||
// What it paints (its members' effects included), and how far its fills' and strokes' raster
|
||||
// effects reach beyond that.
|
||||
let b = vectorcraft_render::painted_bounds(out, whole)?;
|
||||
let look = out.raster_effects.clone();
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + look.add_around;
|
||||
let b = vectorcraft_render::painted_bounds(d, whole)?;
|
||||
let reach = whole.appearance.items.iter().map(|i| effects::outset(i.effects(), b)).fold(0.0, f64::max) + 2.0 + d.raster_effects.add_around;
|
||||
let b = b.inflate(reach, reach);
|
||||
// An area too large for f64 gives a zero scale and an image transform that is not finite.
|
||||
let area = b.width() * b.height();
|
||||
@@ -201,6 +196,19 @@ pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&N
|
||||
return None;
|
||||
}
|
||||
let region = Rect::new(b.x0, b.y0, b.x0 + (b.width() * scale).ceil().max(1.0) / scale, b.y0 + (b.height() * scale).ceil().max(1.0) / scale);
|
||||
Some((region, scale))
|
||||
}
|
||||
|
||||
/// An embedded image (a new node of `out`, its pixels in `out.images`) of `whole` rendered alone
|
||||
/// with `out`'s resources at `scale` over all it paints (the reach of its own, its members' and its
|
||||
/// fills' and strokes' raster effects included). With `knockout`, the coverage of that art is knocked out
|
||||
/// of the image, which then only holds what the effects add around it (a shadow to go under the
|
||||
/// vector object). The document's raster effects settings add room around it and finish its pixels.
|
||||
/// `None` when it paints nothing, when the area it covers overflows `f64` or the scale is not
|
||||
/// positive, or when its PNG can't be encoded.
|
||||
pub(crate) fn effect_image(out: &mut Document, whole: &Node, knockout: Option<&Node>, scale: f64) -> Option<Node> {
|
||||
let (region, scale) = effect_region(out, whole, scale)?;
|
||||
let look = out.raster_effects.clone();
|
||||
// Anti-alias off: hard edges (the effects themselves stay smooth).
|
||||
let anti_alias = if look.anti_alias { AntiAlias::Art } else { AntiAlias::None };
|
||||
let mut img = render(out, vec![whole.clone()], region, scale, anti_alias);
|
||||
@@ -311,6 +319,19 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
if !below && let Some(image) = rasterize_effect_image(d, n) {
|
||||
return Some(image);
|
||||
}
|
||||
let whole = effect_art(n, below, members);
|
||||
let bare = below.then(|| {
|
||||
let mut b = whole.clone();
|
||||
strip_raster(&mut b, false);
|
||||
b
|
||||
});
|
||||
effect_image(d, &whole, bare.as_ref(), image_scale(d, n))
|
||||
}
|
||||
|
||||
/// The art [`raster_image`] renders the raster effects of `n` from with `below` and `members`:
|
||||
/// `n` without its transparency, a group's or layer's members without their raster effects when
|
||||
/// both are set.
|
||||
fn effect_art(n: &Node, below: bool, members: bool) -> Node {
|
||||
let mut whole = n.clone();
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
@@ -319,17 +340,39 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
strip_raster(Arc::make_mut(c), true);
|
||||
}
|
||||
}
|
||||
let bare = below.then(|| {
|
||||
let mut b = whole.clone();
|
||||
strip_raster(&mut b, false);
|
||||
b
|
||||
});
|
||||
// A Rasterize effect at a finer resolution than the document's is rendered at its own.
|
||||
let scale = raster_fx(n)
|
||||
.iter()
|
||||
.filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None })
|
||||
.fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0));
|
||||
effect_image(d, &whole, bare.as_ref(), scale)
|
||||
whole
|
||||
}
|
||||
|
||||
/// Pixels per point of the image of the raster effects of `n`: the document's raster effects
|
||||
/// resolution, or a Rasterize effect's finer one, which is rendered at its own.
|
||||
fn image_scale(d: &Document, n: &Node) -> f64 {
|
||||
raster_fx(n).iter().filter_map(|fx| if let RasterFx::Rasterize(r) = fx { r.ppi } else { None }).fold(effects_scale(d), |s, ppi| s.max(ppi / 72.0))
|
||||
}
|
||||
|
||||
/// The pixels of the image [`raster_image`] makes of the raster effects of `n` in `d` with `below`
|
||||
/// and `members`, as [`effect_image`] sizes it, or at the resolution and with the room around the
|
||||
/// art of the object's own Rasterize effect when that is its only one ([`rasterize_effect_image`]);
|
||||
/// 0 when it paints nothing.
|
||||
pub(crate) fn raster_pixels(d: &Document, n: &Node, below: bool, members: bool) -> u64 {
|
||||
if !below && let Some((art, r, _)) = rasterize_effect_art(d, n) {
|
||||
// Measured as Object › Rasterize measures it.
|
||||
let scale = r.ppi.unwrap_or(d.raster_effects_ppi) / 72.0;
|
||||
let side = f64::from(vectorcraft_render::MAX_RASTER_SIDE);
|
||||
let size = vectorcraft_render::drawn_bounds(d, &art).map(|b| {
|
||||
let b = b.inflate(r.add_around, r.add_around);
|
||||
((b.width() * scale).ceil().max(1.0), (b.height() * scale).ceil().max(1.0))
|
||||
});
|
||||
// Past Object › Rasterize's limits that image is not made, and the effect's image is.
|
||||
if let Some((w, h)) = size
|
||||
&& w * h <= super::menucmds::MAX_PIXELS
|
||||
&& w <= side
|
||||
&& h <= side
|
||||
{
|
||||
return (w * h) as u64;
|
||||
}
|
||||
}
|
||||
effect_region(d, &effect_art(n, below, members), image_scale(d, n))
|
||||
.map_or(0, |(r, scale)| ((r.width() * scale).round() * (r.height() * scale).round()) as u64)
|
||||
}
|
||||
|
||||
/// The image Object › Rasterize makes of `n` with the options of `n`'s Effect › Rasterize, when
|
||||
@@ -339,15 +382,7 @@ pub(crate) fn raster_image(d: &mut Document, n: &Node, below: bool, members: boo
|
||||
/// the image is made of the art before them and moved by them, as the canvas draws it. `None`
|
||||
/// otherwise, when those Transform effects flatten the image, or when the image can't be made.
|
||||
fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let n = staged.as_ref().map_or(n, |(stage, _)| stage);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let (whole, r, map) = rasterize_effect_art(d, n)?;
|
||||
let p = json!({
|
||||
"ppi": r.ppi.unwrap_or(d.raster_effects_ppi),
|
||||
"colorModel": r.color_model.id(),
|
||||
@@ -356,20 +391,39 @@ fn rasterize_effect_image(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
"clippingMask": r.clipping_mask,
|
||||
"addAround": r.add_around,
|
||||
});
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
// shortcut: expanded Rasterize effects stay RGB, as the object keeps its own opacity mask and the
|
||||
// image's transparency would need one too; upgrade when CMYK images carry alpha.
|
||||
let image = super::menucmds::rasterize_art(d, vec![whole], &p, "object.rasterize", false).ok()?;
|
||||
let mut image = image.into_node(d);
|
||||
if let Some((_, map)) = staged {
|
||||
if let Some(map) = map {
|
||||
image.transform(map, false);
|
||||
}
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// What [`rasterize_effect_image`] makes its image of: `n`, or the art before the Transform effects
|
||||
/// that move the image, without the Rasterize effect and without its transparency; that effect's
|
||||
/// options; and the map those Transform effects move the image by. `None` when `n` has another
|
||||
/// raster effect, when the Rasterize effect is not its own, or when those Transform effects
|
||||
/// flatten the image.
|
||||
fn rasterize_effect_art(d: &Document, n: &Node) -> Option<(Node, effects::Rasterize, Option<Affine>)> {
|
||||
let [RasterFx::Rasterize(r)] = raster_fx(n)[..] else { return None };
|
||||
let staged = vectorcraft_render::rasterize_stage(d, n);
|
||||
if let Some((_, map)) = &staged
|
||||
&& !(map.determinant().is_finite() && map.determinant().abs() > 1e-12)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (stage, map) = staged.map_or((None, None), |(stage, map)| (Some(stage), Some(map)));
|
||||
let n = stage.as_ref().unwrap_or(n);
|
||||
let at = n.appearance.effects.iter().position(|e| e.visible && e.id == effects::RASTERIZE)?;
|
||||
let mut whole = n.clone();
|
||||
whole.appearance.effects.remove(at);
|
||||
(whole.opacity, whole.blend) = (1.0, Default::default());
|
||||
whole.extras_mut().mask = None;
|
||||
Some((whole, r, map))
|
||||
}
|
||||
|
||||
/// `v` (an object without its raster effects) replaced by `image` of the object with them: the
|
||||
/// image takes its place with its id, name and transparency (a layer keeps the image as its only
|
||||
/// member).
|
||||
|
||||
@@ -7,17 +7,20 @@
|
||||
//! `removeWord`, `changeWord`), which every document's check takes as right; Ignore All
|
||||
//! (`text.spelling.ignoreAll`) skips a word in the active document only.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use craft_proof::{IssueKind, Options, ProofLang};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_text::edit;
|
||||
|
||||
use super::menucmds::whole_or;
|
||||
use super::textedit::text_mut;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::typemenu::{all_texts, text_ids};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param};
|
||||
|
||||
/// Most unknown words one check lists; past it the result says `more`.
|
||||
pub const MAX_WORDS: usize = 10_000;
|
||||
@@ -36,10 +39,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Check Spelling",
|
||||
[],
|
||||
None,
|
||||
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than 10000 words, the rest left out)}. text.editRange {id, start, end, insert} changes one",
|
||||
"{ids?: [id…] (type objects, or groups holding them; default: every visible, unlocked type object), from?: {id, byte} (go on from there: the words of that type object that start at byte or later, then the objects after it; id must be one of the objects checked), max?: 1..10000 (default 10000)} the words the dictionaries don't know, each in its run's language (English when it has none; none in a language without a dictionary), each paragraph on its own, in paint order (given ids too) → {words: [{id, start: byte, end: byte, word, lang}…], more: bool (more than max words, the rest left out: check again with from {id, byte: end} of the last word)}. text.editRange {id, start, end, insert} changes one",
|
||||
has_doc,
|
||||
check
|
||||
),
|
||||
cmd!(
|
||||
"text.spelling.change",
|
||||
"Change All",
|
||||
[],
|
||||
None,
|
||||
"{to: string, words: [{id, start: byte, end: byte}…] (words of type objects, as text.spelling.check lists them; none overlapping)} replaces each word with to, all in one undo step, each object laid out once (Check Spelling's Change All); a word that already reads as to is left alone, and with no other word there is no edit and no undo step; an error, with nothing changed, when a word's bytes are not in its object's text → {changed: count of words replaced}",
|
||||
has_doc,
|
||||
change_words
|
||||
),
|
||||
cmd!(
|
||||
query "text.spelling.suggest",
|
||||
"Spelling Suggestions",
|
||||
@@ -107,22 +119,42 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// `text.spelling.check`: the unknown words of the given type objects (or every visible, unlocked
|
||||
/// one), in paint order, each paragraph checked on its own, at most [`MAX_WORDS`] of them.
|
||||
/// one), in paint order, each paragraph checked on its own, at most `max` of them, starting at
|
||||
/// `from` when it is given.
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.check";
|
||||
// Given `ids` are checked like Find and Replace's, so a malformed one is an error rather than
|
||||
// a check of the whole document.
|
||||
let ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
let mut ids = match p.get("ids").filter(|v| !v.is_null()) {
|
||||
Some(_) => in_paint_order(&s.doc()?.doc, text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?)),
|
||||
None => all_texts(&s.doc()?.doc),
|
||||
};
|
||||
let max = whole_or(p, "max", MAX_WORDS as u64, C)?;
|
||||
let max = usize::try_from(max).ok().filter(|m| (1..=MAX_WORDS).contains(m)).ok_or_else(|| bad(C, format!("`max` must be 1 to {MAX_WORDS}")))?;
|
||||
let st = s.doc()?;
|
||||
// Where the last check stopped: the objects before it are skipped, and the bytes of its object
|
||||
// before `byte`.
|
||||
let mut from_byte = 0;
|
||||
if let Some(from) = p.get("from").filter(|v| !v.is_null()) {
|
||||
let (id, byte) = from_param(from, C)?;
|
||||
let Some(pos) = ids.iter().position(|i| i.0 == id) else {
|
||||
return Err(bad(C, format!("`from.id` {id} is not one of the type objects checked")));
|
||||
};
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(NodeId(id)).map(|n| &n.kind) else {
|
||||
return Err(bad(C, format!("`from.id` {id} is not a type object")));
|
||||
};
|
||||
let len = t.plain_text().len();
|
||||
from_byte = usize::try_from(byte).ok().filter(|b| *b <= len).ok_or_else(|| bad(C, format!("`from.byte` is past the end of {id}'s text")))?;
|
||||
ids.drain(..pos);
|
||||
}
|
||||
let mut words = vec![];
|
||||
let mut more = false;
|
||||
for id in ids {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(id).map(|n| &n.kind) else { continue };
|
||||
let text = t.plain_text();
|
||||
let (found, cut) = misspellings(t, &st.spelling_ignored, MAX_WORDS - words.len());
|
||||
// Only the first object listed starts part way.
|
||||
let from = std::mem::take(&mut from_byte);
|
||||
let (found, cut) = misspellings_from(t, &st.spelling_ignored, from, max - words.len());
|
||||
for m in found {
|
||||
let Some(word) = text.get(m.range.clone()) else { continue };
|
||||
words.push(json!({ "id": id.0, "start": m.range.start, "end": m.range.end, "word": word, "lang": m.lang.tag() }));
|
||||
@@ -135,6 +167,87 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "words": words, "more": more }))
|
||||
}
|
||||
|
||||
/// `text.spelling.check`'s `from`: `{id, byte}`, both whole numbers.
|
||||
fn from_param(from: &Value, command: &str) -> Result<(u64, u64)> {
|
||||
let Some(o) = from.as_object() else { return Err(bad(command, "`from` must be {id, byte}")) };
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "byte")) {
|
||||
return Err(bad(command, format!("`from` takes id and byte, not `{k}`")));
|
||||
}
|
||||
let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.id` must be a type object's id"))?;
|
||||
let byte = o.get("byte").and_then(Value::as_u64).ok_or_else(|| bad(command, "`from.byte` must be a whole number"))?;
|
||||
Ok((id, byte))
|
||||
}
|
||||
|
||||
/// `text.spelling.change`: Change All, every listed word replaced in one edit. Each object's words
|
||||
/// are changed back to front, so the bytes of the ones before stay true, and the object is laid out
|
||||
/// once at the end rather than once for each word.
|
||||
fn change_words(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.spelling.change";
|
||||
let to = str_param(p, "to").ok_or_else(|| bad(C, "missing `to`"))?.to_string();
|
||||
let list = p.get("words").and_then(Value::as_array).ok_or_else(|| bad(C, "`words` must be a list of {id, start, end}"))?;
|
||||
let mut by_id: BTreeMap<NodeId, Vec<(usize, usize)>> = BTreeMap::new();
|
||||
for w in list {
|
||||
let (id, start, end) = word_param_range(w, C)?;
|
||||
by_id.entry(NodeId(id)).or_default().push((start, end));
|
||||
}
|
||||
// Every word checked against its object before anything changes.
|
||||
let st = s.doc()?;
|
||||
for (id, ranges) in &mut by_id {
|
||||
let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else {
|
||||
return Err(bad(C, format!("{} is not a type object", id.0)));
|
||||
};
|
||||
let text = t.plain_text();
|
||||
ranges.sort_unstable();
|
||||
let mut last_end = 0;
|
||||
for &(a, b) in ranges.iter() {
|
||||
if a >= b || text.get(a..b).is_none() {
|
||||
return Err(bad(C, format!("{a}..{b} is not a word of {}'s text", id.0)));
|
||||
}
|
||||
if a < last_end {
|
||||
return Err(bad(C, format!("words of {} overlap at byte {a}", id.0)));
|
||||
}
|
||||
last_end = b;
|
||||
}
|
||||
// A word that already reads as `to` is left alone, so a list of only those makes no edit.
|
||||
ranges.retain(|&(a, b)| text.get(a..b) != Some(to.as_str()));
|
||||
}
|
||||
by_id.retain(|_, ranges| !ranges.is_empty());
|
||||
let changed: usize = by_id.values().map(Vec::len).sum();
|
||||
if changed == 0 {
|
||||
return Ok(json!({ "changed": 0 }));
|
||||
}
|
||||
s.edit("Change All", |d, _| {
|
||||
for (id, ranges) in &by_id {
|
||||
let t = text_mut(d, *id).ok_or(EngineError::NoNode(*id))?;
|
||||
for &(a, b) in ranges.iter().rev() {
|
||||
// Paragraph styles and ruby follow each edit, as in `text.editRange`.
|
||||
t.splice_paras(a, b, &to);
|
||||
edit::replace_range(&mut t.runs, a, b, &to);
|
||||
t.ruby_after_replace(a, b, to.len());
|
||||
}
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "changed": changed }))
|
||||
}
|
||||
|
||||
/// One of `text.spelling.change`'s `words`: `{id, start, end}`, all whole numbers.
|
||||
fn word_param_range(w: &Value, command: &str) -> Result<(u64, usize, usize)> {
|
||||
let Some(o) = w.as_object() else { return Err(bad(command, "each of `words` must be {id, start, end}")) };
|
||||
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "id" | "start" | "end")) {
|
||||
return Err(bad(command, format!("each of `words` takes id, start and end, not `{k}`")));
|
||||
}
|
||||
let id = o.get("id").and_then(Value::as_u64).ok_or_else(|| bad(command, "a word's `id` must be a type object's id"))?;
|
||||
let byte = |k: &str| {
|
||||
o.get(k)
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|b| usize::try_from(b).ok())
|
||||
.ok_or_else(|| bad(command, format!("a word's `{k}` must be a whole number")))
|
||||
};
|
||||
Ok((id, byte("start")?, byte("end")?))
|
||||
}
|
||||
|
||||
/// One word of a type object its dictionaries don't know ([`misspellings`]).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Misspelling {
|
||||
@@ -149,6 +262,13 @@ pub struct Misspelling {
|
||||
/// All words). At most `max` of them; the flag says the list was cut short there. What
|
||||
/// `text.spelling.check` lists for one object, and what Auto Spell Check underlines.
|
||||
pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (Vec<Misspelling>, bool) {
|
||||
misspellings_from(t, ignored, 0, max)
|
||||
}
|
||||
|
||||
/// [`misspellings`] of the words that start at byte `from` or later. The paragraphs that end at
|
||||
/// or before `from` are not checked; the paragraph that holds `from` is checked whole, since
|
||||
/// craft-proof reads a paragraph's language from all of it.
|
||||
pub fn misspellings_from(t: &TextObject, ignored: &BTreeSet<String>, from: usize, max: usize) -> (Vec<Misspelling>, bool) {
|
||||
let text = t.plain_text();
|
||||
// Each run in its own language, at its bytes of the plain text.
|
||||
let mut spans: Vec<(Range<usize>, ProofLang)> = Vec::with_capacity(t.runs.len());
|
||||
@@ -166,6 +286,11 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (
|
||||
let mut para_start = 0;
|
||||
for para in text.split('\n') {
|
||||
let para_end = para_start + para.len();
|
||||
// No word of a paragraph that ends at `from` starts there or later.
|
||||
if para_end <= from {
|
||||
para_start = para_end + 1;
|
||||
continue;
|
||||
}
|
||||
let para_spans: Vec<(Range<usize>, ProofLang)> = spans
|
||||
.iter()
|
||||
.filter_map(|(r, lang)| {
|
||||
@@ -178,6 +303,9 @@ pub fn misspellings(t: &TextObject, ignored: &BTreeSet<String>, max: usize) -> (
|
||||
continue;
|
||||
}
|
||||
let (start, end) = (para_start + issue.start, para_start + issue.end);
|
||||
if start < from {
|
||||
continue;
|
||||
}
|
||||
let Some(word) = text.get(start..end) else { continue };
|
||||
if craft_proof::custom_word(word).is_some_and(|w| ignored.contains(&w)) {
|
||||
continue;
|
||||
|
||||
@@ -495,7 +495,8 @@ pub(crate) fn sync(before: &Document, d: &mut Document) -> Result<()> {
|
||||
let (old, old_group) = match before.symbol_edit.as_ref().filter(|b| b.layer == se.layer) {
|
||||
None => return Ok(()),
|
||||
Some(b) => match art_of(before) {
|
||||
Some(old) if same(&old) => return Ok(()),
|
||||
// Turning on Align to Pixel Grid writes the art back too, so the layer shows it snapped.
|
||||
Some(old) if same(&old) && (before.symbol_pixel_aligned(&se.symbol) || !d.symbol_pixel_aligned(&se.symbol)) => return Ok(()),
|
||||
old => (old.unwrap_or_default(), b.group),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -455,10 +455,11 @@ fn a_symbol_instance_fill_shadow_shadows_its_filled_art() {
|
||||
|
||||
assert!(expandable(&s), "the fill's shadow can be expanded");
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let ch = node(&s, id).children().cloned().expect("the instance becomes a group");
|
||||
let n = node(&s, id);
|
||||
let ch = n.children().cloned().expect("the instance becomes a group");
|
||||
assert!(matches!(ch[0].kind, NodeKind::Image(_)), "the shadow is an image under the art: {}", ch[0].kind_label());
|
||||
assert!(matches!(ch[1].kind, NodeKind::SymbolInstance { .. }), "the art stays an instance: {}", ch[1].kind_label());
|
||||
no_effects_left(&ch[1]);
|
||||
n.walk(&mut |part| assert!(!matches!(part.kind, NodeKind::SymbolInstance { .. }), "the art is no longer an instance"));
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
@@ -508,6 +509,311 @@ fn a_nested_symbol_instance_takes_the_outer_fill_shadow() {
|
||||
assert!(dark(render(&s).pixel(165, 100)), "the inner art casts the shadow: {:?}", render(&s).pixel(165, 100));
|
||||
}
|
||||
|
||||
/// An instance of an Inner symbol of the square, with a new fill without paint on top that `inner`
|
||||
/// gives effects, placed in the art of an Outer symbol; the Outer instance is selected, with a new
|
||||
/// fill without paint on top. Returns the Outer instance and its new row's index.
|
||||
fn nested_with_row(s: &mut Session, inner: impl FnOnce(&mut Session, NodeId, usize)) -> (NodeId, usize) {
|
||||
let (inner_id, inner_row) = instance_with_row(s, "Inner", true);
|
||||
inner(s, inner_id, inner_row);
|
||||
let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap());
|
||||
run(s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(s, id).appearance.items.len() - 1;
|
||||
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
|
||||
(id, row)
|
||||
}
|
||||
|
||||
/// The symbol instances and the images in `n`.
|
||||
fn instances_and_images(n: &Node) -> (usize, usize) {
|
||||
let mut found = (0, 0);
|
||||
n.walk(&mut |part| match part.kind {
|
||||
NodeKind::SymbolInstance { .. } => found.0 += 1,
|
||||
NodeKind::Image(_) => found.1 += 1,
|
||||
_ => {}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Replace the art of every symbol with an empty group.
|
||||
fn empty_symbols(s: &mut Session) {
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
for (i, sym) in d.symbols.iter_mut().enumerate() {
|
||||
sym.art = std::sync::Arc::new(Node::group(NodeId(91_000 + i as u64), vec![]));
|
||||
}
|
||||
}
|
||||
|
||||
/// When the outer instance's art expands, an instance in it whose own fill has a shadow becomes art
|
||||
/// too, the shadow an image under it: no instance or effect is left, the look stays, and the result
|
||||
/// no longer follows either symbol.
|
||||
#[test]
|
||||
fn a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(175, 100)), "the inner art casts its shadow: {:?}", before.pixel(175, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert!(images >= 1, "the inner shadow is an image");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
empty_symbols(&mut s);
|
||||
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
|
||||
}
|
||||
|
||||
/// A shadow on the outer instance's fill alone: the instance becomes its art over the shadow's
|
||||
/// image, and an instance in that art with a shadow of its own becomes art and an image in turn, in
|
||||
/// one undo step.
|
||||
#[test]
|
||||
fn an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
shadow_row(&mut s, id, row);
|
||||
let before = render(&s);
|
||||
assert!(expandable(&s));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert!(images >= 2, "the outer and inner shadows are images: {images}");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "one undo gives the instance back");
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
empty_symbols(&mut s);
|
||||
assert_eq!(differing(&after, &render(&s), 0), 0, "the expanded art no longer follows the symbols");
|
||||
}
|
||||
|
||||
/// A blur on the nested instance's fill: the nested instance becomes the image.
|
||||
#[test]
|
||||
fn a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands() {
|
||||
let mut s = session();
|
||||
let blur = |s: &mut Session, id: NodeId, row: usize| {
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, blur);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
let (instances, images) = instances_and_images(&n);
|
||||
assert_eq!(instances, 0, "the outer and inner instances become art");
|
||||
assert_eq!(images, 1, "the blurred inner art is one image");
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A blue rectangle from x 140 to 200, drawn first, so a shadow right of the square falls on it.
|
||||
fn blue_backdrop(s: &mut Session) {
|
||||
run(s, "shape.rectangle", json!({"x": 140, "y": 0, "width": 60, "height": 200}));
|
||||
run(s, "paint.setFill", json!({"color": "#0000ff"}));
|
||||
}
|
||||
|
||||
/// A red Drop Shadow 20 pt to the right on row `row` of instance `id`, with no blur, painting with `mode`.
|
||||
fn red_shadow_row(s: &mut Session, id: NodeId, row: usize, mode: &str) {
|
||||
let params = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": mode, "color": "#ff0000"});
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "stylize.dropShadow", "params": params}));
|
||||
}
|
||||
|
||||
/// The blend modes of the images in `n`, in the order the walk visits them.
|
||||
fn image_modes(n: &Node) -> Vec<BlendMode> {
|
||||
let mut modes = vec![];
|
||||
n.walk(&mut |part| {
|
||||
if matches!(part.kind, NodeKind::Image(_)) {
|
||||
modes.push(part.blend);
|
||||
}
|
||||
});
|
||||
modes
|
||||
}
|
||||
|
||||
/// A Multiply shadow on the nested instance's fill: its image multiplies with the blue art below
|
||||
/// as the shadow did, rather than painting red over it.
|
||||
#[test]
|
||||
fn a_nested_instance_multiply_shadow_image_keeps_its_mode() {
|
||||
let mut s = session();
|
||||
blue_backdrop(&mut s);
|
||||
let (id, row) = nested_with_row(&mut s, |s, id, row| red_shadow_row(s, id, row, "multiply"));
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(170, 100)), "red multiplied with blue is dark: {:?}", before.pixel(170, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n).0, 0, "the outer and inner instances become art");
|
||||
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
|
||||
no_effects_left(&n);
|
||||
let after = render(&s);
|
||||
assert!(dark(after.pixel(170, 100)), "the image multiplies with the blue art: {:?}", after.pixel(170, 100));
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A Multiply shadow on an instance's own fill: the image under its art paints with Multiply.
|
||||
#[test]
|
||||
fn an_instance_multiply_shadow_image_keeps_its_mode() {
|
||||
let mut s = session();
|
||||
blue_backdrop(&mut s);
|
||||
let (id, row) = instance_with_row(&mut s, "Square", true);
|
||||
red_shadow_row(&mut s, id, row, "multiply");
|
||||
let before = render(&s);
|
||||
assert!(dark(before.pixel(160, 100)), "red multiplied with blue is dark: {:?}", before.pixel(160, 100));
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(image_modes(&n), [BlendMode::Multiply]);
|
||||
let after = render(&s);
|
||||
assert!(dark(after.pixel(160, 100)), "the image multiplies with the blue art: {:?}", after.pixel(160, 100));
|
||||
assert!(differing(&before, &after, 24) < 400, "expanding changed {} pixels", differing(&before, &after, 24));
|
||||
}
|
||||
|
||||
/// A shadow on a hidden fill of the nested instance draws nothing, and expanding makes no image of it.
|
||||
#[test]
|
||||
fn a_hidden_nested_instance_fill_shadow_makes_no_image() {
|
||||
let mut s = session();
|
||||
let hidden = |s: &mut Session, id: NodeId, row: usize| {
|
||||
shadow_row(s, id, row);
|
||||
run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "visible": false}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, hidden);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert!(!dark(render(&s).pixel(175, 100)), "the hidden fill casts no shadow");
|
||||
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (0, 0), "the instances become art without an image");
|
||||
no_effects_left(&n);
|
||||
}
|
||||
|
||||
/// A nested instance with a shadow whose symbol is missing stays as it is while the outer art
|
||||
/// expands around it.
|
||||
#[test]
|
||||
fn a_nested_instance_of_a_missing_symbol_stays_an_instance() {
|
||||
let mut s = session();
|
||||
let (id, row) = nested_with_row(&mut s, shadow_row);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.symbols.retain(|sym| sym.name != "Inner");
|
||||
}
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (1, 0), "the inner instance stays, without an image");
|
||||
}
|
||||
|
||||
/// 1,100 blurred instances in the outer art, far fewer objects than the symbol limit: one Expand
|
||||
/// Appearance makes 1,024 images of them, and the other 76 stay instances with their blur, which
|
||||
/// the result reports.
|
||||
#[test]
|
||||
fn nested_instance_raster_effects_stop_at_the_image_limit() {
|
||||
let mut s = session();
|
||||
// Images of a pixel or two each.
|
||||
run(&mut s, "document.rasterEffectsSettings", json!({"resolution": 1}));
|
||||
let blur = |s: &mut Session, id: NodeId, row: usize| {
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": row, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
};
|
||||
let (id, row) = nested_with_row(&mut s, blur);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
{
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let outer = d.symbols.iter().position(|sym| sym.name == "Outer").unwrap();
|
||||
let inner = (*d.symbols[outer].art).clone();
|
||||
assert!(matches!(inner.kind, NodeKind::SymbolInstance { .. }), "the outer art is the inner instance");
|
||||
let copies = (0..1_100)
|
||||
.map(|_| {
|
||||
let mut copy = inner.clone();
|
||||
copy.id = d.alloc_id();
|
||||
std::sync::Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
d.symbols[outer].art = std::sync::Arc::new(Node::group(d.alloc_id(), copies));
|
||||
}
|
||||
|
||||
let r = run(&mut s, "effect.expandAppearance", json!({}));
|
||||
assert_eq!(r["rasterLeft"], 76, "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("1,024 images")), "{r}");
|
||||
let n = node(&s, id);
|
||||
assert_eq!(instances_and_images(&n), (76, 1_024), "1,024 instances become images and the rest stay");
|
||||
n.walk(&mut |part| {
|
||||
if matches!(part.kind, NodeKind::SymbolInstance { .. }) {
|
||||
assert!(part.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.id == "blur.gaussian")), "a left instance keeps its blur");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Gives `id` a color adjustment and a blur, puts it in a group above 1,024 blurred squares, which
|
||||
/// take every image one Expand Appearance makes, and expands the group. Returns `id` as it was
|
||||
/// before expanding.
|
||||
fn adjusted_and_left_by_the_image_limit(s: &mut Session, id: NodeId) -> Node {
|
||||
// Images of a pixel or two each.
|
||||
run(s, "document.rasterEffectsSettings", json!({"resolution": 1}));
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "adjust.hueSaturation", "params": {"hue": 120}}));
|
||||
run(s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
let sq = NodeId(run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap());
|
||||
run(s, "effect.apply", json!({"ids": [sq.0], "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}));
|
||||
let before = node(s, id);
|
||||
let group = {
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let blurred = d.node(sq).unwrap().clone();
|
||||
d.remove(sq).unwrap();
|
||||
let mut members: Vec<_> = (0..1_024)
|
||||
.map(|_| {
|
||||
let mut copy = blurred.clone();
|
||||
copy.id = d.alloc_id();
|
||||
std::sync::Arc::new(copy)
|
||||
})
|
||||
.collect();
|
||||
members.push(std::sync::Arc::new(before.clone()));
|
||||
let group = d.alloc_id();
|
||||
*d.node_mut(id).unwrap() = Node::group(group, members);
|
||||
group
|
||||
};
|
||||
|
||||
let r = run(s, "effect.expandAppearance", json!({"ids": [group.0]}));
|
||||
assert_eq!(r["rasterLeft"], 1, "{r}");
|
||||
before
|
||||
}
|
||||
|
||||
/// A symbol instance with a color adjustment and a blur, left by the image limit, stays an instance
|
||||
/// of its symbol, with both effects.
|
||||
#[test]
|
||||
fn a_color_adjusted_instance_left_by_the_image_limit_stays_an_instance() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Adjusted Square"}))["id"].as_u64().unwrap());
|
||||
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
|
||||
assert!(matches!(before.kind, NodeKind::SymbolInstance { .. }));
|
||||
assert_eq!(node(&s, id), before, "the instance stays as it is, with its adjustment and blur");
|
||||
}
|
||||
|
||||
/// An embedded image with a color adjustment and a blur, left by the image limit, stays as it is,
|
||||
/// and the document keeps no recolored copy of its pixels.
|
||||
#[test]
|
||||
fn a_color_adjusted_image_left_by_the_image_limit_adds_no_pixels() {
|
||||
let mut s = session();
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255]))
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let images: Vec<String> = s.doc().unwrap().doc.images.keys().cloned().collect();
|
||||
let before = adjusted_and_left_by_the_image_limit(&mut s, id);
|
||||
assert!(matches!(before.kind, NodeKind::Image(_)));
|
||||
assert_eq!(node(&s, id), before, "the image stays as it is, with its adjustment and blur");
|
||||
// Besides the squares' images, the document holds the image's pixels alone.
|
||||
let after: Vec<String> = s.doc().unwrap().doc.images.keys().filter(|k| !k.starts_with("raster-effect-")).cloned().collect();
|
||||
assert_eq!(after, images, "no recolored copy stays in the document");
|
||||
}
|
||||
|
||||
/// Export draws a symbol instance's fill shadow on the filled shapes of its art: baking leaves the
|
||||
/// shadow on the art's fill, not its stroke, and PDF export makes an image of it.
|
||||
#[test]
|
||||
|
||||
@@ -34,6 +34,59 @@ fn the_font_list_names_every_available_family_with_its_styles() {
|
||||
assert!(s.execute("text.fontList", &json!({"family": "No Such Font"})).is_err());
|
||||
}
|
||||
|
||||
/// Show Similar Fonts (`text.similarFonts`): every listed family, the asked one first, in the
|
||||
/// order the font menus show; bad params are refused.
|
||||
#[test]
|
||||
fn similar_fonts_lists_every_family_by_likeness() {
|
||||
let mut s = Session::new();
|
||||
let db = FontDb::global();
|
||||
let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap();
|
||||
assert_eq!(r["family"], "Source Sans 3");
|
||||
let order = names(&r["families"]);
|
||||
assert_eq!(order.first().map(String::as_str), Some("Source Sans 3"));
|
||||
let mut sorted = order.clone();
|
||||
sorted.sort();
|
||||
let mut listed = db.menu_family_list().to_vec();
|
||||
listed.sort();
|
||||
// Other tests running at the same time add and remove composite fonts; the installed families are compared.
|
||||
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
|
||||
assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once");
|
||||
// The two answers are compared whole when the available fonts did not change while both were
|
||||
// made (the same `FontDb::generation`), and by their installed families when they changed
|
||||
// during every try.
|
||||
let mut answers = (vec![], vec![], false);
|
||||
for _ in 0..20 {
|
||||
let generation = db.generation();
|
||||
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
|
||||
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
|
||||
let unchanged = db.generation() == generation;
|
||||
answers = (all, two, unchanged);
|
||||
if unchanged {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (all, two, unchanged) = answers;
|
||||
assert_eq!(two.len(), 2);
|
||||
if unchanged {
|
||||
assert_eq!(two, all[..2], "the first families, in order");
|
||||
} else {
|
||||
let (two, all) = (installed_only(&two), installed_only(&all));
|
||||
assert_eq!(two[..], all[..two.len()], "the first installed families, in order");
|
||||
}
|
||||
for (params, error) in [
|
||||
(json!({}), "`family` is required"),
|
||||
(json!({"family": " "}), "`family` is required"),
|
||||
(json!({"family": 3}), "`family` must be a string"),
|
||||
(json!({"family": "No Such Font"}), "font family `No Such Font` is not available"),
|
||||
(json!({"family": "Inter", "limit": 0}), "`limit` must be a whole number from 1 to 100000"),
|
||||
(json!({"family": "Inter", "limit": 2.5}), "`limit` must be a whole number from 1 to 100000"),
|
||||
(json!({"family": "Inter", "limit": "2"}), "`limit` must be a whole number from 1 to 100000"),
|
||||
] {
|
||||
let e = s.execute("text.similarFonts", ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains(error), "{params}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -2168,6 +2168,64 @@ fn confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read()
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller's SVG and SVGZ with Preserve Editing Capabilities carry a native document
|
||||
/// without the Export for Screens folder when it is outside the read roots, with the other export
|
||||
/// settings and the art; the open document keeps the folder. A folder inside the roots, and any
|
||||
/// folder without roots, stays in the attachment.
|
||||
#[test]
|
||||
fn confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = Folder::new("svg-export-folder-away");
|
||||
let home = Folder::new("svg-export-folder-home");
|
||||
let outside = away.0.to_string_lossy().into_owned();
|
||||
let inside = home.file("screens");
|
||||
let mut s = session();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
|
||||
let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap();
|
||||
let set_folder = |s: &mut Session, folder: &str| {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.export_settings = serde_json::from_value(json!({"folder": folder, "prefix": "web-"})).unwrap();
|
||||
};
|
||||
let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap();
|
||||
// The native document an SVG's text carries.
|
||||
let attached = |text: &str| {
|
||||
let data = vectorcraft_svg::editing_data(text).expect("editing data");
|
||||
vectorcraft_format::load(&vectorcraft_format::base64_decode(&data).unwrap()).unwrap()
|
||||
};
|
||||
let check = |d: &Document, folder: Option<&str>, what: &str| {
|
||||
assert_eq!(d.export_settings.get("folder").and_then(Value::as_str), folder, "{what}");
|
||||
assert_eq!(d.export_settings.get("prefix").and_then(Value::as_str), Some("web-"), "{what}");
|
||||
assert!(d.node(rect).is_some(), "{what}: no art");
|
||||
};
|
||||
// Every way an SVG is asked for with Preserve Editing, its text and its native document.
|
||||
let every = |s: &mut Session, confined: bool, folder: Option<&str>| {
|
||||
let run = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let r = if confined { confine(roots.as_ref(), || s.execute(cmd, &p)) } else { s.execute(cmd, &p) };
|
||||
r.unwrap()
|
||||
};
|
||||
for format in ["svg", "svgz"] {
|
||||
let r = run(s, "document.serialize", json!({"format": format, "preserveEditing": true}));
|
||||
check(&attached(&svg_text(&r)), folder, &format!("{format} serialize"));
|
||||
let r = run(s, "document.serialize", json!({"format": format, "svg": {"preserveEditing": true}}));
|
||||
check(&attached(&svg_text(&r)), folder, &format!("{format} options object"));
|
||||
let path = home.file(&format!("export.{format}"));
|
||||
run(s, "document.export", json!({"format": format, "path": path, "preserveEditing": true}));
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
check(&attached(&vectorcraft_svg::text_of(&bytes).unwrap()), folder, &format!("{format} export"));
|
||||
}
|
||||
};
|
||||
set_folder(&mut s, &outside);
|
||||
every(&mut s, true, None);
|
||||
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder").and_then(Value::as_str), Some(outside.as_str()));
|
||||
every(&mut s, false, Some(&outside));
|
||||
// Without Preserve Editing the SVG carries no native document.
|
||||
let r = confine(roots.as_ref(), || s.execute("document.serialize", &json!({"format": "svg"}))).unwrap();
|
||||
assert!(vectorcraft_svg::editing_data(&svg_text(&r)).is_none(), "{r}");
|
||||
set_folder(&mut s, &inside);
|
||||
every(&mut s, true, Some(&inside));
|
||||
}
|
||||
|
||||
/// A confined caller's SVG of a placed document whose art links an image: the file draws that art
|
||||
/// and names the image's file, so a file outside the read roots refuses it and one inside them is
|
||||
/// written. Any output that names no file is written.
|
||||
|
||||
@@ -1588,6 +1588,235 @@ fn crop_image_to_a_rect_between_pixels_keeps_the_rect() {
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// Crop Image's `ppi` resamples the cut pixels to that resolution; the image keeps the box's size.
|
||||
#[test]
|
||||
fn crop_image_resamples_the_cut_to_the_resolution_asked_for() {
|
||||
let (mut s, img, px) = busy_image_at_two_points_a_pixel();
|
||||
// The image is 36 ppi (2 pt a pixel); 18 ppi halves the cut's 30 × 20 pixels.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 20.0) && close(b.y0, 10.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
let cut = image::imageops::crop_imm(&px, 10, 5, 30, 20).to_image();
|
||||
// Resampled in 16 bits a channel: within a level of the 8-bit resampling.
|
||||
let want = image::imageops::resize(&cut, 15, 10, image::imageops::FilterType::Lanczos3);
|
||||
assert_eq!(out.dimensions(), want.dimensions());
|
||||
assert!(out.as_raw().iter().zip(want.as_raw()).all(|(a, b)| a.abs_diff(*b) <= 1));
|
||||
}
|
||||
|
||||
/// Resampling weights colors by their alpha: the color hidden in fully transparent pixels does not
|
||||
/// tint the partly transparent edge of what is opaque.
|
||||
#[test]
|
||||
fn crop_image_resampling_keeps_hidden_colors_out_of_the_edges() {
|
||||
// Opaque white on the left half, fully transparent red on the right.
|
||||
let px = image::RgbaImage::from_fn(40, 20, |x, _| if x < 20 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([255, 0, 0, 0]) });
|
||||
let mut png = Vec::new();
|
||||
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let img = selected(&s)[0];
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
// 36 ppi to 15 ppi over pixels 5 to 35 across: the edge pixels mix white and clear.
|
||||
s.execute("object.cropImage", &json!({"rect": [10, 0, 60, 40], "ppi": 15})).unwrap();
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
assert!(out.pixels().any(|p| p[3] > 0 && p[3] < 255), "the edge is partly transparent");
|
||||
for p in out.pixels().filter(|p| p[3] > 0) {
|
||||
assert!(p[1] >= 250 && p[2] >= 250, "white, not tinted red: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Resampling keeps the color of pixels that are nearly transparent: a uniform color at the lowest
|
||||
/// alpha comes out as that color, not black.
|
||||
#[test]
|
||||
fn crop_image_resampling_keeps_the_color_of_nearly_transparent_pixels() {
|
||||
let px = image::RgbaImage::from_pixel(100, 80, image::Rgba([100, 50, 25, 1]));
|
||||
let mut png = Vec::new();
|
||||
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "faint.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let img = selected(&s)[0];
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 18})).unwrap();
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
for p in out.pixels() {
|
||||
let near = |a: u8, b: u8| a.abs_diff(b) <= 1;
|
||||
assert!(p[3] == 1 && near(p[0], 100) && near(p[1], 50) && near(p[2], 25), "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A box between pixels drawn at a resolution asked for holds what is inside the box only, at its
|
||||
/// place: the edge of the image's content lands where it was in the box.
|
||||
#[test]
|
||||
fn crop_image_between_pixels_keeps_the_content_at_its_place() {
|
||||
// White pixels 0 to 49 across, black from 50: at 2 pt a pixel, the edge is at x = 100 pt.
|
||||
let px = image::RgbaImage::from_fn(100, 80, |x, _| if x < 50 { image::Rgba([255, 255, 255, 255]) } else { image::Rgba([0, 0, 0, 255]) });
|
||||
let mut png = Vec::new();
|
||||
px.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "edge.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let img = selected(&s)[0];
|
||||
s.execute("object.scale", &json!({"sx": 200, "origin": [0, 0]})).unwrap();
|
||||
// 101 × 31 pt from (21, 11), off the pixel grid, at 35 ppi: 49 × 15 px. The edge is 79 pt into
|
||||
// the 101 pt box, so each row holds 49 × 79 / 101 pixels' worth of white.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 101, 31], "ppi": 35})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (49, 15), "{r}");
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
let out = image::load_from_memory(&s.doc().unwrap().doc.images[&im.key].bytes).unwrap().to_rgba8();
|
||||
let white: f64 = out.pixels().map(|p| f64::from(p[1]) / 255.0).sum::<f64>() / f64::from(out.height());
|
||||
let want = 49.0 * 79.0 / 101.0;
|
||||
assert!((white - want).abs() < 0.1, "{white} pixels of white a row, want {want}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 101.0) && close(b.height(), 31.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// A box between pixels is drawn at the resolution asked for, and lands on the box.
|
||||
#[test]
|
||||
fn crop_image_between_pixels_draws_at_the_resolution_asked_for() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 60, 40], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (15, 10), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 60.0) && close(b.height(), 40.0), "{b:?}");
|
||||
// 100 × 30 pt at 20 ppi is 27.8 × 8.3 px: the 28 × 8 px drawn are fitted to the box.
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [21, 11, 100, 30], "ppi": 20})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (28, 8), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 21.0) && close(b.y0, 11.0) && close(b.width(), 100.0) && close(b.height(), 30.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// A box over the whole image with a new resolution resamples it; with the image's own there is
|
||||
/// nothing to do.
|
||||
#[test]
|
||||
fn crop_image_over_the_whole_image_only_resamples_it() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let before = undo_len(&s);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 36}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
|
||||
assert_eq!(undo_len(&s), before);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 160], "ppi": 9})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (25, 20), "{r}");
|
||||
assert_eq!(undo_len(&s), before + 1, "one undo step");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 160.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// An image scaled more down than across is resampled on both sides at the resolution of its denser
|
||||
/// side, so its pixels come out square.
|
||||
#[test]
|
||||
fn crop_image_resamples_pixels_that_are_not_square() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
// 2 pt a pixel across (36 ppi) and 1 pt a pixel down (72 ppi), 200 × 80 pt.
|
||||
s.execute("object.scale", &json!({"sx": 100, "sy": 50, "origin": [0, 0]})).unwrap();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [0, 0, 200, 80], "ppi": 72})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (200, 80), "{r}");
|
||||
let b = bounds(&s, img);
|
||||
assert!(close(b.x0, 0.0) && close(b.y0, 0.0) && close(b.width(), 200.0) && close(b.height(), 80.0), "{b:?}");
|
||||
}
|
||||
|
||||
/// Crop Image refuses a resolution that isn't a positive number, one above the image's own, and one
|
||||
/// with trim; the image stays as it was.
|
||||
#[test]
|
||||
fn crop_image_refuses_a_resolution_it_cannot_give() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
let before = (undo_len(&s), node(&s, img));
|
||||
let refused = |s: &mut Session, p: Value, want: &str| {
|
||||
let r = s.execute("object.cropImage", &p);
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
|
||||
};
|
||||
for v in [json!(0), json!(-72), json!("high"), json!(true)] {
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), &format!("ppi must be a positive number, not {v}"));
|
||||
}
|
||||
for v in [0.5, 1e-310, 2401.0] {
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": v}), "ppi must be between 1 and 2400");
|
||||
}
|
||||
refused(&mut s, json!({"rect": [20, 10, 60, 40], "ppi": 72}), "ppi can't be more than 36 for this image");
|
||||
refused(&mut s, json!({"trim": true, "ppi": 18}), "trim keeps the image's pixels as they are: leave out ppi");
|
||||
assert_eq!((undo_len(&s), node(&s, img)), before);
|
||||
// A null ppi keeps the image's own, as a missing one does.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": null})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (30, 20), "{r}");
|
||||
}
|
||||
|
||||
/// A turned image keeps its own resolution as the limit (not the density across its bounding box),
|
||||
/// and its drawn cut is resampled to the box's size at the resolution asked for.
|
||||
#[test]
|
||||
fn crop_image_of_a_turned_image_resamples_its_drawing() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let b = bounds(&s, img);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 37}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 36 for this image"), "{r:?}");
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 18})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (18, 9), "{r}");
|
||||
let c = bounds(&s, img);
|
||||
assert!(close(c.x0, b.x0 + 40.0) && close(c.y0, b.y0 + 40.0) && close(c.width(), 72.0) && close(c.height(), 36.0), "{c:?}");
|
||||
}
|
||||
|
||||
/// A turned image cropped at its own resolution, asked for, gets that resolution, not the lower
|
||||
/// density of the box around it.
|
||||
#[test]
|
||||
fn crop_image_of_a_turned_image_at_its_own_resolution_keeps_it() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
|
||||
let b = bounds(&s, img);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0 + 40.0, b.y0 + 40.0, 72, 36], "ppi": 36})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (36, 18), "{r}");
|
||||
// Over the whole box around it, its own resolution draws it square to the page.
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.execute("object.rotate", &json!({"angle": 45})).unwrap();
|
||||
let b = bounds(&s, img);
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()], "ppi": 36})).unwrap();
|
||||
assert_eq!(r["width"].as_u64().unwrap(), (b.width() / 2.0).round() as u64, "{r}");
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [b.x0, b.y0, b.width(), b.height()]}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "nothing to crop"), "{r:?}");
|
||||
}
|
||||
|
||||
/// A linked image can be cropped to up to 300 ppi, even above its own; the crop embeds it.
|
||||
#[test]
|
||||
fn crop_image_takes_a_linked_image_up_to_300_ppi() {
|
||||
let (mut s, img, _) = busy_image_at_two_points_a_pixel();
|
||||
s.edit("Link", |d, _| {
|
||||
let NodeKind::Image(im) = &mut d.node_mut(img).unwrap().kind else { panic!("not an image") };
|
||||
im.link = Some(vectorcraft_doc::LinkInfo::new("art.png"));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 301}));
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "ppi can't be more than 300 for this image"), "{r:?}");
|
||||
// 72 ppi: a pixel a point.
|
||||
let r = s.execute("object.cropImage", &json!({"rect": [20, 10, 60, 40], "ppi": 72})).unwrap();
|
||||
assert_eq!((r["width"].as_u64().unwrap(), r["height"].as_u64().unwrap()), (60, 40), "{r}");
|
||||
let NodeKind::Image(im) = &node(&s, img).kind else { panic!("an image") };
|
||||
assert!(im.link.is_none());
|
||||
}
|
||||
|
||||
/// `tool.setOption` refuses a Crop Image resolution, reference point or link it can't use, and
|
||||
/// changes nothing.
|
||||
#[test]
|
||||
fn crop_image_tool_options_refuse_values_they_cannot_use() {
|
||||
let (mut s, _, _) = busy_image_at_two_points_a_pixel();
|
||||
s.select_tool("cropImage", ViewInfo::default()).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"values": {"ppi": 18, "reference": 0, "linked": true}})).unwrap();
|
||||
// 72 ppi is above the selected 36 ppi image's own.
|
||||
for (key, value) in
|
||||
[("ppi", json!("high")), ("ppi", json!(-1)), ("ppi", json!(0.5)), ("ppi", json!(72)), ("reference", json!(9)), ("linked", json!(1))]
|
||||
{
|
||||
assert!(s.set_tool_option_cmd(&json!({"key": key, "value": value})).is_err(), "{key}: {value}");
|
||||
}
|
||||
let o = s.tool_options();
|
||||
assert_eq!((o["ppi"].clone(), o["reference"].clone(), o["linked"].clone()), (json!(18.0), json!(0), json!(true)), "{o}");
|
||||
s.set_tool_option_cmd(&json!({"key": "ppi", "value": null})).unwrap();
|
||||
assert!(s.tool_options().get("ppi").is_none());
|
||||
}
|
||||
|
||||
/// Crop Image refuses a `rect` that is not an array, such as text, and the image stays as it was; a
|
||||
/// null `rect` crops to the artboard as a missing one does.
|
||||
#[test]
|
||||
@@ -5331,6 +5560,22 @@ fn crop_image_trim_checks_the_rgba_size_before_decoding() {
|
||||
assert!(within.contains("the image's pixels can't be read"), "{within}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_image_resampling_is_held_to_the_raster_allowance() {
|
||||
use crate::cmd::menucmds::check_resample_size;
|
||||
let max = crate::cmd::fileio::MAX_RASTER_ALLOC;
|
||||
// 40 bytes a pixel resampled to the same size (12 + 16 + 12).
|
||||
let side = ((max / 40) as f64).sqrt() as u32;
|
||||
assert!(check_resample_size(side, side, side, side).is_ok());
|
||||
let e = check_resample_size(side + 1, side + 1, side + 1, side + 1).unwrap_err().to_string();
|
||||
assert!(e.contains(&format!("an image of {0} × {0} pixels is too large to resample", side + 1)), "{e}");
|
||||
// A large source counts even when the result is small.
|
||||
let wide = ((max / 12) as f64).sqrt() as u32 + 1;
|
||||
assert!(check_resample_size(wide, wide, 1, 1).is_err());
|
||||
assert!(check_resample_size(u32::MAX, u32::MAX, u32::MAX, u32::MAX).is_err());
|
||||
assert!(check_resample_size(100, 100, 50, 50).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crop_image_trim_leaves_a_cmyk_image_alone() {
|
||||
// CMYK images keep their ink amounts and have no alpha: nothing to cut, and not an error.
|
||||
|
||||
@@ -1436,6 +1436,40 @@ fn an_instance_in_an_opacity_mask_snaps_with_its_symbol() {
|
||||
assert!(whole(&[(e, f)]), "{e} {f}");
|
||||
}
|
||||
|
||||
/// An instance snapped to whole points takes the art of its linked opacity mask along by the same
|
||||
/// amount, as a move does; the art of an unlinked mask stays where it is.
|
||||
#[test]
|
||||
fn an_instance_snapped_to_the_grid_moves_its_linked_mask() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
s.execute("symbol.new", &json!({"name": "Px"})).unwrap();
|
||||
let place = |s: &mut Session, x: f64, linked: bool| {
|
||||
let inst = s.execute("symbol.place", &json!({"name": "Px", "x": x, "y": 200.7})).unwrap()["id"].as_u64().unwrap();
|
||||
let m = path(s, "M80.25 180.5 L160.25 180.5 L160.25 240.5 L80.25 240.5 Z", 1.0);
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let art = d.remove(NodeId(m)).unwrap();
|
||||
let mask = vectorcraft_doc::OpacityMask { linked, ..vectorcraft_doc::OpacityMask::new((*art).clone(), true) };
|
||||
d.node_mut(NodeId(inst)).unwrap().extras_mut().mask = Some(Box::new(mask));
|
||||
inst
|
||||
};
|
||||
let (linked, unlinked) = (place(&mut s, 100.3, true), place(&mut s, 300.3, false));
|
||||
let mask_points = |s: &Session, inst: u64| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mask = d.node(NodeId(inst)).unwrap().extras().mask.clone().unwrap();
|
||||
mask.art.path_data().unwrap().anchors().map(|(_, _, a)| (a.p.x, a.p.y)).collect::<Vec<_>>()
|
||||
};
|
||||
let (xf_before, mask_before, unlinked_before) = (instance_xf(&s, linked), mask_points(&s, linked), mask_points(&s, unlinked));
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
let [.., e0, f0] = xf_before.as_coeffs();
|
||||
let [.., e, f] = instance_xf(&s, linked).as_coeffs();
|
||||
assert!(whole(&[(e, f)]) && (e, f) != (e0, f0), "{e} {f}");
|
||||
let moved: Vec<_> = mask_before.iter().map(|(x, y)| (x + e - e0, y + f - f0)).collect();
|
||||
let after = mask_points(&s, linked);
|
||||
assert!(moved.iter().zip(&after).all(|(a, b)| close(*a, *b)), "{after:?} != {moved:?}");
|
||||
assert!(whole(&placed_points(&s, unlinked)));
|
||||
assert_eq!(mask_points(&s, unlinked), unlinked_before);
|
||||
}
|
||||
|
||||
/// While a pixel-aligned symbol is edited, the art written back from the editing layer is stored
|
||||
/// on the pixel grid, so its instances stay on it.
|
||||
#[test]
|
||||
@@ -1459,3 +1493,49 @@ fn art_edited_in_symbol_editing_mode_stays_on_the_pixel_grid() {
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// Turning it on while the symbol is open in symbol editing mode shows its art on the pixel grid
|
||||
/// on the editing layer at once, and its instance stays on it after editing ends.
|
||||
#[test]
|
||||
fn turning_it_on_in_symbol_editing_mode_snaps_the_editing_layer() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("symbol.edit", &json!({"ids": [inst]})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
|
||||
let part = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
|
||||
let before = points(&s, part);
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let xf = d.symbol_edit.as_ref().unwrap().xf;
|
||||
let art = &d.symbols.iter().find(|x| x.name == "Px").unwrap().art;
|
||||
let stored: Vec<_> = art.path_data().unwrap().anchors().map(|(_, _, a)| xf * a.p).map(|p| (p.x, p.y)).collect();
|
||||
let shown = points(&s, part);
|
||||
assert!(shown.iter().zip(&stored).all(|(a, b)| close(*a, *b)) && shown != before, "{shown:?} != {stored:?}");
|
||||
s.execute("symbol.exitEditing", &json!({})).unwrap();
|
||||
let pts = placed_points(&s, inst);
|
||||
assert!(whole(&pts), "{pts:?}");
|
||||
}
|
||||
|
||||
/// An instance of a pixel-aligned symbol on the editing layer of another symbol is part of that
|
||||
/// symbol's art, so turning it on leaves the instance and the other symbol's art where they are.
|
||||
#[test]
|
||||
fn an_instance_on_another_symbols_editing_layer_is_left_as_it_is() {
|
||||
let mut s = new_doc();
|
||||
path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 2.0);
|
||||
let a = s.execute("symbol.new", &json!({"name": "Px"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let b = s.execute("symbol.new", &json!({"name": "Outer"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("symbol.edit", &json!({"ids": [b]})).unwrap();
|
||||
let st = s.doc().unwrap();
|
||||
let layer = st.doc.symbol_edit.as_ref().unwrap().layer;
|
||||
let inner = st.doc.node(layer).unwrap().children().unwrap()[0].id.0;
|
||||
let outer_art = st.doc.symbols.iter().find(|x| x.name == "Outer").unwrap().art.clone();
|
||||
let shown = instance_xf(&s, inner);
|
||||
assert!(!whole(&placed_points(&s, inner)));
|
||||
s.execute("symbol.options", &json!({"name": "Px", "alignToPixelGrid": true})).unwrap();
|
||||
assert_eq!(instance_xf(&s, inner), shown);
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert!(std::sync::Arc::ptr_eq(&d.symbols.iter().find(|x| x.name == "Outer").unwrap().art, &outer_art));
|
||||
}
|
||||
|
||||
@@ -345,6 +345,134 @@ fn misspellings_of_one_object_are_what_the_check_lists() {
|
||||
assert_eq!(found.iter().map(|m| m.range.clone()).collect::<Vec<_>>(), [listed[0].clone(), listed[2].clone()]);
|
||||
}
|
||||
|
||||
/// The (id, start, word) of each word a check lists, and its `more`.
|
||||
fn listed(s: &mut Session, p: Value) -> (Vec<(u64, u64, String)>, bool) {
|
||||
let r = run(s, "text.spelling.check", p);
|
||||
let words = r["words"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|w| (w["id"].as_u64().unwrap(), w["start"].as_u64().unwrap(), w["word"].as_str().unwrap().to_string()))
|
||||
.collect();
|
||||
(words, r["more"].as_bool().unwrap())
|
||||
}
|
||||
|
||||
/// A check cut short at `max` goes on with `from` at the end of the last word listed: the rest of
|
||||
/// that type object first, then the objects after it, and nothing listed twice.
|
||||
#[test]
|
||||
fn a_check_goes_on_from_where_the_last_one_stopped() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, 50.0, "qzxvw one wvxzq two\nthree qqzzx");
|
||||
let b = text(&mut s, 100.0, "zzqqx");
|
||||
let (first, more) = listed(&mut s, json!({"max": 2}));
|
||||
assert_eq!((first.clone(), more), (vec![(a.0, 0, "qzxvw".into()), (a.0, 10, "wvxzq".into())], true));
|
||||
// From the end of the second word: the third, in the next paragraph of the same object, not
|
||||
// the start of the next object.
|
||||
let (rest, more) = listed(&mut s, json!({"from": {"id": a.0, "byte": 15}, "max": 2}));
|
||||
assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into()), (b.0, 0, "zzqqx".into())], false));
|
||||
// A byte inside a word starts from the next word.
|
||||
let (rest, _) = listed(&mut s, json!({"from": {"id": a.0, "byte": 1}}));
|
||||
assert_eq!(rest.first(), Some(&(a.0, 10, "wvxzq".to_string())));
|
||||
// `from` follows the ids given, groups' type included.
|
||||
run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
|
||||
let g = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap();
|
||||
let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 26}, "max": 1}));
|
||||
assert_eq!((rest, more), (vec![(a.0, 26, "qqzzx".into())], true));
|
||||
let (rest, more) = listed(&mut s, json!({"ids": [g], "from": {"id": a.0, "byte": 31}, "max": 1}));
|
||||
assert_eq!((rest, more), (vec![(b.0, 0, "zzqqx".into())], false));
|
||||
let bad = [
|
||||
json!({"from": {"id": a.0}}),
|
||||
json!({"from": {"id": a.0, "byte": -1}}),
|
||||
json!({"from": {"id": a.0, "byte": 1000}}),
|
||||
json!({"from": {"id": a.0, "byte": 0, "x": 1}}),
|
||||
json!({"from": a.0}),
|
||||
json!({"ids": [b.0], "from": {"id": a.0, "byte": 0}}),
|
||||
json!({"max": 0}),
|
||||
json!({"max": 10_001}),
|
||||
json!({"max": "2"}),
|
||||
];
|
||||
for p in bad {
|
||||
assert!(s.execute("text.spelling.check", &p).is_err(), "{p} is refused");
|
||||
}
|
||||
}
|
||||
|
||||
/// One type object with one unknown word more than a check lists: going on from the last word
|
||||
/// listed reaches the last one.
|
||||
#[test]
|
||||
fn a_check_past_the_limit_in_one_object_goes_on_to_its_last_word() {
|
||||
use crate::cmd::spelling::MAX_WORDS;
|
||||
let mut s = session();
|
||||
let t = text(&mut s, 50.0, &vec!["qzxvw"; MAX_WORDS + 1].join(" "));
|
||||
let r = run(&mut s, "text.spelling.check", json!({}));
|
||||
let words = r["words"].as_array().unwrap();
|
||||
assert_eq!((words.len(), &r["more"]), (MAX_WORDS, &json!(true)));
|
||||
let end = words.last().unwrap()["end"].as_u64().unwrap();
|
||||
let (rest, more) = listed(&mut s, json!({"from": {"id": t.0, "byte": end}}));
|
||||
assert_eq!((rest, more), (vec![(t.0, end + 1, "qzxvw".into())], false));
|
||||
}
|
||||
|
||||
/// The plain text of type object `id`.
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not type"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Change All's command replaces every word listed, in several objects, as one undo step, and
|
||||
/// refuses a list with any word not in its object's text, changing nothing.
|
||||
#[test]
|
||||
fn change_all_replaces_every_word_listed_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, 50.0, "qzxvw one qzxvw\nqzxvw");
|
||||
let b = text(&mut s, 100.0, "é qzxvw");
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
let words = json!([{"id": a.0, "start": 16, "end": 21}, {"id": a.0, "start": 0, "end": 5}, {"id": b.0, "start": 3, "end": 8}, {"id": a.0, "start": 10, "end": 15}]);
|
||||
let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}));
|
||||
assert_eq!(r["changed"], 4);
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), ("fixed one fixed\nfixed".to_string(), "é fixed".to_string()));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), ("qzxvw one qzxvw\nqzxvw".to_string(), "é qzxvw".to_string()));
|
||||
let bad = [
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 3, "end": 8}]}),
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 20, "end": 99}]}),
|
||||
json!({"to": "x", "words": [{"id": b.0, "start": 1, "end": 4}]}),
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": 5, "end": 5}]}),
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": 0, "end": 5, "x": 1}]}),
|
||||
json!({"to": "x", "words": [{"id": a.0, "start": -1, "end": 5}]}),
|
||||
json!({"to": "x", "words": [{"id": 999_999, "start": 0, "end": 5}]}),
|
||||
json!({"to": "x", "words": {"id": a.0}}),
|
||||
json!({"words": []}),
|
||||
];
|
||||
for p in bad {
|
||||
assert!(s.execute("text.spelling.change", &p).is_err(), "{p} is refused");
|
||||
}
|
||||
assert_eq!(plain(&s, a), "qzxvw one qzxvw\nqzxvw", "nothing changed by a refused list");
|
||||
assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "x", "words": []}))["changed"], 0);
|
||||
}
|
||||
|
||||
/// A listed word that already reads as `to` is left alone: with no other word, no edit and no
|
||||
/// undo step, so the redo history stays.
|
||||
#[test]
|
||||
fn change_all_skips_words_that_already_read_as_the_replacement() {
|
||||
let mut s = session();
|
||||
let a = text(&mut s, 50.0, "fixed qzxvw");
|
||||
run(&mut s, "text.editRange", json!({"id": a.0, "start": 6, "end": 11, "insert": "other"}));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
let (undo, redo) = {
|
||||
let h = &s.doc().unwrap().history;
|
||||
(h.undo.len(), h.redo.len())
|
||||
};
|
||||
let r = run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": [{"id": a.0, "start": 0, "end": 5}]}));
|
||||
assert_eq!(r["changed"], 0);
|
||||
let h = &s.doc().unwrap().history;
|
||||
assert_eq!((h.undo.len(), h.redo.len()), (undo, redo), "no undo step, and redo kept");
|
||||
let words = json!([{"id": a.0, "start": 0, "end": 5}, {"id": a.0, "start": 6, "end": 11}]);
|
||||
assert_eq!(run(&mut s, "text.spelling.change", json!({"to": "fixed", "words": words}))["changed"], 1);
|
||||
assert_eq!(plain(&s, a), "fixed fixed");
|
||||
}
|
||||
|
||||
/// Each change to the custom dictionary moves its generation on, whether it is saved or not, so
|
||||
/// what Auto Spell Check found before is checked again.
|
||||
#[test]
|
||||
|
||||
@@ -1347,6 +1347,18 @@ impl Session {
|
||||
}
|
||||
// Every value is checked before any is set, so an invalid one changes nothing.
|
||||
vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?;
|
||||
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
|
||||
use vectorcraft_tools::cropimage as crop;
|
||||
// The most the selected image can be cropped to, when one is selected.
|
||||
let max = self.doc().ok().and_then(|st| {
|
||||
let (id, _) = crop::selected_image(&st.doc, &st.selection)?;
|
||||
match &st.doc.node(id)?.kind {
|
||||
vectorcraft_doc::NodeKind::Image(im) => Some(crop::image_ppi(im).1),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
crop::check_options(&values, max)?;
|
||||
}
|
||||
// The Place queue is read later, by a click outside any automation scope: its files must
|
||||
// be readable now, under the roots of whoever sets it.
|
||||
if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) {
|
||||
|
||||
Reference in New Issue
Block a user