mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 09:13:34 +00:00
Merge main into feat/polygon-side-widget
This commit is contained in:
@@ -154,6 +154,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
|
||||
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
|
||||
|
||||
@@ -96,7 +96,24 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
|
||||
Some(folder) => d.folder(folder),
|
||||
None => d,
|
||||
};
|
||||
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
|
||||
if pick.name.is_empty() {
|
||||
return d;
|
||||
}
|
||||
// Windows' save dialog changes the extension when a different file type is chosen only when
|
||||
// the suggested name has no explicit extension. rfd supplies the first filter's extension to
|
||||
// that dialog, so leave the suffix to Windows for saves that offer several formats (#5451).
|
||||
// A remaining dot in the stem would look like another explicit extension to Windows.
|
||||
#[cfg(windows)]
|
||||
if matches!(request, PickRequest::Save(_))
|
||||
&& pick.filters.len() > 1
|
||||
&& let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str())
|
||||
&& pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext)))
|
||||
&& let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str())
|
||||
&& !stem.contains('.')
|
||||
{
|
||||
return d.file_name(stem);
|
||||
}
|
||||
d.file_name(&pick.name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -796,7 +813,7 @@ mod dialog_tests {
|
||||
|
||||
/// The file types a dialog was given, by label.
|
||||
#[derive(Default)]
|
||||
struct Filters(Vec<(String, Vec<String>)>);
|
||||
struct Filters(Vec<(String, Vec<String>)>, Option<String>);
|
||||
|
||||
impl DialogSettings for Filters {
|
||||
fn parent(self, _window: &winit::window::Window) -> Self {
|
||||
@@ -812,7 +829,8 @@ mod dialog_tests {
|
||||
fn folder(self, _folder: &str) -> Self {
|
||||
self
|
||||
}
|
||||
fn file_name(self, _name: &str) -> Self {
|
||||
fn file_name(mut self, name: &str) -> Self {
|
||||
self.1 = Some(name.to_string());
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -869,4 +887,24 @@ mod dialog_tests {
|
||||
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
|
||||
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
|
||||
}
|
||||
|
||||
/// A format selected after the Windows Save As dialog opens can replace the suffix of the
|
||||
/// suggested name. Single-format saves and open dialogs keep the supplied name verbatim.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn save_dialog_with_several_formats_leaves_the_extension_to_windows() {
|
||||
let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])];
|
||||
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster"));
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft"));
|
||||
|
||||
let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster"));
|
||||
let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design"));
|
||||
let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft"));
|
||||
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() };
|
||||
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,18 @@ pub enum ArrowStyle {
|
||||
None,
|
||||
}
|
||||
|
||||
impl ArrowStyle {
|
||||
/// The stroke arrowhead drawn at each end of the dimension line, or None for no head.
|
||||
pub fn arrowhead(self) -> Option<crate::Arrowhead> {
|
||||
match self {
|
||||
Self::Filled => Some(crate::Arrowhead::Triangle),
|
||||
Self::Open => Some(crate::Arrowhead::TriangleOpen),
|
||||
Self::Tick => Some(crate::Arrowhead::Slash),
|
||||
Self::None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the label sits across the dimension line.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
|
||||
@@ -424,6 +424,44 @@ impl Document {
|
||||
out
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike
|
||||
/// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every
|
||||
/// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still
|
||||
/// checks out, the nodes are found along those paths; otherwise one walk of the tree finds
|
||||
/// them. As for every cached lookup, a second node given an existing id after the cache was
|
||||
/// built is not found while the first one's cached path checks out (see [`id_index`]).
|
||||
pub fn nodes_in_order(&self, ids: impl IntoIterator<Item = NodeId>) -> Vec<&Node> {
|
||||
let want: std::collections::HashSet<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = ids.into_iter().collect();
|
||||
// As in `index_paths`, one walk is quicker than checking the cached paths of a good share
|
||||
// of the document.
|
||||
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
|
||||
let mut paths = Vec::with_capacity(want.len());
|
||||
let cached = want.iter().all(|id| match cache.get(id) {
|
||||
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
|
||||
paths.push(p);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
if cached {
|
||||
// A node's path sorts after the paths of the nodes before it in tree order, its
|
||||
// ancestors included.
|
||||
paths.sort_unstable();
|
||||
return paths.iter().filter_map(|p| self.node_at(p)).collect();
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if !want.is_empty() {
|
||||
crate::id_index::note_tree_walk();
|
||||
self.walk(|n| {
|
||||
if want.contains(&n.id) {
|
||||
out.push(n);
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The node at index path `path` (as [`Document::index_path`] gives it).
|
||||
pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
|
||||
let (first, rest) = path.split_first()?;
|
||||
|
||||
+89
-46
@@ -2096,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving
|
||||
/// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured
|
||||
/// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are
|
||||
/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a
|
||||
/// touched where the live geometry effects of a clipping path in their art show it, or where the
|
||||
/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except
|
||||
/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a
|
||||
/// clipping mask counts only when the marquee meets the region its clipping path clips to, and then
|
||||
/// only within that region's bounds. In isolation mode the clipping mask of the isolated container,
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
@@ -2104,20 +2106,39 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// the members of a group or layer with geometry effects of its own, are touched where the art those
|
||||
/// effects draw lies ([`set_drawn_art`]), as clicks hit them.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, false)
|
||||
marquee_with(doc, r, scope, leaves, false, false, false)
|
||||
}
|
||||
|
||||
/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer
|
||||
/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as
|
||||
/// the clicks of [`HitOptions::outline`] do.
|
||||
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, outline)
|
||||
/// the clicks of [`HitOptions::outline`] do. With `skip_guides` (Lock Guides is on or the guides
|
||||
/// are hidden, as [`HitOptions::skip_guides`]), the paths made into guides are not touched, at the
|
||||
/// top or inside a group, so a group is not taken for a guide in it (#8538).
|
||||
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool, skip_guides: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, outline, skip_guides)
|
||||
}
|
||||
|
||||
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
|
||||
/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint.
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true, outline)
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool, skip_guides: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true, outline, skip_guides)
|
||||
}
|
||||
|
||||
/// What a marquee ([`marquee_with`]) takes, besides where it is: whether a compound path is
|
||||
/// touched by every path it paints (`whole_compounds`, for an enclosing loop's candidates), and
|
||||
/// whether the paths made into guides are left out (`skip_guides`: Lock Guides is on or the
|
||||
/// guides are hidden, [`HitOptions::skip_guides`] for the marquee).
|
||||
#[derive(Clone, Copy)]
|
||||
struct Rules {
|
||||
whole_compounds: bool,
|
||||
skip_guides: bool,
|
||||
}
|
||||
|
||||
impl Rules {
|
||||
/// Is `n` a path made into a guide that the marquee leaves out?
|
||||
fn skips(self, n: &Node) -> bool {
|
||||
self.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
|
||||
@@ -2125,8 +2146,17 @@ fn previews_off(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Layer { preview: false, .. })
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
fn marquee_with(
|
||||
doc: &Document,
|
||||
r: Rect,
|
||||
scope: Option<NodeId>,
|
||||
leaves: bool,
|
||||
whole_compounds: bool,
|
||||
outline: bool,
|
||||
skip_guides: bool,
|
||||
) -> Vec<NodeId> {
|
||||
let _walk = ArtWalk::open();
|
||||
let rules = Rules { whole_compounds, skip_guides };
|
||||
let mut out = Vec::new();
|
||||
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
|
||||
let locks = doc.locked_artboards_kept();
|
||||
@@ -2140,7 +2170,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
Some(c) => {
|
||||
// In an isolated clip group, its members by their own geometry, as clicks take
|
||||
// them ([`edits_inside`]).
|
||||
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, whole_compounds, outline || previews_off(s)) };
|
||||
let drawn = if s.clips() { None } else { touched_in_art(s, &symbols, r, rules, outline || previews_off(s)) };
|
||||
c.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
@@ -2162,7 +2192,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
|
||||
.flat_map(|l| layer_objects(l, &symbols, r, outline, whole_compounds, None))
|
||||
.flat_map(|l| layer_objects(l, &symbols, r, outline, rules, None))
|
||||
.collect(),
|
||||
};
|
||||
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
|
||||
@@ -2171,17 +2201,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// shapes ([`mask_marquee`]). In a layer whose own geometry effects reshape its art, each object
|
||||
/// comes with the objects that art touches ([`touched_in_art`]), `drawn` when a layer around
|
||||
/// `l` has such effects.
|
||||
fn layer_objects<'a>(
|
||||
l: &'a Node,
|
||||
s: &SymbolBoxes,
|
||||
r: Rect,
|
||||
outline: bool,
|
||||
whole_compounds: bool,
|
||||
drawn: Option<Rc<HashSet<NodeId>>>,
|
||||
) -> Vec<Top<'a>> {
|
||||
fn layer_objects<'a>(l: &'a Node, s: &SymbolBoxes, r: Rect, outline: bool, rules: Rules, drawn: Option<Rc<HashSet<NodeId>>>) -> Vec<Top<'a>> {
|
||||
let mut out = vec![];
|
||||
let outline = outline || previews_off(l);
|
||||
let drawn = drawn.or_else(|| touched_in_art(l, s, r, whole_compounds, outline));
|
||||
let drawn = drawn.or_else(|| touched_in_art(l, s, r, rules, outline));
|
||||
let inner = marquee_in_parent(l, r, outline);
|
||||
for (i, c) in l.children().into_iter().flatten().enumerate() {
|
||||
if c.is_layer() {
|
||||
@@ -2190,7 +2213,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
&& !c.locked
|
||||
&& !c.is_template()
|
||||
{
|
||||
out.extend(layer_objects(c, s, inner, outline, whole_compounds, drawn.clone()));
|
||||
out.extend(layer_objects(c, s, inner, outline, rules, drawn.clone()));
|
||||
}
|
||||
} else if !c.is_ruler_guide() {
|
||||
if drawn.is_some() {
|
||||
@@ -2207,12 +2230,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// The ids of the objects of the art that group or layer `n` draws with its own geometry
|
||||
/// effects ([`drawn_art`]) that the marquee `r` touches, as [`collect_leaves`] collects them.
|
||||
/// `None` in outline and when it has no such effects.
|
||||
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
|
||||
fn touched_in_art(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules, outline: bool) -> Option<Rc<HashSet<NodeId>>> {
|
||||
let art = drawn_art(s, n, outline)?;
|
||||
let _off = DrawnOff::set();
|
||||
let mut ids = vec![];
|
||||
for a in art.iter().filter(|a| a.visible) {
|
||||
collect_leaves(a, s, r, None, whole_compounds, false, &mut ids);
|
||||
collect_leaves(a, s, r, None, rules, false, &mut ids);
|
||||
}
|
||||
Some(Rc::new(ids.into_iter().collect()))
|
||||
}
|
||||
@@ -2265,14 +2288,20 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
|
||||
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
|
||||
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
|
||||
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
|
||||
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
/// compound paths, layers and groups are touched by their box, and an image or a symbol
|
||||
/// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping
|
||||
/// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region
|
||||
/// ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, rules: Rules, outline: bool) -> bool {
|
||||
// Locked or hidden guides are not touched ([`Rules::skips`]).
|
||||
if rules.skips(n) {
|
||||
return false;
|
||||
}
|
||||
// A path or compound path whose geometry effects reshape it, or a group or layer whose own
|
||||
// geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]).
|
||||
if let Some(art) = drawn_art(s, n, outline || previews_off(n)) {
|
||||
let _off = DrawnOff::set();
|
||||
return art.iter().any(|a| a.visible && touches(a, s, r, None, whole_compounds, false));
|
||||
return art.iter().any(|a| a.visible && touches(a, s, r, None, rules, false));
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
|
||||
@@ -2283,25 +2312,41 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
c.visible
|
||||
&& !shaper_hides(n, i, scope)
|
||||
&& if i == 0 && n.clips() {
|
||||
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)))
|
||||
plain(true, || mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, rules, outline)))
|
||||
|| clip_edge_touches(c, r, outline)
|
||||
} else {
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, rules, outline))
|
||||
}
|
||||
})
|
||||
}
|
||||
NodeKind::Compound { children, .. } if whole_compounds => {
|
||||
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
|
||||
NodeKind::Compound { children, .. } if rules.whole_compounds => {
|
||||
// Guide contours left out ([`Rules::skips`]) don't make the compound a candidate.
|
||||
children.iter().filter(|c| !rules.skips(c)).filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
|
||||
}
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, rules, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, rules, outline)),
|
||||
// A symbol instance is touched by its box, and outside it where the live geometry
|
||||
// effects of a clipping path in its art show the art. In the art of another instance
|
||||
// walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]).
|
||||
NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds),
|
||||
// effects of a clipping path in its art show the art, or where the geometry effects of
|
||||
// its active fill or stroke reshape the art ([`painted_touches`]). In the art of another
|
||||
// instance walked outside that instance's box, it is touched only by its own art
|
||||
// ([`ArtOnly`]) and those shapes.
|
||||
NodeKind::SymbolInstance { .. } => {
|
||||
!ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, rules) || painted_touches(n, s, r))
|
||||
}
|
||||
// An image is touched by its box, and outside it where its own fills and strokes paint.
|
||||
NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r),
|
||||
_ => box_touches(n, s, r),
|
||||
}
|
||||
}
|
||||
/// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol
|
||||
/// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is
|
||||
/// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when
|
||||
/// `r` meets the reach of `n` ([`Node::reach_bounds_with`]).
|
||||
fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
n.reach_bounds_with(s).is_some_and(meets)
|
||||
&& image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r))
|
||||
}
|
||||
/// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of
|
||||
/// a symbol that draws a straight line) is touched where the marquee crosses it.
|
||||
fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool {
|
||||
@@ -2315,7 +2360,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
/// ([`SymbolBoxes::art`]), or for any art while [`ArtOnly`] is on, and only when `r` meets the
|
||||
/// instance's reach ([`Node::reach_bounds_with`]): elsewhere the art lies within the instance's
|
||||
/// box. Not once the marquee has placed as many objects of symbol art as [`ArtWalk`] allows.
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, whole_compounds: bool) -> bool {
|
||||
fn instance_art_touches(n: &Node, s: &SymbolBoxes, r: Rect, rules: Rules) -> bool {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return false };
|
||||
let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1;
|
||||
if s.art(symbol).is_none_or(|a| a.reshaped.is_none() && !ArtOnly::on()) || !n.reach_bounds_with(s).is_some_and(meets) {
|
||||
@@ -2332,15 +2377,15 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
#[cfg(test)]
|
||||
ARTS_WALKED.with(|c| c.set(c.get() + 1));
|
||||
let _art_only = ArtOnly::set();
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, whole_compounds, false))
|
||||
art.place(&art.art, None).is_some_and(|placed| placed.visible && touches(&placed, s, r, None, rules, false))
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, rules: Rules, outline: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
let outline = outline || previews_off(n);
|
||||
// The members that the art its own geometry effects draw touches, and a group whose
|
||||
// own fills and strokes that art paints, as clicks hit it ([`member_chain`]).
|
||||
if let Some(drawn) = touched_in_art(n, s, r, whole_compounds, outline) {
|
||||
if let Some(drawn) = touched_in_art(n, s, r, rules, outline) {
|
||||
if drawn.contains(&n.id) && !n.is_layer() {
|
||||
out.push(n.id);
|
||||
}
|
||||
@@ -2355,18 +2400,18 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if i == 0 && n.clips() {
|
||||
let before = out.len();
|
||||
if let Some(r) = mask_marquee(n, r) {
|
||||
plain(true, || collect_leaves(c, s, r, scope, whole_compounds, outline, out));
|
||||
plain(true, || collect_leaves(c, s, r, scope, rules, outline, out));
|
||||
}
|
||||
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
|
||||
out.push(c.id);
|
||||
}
|
||||
} else if let Some(r) = inner {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
collect_leaves(c, s, r, scope, rules, outline, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if touches(n, s, r, scope, whole_compounds, outline) {
|
||||
if touches(n, s, r, scope, rules, outline) {
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
@@ -2401,14 +2446,12 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
if leaves {
|
||||
let before = out.len();
|
||||
if let Some(r) = r {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
|
||||
collect_leaves(t, &symbols, r, scope, rules, outline, &mut out);
|
||||
}
|
||||
if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) {
|
||||
out.push(t.id);
|
||||
}
|
||||
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline))
|
||||
|| edge.is_some_and(|e| clip_edge_touches(t, e, outline))
|
||||
{
|
||||
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, rules, outline)) || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) {
|
||||
out.push(t.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,8 +164,8 @@ fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_chang
|
||||
// So with a marquee across the art's left edge: in the view, only in Outline view. The
|
||||
// clipping path's own left edge lies there too, and counts in both.
|
||||
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, false, false), [mask_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, true, false), [mask_id, art_id]);
|
||||
// `marquee_in` measures by the plain shapes, as its callers clip by them.
|
||||
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
|
||||
// Hidden, the effect no longer moves the region.
|
||||
@@ -489,8 +489,8 @@ fn a_marquee_touches_a_paths_shifted_art_not_its_source() {
|
||||
for leaves in [false, true] {
|
||||
assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn");
|
||||
assert!(marquee(&d, own, None, leaves).is_empty(), "its own place");
|
||||
assert!(marquee_in_view(&d, drawn, None, leaves, true).is_empty(), "outline: no drawn art");
|
||||
assert_eq!(marquee_in_view(&d, own, None, leaves, true), [a], "outline: its own place");
|
||||
assert!(marquee_in_view(&d, drawn, None, leaves, true, false).is_empty(), "outline: no drawn art");
|
||||
assert_eq!(marquee_in_view(&d, own, None, leaves, true, false), [a], "outline: its own place");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -870,6 +870,68 @@ fn a_selected_guide_hidden_by_a_mask_counts_only_while_guides_can_be_clicked() {
|
||||
assert_eq!(selected_hidden_at(&d, hidden, HitOptions { skip_guides: true, ..opt }, &[guide_id]), None);
|
||||
}
|
||||
|
||||
/// #8538: while guides are locked or hidden (`skip_guides`), a marquee touches no guide path, at
|
||||
/// the top of a layer or in a group (the group is not taken for it), nor in a group in a group,
|
||||
/// with leaves or without. The group's other members still take it, and with the guides unlocked
|
||||
/// the guide does.
|
||||
#[test]
|
||||
fn a_marquee_skips_guide_paths_in_groups_while_guides_are_locked() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let guide = |d: &mut Document, r: Rect| {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
n
|
||||
};
|
||||
let top = guide(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0));
|
||||
let inner = guide(&mut d, Rect::new(100.0, 0.0, 120.0, 20.0));
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(200.0, 0.0, 220.0, 20.0)), Appearance::default_art());
|
||||
let (top_id, inner_id, art_id) = (top.id, inner.id, art.id);
|
||||
let (outer_id, nested_id) = (d.alloc_id(), d.alloc_id());
|
||||
let nested = Node::group(nested_id, vec![Arc::new(inner)]);
|
||||
d.insert(Some(l), 0, top).unwrap();
|
||||
d.insert(Some(l), 1, Node::group(outer_id, vec![Arc::new(nested), Arc::new(art)])).unwrap();
|
||||
let (on_top, on_inner, on_art) = (Rect::new(-5.0, 5.0, 5.0, 10.0), Rect::new(95.0, 5.0, 105.0, 10.0), Rect::new(195.0, 5.0, 205.0, 10.0));
|
||||
for leaves in [false, true] {
|
||||
let m = |r: Rect, skip: bool| marquee_in_view(&d, r, None, leaves, false, skip);
|
||||
assert!(m(on_top, true).is_empty(), "a guide at the top, leaves {leaves}");
|
||||
assert!(m(on_inner, true).is_empty(), "a guide in a group in a group, leaves {leaves}");
|
||||
assert!(m(Rect::new(0.0, 0.0, 300.0, 200.0), true).iter().all(|id| ![top_id, inner_id].contains(id)), "all, leaves {leaves}");
|
||||
assert_eq!(m(on_art, true), [if leaves { art_id } else { outer_id }], "the group's art, leaves {leaves}");
|
||||
// Unlocked: the guides are touched.
|
||||
assert_eq!(m(on_top, false), [top_id], "unlocked, leaves {leaves}");
|
||||
assert_eq!(m(on_inner, false), [if leaves { inner_id } else { outer_id }], "unlocked, leaves {leaves}");
|
||||
}
|
||||
// An enclosing loop's candidates leave them out alike.
|
||||
assert!(enclosure_candidates(&d, on_inner, None, false, true).is_empty());
|
||||
assert_eq!(enclosure_candidates(&d, on_inner, None, false, false), [inner_id]);
|
||||
}
|
||||
|
||||
/// #8538: an enclosing loop's candidates leave out a compound path whose touched contours are all
|
||||
/// locked or hidden guides, as the marquee does.
|
||||
#[test]
|
||||
fn guide_contours_do_not_make_a_compound_an_enclosure_candidate() {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let part = |d: &mut Document, r: Rect| {
|
||||
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
Arc::new(n)
|
||||
};
|
||||
let (a, b) = (part(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0)), part(&mut d, Rect::new(20.0, 20.0, 40.0, 40.0)));
|
||||
let id = d.alloc_id();
|
||||
let mut compound = Node::group(id, vec![]);
|
||||
compound.kind = NodeKind::Compound { children: vec![a, b], rule: Default::default() };
|
||||
d.insert(Some(l), 0, compound).unwrap();
|
||||
let r = Rect::new(0.0, 0.0, 60.0, 60.0);
|
||||
assert!(enclosure_candidates(&d, r, None, false, true).is_empty(), "locked or hidden");
|
||||
assert_eq!(enclosure_candidates(&d, r, None, false, false), [id], "shown and unlocked");
|
||||
}
|
||||
|
||||
/// A selected path in a Shaper group's original shapes, where an outer mask hides it, counts only
|
||||
/// while those shapes can be clicked (Construction mode, with them isolated), however deep it
|
||||
/// lies in them.
|
||||
@@ -2674,7 +2736,7 @@ fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art
|
||||
assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}");
|
||||
assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}");
|
||||
assert!(marquee(&d, past, None, false).is_empty());
|
||||
assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view");
|
||||
assert!(marquee_in_view(&d, edge, None, false, true, false).is_empty(), "Outline view");
|
||||
}
|
||||
// Preview off for the layer the instance is on.
|
||||
let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false);
|
||||
|
||||
@@ -90,6 +90,42 @@ impl Node {
|
||||
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
|
||||
/// This object without the paths made into guides among the members of its groups, layers,
|
||||
/// Intertwine groups and compound paths, at any depth, for measuring the art around them while
|
||||
/// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or
|
||||
/// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps
|
||||
/// its structure. `None` when it holds no such guide.
|
||||
pub fn without_guides(&self) -> Option<Node> {
|
||||
let (NodeKind::Layer { children, .. }
|
||||
| NodeKind::Group { children, .. }
|
||||
| NodeKind::Intertwine { children }
|
||||
| NodeKind::Compound { children, .. }) = &self.kind
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let keep = usize::from(self.clips() || self.extras().shaper.is_some());
|
||||
let mut changed = false;
|
||||
let mut out = Vec::with_capacity(children.len());
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
|
||||
changed = true;
|
||||
} else if let Some(stripped) = c.without_guides() {
|
||||
changed = true;
|
||||
out.push(Arc::new(stripped));
|
||||
} else {
|
||||
out.push(c.clone());
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return None;
|
||||
}
|
||||
let mut n = self.clone();
|
||||
if let Some(c) = n.children_mut() {
|
||||
*c = out;
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// A template layer (Layer Options → Template).
|
||||
pub fn is_template(&self) -> bool {
|
||||
matches!(self.kind, NodeKind::Layer { template: true, .. })
|
||||
|
||||
@@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option<Quotes> {
|
||||
LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q)
|
||||
}
|
||||
|
||||
/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the
|
||||
/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written
|
||||
/// as in an exported file. `None` for a language not in the list.
|
||||
pub fn language_tag(language: &str) -> Option<&'static str> {
|
||||
LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t)
|
||||
}
|
||||
|
||||
/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's
|
||||
/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the
|
||||
/// first entry); `Err` for a language not in the list.
|
||||
@@ -404,6 +411,16 @@ impl DocSetup {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A document's language is written by its tag, the default's included (#3644).
|
||||
#[test]
|
||||
fn document_languages_have_their_tags() {
|
||||
assert_eq!(language_tag(&DocSetup::default().language), Some("en-US"));
|
||||
assert_eq!(language_tag("French"), Some("fr"));
|
||||
assert_eq!(language_tag("german: swiss"), Some("de-CH"));
|
||||
assert_eq!(language_tag("sr-latn"), Some("sr-Latn"));
|
||||
assert_eq!((language_tag("Klingon"), language_tag("")), (None, None));
|
||||
}
|
||||
|
||||
/// Characters store a language of the list by its tag, the default as none.
|
||||
#[test]
|
||||
fn char_languages_are_stored_by_tag() {
|
||||
|
||||
@@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every node whose id is in `ids`, by walking the tree.
|
||||
fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> {
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
out.push(n as *const Node);
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids
|
||||
/// included, with the cache built and without it, for a few ids (cached paths) and for many (a
|
||||
/// walk).
|
||||
#[test]
|
||||
fn nodes_in_order_match_a_walk() {
|
||||
for seed in 1..40 {
|
||||
let (d, ids) = tree(seed);
|
||||
let few: Vec<NodeId> = ids.iter().copied().step_by(17).collect();
|
||||
for cold in [true, false] {
|
||||
if cold {
|
||||
d.drop_lookup_cache();
|
||||
} else {
|
||||
d.node(ids[0]);
|
||||
}
|
||||
for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] {
|
||||
let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect();
|
||||
assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}");
|
||||
}
|
||||
}
|
||||
// An id that the tree repeats: every node with it.
|
||||
let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue };
|
||||
assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once");
|
||||
// A second node given an id once held once, after the cache was built: the lookup finds the
|
||||
// cached node, which has that id; with the cache built afresh, both.
|
||||
let mut d = d;
|
||||
let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer()));
|
||||
let Some(once) = once else { continue };
|
||||
d.node(once);
|
||||
let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art()));
|
||||
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
|
||||
ch.insert(0, copy);
|
||||
}
|
||||
let found = d.nodes_in_order([once]);
|
||||
assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}");
|
||||
d.drop_lookup_cache();
|
||||
d.node(once);
|
||||
let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect();
|
||||
assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh");
|
||||
}
|
||||
}
|
||||
|
||||
/// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each
|
||||
/// node it is in, appears in the tree once.
|
||||
fn picks(d: &Document, seed: u64) -> Vec<NodeId> {
|
||||
|
||||
@@ -74,6 +74,7 @@ pub mod perspgrid;
|
||||
pub mod place;
|
||||
pub mod plugin;
|
||||
pub(crate) mod plugin_call;
|
||||
mod preflight;
|
||||
pub mod prefscmds;
|
||||
pub mod print;
|
||||
pub(crate) mod printadvanced;
|
||||
@@ -382,6 +383,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(package::specs());
|
||||
v.extend(slices::specs());
|
||||
v.extend(print::specs());
|
||||
v.extend(preflight::specs());
|
||||
v.extend(recovery::specs());
|
||||
v.extend(fileio::dxfimport::specs());
|
||||
v.extend(webexport::specs());
|
||||
@@ -840,6 +842,8 @@ pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
|
||||
pub use object::{reflect_axis, scale_factors, shear_tangent};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Common Tangents (`addon.pathtools.commonTangents`): the straight lines that touch two selected
|
||||
//! convex closed paths (ellipses at any rotation and scale, and convex Bézier paths) without
|
||||
//! crossing into either, added as separate open paths, with the line joining their centers if
|
||||
//! asked. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
//! asked. One of the two may be a point (a path of one anchor) instead: the lines then run from it
|
||||
//! to where they touch the path. The geometry is `vectorcraft_pathops::addons::pathtools::common_tangents`.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -30,19 +31,24 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Common Tangents",
|
||||
["Object", "Plug-ins", "Path Precision Tools"],
|
||||
None,
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
"{tangents?: \"external\" (both paths on the same side of each line) | \"internal\" (the lines that run between them) | \"all\" (\"all\"), centerline?: bool (false: true also adds the line joining the two centers, an ellipse's center or a path's center of area), ids?: [id, id] (default: the selection)} add the common tangent lines of two convex closed paths as separate open paths, each from where it touches the first path to where it touches the second (the whole stretch where a straight side lies along it), stroked with the current stroke color and weight (black when the stroke is None) and unfilled, directly above the upper of the two, as one undo step; the new lines are selected. An ellipse drawn with the Ellipse tool, turned or scaled, is measured as an exact ellipse; any other path must be closed, have one outline, bend the same way all around and have at most 10000 segments. Separate paths have two external and two internal tangents; overlapping paths only external ones; one path inside the other has none. Paths that touch, from outside or from inside, share one tangent there instead: a line centered on the point where they touch and as long as the narrower path is wide along it; paths that meet at a corner or along a shared stretch of outline get one such line, at the middle of the directions that touch both. Paths count as touching when the gap between them is less than a billionth of the larger of their sizes and the distance between their centers. One of the two may be a point (a path of one anchor): the lines then run from the point to where they touch the path, two when the point lies outside it (one that lies along a straight side covers the whole side), one when the point lies on its outline, that is, less than the touching tolerance from it, with the point's distance from the path's center in place of the distance between centers (centered on the point and as long as the path is wide along it, or the whole straight side the point lies on), none when it lies inside; every `tangents` value gives the same lines, counted as internal when `tangents` is \"internal\" and as external otherwise, and the centerline runs from the point to the path's center; two points are refused. When there is no tangent of the kind asked for, nothing changes and the result has a `warning` → {ids, external, internal, centerline (its id or null), warning?}",
|
||||
has_selection,
|
||||
common_tangents
|
||||
)]
|
||||
}
|
||||
|
||||
/// The outline of path `id` as the geometry takes it: an exact ellipse for a whole live ellipse,
|
||||
/// else the path's one closed convex subpath.
|
||||
/// The outline of path `id` as the geometry takes it: a point for a path of one anchor, an exact
|
||||
/// ellipse for a whole live ellipse, else the path's one closed convex subpath.
|
||||
fn outline_of(d: &Document, id: NodeId) -> Result<pt::Outline> {
|
||||
const C: &str = COMMON_TANGENTS;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Path { path, live, .. } = &n.kind else { return Err(bad(C, "select two closed paths")) };
|
||||
let [sp] = path.subpaths.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
if sp.anchors.len() == 1
|
||||
&& let Some(only) = sp.anchors.first()
|
||||
{
|
||||
return pt::Outline::point(only.p).map_err(refusal);
|
||||
}
|
||||
if let Some(LiveShape::Ellipse { w, h, pie, xf }) = live.as_deref() {
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
if span < 1e-9 || 360.0 - span < 1e-9 {
|
||||
@@ -74,17 +80,36 @@ fn common_tangents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ordered = d.paint_order(roots.iter().copied());
|
||||
let [first, second] = ordered.as_slice() else { return Err(bad(C, "select two closed paths")) };
|
||||
let (a, b) = (outline_of(d, *first)?, outline_of(d, *second)?);
|
||||
if a.is_point() && b.is_point() {
|
||||
return Err(bad(C, "select two closed paths"));
|
||||
}
|
||||
// A point goes first, so that each line runs from it to where it touches the path.
|
||||
let point = a.is_point() || b.is_point();
|
||||
let (a, b) = if b.is_point() { (b, a) } else { (a, b) };
|
||||
let all = pt::common_tangents(&a, &b).map_err(|_| bad(C, "the two paths have the same outline"))?;
|
||||
let external = all.iter().filter(|t| t.kind == pt::TangentKind::External).count();
|
||||
let keep = |t: &&pt::Tangent| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
// A point's external and internal tangents are the same lines: every kind keeps them.
|
||||
let keep = |t: &&pt::Tangent| {
|
||||
point
|
||||
|| match kinds {
|
||||
"external" => t.kind == pt::TangentKind::External,
|
||||
"internal" => t.kind == pt::TangentKind::Internal,
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let kept: Vec<&pt::Tangent> = all.iter().filter(keep).collect();
|
||||
let count = |kind: pt::TangentKind| kept.iter().filter(|t| t.kind == kind).count();
|
||||
let (external_kept, internal_kept) = (count(pt::TangentKind::External), count(pt::TangentKind::Internal));
|
||||
let (external_kept, internal_kept) = match (point, kinds) {
|
||||
(true, "internal") => (0, kept.len()),
|
||||
(true, _) => (kept.len(), 0),
|
||||
_ => (count(pt::TangentKind::External), count(pt::TangentKind::Internal)),
|
||||
};
|
||||
let lines: Vec<(Point, Point)> = kept.iter().map(|t| (t.from, t.to)).collect();
|
||||
if lines.is_empty() && point {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds it.
|
||||
let warning = EngineError::Other("The point lies inside the path, so it has no tangents".into());
|
||||
return Ok(json!({ "ids": [], "external": 0, "internal": 0, "centerline": null, "warning": warning.to_string() }));
|
||||
}
|
||||
if lines.is_empty() {
|
||||
// Written as `EngineError::Other` so that the i18n message scan finds them. Exactly one
|
||||
// external tangent means one path lies inside the other and touches it there; paths that
|
||||
|
||||
@@ -248,6 +248,84 @@ fn nested_and_overlapping_paths_change_nothing_and_say_why() {
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(1), Some(0)), "{r}");
|
||||
}
|
||||
|
||||
fn point(s: &mut Session, x: f64, y: f64) -> NodeId {
|
||||
id_of(&s.execute("path.create", &json!({"anchors": [{"x": x, "y": y}]})).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_and_an_ellipse_get_the_two_lines_from_the_point_and_the_centerline() {
|
||||
let mut s = session();
|
||||
// The point is drawn after the oval, so it is the upper object; the lines still start at it.
|
||||
let oval = id_of(&s.execute("shape.ellipse", &json!({"x": 260, "y": 170, "width": 80, "height": 60})).unwrap());
|
||||
let dot = point(&mut s, 100.0, 200.0);
|
||||
select(&mut s, &[oval, dot]);
|
||||
let before = steps(&s);
|
||||
let r = s.execute(C, &json!({"centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
assert_eq!(steps(&s), before + 1);
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 3, "two tangents and the centerline");
|
||||
let (p, c) = (Point::new(100.0, 200.0), Point::new(300.0, 200.0));
|
||||
// From (-200, 0) to an ellipse with semi-axes 40 and 30 about the origin: the touching points
|
||||
// are x = -a²/200 = -8, y = ±b √(1 - x²/a²).
|
||||
let y = 30.0 * (1.0f64 - (8.0f64 / 40.0).powi(2)).sqrt();
|
||||
for sy in [1.0, -1.0] {
|
||||
let touch = c + Vec2::new(-8.0, sy * y);
|
||||
assert!(found[..2].iter().any(|(a, b)| near(*a, p) && near(*b, touch)), "{touch:?} in {found:?}");
|
||||
}
|
||||
assert_eq!(r["centerline"], r["ids"][2]);
|
||||
assert!(near(found[2].0, p) && near(found[2].1, c), "{:?}", found[2]);
|
||||
// Every `tangents` value gives the same two lines.
|
||||
for (kind, external, internal) in [("external", 2, 0), ("internal", 0, 2)] {
|
||||
let r = s.execute(C, &json!({"ids": [oval.0, dot.0], "tangents": kind})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(external), Some(internal)), "{kind}: {r}");
|
||||
assert_eq!(lines(&s, &r).len(), 2, "{kind}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_below_the_path_still_starts_the_lines() {
|
||||
let mut s = session();
|
||||
// The point is drawn first, so it is the lower object and needs no swap.
|
||||
let dot = point(&mut s, 100.0, 200.0);
|
||||
let round = circle(&mut s, 300.0, 200.0, 50.0);
|
||||
let r = s.execute(C, &json!({"ids": [round.0, dot.0], "centerline": true})).unwrap();
|
||||
assert_eq!((r["external"].as_u64(), r["internal"].as_u64()), (Some(2), Some(0)), "{r}");
|
||||
let found = lines(&s, &r);
|
||||
assert_eq!(found.len(), 3, "two tangents and the centerline");
|
||||
let p = Point::new(100.0, 200.0);
|
||||
assert!(found.iter().all(|(a, _)| near(*a, p)), "every line starts at the point: {found:?}");
|
||||
// From 200 away to a circle of radius 50, each tangent is √(200² - 50²) long.
|
||||
let length = (200.0f64 * 200.0 - 50.0 * 50.0).sqrt();
|
||||
assert!(found[..2].iter().all(|(a, b)| (a.distance(*b) - length).abs() < 1e-6), "{found:?}");
|
||||
assert!(near(found[2].1, Point::new(300.0, 200.0)), "{:?}", found[2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_on_or_inside_a_path_and_two_points() {
|
||||
let mut s = session();
|
||||
let round = circle(&mut s, 200.0, 200.0, 50.0);
|
||||
// On the circle: one line, centered on the point and as long as the circle is wide.
|
||||
let on = point(&mut s, 250.0, 200.0);
|
||||
let r = s.execute(C, &json!({"ids": [round.0, on.0]})).unwrap();
|
||||
assert_eq!(r["external"].as_u64(), Some(1), "{r}");
|
||||
let (p, q) = lines(&s, &r)[0];
|
||||
assert!((p.x - 250.0).abs() < 1e-5 && (q.x - 250.0).abs() < 1e-5 && (p.distance(q) - 100.0).abs() < 1e-5, "{p:?} {q:?}");
|
||||
// Inside: nothing changes, and the warning says why.
|
||||
let inside = point(&mut s, 210.0, 190.0);
|
||||
let before = (steps(&s), s.doc().unwrap().doc.node_count());
|
||||
let r = s.execute(C, &json!({"ids": [round.0, inside.0], "centerline": true})).unwrap();
|
||||
assert_eq!(r["ids"], json!([]));
|
||||
assert!(r["warning"].as_str().unwrap().contains("point lies inside the path"), "{r}");
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), before, "nothing changes");
|
||||
// Two points, or a point and an open path, are refused.
|
||||
let err = |s: &mut Session, p: Value| s.execute(C, &p).unwrap_err().to_string();
|
||||
assert!(err(&mut s, json!({"ids": [on.0, inside.0]})).contains("select two closed paths"));
|
||||
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 50, "y": 0}, {"x": 50, "y": 50}]})).unwrap());
|
||||
assert!(err(&mut s, json!({"ids": [open.0, on.0]})).contains("open"));
|
||||
assert_eq!((steps(&s), s.doc().unwrap().doc.node_count()), (before.0 + 1, before.1 + 1), "only the open path was added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_selections_and_params_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -172,6 +172,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
|
||||
BuiltinBrushLibrary { id: "ink-and-wash", name: "Ink and Wash", make: ink_and_wash },
|
||||
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
|
||||
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
|
||||
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
@@ -374,6 +375,47 @@ fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, o
|
||||
Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) }
|
||||
}
|
||||
|
||||
/// Pressure Sensitive: four original marks whose art width or nib size responds to recorded pen
|
||||
/// pressure. Mouse paths keep the engine's neutral middle-pressure rendering.
|
||||
fn pressure_sensitive() -> BrushLibrary {
|
||||
let flex = black(band(100.0, 5.0, 48, |x| 0.5 * (x / 100.0 * std::f64::consts::TAU).sin()));
|
||||
let pulse = group(vec![
|
||||
black(band(100.0, 2.8, 64, |x| 1.4 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
|
||||
black(shapes::ellipse(Rect::new(46.0, -2.2, 54.0, 2.2))),
|
||||
]);
|
||||
let art_pressure = |name: &str, art: Node, light: f64, heavy: f64| Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Art(ArtBrush {
|
||||
art,
|
||||
width: light,
|
||||
width_mode: Some(Variation::Pressure),
|
||||
width_max: Some(heavy),
|
||||
colorization: Colorization::Tints,
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
let nib_pressure = |name: &str, angle: f64, roundness: f64, size: f64, variation: f64| Brush {
|
||||
name: name.into(),
|
||||
kind: BrushKind::Calligraphic(Calligraphic {
|
||||
angle,
|
||||
roundness,
|
||||
size,
|
||||
variation: [0.0, 0.0, variation],
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
|
||||
}),
|
||||
};
|
||||
built(
|
||||
"Pressure Sensitive",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
art_pressure("Flex Ribbon", flex, 35.0, 250.0),
|
||||
art_pressure("Pulse Stroke", pulse, 45.0, 280.0),
|
||||
nib_pressure("Round Flow", 0.0, 100.0, 7.0, 5.0),
|
||||
nib_pressure("Chisel Flow", 35.0, 25.0, 9.0, 7.0),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for
|
||||
/// blending and texture.
|
||||
fn bristle_brushes() -> BrushLibrary {
|
||||
|
||||
@@ -211,7 +211,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Symbol…",
|
||||
[],
|
||||
None,
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
"{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}",
|
||||
has_selection,
|
||||
symbol_new
|
||||
),
|
||||
|
||||
@@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let nine = nine_slice_param(p, C, None)?.flatten();
|
||||
let dynamic = type_param(p, C)?.unwrap_or(false);
|
||||
let pixel = pixel_grid_param(p, C)?.unwrap_or(false);
|
||||
// `keepArt` leaves the art as ordinary art instead of replacing it with an instance.
|
||||
let keep_art = switch_or(p, "keepArt", false, C)?;
|
||||
let iso = s.doc()?.isolation;
|
||||
// Keep the art where it was: the geometric centre stays at `c`, whatever the registration is.
|
||||
let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg);
|
||||
let id = s.edit("New Symbol", |d, sel| {
|
||||
@@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
d.set_symbol_export_type(&name, export);
|
||||
d.set_symbol_nine_slice(&name, nine);
|
||||
d.set_symbol_pixel_aligned(&name, pixel);
|
||||
if keep_art {
|
||||
// The art stays where it is and stays selected, apart from art that is hidden or
|
||||
// locked, in a hidden or locked group or layer, or on a locked artboard.
|
||||
let locks = d.locked_artboards();
|
||||
sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i)));
|
||||
return Ok(None);
|
||||
}
|
||||
let id = instance_in_place(d, &ids, &name, place)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
Ok(Some(id))
|
||||
})?;
|
||||
Ok(json!({
|
||||
"name": name,
|
||||
"id": id.0,
|
||||
"id": id.map(|i| i.0),
|
||||
"registration": reg.0,
|
||||
"exportType": export.id(),
|
||||
"nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value),
|
||||
|
||||
@@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::dimension::{
|
||||
ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition,
|
||||
};
|
||||
use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
|
||||
LineType::Solid => None,
|
||||
};
|
||||
if arrows {
|
||||
let head = match o.arrow_style {
|
||||
ArrowStyle::Filled => Some(Arrowhead::Triangle),
|
||||
ArrowStyle::Open => Some(Arrowhead::TriangleOpen),
|
||||
ArrowStyle::Tick => Some(Arrowhead::Slash),
|
||||
ArrowStyle::None => None,
|
||||
};
|
||||
let head = o.arrow_style.arrowhead();
|
||||
st.start_arrow = head.clone();
|
||||
st.end_arrow = head;
|
||||
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
|
||||
|
||||
@@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p
|
||||
}
|
||||
|
||||
/// Does a file of a document with `artboards` artboards, written in format `format` with options
|
||||
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
|
||||
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
|
||||
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates,
|
||||
/// EPS files and the files of an exporter plug-in's format (`plugin.<id>`, whose plug-in is given
|
||||
/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
|
||||
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
|
||||
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
|
||||
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
|
||||
@@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards
|
||||
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
|
||||
match format {
|
||||
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
|
||||
_ if vectorcraft_plugins::export::plugin_id(format).is_some() => true,
|
||||
"ai" | "ait" => {
|
||||
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
|
||||
!legacy && !(format == "ai" && art_page()) && every_artboard()
|
||||
@@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu
|
||||
|
||||
/// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`:
|
||||
/// always, unless read roots are in force, the file carries the native document (a native file or
|
||||
/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as
|
||||
/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter
|
||||
/// plug-in's file, as
|
||||
/// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file
|
||||
/// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the
|
||||
/// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be
|
||||
|
||||
@@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
|
||||
/// The file exporter plug-in `plugin` writes of `doc` in its format `f`
|
||||
/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON
|
||||
/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else
|
||||
/// one named after the document) with that path's extension when the plug-in lists it, else its
|
||||
/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
|
||||
/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots
|
||||
/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path`
|
||||
/// names (else one named after the document) with that path's extension when the plug-in lists it,
|
||||
/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind).
|
||||
fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
use vectorcraft_plugins::{Error, export};
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let doc = doc.without_edit_modes();
|
||||
let doc = &*super::access::with_readable_settings_folder(&doc);
|
||||
let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let path = p.get("path").and_then(Value::as_str);
|
||||
let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e));
|
||||
|
||||
@@ -532,6 +532,24 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
|
||||
super::typecmd::export_overflow_warning(&overflow)
|
||||
}
|
||||
|
||||
/// The objects behind production findings. Resource art points to its first visible owner on
|
||||
/// the canvas, so a finding can be located without selecting an id outside the layer tree.
|
||||
#[derive(Default)]
|
||||
pub(super) struct PreflightType {
|
||||
pub fonts: BTreeMap<UsedFont, BTreeSet<NodeId>>,
|
||||
pub overflow: BTreeSet<NodeId>,
|
||||
pub images: BTreeMap<NodeId, NodeId>,
|
||||
}
|
||||
|
||||
pub(super) fn preflight_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> PreflightType {
|
||||
let mut walk = Printed::new(d);
|
||||
walk.preflight = Some(PreflightType::default());
|
||||
for l in layers {
|
||||
walk.node(l, Some(areas));
|
||||
}
|
||||
walk.preflight.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The walk of [`printed_type`].
|
||||
struct Printed<'a> {
|
||||
d: &'a Document,
|
||||
@@ -546,13 +564,25 @@ struct Printed<'a> {
|
||||
/// The symbols and patterns whose art was walked.
|
||||
symbols: BTreeSet<String>,
|
||||
patterns: BTreeSet<String>,
|
||||
preflight: Option<PreflightType>,
|
||||
owner: Option<NodeId>,
|
||||
}
|
||||
|
||||
impl<'a> Printed<'a> {
|
||||
/// A walk of `d` among its own objects, nothing found yet.
|
||||
fn new(d: &'a Document) -> Self {
|
||||
let boxes = d.symbol_boxes();
|
||||
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
|
||||
Self {
|
||||
d,
|
||||
boxes,
|
||||
own: true,
|
||||
fonts: BTreeSet::new(),
|
||||
overflow: BTreeSet::new(),
|
||||
symbols: BTreeSet::new(),
|
||||
patterns: BTreeSet::new(),
|
||||
preflight: None,
|
||||
owner: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
|
||||
@@ -560,6 +590,15 @@ impl<'a> Printed<'a> {
|
||||
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
|
||||
/// object) all of them but those outside the clipping path of a clip group.
|
||||
fn node(&mut self, n: &Node, areas: Option<&[Rect]>) {
|
||||
let previous = self.owner;
|
||||
if self.own {
|
||||
self.owner = Some(n.id);
|
||||
}
|
||||
self.node_contents(n, areas);
|
||||
self.owner = previous;
|
||||
}
|
||||
|
||||
fn node_contents(&mut self, n: &Node, areas: Option<&[Rect]>) {
|
||||
if !n.visible || matches!(n.kind, NodeKind::Layer { template: true, .. }) {
|
||||
return;
|
||||
}
|
||||
@@ -571,6 +610,14 @@ impl<'a> Printed<'a> {
|
||||
&& !open
|
||||
&& !self.meets(n, a)
|
||||
{
|
||||
// An entirely overset frame paints nothing, but is still a delivery problem. Keep
|
||||
// the export walk unchanged; only preflight checks the frame itself in this case.
|
||||
if let (Some(p), Some(owner), NodeKind::Text(t)) = (&mut self.preflight, self.owner, &n.kind)
|
||||
&& n.geometric_bounds().is_some_and(|b| a.iter().any(|r| r.intersect(b).area() > 0.0 || r.contains_rect(b)))
|
||||
&& vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).overflow
|
||||
{
|
||||
p.overflow.insert(owner);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The art that its opacity mask, pattern paints and brushed strokes draw.
|
||||
@@ -616,16 +663,33 @@ impl<'a> Printed<'a> {
|
||||
if overflows && self.own {
|
||||
self.overflow.insert(n.id);
|
||||
}
|
||||
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
p.overflow.insert(owner);
|
||||
}
|
||||
for r in runs {
|
||||
self.fonts.extend(run_fonts(r));
|
||||
let fonts = run_fonts(r);
|
||||
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
for font in &fonts {
|
||||
p.fonts.entry(font.clone()).or_default().insert(owner);
|
||||
}
|
||||
}
|
||||
self.fonts.extend(fonts);
|
||||
// Inline graphics draw their symbols' art.
|
||||
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
|
||||
self.symbol(&art.symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
NodeKind::Image(_) => {
|
||||
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
p.images.entry(n.id).or_insert(owner);
|
||||
}
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, .. } => self.symbol(symbol),
|
||||
NodeKind::PlacedDocument(p) => {
|
||||
if let (Some(report), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
report.images.entry(n.id).or_insert(owner);
|
||||
}
|
||||
for art in p.art(n) {
|
||||
self.art(&art);
|
||||
}
|
||||
|
||||
@@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{
|
||||
};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
pub use transform::{reflect_axis, scale_factors, shear_tangent};
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shear…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
shear
|
||||
),
|
||||
|
||||
@@ -369,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let sx = f64_req(p, "sx", "object.scale")? / 100.0;
|
||||
let sy = f64_or(p, "sy", sx * 100.0) / 100.0;
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err(bad("object.scale", "scale must be non-zero"));
|
||||
}
|
||||
let sx = f64_req(p, "sx", "object.scale")?;
|
||||
let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?;
|
||||
let frame = basis_frame(s, p, "object.scale", &ids)?;
|
||||
apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true)
|
||||
}
|
||||
|
||||
/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when
|
||||
/// either factor is 0.
|
||||
pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> {
|
||||
let (sx, sy) = (sx / 100.0, sy / 100.0);
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err("scale must be non-zero".into());
|
||||
}
|
||||
Ok((sx, sy))
|
||||
}
|
||||
|
||||
/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param:
|
||||
/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset
|
||||
/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with
|
||||
@@ -402,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
// A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page.
|
||||
let named = match p.get("axis") {
|
||||
Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)),
|
||||
Some(Value::Number(_)) => None,
|
||||
None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")));
|
||||
}
|
||||
};
|
||||
let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?;
|
||||
let m = match named {
|
||||
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
|
||||
None => {
|
||||
@@ -423,12 +421,47 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
apply_transform(s, "Reflect", ids, about(o, m), p, true)
|
||||
}
|
||||
|
||||
/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis
|
||||
/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle,
|
||||
/// which is a line on the page; or the error for any other value.
|
||||
pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result<Option<Affine>, String> {
|
||||
match axis {
|
||||
Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))),
|
||||
Some(Value::Number(_)) => Ok(None),
|
||||
None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
|
||||
Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))),
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It
|
||||
/// is far above the rounding error of an angle up to 359° and below any angle a field shows.
|
||||
const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An
|
||||
/// angle outside -359 to 359, or ±90 or ±270, is an error.
|
||||
pub fn shear_tangent(angle: f64) -> std::result::Result<f64, String> {
|
||||
if !(-359.0..=359.0).contains(&angle) {
|
||||
return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}"));
|
||||
}
|
||||
// ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded.
|
||||
let flat = angle.rem_euclid(180.0);
|
||||
if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE {
|
||||
return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"));
|
||||
}
|
||||
// 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0.
|
||||
Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() })
|
||||
}
|
||||
|
||||
pub(super) fn shear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["angle"], "object.shear")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?;
|
||||
let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan();
|
||||
let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]);
|
||||
// A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal.
|
||||
let m = match p.get("axis") {
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Package",
|
||||
[],
|
||||
None,
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied",
|
||||
has_doc,
|
||||
package
|
||||
)]
|
||||
@@ -113,27 +113,65 @@ thread_local! {
|
||||
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
|
||||
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
|
||||
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
if super::place::document::is_native(name, bytes) {
|
||||
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
|
||||
}
|
||||
let data =
|
||||
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
|
||||
vectorcraft_format::load(&data?).ok()
|
||||
/// The native document a linked file is or carries ([`carried_document`]).
|
||||
enum Carried {
|
||||
/// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file
|
||||
/// without editing data.
|
||||
Absent,
|
||||
/// The native document, read.
|
||||
Readable(Box<Document>),
|
||||
/// The file is a native document, or carries one, that can't be read: a damaged native file,
|
||||
/// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF
|
||||
/// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file
|
||||
/// whose attachments are too many to search to their end, or editing data that doesn't read as
|
||||
/// a native document.
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
|
||||
/// a PDF, `.ai` or EPS file.
|
||||
fn carried_document(name: &str, bytes: &[u8]) -> Carried {
|
||||
let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d)));
|
||||
if super::place::document::is_native(name, bytes) {
|
||||
return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc)));
|
||||
}
|
||||
if super::place::document::is_pdf(name, bytes) {
|
||||
// A PDF that can't be opened may carry editing data all the same.
|
||||
return match vectorcraft_pdf::open_pdf(bytes, None) {
|
||||
// Attachments left unsearched may list another editing file, which can't be checked.
|
||||
Ok(opened) if opened.editing_search_cut() => Carried::Unreadable,
|
||||
// An editing file listed whose data can't be resolved can't be checked either.
|
||||
Ok(opened) => match opened.editing() {
|
||||
Some(e) => read(&e.data),
|
||||
None if opened.has_editing_file() => Carried::Unreadable,
|
||||
None => Carried::Absent,
|
||||
},
|
||||
Err(_) => Carried::Unreadable,
|
||||
};
|
||||
}
|
||||
if !vectorcraft_eps::has_native(bytes) {
|
||||
return Carried::Absent;
|
||||
}
|
||||
vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data))
|
||||
}
|
||||
|
||||
/// The error for a linked file the package would copy whose native document can't be read to
|
||||
/// check the files and folders it names against the read roots.
|
||||
const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots";
|
||||
|
||||
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
|
||||
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
|
||||
/// relative path taken from the file's folder): the copy would name it.
|
||||
/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file
|
||||
/// outside them (a relative path taken from the file's folder): the copy would name it. A file
|
||||
/// whose native document can't be read is refused, as its links can't be checked. The error names
|
||||
/// no file or folder.
|
||||
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
|
||||
None => Ok(()),
|
||||
Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
|
||||
Carried::Unreadable => Err(bad(C, UNREADABLE)),
|
||||
Carried::Absent => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,7 +188,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
match carried_document(name, bytes) {
|
||||
Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)),
|
||||
Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => {
|
||||
Err(bad(C, FOLDER_OUTSIDE))
|
||||
}
|
||||
Carried::Unreadable => Err(bad(C, UNREADABLE)),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -498,6 +539,9 @@ pub struct Package {
|
||||
root: Option<PathBuf>,
|
||||
info: Option<String>,
|
||||
doc: std::sync::Arc<Document>,
|
||||
/// The read roots in force where the package was prepared: [`Package::write`] collects under
|
||||
/// them.
|
||||
scope: crate::file_access::ScopeHandle,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -544,21 +588,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
let doc = s.doc()?.doc.clone();
|
||||
let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc };
|
||||
let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone());
|
||||
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc })
|
||||
let scope = crate::file_access::ScopeHandle::capture();
|
||||
Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope })
|
||||
}
|
||||
|
||||
impl Package {
|
||||
/// Collect the linked files and fonts and write the package's files with `write` into
|
||||
/// `folder/name`, making its folders first, or into the zip without a folder → the reply of
|
||||
/// `file.package`.
|
||||
/// `file.package`, with the read roots in force where it was prepared, on any thread.
|
||||
pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
collect_and_write(self, write)
|
||||
self.scope.clone().run(|| collect_and_write(self, write))
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Package::write`].
|
||||
fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package;
|
||||
let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package;
|
||||
let mut doc = (*original).clone();
|
||||
let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION);
|
||||
let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) };
|
||||
|
||||
@@ -274,8 +274,9 @@ impl DocState {
|
||||
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
|
||||
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
|
||||
/// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of
|
||||
/// each selected object's own stack is compared. One walk of the document, so callers that ask
|
||||
/// every frame cache it by revision.
|
||||
/// each selected object's own stack is compared. The selected objects are found through the id
|
||||
/// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk
|
||||
/// of the document, so callers that ask every frame cache it by revision.
|
||||
pub fn proxy_mixed(&self, item: Option<usize>) -> (bool, bool) {
|
||||
self.proxy_mixed_with(item, &[])
|
||||
}
|
||||
@@ -290,15 +291,17 @@ impl DocState {
|
||||
if self.selection.symbol_part.is_some() {
|
||||
return (false, false);
|
||||
}
|
||||
let ids: std::collections::HashSet<NodeId> = self.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
self.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
});
|
||||
// Looking the first object up builds the id cache when there is none.
|
||||
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
|
||||
// place it appears.
|
||||
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
|
||||
#[cfg(test)]
|
||||
tests::note_gathered();
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
@@ -1323,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.execute("object.setProps", &Value::Object(q))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the
|
||||
//! id cache: it answers as a walk of the whole document does, and with a few objects selected it
|
||||
//! reads only those.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{painted, picked_colors, proxy_paint, same_in_proxy};
|
||||
use crate::{DocState, Session};
|
||||
|
||||
thread_local! {
|
||||
/// [`gathered`] of this thread.
|
||||
static GATHERED: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones.
|
||||
pub(super) fn note_gathered() {
|
||||
GATHERED.set(GATHERED.get() + 1);
|
||||
}
|
||||
|
||||
/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones.
|
||||
fn gathered() -> u64 {
|
||||
GATHERED.get()
|
||||
}
|
||||
|
||||
/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document.
|
||||
fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -> (bool, bool) {
|
||||
if st.selection.is_empty() {
|
||||
return (false, false);
|
||||
}
|
||||
if st.selection.symbol_part.is_some() {
|
||||
return (false, false);
|
||||
}
|
||||
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
|
||||
let (mut selected, mut nodes) = (vec![], vec![]);
|
||||
st.doc.walk(|n| {
|
||||
if ids.contains(&n.id) {
|
||||
selected.push(n);
|
||||
painted(n, true, &mut nodes);
|
||||
}
|
||||
});
|
||||
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
|
||||
let differ = |stroke: bool| {
|
||||
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
|
||||
let set = if item.is_some() { &selected } else { &nodes };
|
||||
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
|
||||
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
|
||||
c => c.into_iter().map(Paint::solid).collect(),
|
||||
});
|
||||
let Some(p0) = paints.next() else { return false };
|
||||
paints.any(|p| !same_in_proxy(&p0, &p))
|
||||
};
|
||||
(differ(false), differ(true))
|
||||
}
|
||||
|
||||
/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item
|
||||
/// and with and without `points`, with the id cache built and without it.
|
||||
fn agree(st: &DocState, points: &[(NodeId, Vec<usize>)], what: &str) {
|
||||
for cold in [true, false] {
|
||||
if cold {
|
||||
st.doc.drop_lookup_cache();
|
||||
}
|
||||
for item in [None, Some(0), Some(1), Some(2), Some(3)] {
|
||||
for points in [points, &[]] {
|
||||
assert_eq!(
|
||||
st.proxy_mixed_with(item, points),
|
||||
walked(st, item, points),
|
||||
"{what}: item {item:?}, {} picked points, cold cache {cold}",
|
||||
points.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn id_of(v: &serde_json::Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId {
|
||||
let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap());
|
||||
s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object,
|
||||
/// different fills or strokes, a group with different contents, a group with one of its objects,
|
||||
/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a
|
||||
/// gradient mesh with points picked beside another object, ids not in the document and an id that
|
||||
/// appears twice (a damaged file) with different paints.
|
||||
#[test]
|
||||
fn the_question_marks_match_a_walk_of_the_document() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let a = rect(&mut s, 10.0, "#ff0000", "#000000");
|
||||
let b = rect(&mut s, 40.0, "#0000ff", "#000000");
|
||||
let c = rect(&mut s, 70.0, "#ff0000", "#00ff00");
|
||||
// Two fills: [Fill, Stroke, Fill].
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
s.execute("appearance.addFill", &json!({})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap();
|
||||
let e = rect(&mut s, 100.0, "#ff0000", "#000000");
|
||||
let f = rect(&mut s, 130.0, "#00ff00", "#000000");
|
||||
let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap());
|
||||
let mesh = rect(&mut s, 160.0, "#ff0000", "#000000");
|
||||
s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap();
|
||||
let hidden = rect(&mut s, 190.0, "#0000ff", "#000000");
|
||||
s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap();
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let h = rect(&mut s, 220.0, "#ff0000", "#000000");
|
||||
let missing = NodeId(999_999);
|
||||
let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") };
|
||||
let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1));
|
||||
s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap();
|
||||
let points = vec![(mesh, vec![p00, p01])];
|
||||
let points_alike = vec![(mesh, vec![p01, p11])];
|
||||
|
||||
let selections = [
|
||||
vec![a],
|
||||
vec![a, b],
|
||||
vec![b, a],
|
||||
vec![a, h],
|
||||
vec![g],
|
||||
vec![g, e],
|
||||
vec![e, g],
|
||||
vec![f, e],
|
||||
vec![c],
|
||||
vec![c, a],
|
||||
vec![a, c],
|
||||
vec![mesh],
|
||||
vec![mesh, a],
|
||||
vec![a, mesh, h],
|
||||
vec![hidden],
|
||||
vec![hidden, b],
|
||||
vec![missing],
|
||||
vec![missing, a],
|
||||
vec![a, missing, b],
|
||||
vec![a, a],
|
||||
];
|
||||
let check = |s: &mut Session, what: &str| {
|
||||
for sel in &selections {
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
let st = s.active().unwrap();
|
||||
agree(st, &points, &format!("{what}: {sel:?}"));
|
||||
agree(st, &points_alike, &format!("{what}: {sel:?}, alike points"));
|
||||
}
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
agree(s.active().unwrap(), &points, &format!("{what}: Select All"));
|
||||
};
|
||||
check(&mut s, "unique ids");
|
||||
|
||||
// A second node with a's id and another fill, at the end of the tree.
|
||||
let st = s.active_mut().unwrap();
|
||||
let mut copy = st.doc.node(a).unwrap().clone();
|
||||
copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
|
||||
let doc = Arc::make_mut(&mut st.doc);
|
||||
let last = doc.layers.len() - 1;
|
||||
Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy));
|
||||
doc.drop_lookup_cache();
|
||||
check(&mut s, "a repeated id");
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = vec![a];
|
||||
assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill");
|
||||
}
|
||||
|
||||
/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other
|
||||
/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order.
|
||||
fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec<NodeId>) {
|
||||
let mut d = Document::new(612.0, 792.0);
|
||||
d.layers.clear();
|
||||
let mut rects = vec![];
|
||||
for l in 0..layers {
|
||||
let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0));
|
||||
for _ in 0..groups {
|
||||
let children = (0..per_group)
|
||||
.map(|_| {
|
||||
let id = d.alloc_id();
|
||||
let mut ap = Appearance::default_art();
|
||||
let red = rects.len() % 2 == 0;
|
||||
ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) }));
|
||||
rects.push(id);
|
||||
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap))
|
||||
})
|
||||
.collect();
|
||||
let group = Node::group(d.alloc_id(), children);
|
||||
layer.children_mut().unwrap().push(Arc::new(group));
|
||||
}
|
||||
d.layers.push(Arc::new(layer));
|
||||
}
|
||||
(d, rects)
|
||||
}
|
||||
|
||||
fn state(doc: Document) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap();
|
||||
s.active_mut().unwrap().doc = Arc::new(doc);
|
||||
s
|
||||
}
|
||||
|
||||
/// With one object selected, the "?" reads only that object, not every node of the document, and
|
||||
/// does not walk the tree once the id cache is built; with every object selected it walks the tree
|
||||
/// once.
|
||||
#[test]
|
||||
fn the_question_marks_read_only_the_selected_objects() {
|
||||
let (doc, rects) = big(2, 40, 25);
|
||||
let mut s = state(doc);
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = vec![rects[777]];
|
||||
assert_eq!(st.proxy_mixed(None), (false, false));
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (false, false));
|
||||
assert_eq!(gathered() - read, 1, "only the selected object is read");
|
||||
assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers");
|
||||
|
||||
st.selection.objects = vec![rects[3], rects[1500]];
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (true, false));
|
||||
assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0));
|
||||
|
||||
st.selection.objects = rects.clone();
|
||||
let (read, walks) = (gathered(), vectorcraft_doc::tree_walks());
|
||||
assert_eq!(st.proxy_mixed(None), (true, false));
|
||||
assert_eq!(gathered() - read, rects.len() as u64);
|
||||
assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection");
|
||||
}
|
||||
|
||||
/// Random selections of a document with nested groups answer as a walk does.
|
||||
#[test]
|
||||
fn random_selections_match_a_walk_of_the_document() {
|
||||
let (doc, rects) = big(3, 12, 6);
|
||||
let mut s = state(doc);
|
||||
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
|
||||
let layers: Vec<NodeId> = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect();
|
||||
let all: Vec<NodeId> = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect();
|
||||
let mut r = 0x2545_f491_4f6c_dd1d_u64;
|
||||
let mut next = |n: usize| {
|
||||
r ^= r << 13;
|
||||
r ^= r >> 7;
|
||||
r ^= r << 17;
|
||||
(r % n as u64) as usize
|
||||
};
|
||||
for round in 0..200 {
|
||||
let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 });
|
||||
let sel: Vec<NodeId> = (0..count).map(|_| all[next(all.len())]).collect();
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere.
|
||||
fn thread_cpu() -> Option<std::time::Duration> {
|
||||
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?;
|
||||
stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos)
|
||||
}
|
||||
|
||||
/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock.
|
||||
fn time(f: impl FnOnce()) -> std::time::Duration {
|
||||
match thread_cpu() {
|
||||
Some(before) => {
|
||||
f();
|
||||
thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before))
|
||||
}
|
||||
None => {
|
||||
let start = std::time::Instant::now();
|
||||
f();
|
||||
start.elapsed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on
|
||||
/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "timing; run by hand"]
|
||||
fn proxy_mixed_timing() {
|
||||
let (doc, rects) = big(5, 100, 100);
|
||||
let mut s = state(doc);
|
||||
let groups: Vec<NodeId> = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect();
|
||||
let cases: [(&str, Vec<NodeId>); 5] = [
|
||||
("1 object", vec![rects[25_000]]),
|
||||
("2 objects, different fills", vec![rects[10], rects[40_001]]),
|
||||
("a group of 100", vec![groups[250]]),
|
||||
("all 500 groups", groups.clone()),
|
||||
("all 50,000 objects", rects.clone()),
|
||||
];
|
||||
const CALLS: usize = 200;
|
||||
let median = |mut v: Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" });
|
||||
println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |");
|
||||
println!("|---|---|---|---|---|");
|
||||
for (name, sel) in &cases {
|
||||
for cold in [false, true] {
|
||||
let st = s.active_mut().unwrap();
|
||||
st.selection.objects = sel.clone();
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}");
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
let calls = if cold { CALLS / 10 } else { CALLS };
|
||||
for _ in 0..7 {
|
||||
for (times, use_walk) in [(&mut old, true), (&mut new, false)] {
|
||||
let d = time(|| {
|
||||
for _ in 0..calls {
|
||||
if cold {
|
||||
st.doc.drop_lookup_cache();
|
||||
}
|
||||
std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) });
|
||||
}
|
||||
});
|
||||
times.push(d.as_secs_f64() * 1e6 / calls as f64);
|
||||
}
|
||||
}
|
||||
let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::<Vec<_>>().join(" ");
|
||||
println!(
|
||||
"| {name} | {} | {:.1} | {:.1} | {} / {} |",
|
||||
if cold { "dropped before each call" } else { "built" },
|
||||
median(old.clone()),
|
||||
median(new.clone()),
|
||||
runs(&old),
|
||||
runs(&new)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1152,6 +1152,13 @@ pub fn read_info(p: &Value) -> Result<Value> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Resolution at a placed image's transform: 72 points per inch over each pixel axis.
|
||||
pub(super) fn effective_ppi(xf: Affine) -> [f64; 2] {
|
||||
let [a, b, c, d, ..] = xf.as_coeffs();
|
||||
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
|
||||
[ppi(a, b), ppi(c, d)]
|
||||
}
|
||||
|
||||
pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "image.info";
|
||||
let st = s.doc()?;
|
||||
@@ -1165,9 +1172,6 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let doc = super::links::with_brush_art(&st.doc);
|
||||
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
|
||||
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
|
||||
// Effective resolution: 72 pt per inch over the points one pixel spans along each axis.
|
||||
let [a, b, c, d, ..] = im.xf.as_coeffs();
|
||||
let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l);
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
|
||||
let doc_path = super::links::LinkBase::of(st).doc;
|
||||
@@ -1179,7 +1183,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
|
||||
"pixelWidth": im.width,
|
||||
"pixelHeight": im.height,
|
||||
"ppi": [ppi(a, b), ppi(c, d)],
|
||||
"ppi": effective_ppi(im.xf),
|
||||
"width": size.width(),
|
||||
"height": size.height(),
|
||||
}))
|
||||
|
||||
@@ -161,6 +161,8 @@ pub struct FilterRun {
|
||||
parent: Option<NodeId>,
|
||||
/// The document it was made from, and that document's revision then.
|
||||
document: (u64, u64),
|
||||
/// The plug-in's limits with the Plug-in Instruction Budget in force when it was made.
|
||||
limits: vectorcraft_plugins::Limits,
|
||||
}
|
||||
|
||||
/// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run
|
||||
@@ -245,7 +247,11 @@ impl FilterRun {
|
||||
let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len());
|
||||
let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?;
|
||||
let document = (st.uid, st.revision);
|
||||
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document })
|
||||
let limits = match s.prefs.plugin_instruction_budget {
|
||||
crate::PluginBudget::Normal => plugin.limits().clone(),
|
||||
crate::PluginBudget::Large => plugin.large_limits(),
|
||||
};
|
||||
Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits })
|
||||
}
|
||||
|
||||
/// The plug-in, for its name and budget.
|
||||
@@ -274,7 +280,13 @@ impl FilterRun {
|
||||
/// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between
|
||||
/// two slices of its budget.
|
||||
pub fn run(&self) -> Result<Vec<u8>> {
|
||||
self.plugin.run(&self.input, &self.params).map_err(err)
|
||||
self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err)
|
||||
}
|
||||
|
||||
/// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when
|
||||
/// it was made.
|
||||
pub fn limits(&self) -> &vectorcraft_plugins::Limits {
|
||||
&self.limits
|
||||
}
|
||||
|
||||
/// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the
|
||||
@@ -289,7 +301,7 @@ impl FilterRun {
|
||||
let may = self.plugin.manifest().permissions();
|
||||
let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite));
|
||||
let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args);
|
||||
self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err)
|
||||
self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err)
|
||||
}
|
||||
|
||||
/// Runs a plug-in that calls commands and applies its output: the calls and the output are one
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Production preflight: the existing output-aware type walk, linked-file probes and image
|
||||
//! resolution calculation, returned as findings that the interface can locate and recheck.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, number_or, text_param};
|
||||
|
||||
const COMMAND: &str = "document.preflight";
|
||||
const KINDS: [&str; 4] = ["fonts", "text", "links", "resolution"];
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "document.preflight",
|
||||
"Production Preflight",
|
||||
[],
|
||||
None,
|
||||
"{output?: pdf|print|screen (pdf), minPpi?: 1..9600 (300, or 96 for screen), artboards?: [index, …] (0-based whole numbers; default all)} check the selected output without writing files or editing the document; print reuses the saved print settings with these artboards, pdf and screen check visible artwork on these artboards. Reuses output-aware font and overflow checks, Links file status and image.info effective resolution. Resource findings locate their first visible canvas owner; resolution inside resource art is reported as not checked because its placed scale can differ. → {output, minPpi, artboards, checks: [{kind: fonts|text|links|resolution, status: passed|failed|notChecked, count, notChecked}], findings: [{kind, code, ids (canvas objects), name, detail?, sourceId?, effectivePpi?, threshold?}], outputWarnings, limitations}; a pass covers only these checks, not certification of a produced file",
|
||||
has_doc,
|
||||
check
|
||||
)]
|
||||
}
|
||||
|
||||
fn check(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let output = text_param(p, "output", COMMAND)?.unwrap_or("pdf");
|
||||
if !matches!(output, "pdf" | "print" | "screen") {
|
||||
return Err(bad(COMMAND, "output must be pdf, print or screen"));
|
||||
}
|
||||
let min_ppi = number_or(p, "minPpi", if output == "screen" { 96.0 } else { 300.0 }, COMMAND)?;
|
||||
if !min_ppi.is_finite() || !(1.0..=9600.0).contains(&min_ppi) {
|
||||
return Err(bad(COMMAND, "minPpi must be from 1 to 9600"));
|
||||
}
|
||||
let indices = match p.get("artboards").filter(|v| !v.is_null()) {
|
||||
Some(v) => super::panelcmds::listed_artboards(&s.doc()?.doc, v, "artboards", COMMAND)?,
|
||||
None => (0..s.doc()?.doc.artboards.len()).collect(),
|
||||
};
|
||||
let context = if output == "print" {
|
||||
super::print::preflight_context(s, &indices)?
|
||||
} else {
|
||||
let doc = &s.doc()?.doc;
|
||||
let pages = indices.iter().filter_map(|i| doc.artboards.get(*i).map(|a| (a.rect, vectorcraft_geom::Affine::IDENTITY))).collect();
|
||||
super::print::PreflightContext { layers: vectorcraft_pdf::PrintLayers::Visible, pages, warnings: vec![] }
|
||||
};
|
||||
let areas = context.pages.iter().map(|(r, _)| *r).collect::<Vec<_>>();
|
||||
let st = s.doc()?;
|
||||
let doc = st.doc.with_placed_art();
|
||||
let mut layers = doc.layers.clone();
|
||||
vectorcraft_pdf::keep_layers(&mut layers, context.layers);
|
||||
let typed = super::fonts::preflight_type(&doc, &layers, &areas);
|
||||
let statuses = super::links::statuses(st);
|
||||
let mut findings = vec![];
|
||||
let db = FontDb::global();
|
||||
for (font, ids) in typed.fonts {
|
||||
let code = match db.resolve(&font.0, &font.1).map(|(_, m)| m) {
|
||||
None | Some(FontMatch::Missing) => "missingFont",
|
||||
Some(FontMatch::Style) => "substitutedFont",
|
||||
_ => continue,
|
||||
};
|
||||
findings.push(
|
||||
json!({ "kind": "fonts", "code": code, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "name": super::fonts::font_label(&font) }),
|
||||
);
|
||||
}
|
||||
for id in typed.overflow {
|
||||
findings.push(finding("text", "overflow", id, &doc));
|
||||
}
|
||||
let mut resolution_unchecked = 0usize;
|
||||
for (source, owner) in typed.images {
|
||||
if let Some((status, _, _)) = statuses.get(&source) {
|
||||
let code = match status.as_str() {
|
||||
"missing" => Some("missingLink"),
|
||||
"modified" => Some("modifiedLink"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(code) = code {
|
||||
let mut f = finding("links", code, owner, &doc);
|
||||
f["sourceId"] = json!(source.0);
|
||||
findings.push(f);
|
||||
}
|
||||
}
|
||||
// A vector placed document has no single bitmap resolution. Its embedded artwork, and
|
||||
// resources with their own coordinate systems, must never be certified at a local scale.
|
||||
if doc.node(source).is_none() || source != owner {
|
||||
resolution_unchecked += 1;
|
||||
continue;
|
||||
}
|
||||
let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node(source).map(|n| &n.kind) else {
|
||||
resolution_unchecked += 1;
|
||||
continue;
|
||||
};
|
||||
let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n));
|
||||
let ppi = context
|
||||
.pages
|
||||
.iter()
|
||||
.filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0))
|
||||
.map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf))
|
||||
.reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]);
|
||||
let Some(ppi) = ppi else {
|
||||
resolution_unchecked += 1;
|
||||
continue;
|
||||
};
|
||||
// Inverting the placed-size transform can round an exact threshold slightly down.
|
||||
if ppi.iter().any(|n| !n.is_finite() || *n <= 0.0) {
|
||||
resolution_unchecked += 1;
|
||||
} else if ppi.iter().any(|n| *n < min_ppi * (1.0 - 1e-9)) {
|
||||
let mut f = finding("resolution", "lowResolution", owner, &doc);
|
||||
f["effectivePpi"] = json!(ppi);
|
||||
f["threshold"] = json!(min_ppi);
|
||||
findings.push(f);
|
||||
}
|
||||
}
|
||||
let checks = KINDS.map(|kind| {
|
||||
let count = findings.iter().filter(|f| f["kind"] == kind).count();
|
||||
let not_checked = if kind == "resolution" { resolution_unchecked } else { 0 };
|
||||
let status = if count > 0 {
|
||||
"failed"
|
||||
} else if not_checked > 0 {
|
||||
"notChecked"
|
||||
} else {
|
||||
"passed"
|
||||
};
|
||||
json!({ "kind": kind, "status": status, "count": count, "notChecked": not_checked })
|
||||
});
|
||||
Ok(json!({
|
||||
"output": output, "minPpi": min_ppi, "artboards": indices, "checks": checks,
|
||||
"findings": findings, "outputWarnings": context.warnings,
|
||||
"limitations": ["These checks do not certify an exported file.", "Resolution inside symbols, patterns, brushes, opacity masks and placed documents is not checked."]
|
||||
}))
|
||||
}
|
||||
|
||||
fn finding(kind: &str, code: &str, id: NodeId, doc: &vectorcraft_doc::Document) -> Value {
|
||||
json!({ "kind": kind, "code": code, "ids": [id.0], "name": doc.node(id).map(|n| n.display_name()).unwrap_or_else(|| id.0.to_string()) })
|
||||
}
|
||||
@@ -324,6 +324,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text),
|
||||
// Plug-ins & Scratch Disks
|
||||
p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text),
|
||||
// The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input.
|
||||
p!(
|
||||
"pluginInstructionBudget",
|
||||
"Plug-ins & Scratch Disks",
|
||||
"Plug-ins",
|
||||
"Plug-in Instruction Budget",
|
||||
choice(&[("normal", "Normal"), ("large", "Large")])
|
||||
),
|
||||
p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text),
|
||||
p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text),
|
||||
// User Interface
|
||||
|
||||
@@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Reuse the Print dialog's saved settings and page geometry for production preflight, without
|
||||
/// printing, writing a file or duplicating its type warnings.
|
||||
pub(super) struct PreflightContext {
|
||||
pub layers: PrintLayers,
|
||||
pub pages: Vec<(Rect, Affine)>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result<PreflightContext> {
|
||||
let settings =
|
||||
json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::<Vec<_>>().join(",") } });
|
||||
let set = preset_or_saved("document.preflight", s, &s.doc()?.doc, &settings)?;
|
||||
super::printadvanced::flattener("document.preflight", &set, &s.prefs.flattener_presets)?;
|
||||
let mut pv = vectorcraft_pdf::preview(&s.doc()?.doc, &set).map_err(|e| pdf_error("document.preflight", e))?;
|
||||
let pages = pv
|
||||
.sheets
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let to_page = Affine::new(p.transform);
|
||||
on_page(Rect::new(p.area[0], p.area[1], p.area[2], p.area[3]), to_page, (p.width, p.height)).map(|area| (area, to_page))
|
||||
})
|
||||
.collect();
|
||||
pv.warnings.extend(pv.setting_notes);
|
||||
Ok(PreflightContext { layers: set.print_layers, pages, warnings: pv.warnings })
|
||||
}
|
||||
|
||||
/// The parts of the document (document space) that the pages of `pv` print.
|
||||
fn areas(pv: &PrintPreview) -> Vec<Rect> {
|
||||
pv.sheets
|
||||
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Redefine Graphic Style",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
"{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}",
|
||||
has_doc,
|
||||
style_redefine
|
||||
),
|
||||
@@ -489,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value {
|
||||
|
||||
fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "graphicStyle.redefine";
|
||||
let (src, n) = source(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = if n.id == src { src } else { n.id };
|
||||
let i = match str_param(p, "name") {
|
||||
Some(name) => style_index(d, name)?,
|
||||
None => n
|
||||
.extras()
|
||||
.graphic_style
|
||||
.and_then(|id| d.graphic_style_by_id(id))
|
||||
.and_then(|g| d.graphic_style_index(&g.name))
|
||||
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
|
||||
// The style to replace, its new look, and the object that look comes from (none for another style's look).
|
||||
let (i, look, src) = match p.get("from") {
|
||||
Some(from) => {
|
||||
let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?;
|
||||
if p.get("id").is_some() {
|
||||
return Err(bad(cmd, "pass `id` or `from`, not both"));
|
||||
}
|
||||
let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
let (i, j) = (style_index(d, name)?, style_index(d, from)?);
|
||||
// A style dropped on itself, or on a style with the same look, stays as it is.
|
||||
let target = &d.graphic_styles[i];
|
||||
let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() };
|
||||
if i == j || look == *target {
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
(i, look, None)
|
||||
}
|
||||
None => {
|
||||
let (src, n) = source(s, p, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
|
||||
let n = super::appearance::look_holder(d, n);
|
||||
let src = if n.id == src { src } else { n.id };
|
||||
let i = match str_param(p, "name") {
|
||||
Some(name) => style_index(d, name)?,
|
||||
None => n
|
||||
.extras()
|
||||
.graphic_style
|
||||
.and_then(|id| d.graphic_style_by_id(id))
|
||||
.and_then(|g| d.graphic_style_index(&g.name))
|
||||
.ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?,
|
||||
};
|
||||
(i, GraphicStyle::of(String::new(), captured(n), n), Some(src))
|
||||
}
|
||||
};
|
||||
let look = GraphicStyle::of(String::new(), captured(n), n);
|
||||
let name = d.graphic_styles[i].name.clone();
|
||||
let name = s.doc()?.doc.graphic_styles[i].name.clone();
|
||||
let chars = s.prefs.override_char_color;
|
||||
let before = s.doc()?.doc.clone();
|
||||
s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| {
|
||||
@@ -513,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the
|
||||
// source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the
|
||||
// source or as a linked object: the graph draws it again from the design.
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
|
||||
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src);
|
||||
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) =
|
||||
linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old)));
|
||||
set_link(d, &edited, None);
|
||||
@@ -521,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
|
||||
let mut follow_marks = super::graph::series_group_marks(d, &follow);
|
||||
let edited: HashSet<NodeId> = edited.into_iter().collect();
|
||||
follow_marks.retain(|nid| *nid != src && !edited.contains(nid));
|
||||
follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid));
|
||||
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
|
||||
let g = d.graphic_styles[i].clone();
|
||||
let mut shared = None;
|
||||
@@ -530,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
|
||||
super::graph::capture_label_rows(d, &follow_marks);
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
if let Some(src) = src {
|
||||
let link = (!super::graph::is_design_art(d, src)).then_some(id);
|
||||
set_link(d, &[src], link);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": name }))
|
||||
|
||||
@@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() {
|
||||
}
|
||||
}
|
||||
|
||||
/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the
|
||||
/// thread as it was: every frame stays a frame of the thread with the text it holds, and the
|
||||
/// symbol's art holds a copy of the text the frame shows.
|
||||
#[test]
|
||||
fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() {
|
||||
for command in ["symbol.new", "symbol.update"] {
|
||||
let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0);
|
||||
let shown = frames.map(|id| text(&s, id));
|
||||
let name = if command == "symbol.update" {
|
||||
let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap());
|
||||
s.execute("select.set", &json!({"ids": [mark]})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Mark"})).unwrap();
|
||||
"Mark"
|
||||
} else {
|
||||
"Story"
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap();
|
||||
let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap();
|
||||
assert!(r["id"].is_null(), "{command}: {r}");
|
||||
assert_eq!(threads(&s), [frames], "{command}: the thread is as it was");
|
||||
assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text");
|
||||
assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows");
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the
|
||||
/// mask art too.
|
||||
#[test]
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
"{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/<slice name>.<ext>), output?: images (default)|html (an HTML page placing the image or slices, <stem>.html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself",
|
||||
has_doc,
|
||||
export
|
||||
),
|
||||
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Save for Web Preview",
|
||||
[],
|
||||
None,
|
||||
"{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}",
|
||||
"{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, shifted (by colorTable.shifted; also locked), webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}",
|
||||
has_doc,
|
||||
preview
|
||||
),
|
||||
@@ -331,8 +331,14 @@ pub struct ColorTable {
|
||||
/// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the
|
||||
/// table when the first color was deleted. Empty: the reduction makes the palette.
|
||||
pub custom_palette: Vec<String>,
|
||||
/// Colors shifted by hand: each source color (`#rrggbb`) and the color it is written as. A
|
||||
/// shifted color is locked, and a source the table does not hold shifts nothing.
|
||||
pub shifted: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A color shifted by hand: (source, color written).
|
||||
type Shift = ([u8; 3], [u8; 3]);
|
||||
|
||||
/// The most colours a colour table list holds.
|
||||
const MAX_TABLE: usize = 256;
|
||||
|
||||
@@ -352,6 +358,21 @@ impl ColorTable {
|
||||
list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect()
|
||||
}
|
||||
|
||||
/// The colors shifted by hand as (source, color written). An error names a value that is not a
|
||||
/// color such as `#ff8800`, two keys that name one color, or more than 256 entries.
|
||||
fn shifts(&self) -> std::result::Result<Vec<Shift>, String> {
|
||||
// One entry past the limit is enough for `colors` to refuse a longer map.
|
||||
let (keys, values): (Vec<String>, Vec<String>) = self.shifted.iter().take(MAX_TABLE + 1).map(|(k, v)| (k.clone(), v.clone())).unzip();
|
||||
let sources = Self::colors(&keys, "shifted")?;
|
||||
let to = Self::colors(&values, "shifted")?;
|
||||
for (i, (s, k)) in sources.iter().zip(&keys).enumerate() {
|
||||
if sources[..i].contains(s) {
|
||||
return Err(format!("colorTable.shifted: `{k}` names a color another key names"));
|
||||
}
|
||||
}
|
||||
Ok(sources.into_iter().zip(to).collect())
|
||||
}
|
||||
|
||||
/// `h` as RGB; `None` when it is not a color such as `#ff8800`.
|
||||
fn rgb(h: &str) -> Option<[u8; 3]> {
|
||||
vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| {
|
||||
@@ -487,13 +508,18 @@ impl WebSettings {
|
||||
{
|
||||
ColorTable::colors(list, what)?;
|
||||
}
|
||||
// A deleted color is no longer locked, transparent or web-shifted.
|
||||
// A deleted color is no longer locked, transparent, web-shifted or shifted.
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
if !deleted.is_empty() {
|
||||
for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] {
|
||||
list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c)));
|
||||
}
|
||||
}
|
||||
// Shifts are kept as `#rrggbb` in lowercase; a color shifted to itself is not shifted, and
|
||||
// a color shifted by hand is not web-shifted.
|
||||
let shifts: Vec<Shift> = table.shifts()?.into_iter().filter(|(s, to)| s != to && !deleted.contains(s)).collect();
|
||||
table.web_shift.retain(|h| ColorTable::rgb(h).is_none_or(|c| !shifts.iter().any(|(s, _)| *s == c)));
|
||||
table.shifted = shifts.into_iter().map(|(s, to)| (hex(s), hex(to))).collect();
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -640,6 +666,8 @@ pub struct TableColor {
|
||||
pub transparent: bool,
|
||||
pub locked: bool,
|
||||
pub web_shifted: bool,
|
||||
/// Shifted by hand (`colorTable.shifted`): written as `color` instead of `source`.
|
||||
pub shifted: bool,
|
||||
}
|
||||
|
||||
/// An optimised image file.
|
||||
@@ -759,6 +787,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
let locked = ColorTable::colors(&table.locked, "locked")?;
|
||||
let to_clear = ColorTable::colors(&table.transparent, "transparent")?;
|
||||
let shift = ColorTable::colors(&table.web_shift, "webShift")?;
|
||||
let by_hand = table.shifts()?;
|
||||
let shifted_to = |src: &[u8; 3]| by_hand.iter().find(|(s, _)| s == src).map(|(_, to)| *to);
|
||||
// A color shifted by hand is kept when the colors are reduced, as a locked one is, and takes
|
||||
// one of the slots kept for them before the locked colors do.
|
||||
let kept: Vec<[u8; 3]> = by_hand.iter().map(|(s, _)| *s).chain(locked.iter().copied()).collect();
|
||||
let o = PaletteOptions {
|
||||
colors: s.colors,
|
||||
reduction: s.reduction,
|
||||
@@ -767,7 +800,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
transparency: s.transparency,
|
||||
matte,
|
||||
};
|
||||
let mut ix = reduced(rgba, w, h, s, &o, &locked)?;
|
||||
let mut ix = reduced(rgba, w, h, s, &o, &kept)?;
|
||||
// Map to transparent works on the colours the reduction made.
|
||||
let before = ix.palette.clone();
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
@@ -781,11 +814,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
*slot = *c;
|
||||
}
|
||||
}
|
||||
// Web snap, then the colours shifted by hand (locked colours stay as they are).
|
||||
// Web shift and web snap (locked colors and colors shifted by hand stay as they are).
|
||||
let clear = ix.transparent.map(usize::from);
|
||||
for (i, c) in ix.palette.iter_mut().enumerate() {
|
||||
let src = sources.get(i).copied().unwrap_or(*c);
|
||||
if Some(i) == clear || locked.contains(&src) {
|
||||
if Some(i) == clear || shifted_to(&src).is_some() || locked.contains(&src) {
|
||||
continue;
|
||||
}
|
||||
if shift.contains(&src) {
|
||||
@@ -794,8 +827,19 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
*c = snapped;
|
||||
}
|
||||
}
|
||||
// Lossy compares the pixels with the colors written for them, and moves no pixel into or out of
|
||||
// a color shifted by hand.
|
||||
if s.format == WebFormat::Gif {
|
||||
web::lossy(&mut ix, rgba, s.lossy);
|
||||
let fixed: Vec<u8> = sources.iter().enumerate().filter(|(_, c)| shifted_to(c).is_some()).filter_map(|(i, _)| u8::try_from(i).ok()).collect();
|
||||
web::lossy(&mut ix, rgba, s.lossy, &fixed);
|
||||
}
|
||||
// The colors shifted by hand.
|
||||
for (i, c) in ix.palette.iter_mut().enumerate() {
|
||||
if Some(i) != clear
|
||||
&& let Some(to) = sources.get(i).and_then(shifted_to)
|
||||
{
|
||||
*c = to;
|
||||
}
|
||||
}
|
||||
let order = web::sort(&mut ix, table.sort);
|
||||
let sources: Vec<[u8; 3]> = order.iter().map(|&i| sources.get(i).copied().unwrap_or_default()).collect();
|
||||
@@ -804,12 +848,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
.iter()
|
||||
.zip(&sources)
|
||||
.enumerate()
|
||||
.map(|(i, (c, src))| TableColor {
|
||||
color: *c,
|
||||
source: *src,
|
||||
transparent: ix.transparent == u8::try_from(i).ok(),
|
||||
locked: locked.contains(src),
|
||||
web_shifted: shift.contains(src),
|
||||
.map(|(i, (c, src))| {
|
||||
let transparent = ix.transparent == u8::try_from(i).ok();
|
||||
let shifted = !transparent && shifted_to(src).is_some();
|
||||
TableColor {
|
||||
color: *c,
|
||||
source: *src,
|
||||
transparent,
|
||||
locked: locked.contains(src) || shifted,
|
||||
web_shifted: shift.contains(src) && !shifted,
|
||||
shifted,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Ok(PaletteImage { ix, colors, mapped })
|
||||
@@ -818,7 +867,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8
|
||||
/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the
|
||||
/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the
|
||||
/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to
|
||||
/// transparent.
|
||||
/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of
|
||||
/// `colors` together, and its first opaque colors that fit in the rest.
|
||||
fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result<Indexed, String> {
|
||||
let table = &s.color_table;
|
||||
let deleted = ColorTable::colors(&table.deleted, "deleted")?;
|
||||
@@ -847,11 +897,70 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc
|
||||
left.push(c);
|
||||
}
|
||||
}
|
||||
left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear));
|
||||
if left.is_empty() || (removed && !opaque_left(&left)) {
|
||||
return Err(KEEP_ONE.into());
|
||||
}
|
||||
Ok(quantize::quantize_to(rgba, w, h, o, &left))
|
||||
// The colors mapped to transparent all become the one transparent entry, so together they take
|
||||
// one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of
|
||||
// them and no pixel is transparent, that slot goes to the next opaque color instead.
|
||||
let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true);
|
||||
let mut ix = quantize::quantize_to(rgba, w, h, o, &kept);
|
||||
clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear);
|
||||
if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) {
|
||||
return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false)));
|
||||
}
|
||||
Ok(ix)
|
||||
}
|
||||
|
||||
/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in
|
||||
/// `to_clear` are kept and take one slot together; without it they are left out. The list holds
|
||||
/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry).
|
||||
fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> {
|
||||
let any_clear = clear && left.iter().any(|c| to_clear.contains(c));
|
||||
let total = 256 - usize::from(has_clear);
|
||||
let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear));
|
||||
let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room);
|
||||
let mut clear_room = if clear { total - opaque } else { 0 };
|
||||
left.iter()
|
||||
.copied()
|
||||
.filter(|c| {
|
||||
let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room };
|
||||
let keep = *slots > 0;
|
||||
*slots = slots.saturating_sub(1);
|
||||
keep
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to
|
||||
/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the
|
||||
/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later.
|
||||
fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) {
|
||||
let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect();
|
||||
if dropped.is_empty() {
|
||||
return;
|
||||
}
|
||||
let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect();
|
||||
let near = quantize::nearest_entries(rgba, o, &all);
|
||||
if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) {
|
||||
return;
|
||||
}
|
||||
let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
// A kept color mapped to transparent that no pixel took; at most 255 entries are used then.
|
||||
let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else {
|
||||
return;
|
||||
};
|
||||
ix.palette.push(*c);
|
||||
i
|
||||
}
|
||||
};
|
||||
for (v, n) in ix.indices.iter_mut().zip(&near) {
|
||||
if n.is_some_and(|n| n >= kept.len()) {
|
||||
*v = entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview).
|
||||
@@ -1116,7 +1225,7 @@ fn preview(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|c| {
|
||||
json!({
|
||||
"color": hex(c.color), "source": hex(c.source), "transparent": c.transparent, "locked": c.locked,
|
||||
"webShifted": c.web_shifted, "webSafe": quantize::web_safe(c.color) == c.color,
|
||||
"webShifted": c.web_shifted, "shifted": c.shifted, "webSafe": quantize::web_safe(c.color) == c.color,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -415,7 +415,7 @@ use history::history_budget_for;
|
||||
pub use history::{History, HistoryEntry, NamedStep, default_history_budget};
|
||||
pub(crate) use interaction::PreviewCopies;
|
||||
pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope};
|
||||
pub use prefs::{DrawMode, Prefs};
|
||||
pub use prefs::{DrawMode, PluginBudget, Prefs};
|
||||
pub use sanity::TOO_DEEP;
|
||||
pub(crate) use sanity::{deselect_hidden, is_guide_path};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -10,6 +10,26 @@ pub enum DrawMode {
|
||||
Inside,
|
||||
}
|
||||
|
||||
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run
|
||||
/// may use ([`vectorcraft_plugins::Plugin::large_limits`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PluginBudget {
|
||||
/// The plug-in's own limits.
|
||||
#[default]
|
||||
Normal,
|
||||
/// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of
|
||||
/// input; the time budget is unchanged.
|
||||
Large,
|
||||
}
|
||||
|
||||
/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the
|
||||
/// other preferences are read as they are.
|
||||
fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<PluginBudget, D::Error> {
|
||||
let saved = <Value as serde::Deserialize>::deserialize(d)?;
|
||||
Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal })
|
||||
}
|
||||
|
||||
/// A saved Default Language as its tag: older preferences hold the language's name, and one the list
|
||||
/// no longer has reads as the default.
|
||||
fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<String, D::Error> {
|
||||
@@ -179,6 +199,11 @@ pub struct Prefs {
|
||||
pub fonts_folder: String,
|
||||
// Plug-ins & Scratch Disks
|
||||
pub plugins_folder: String,
|
||||
/// Plug-in Instruction Budget: the instructions each object filter run gets, from
|
||||
/// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers
|
||||
/// keep their own budgets.
|
||||
#[serde(deserialize_with = "plugin_budget")]
|
||||
pub plugin_instruction_budget: PluginBudget,
|
||||
pub scratch_primary: String,
|
||||
pub scratch_secondary: String,
|
||||
// User Interface
|
||||
@@ -496,6 +521,7 @@ impl Default for Prefs {
|
||||
hyphenation_exceptions: String::new(),
|
||||
fonts_folder: String::new(),
|
||||
plugins_folder: String::new(),
|
||||
plugin_instruction_budget: PluginBudget::Normal,
|
||||
scratch_primary: s("Startup"),
|
||||
scratch_secondary: s("None"),
|
||||
ui_brightness: s("mediumDark"),
|
||||
|
||||
@@ -110,6 +110,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
"art-ribbons",
|
||||
"ink-and-wash",
|
||||
"calligraphic-nibs",
|
||||
"pressure-sensitive",
|
||||
"bristle-brushes",
|
||||
"pattern-borders",
|
||||
"scatter-shapes",
|
||||
@@ -131,19 +132,19 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"]
|
||||
);
|
||||
assert_eq!(libs[6]["count"].as_u64(), Some(4));
|
||||
assert_eq!(libs[7]["count"].as_u64(), Some(4));
|
||||
let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"}));
|
||||
assert_eq!(
|
||||
beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"]
|
||||
);
|
||||
assert_eq!(libs[7]["count"].as_u64(), Some(4));
|
||||
assert_eq!(libs[8]["count"].as_u64(), Some(4));
|
||||
let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"}));
|
||||
assert_eq!(
|
||||
dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::<Vec<_>>(),
|
||||
[("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")]
|
||||
);
|
||||
assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4)));
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap();
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]}));
|
||||
@@ -154,6 +155,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
("art-ribbons", "art"),
|
||||
("ink-and-wash", "art"),
|
||||
("calligraphic-nibs", "calligraphic"),
|
||||
("pressure-sensitive", "art"),
|
||||
("bristle-brushes", "bristle"),
|
||||
("pattern-borders", "pattern"),
|
||||
("scatter-shapes", "scatter"),
|
||||
@@ -164,7 +166,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.len() >= 4, "{id}");
|
||||
for b in &lib.brushes {
|
||||
let kind = if b.name == "Brush Pen" { "calligraphic" } else { kind };
|
||||
let kind = if ["Brush Pen", "Round Flow", "Chisel Flow"].contains(&b.name.as_str()) { "calligraphic" } else { kind };
|
||||
assert_eq!(b.kind.type_id(), kind, "{}", b.name);
|
||||
let mut line = vectorcraft_geom::BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
@@ -299,6 +301,52 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() {
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
|
||||
let mut s = session();
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Pressure Sensitive").unwrap();
|
||||
let names = ["Flex Ribbon", "Pulse Stroke", "Round Flow", "Chisel Flow"];
|
||||
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
|
||||
let mut curve = line_to(20.0);
|
||||
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
|
||||
for b in &lib.brushes {
|
||||
let width_at = |pressure| {
|
||||
let stroke = vectorcraft_doc::StrokeLayer {
|
||||
pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }),
|
||||
..black_stroke()
|
||||
};
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke);
|
||||
let points = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at pressure {pressure}", b.name);
|
||||
let min = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);
|
||||
let max = points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max);
|
||||
max - min
|
||||
};
|
||||
let light = width_at(0.0);
|
||||
let heavy = width_at(1.0);
|
||||
for width in [light, heavy] {
|
||||
assert!(width.is_finite() && width > 0.0, "{}: light={light}, heavy={heavy}", b.name);
|
||||
}
|
||||
assert!(heavy > light * 1.3, "{}: light={light}, heavy={heavy}", b.name);
|
||||
for line in [line_to(2.0), curve.clone()] {
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
|
||||
let points = anchors(&pieces.iter().collect::<Vec<_>>());
|
||||
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
|
||||
}
|
||||
let before = undo_len(&s);
|
||||
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "pressure-sensitive", "name": b.name, "apply": true, "ids": [path]}));
|
||||
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
|
||||
assert_eq!(added["applied"], json!([path]));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
|
||||
}
|
||||
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
|
||||
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let reopened = vectorcraft_format::load(&bytes).unwrap();
|
||||
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
|
||||
}
|
||||
|
||||
/// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two
|
||||
/// translucent washes, with names of their own and a few paths of art each.
|
||||
#[test]
|
||||
|
||||
@@ -2274,6 +2274,93 @@ fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch()
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of symbol instances in the document.
|
||||
fn instance_count(s: &Session) -> usize {
|
||||
let mut n = 0;
|
||||
s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. })));
|
||||
n
|
||||
}
|
||||
|
||||
/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current
|
||||
/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the
|
||||
/// result has no instance id and nothing places the symbol. One undo step takes the symbol away
|
||||
/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance.
|
||||
#[test]
|
||||
fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
|
||||
let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
|
||||
let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i));
|
||||
let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b));
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
select(&mut s, &[a, b]);
|
||||
let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap();
|
||||
assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}");
|
||||
assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected");
|
||||
assert_eq!(instance_count(&s), 0, "no instance");
|
||||
let list = s.execute("symbol.list", &json!({})).unwrap();
|
||||
assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0)));
|
||||
// The symbol's art is the pair: an instance placed from it is 120 × 50.
|
||||
let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap());
|
||||
let w = bounds(&s, placed);
|
||||
assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away");
|
||||
assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo");
|
||||
assert_eq!(instance_count(&s), 0, "redo places no instance");
|
||||
// false, like no keepArt, makes the art an instance.
|
||||
for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] {
|
||||
let r = s.execute("symbol.new", &p).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().expect("an instance id"));
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}");
|
||||
}
|
||||
assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none());
|
||||
}
|
||||
|
||||
/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it
|
||||
/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the
|
||||
/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and
|
||||
/// no undo step.
|
||||
#[test]
|
||||
fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() {
|
||||
let mut s = session();
|
||||
let (inst, _, _) = make_symbol(&mut s);
|
||||
let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0);
|
||||
let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0);
|
||||
let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0);
|
||||
{
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.node_mut(locked).unwrap().locked = true;
|
||||
doc.node_mut(hidden).unwrap().visible = false;
|
||||
}
|
||||
for bad in [json!("true"), json!(1), json!([true])] {
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err();
|
||||
assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}");
|
||||
assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step");
|
||||
}
|
||||
select(&mut s, &[]);
|
||||
let symbols = s.doc().unwrap().doc.symbols.len();
|
||||
let ids = [a.0, locked.0, hidden.0, inst.0];
|
||||
s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1);
|
||||
let selected = &s.doc().unwrap().selection.objects;
|
||||
assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}");
|
||||
for id in [a, locked, hidden] {
|
||||
assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art");
|
||||
}
|
||||
assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance");
|
||||
assert_eq!(instance_count(&s), 1, "no new instance");
|
||||
}
|
||||
|
||||
/// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a
|
||||
/// group, in an opacity mask, or through the art of another symbol it holds an instance of, and
|
||||
/// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines
|
||||
|
||||
@@ -387,22 +387,79 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() {
|
||||
assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8));
|
||||
}
|
||||
|
||||
/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115;
|
||||
/// the fill's shape is 9 pt larger on each side.
|
||||
fn image_with_shaped_fill(s: &mut Session) -> NodeId {
|
||||
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(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let im = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
run(s, "select.set", json!({"ids": [im.0]}));
|
||||
run(s, "appearance.addFill", json!({}));
|
||||
run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
|
||||
run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
|
||||
im
|
||||
}
|
||||
|
||||
/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in
|
||||
/// outline with `outline`.
|
||||
fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec<NodeId> {
|
||||
let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0);
|
||||
vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline, false)
|
||||
}
|
||||
|
||||
/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its
|
||||
/// art outside its box, as a click there selects it, except in outline.
|
||||
#[test]
|
||||
fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() {
|
||||
let mut s = session();
|
||||
let (id, row) = instance_with_row(&mut s, "Square", true);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), []);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill");
|
||||
assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill");
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is");
|
||||
|
||||
let mut s = session();
|
||||
let (id, row) = instance_with_row(&mut s, "Square", false);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke");
|
||||
assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill");
|
||||
|
||||
let mut s = session();
|
||||
let (id, row) = nested_instance_with_row(&mut s);
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art");
|
||||
}
|
||||
|
||||
/// A marquee touches an image where the shape of its own fill lies outside its frame, and an
|
||||
/// instance of a symbol made of that image where the instance's fill effect grows that shape, as
|
||||
/// clicks there select them, except in outline.
|
||||
#[test]
|
||||
fn a_marquee_on_the_shape_of_an_image_fill_selects_it() {
|
||||
let mut s = session();
|
||||
let im = image_with_shaped_fill(&mut s);
|
||||
assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame");
|
||||
assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape");
|
||||
assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame");
|
||||
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(&s, id).appearance.items.len() - 1;
|
||||
run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true}));
|
||||
offset_row(&mut s, id, row, 10.0);
|
||||
assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill");
|
||||
assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill");
|
||||
}
|
||||
|
||||
/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill
|
||||
/// effect grows what that fill paints, and a click there selects the instance.
|
||||
#[test]
|
||||
fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() {
|
||||
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();
|
||||
// The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side.
|
||||
let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]}));
|
||||
let im = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
run(&mut s, "select.set", json!({"ids": [im.0]}));
|
||||
run(&mut s, "appearance.addFill", json!({}));
|
||||
run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0}));
|
||||
image_with_shaped_fill(&mut s);
|
||||
let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap());
|
||||
run(&mut s, "appearance.addFill", json!({"ids": [id.0]}));
|
||||
let row = node(&s, id).appearance.items.len() - 1;
|
||||
|
||||
@@ -465,6 +465,117 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_
|
||||
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
|
||||
}
|
||||
|
||||
/// A confined request packages no linked file whose native document it can't read to check against
|
||||
/// its read roots: a PDF that needs a password to open, and a native document that doesn't load,
|
||||
/// even inside the roots. The package is refused before anything is written, with an error that
|
||||
/// names no file or folder. A PDF without editing data is copied, and the person's package copies
|
||||
/// every file.
|
||||
#[test]
|
||||
fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() {
|
||||
let home = Folder::new("package-unreadable-home");
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let out = home.file("out");
|
||||
let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p));
|
||||
let refused = |s: &mut Session, p: Value| {
|
||||
let e = package(s, p.clone()).expect_err("refused");
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}");
|
||||
assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}");
|
||||
assert!(!std::path::Path::new(&out).exists(), "{p}");
|
||||
};
|
||||
let mut part = session();
|
||||
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
|
||||
std::fs::create_dir_all(home.0.join("art")).unwrap();
|
||||
let native = home.file("art/part.vectorcraft");
|
||||
let pdf = home.file("art/part.pdf");
|
||||
save(&mut part, &native);
|
||||
let pdf_of =
|
||||
|part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap();
|
||||
let editable = pdf_of(&mut part, json!({"format": "pdf"}));
|
||||
let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}}));
|
||||
assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data");
|
||||
let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false}));
|
||||
let poster = |placed: &str| {
|
||||
let mut s = session();
|
||||
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
|
||||
assert_eq!(r["linked"], true, "{r}");
|
||||
save(&mut s, &home.file("poster.vectorcraft"));
|
||||
s
|
||||
};
|
||||
write(&pdf, &editable);
|
||||
let mut s = poster(&pdf);
|
||||
write(&pdf, &locked);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
// A package prepared in the confined request and written on another thread.
|
||||
let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap();
|
||||
let e =
|
||||
std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused");
|
||||
assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}");
|
||||
assert!(!std::path::Path::new(&out).exists());
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A PDF listing the editing file without its data (`EF` renamed, the same length).
|
||||
let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF");
|
||||
let mut detached = editable.clone();
|
||||
detached[at..at + 3].copy_from_slice(b"/XF");
|
||||
assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved");
|
||||
write(&pdf, &detached);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A PDF without editing data.
|
||||
write(&pdf, &plain);
|
||||
assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1);
|
||||
std::fs::remove_dir_all(&out).unwrap();
|
||||
// A PDF whose attachments are too many to search to their end, with a readable editing file
|
||||
// listed before the ones left unsearched.
|
||||
let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data);
|
||||
assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read");
|
||||
write(&pdf, &cut);
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
// A native document that doesn't load, rewritten or copied as it is.
|
||||
let mut s = poster(&native);
|
||||
write(&native, b"not a document");
|
||||
refused(&mut s, json!({"folder": out}));
|
||||
refused(&mut s, json!({"folder": out, "relink": false}));
|
||||
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package");
|
||||
}
|
||||
|
||||
/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree
|
||||
/// whose second subtree has 70,000 nodes, more than are searched.
|
||||
fn attachments_cut_short(native: &[u8]) -> Vec<u8> {
|
||||
let name = vectorcraft_pdf::EDITING_FILE;
|
||||
let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes();
|
||||
stream.extend_from_slice(native);
|
||||
stream.extend_from_slice(b"\nendstream");
|
||||
let objects = [
|
||||
b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(),
|
||||
b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(),
|
||||
format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(),
|
||||
format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(),
|
||||
stream,
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, body) in objects.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
|
||||
out.extend_from_slice(body);
|
||||
out.extend_from_slice(b"\nendobj\n");
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes());
|
||||
for at in &offsets {
|
||||
out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
/// A missing link stored as a path relative to the document names a file inside a confined
|
||||
/// request's read root: the package report and Document Info give its stored path.
|
||||
#[test]
|
||||
|
||||
@@ -4446,6 +4446,59 @@ fn a_cancelled_filter_run_changes_nothing() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter
|
||||
/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as
|
||||
/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's
|
||||
/// larger budget stay as they are, and setting Normal again applies to the next run.
|
||||
#[test]
|
||||
fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() {
|
||||
use cmd::plugin::FilterRun;
|
||||
let mut s = session();
|
||||
let id = "test.engine.largebudget";
|
||||
let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string();
|
||||
// More steps than a light budget pays for, fewer than 5 times it.
|
||||
install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output));
|
||||
let p = json!({"id": id, "ids": []});
|
||||
let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
|
||||
|
||||
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"}));
|
||||
let light = vectorcraft_plugins::Limits::default();
|
||||
let large = FilterRun::prepare(&s, &p).unwrap().limits().clone();
|
||||
assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() });
|
||||
assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms));
|
||||
// Cancel still stops it, and it changes nothing.
|
||||
let token = vectorcraft_doc::cancel::CancelToken::new();
|
||||
token.cancel();
|
||||
let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p));
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo));
|
||||
let made = run(&mut s, "plugin.run", p.clone())["ids"].clone();
|
||||
assert_eq!(made.as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
|
||||
// A heavy filter keeps its larger budget with either choice.
|
||||
let heavy_id = "test.engine.largebudget.heavy";
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true}));
|
||||
let hp = json!({"id": heavy_id, "ids": []});
|
||||
for budget in ["large", "normal"] {
|
||||
run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget}));
|
||||
let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone();
|
||||
let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS);
|
||||
assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}");
|
||||
}
|
||||
|
||||
// Normal again: the next run runs out of instructions.
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("plugin.run", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("instruction budget"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
run(&mut s, "plugin.remove", json!({"id": heavy_id}));
|
||||
}
|
||||
|
||||
/// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list).
|
||||
fn with_commands(id: &str, kind: &str, commands: &str) -> String {
|
||||
format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#)
|
||||
|
||||
@@ -464,6 +464,38 @@ fn gpu_preference_defaults_to_automatic_and_validates() {
|
||||
assert_eq!(s.prefs.gpu_preference, "automatic");
|
||||
}
|
||||
|
||||
/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or
|
||||
/// label, kept through a save and load, and reset with its category. Setting another value is an
|
||||
/// error that changes nothing; a saved value that is missing, unknown or of another type reads as
|
||||
/// Normal and leaves the other saved preferences as they are.
|
||||
#[test]
|
||||
fn plugin_instruction_budget_defaults_to_normal_and_validates() {
|
||||
let mut s = Session::new();
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal"));
|
||||
set_pref(&mut s, "pluginInstructionBudget", json!("Large"));
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large"));
|
||||
for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] {
|
||||
assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}");
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}");
|
||||
}
|
||||
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
|
||||
assert_eq!(back.plugin_instruction_budget, PluginBudget::Large);
|
||||
let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")];
|
||||
let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v}));
|
||||
for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) {
|
||||
let read: Prefs = serde_json::from_value(saved.clone()).unwrap();
|
||||
assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}");
|
||||
}
|
||||
let l = s.execute("prefs.list", &json!({})).unwrap();
|
||||
let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone();
|
||||
assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins")));
|
||||
assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large")));
|
||||
s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap();
|
||||
assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal);
|
||||
}
|
||||
|
||||
/// Performance › Low-Latency Drawing (#6013): off by default and for preference files written
|
||||
/// before it, a boolean only, kept through a save/load round trip, listed under Performance and
|
||||
/// reset with it.
|
||||
|
||||
@@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() {
|
||||
assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance));
|
||||
}
|
||||
|
||||
/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id,
|
||||
/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as
|
||||
/// they are, in one undo step. A style replaced by itself or by a style with the same look records
|
||||
/// nothing, and bad parameters are errors that change nothing.
|
||||
#[test]
|
||||
fn redefine_from_a_style_gives_the_style_that_look() {
|
||||
let mut s = session();
|
||||
let (a, b, c) = linked_three(&mut s);
|
||||
let d = rect(&mut s, 300.0);
|
||||
set_fill(&mut s, d, "#0000ff");
|
||||
run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"}));
|
||||
run(&mut s, "graphicStyle.new", json!({"name": "Blue"}));
|
||||
set_fill(&mut s, c, "#00ff00");
|
||||
let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::<Vec<_>>();
|
||||
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s));
|
||||
assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S");
|
||||
assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() });
|
||||
assert_eq!(names(&s), order);
|
||||
let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap());
|
||||
for id in [a, b] {
|
||||
let n = node(&s, id);
|
||||
assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply));
|
||||
}
|
||||
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
|
||||
// The edited object keeps its look and is unlinked; Blue and its object are as they were.
|
||||
assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap()));
|
||||
assert_eq!(node(&s, c).extras().graphic_style, None);
|
||||
assert_eq!(style(&s, "Blue"), blue);
|
||||
assert_eq!(linked(&mut s, "Blue"), vec![d.0]);
|
||||
let step = s.doc().unwrap().history.undo.last().unwrap().clone();
|
||||
assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(style(&s, "S"), old);
|
||||
assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE)));
|
||||
assert_eq!(node(&s, c).extras().graphic_style, Some(old.id));
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!(style(&s, "S").appearance, blue.appearance);
|
||||
assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
|
||||
// A style replaced by itself, or by a copy with the same look, records nothing.
|
||||
run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"}));
|
||||
let before = steps(&s);
|
||||
run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"}));
|
||||
run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"}));
|
||||
assert_eq!(steps(&s), before);
|
||||
assert_eq!(style(&s, "S"), old);
|
||||
|
||||
// A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors.
|
||||
for p in [
|
||||
json!({"name": "S", "from": "nope"}),
|
||||
json!({"name": "nope", "from": "Blue"}),
|
||||
json!({"name": "S", "from": 3}),
|
||||
json!({"name": "S", "from": "Blue", "id": a.0}),
|
||||
json!({"from": "Blue"}),
|
||||
] {
|
||||
assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!((steps(&s), style(&s, "S")), (before, old));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_style_unlinks_and_renaming_keeps_links() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -539,6 +539,196 @@ fn colour_table_delete_maps_pixels_to_the_nearest_color_left() {
|
||||
assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]);
|
||||
}
|
||||
|
||||
/// The colors of a fixed palette mapped to transparent take one slot of Colors together with the
|
||||
/// transparent pixels, so the opaque colors after them still fit: their pixels stay opaque, and the
|
||||
/// pixels of the colors mapped to transparent become transparent.
|
||||
#[test]
|
||||
fn colour_table_fixed_palette_keeps_an_opaque_color() {
|
||||
// 40×10: red, a near red and blue, and 10 px with nothing (transparent).
|
||||
let mut s = session(40.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100");
|
||||
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
for table in [
|
||||
json!({"customPalette": ["#ff0000", "#ee1100", "#0000ff"], "deleted": ["#ee1100"], "transparent": ["#ff0000"]}),
|
||||
json!({"customPalette": ["#ff0000", "#0000ff"], "transparent": ["#ff0000"]}),
|
||||
] {
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table});
|
||||
let v = run(&mut s, "document.exportForWeb.preview", p.clone());
|
||||
let opaque: Vec<&Value> = v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| &c["source"]).collect();
|
||||
assert_eq!((opaque, v["colors"].as_array().unwrap().len()), (vec![&json!("#0000ff")], 2), "{p}");
|
||||
let img = pixels(&one(&mut s, p.clone()));
|
||||
let alpha = |x: u32| img.get_pixel(x, 5).0[3];
|
||||
assert_eq!((alpha(5), alpha(15), img.get_pixel(25, 5).0, alpha(35)), (0, 0, [0, 0, 255, 255], 0), "{p}");
|
||||
}
|
||||
// A color mapped to transparent that no pixel takes leaves its slot to an opaque color.
|
||||
let mut u = session(20.0, 10.0);
|
||||
rect(&mut u, [0.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut u, [10.0, 0.0, 10.0, 10.0], "#00ff00");
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#00ff00", "#ff0000"], "transparent": ["#ff0000"]}});
|
||||
let img = pixels(&one(&mut u, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0), ([0, 0, 255, 255], [0, 255, 0, 255]));
|
||||
// At 256 colors a color mapped to transparent after 255 opaque ones still keeps an entry.
|
||||
let full: Vec<String> =
|
||||
std::iter::once("#0000ff".to_string()).chain((1..255).map(|i| format!("#00{i:02x}00"))).chain(["#ff0000".to_string()]).collect();
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0));
|
||||
// With one opaque color and 255 mapped to transparent, the last of those does not fit, and its
|
||||
// pixels still become transparent rather than taking the opaque color nearest them.
|
||||
let mut d = session(30.0, 10.0);
|
||||
rect(&mut d, [0.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut d, [10.0, 0.0, 10.0, 10.0], "#0000ee");
|
||||
let clear: Vec<String> = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect();
|
||||
let palette: Vec<String> = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect();
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}});
|
||||
let img = pixels(&one(&mut d, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0));
|
||||
// Without transparent pixels the colors mapped to transparent still take one slot together.
|
||||
let mut t = session(30.0, 10.0);
|
||||
rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut t, [10.0, 0.0, 10.0, 10.0], "#ee1100");
|
||||
rect(&mut t, [20.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {
|
||||
"customPalette": ["#ff0000", "#ee1100", "#0000ff", "#00ff00"], "transparent": ["#ff0000", "#ee1100"],
|
||||
}});
|
||||
let v = run(&mut t, "document.exportForWeb.preview", p.clone());
|
||||
assert_eq!(v["colors"].as_array().unwrap().len(), 2, "{v}");
|
||||
let img = pixels(&one(&mut t, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255]));
|
||||
}
|
||||
|
||||
/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in
|
||||
/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is
|
||||
/// the file.
|
||||
#[test]
|
||||
fn colour_table_shift_writes_the_picked_color_wherever_the_source_is() {
|
||||
let mut s = session(30.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000");
|
||||
rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#00ff00");
|
||||
let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p);
|
||||
let entry = |v: &Value, source: &str| v["colors"].as_array().unwrap().iter().find(|c| c["source"] == source).cloned().unwrap_or(Value::Null);
|
||||
for format in ["gif", "png8"] {
|
||||
let p = json!({"format": format, "dither": "none", "colorTable": {"shifted": {"#0000FF": "#FF8800"}}});
|
||||
let v = preview(&mut s, p.clone());
|
||||
let c = entry(&v, "#0000ff");
|
||||
assert_eq!(
|
||||
(c["color"].as_str(), c["shifted"].as_bool(), c["locked"].as_bool(), c["webShifted"].as_bool()),
|
||||
(Some("#ff8800"), Some(true), Some(true), Some(false)),
|
||||
"{format}: {v}"
|
||||
);
|
||||
assert_eq!((entry(&v, "#ff0000")["shifted"].as_bool(), entry(&v, "#ff0000")["color"].as_str()), (Some(false), Some("#ff0000")));
|
||||
let file = one(&mut s, p);
|
||||
assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file");
|
||||
let img = pixels(&file);
|
||||
assert_eq!(
|
||||
(img.get_pixel(5, 5).0, img.get_pixel(12, 2).0, img.get_pixel(18, 8).0, img.get_pixel(25, 5).0),
|
||||
([255, 0, 0, 255], [255, 136, 0, 255], [255, 136, 0, 255], [0, 255, 0, 255]),
|
||||
"{format}"
|
||||
);
|
||||
assert_eq!(distinct(&img), 3, "{format}");
|
||||
}
|
||||
// A shifted color is kept when the colors are reduced, as a locked one is.
|
||||
let two = preview(&mut s, json!({"colors": 2, "dither": "none", "colorTable": {"shifted": {"#00ff00": "#123456"}}}));
|
||||
assert_eq!(entry(&two, "#00ff00")["color"], "#123456", "{two}");
|
||||
// With one slot to keep, the shifted color takes it before a locked one.
|
||||
let p = json!({"colors": 2, "dither": "none", "colorTable": {"locked": ["#ff0000"], "shifted": {"#0000ff": "#123456"}}});
|
||||
let first = preview(&mut s, p);
|
||||
assert_eq!(entry(&first, "#0000ff")["color"], "#123456", "{first}");
|
||||
// A source the table does not hold shifts nothing, and the shift stays with the settings.
|
||||
let base = preview(&mut s, json!({"dither": "none"}));
|
||||
let absent = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#123456": "#000000"}}}));
|
||||
assert_eq!(absent["colors"], base["colors"]);
|
||||
// Two colors may be shifted to one color and keep their own sources.
|
||||
let same = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#ff0000": "#123456", "#0000ff": "#123456"}}}));
|
||||
assert_eq!((entry(&same, "#ff0000")["color"].as_str(), entry(&same, "#0000ff")["color"].as_str()), (Some("#123456"), Some("#123456")));
|
||||
assert_eq!(entry(&same, "#00ff00")["shifted"], false);
|
||||
// A shift by hand wins over web shift, web snap and a lock; transparency wins over it.
|
||||
let p =
|
||||
json!({"dither": "none", "webSnap": 100, "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "webShift": ["#0000ff"], "locked": ["#0000ff"]}});
|
||||
let c = entry(&preview(&mut s, p), "#0000ff");
|
||||
assert_eq!((c["color"].as_str(), c["webShifted"].as_bool(), c["locked"].as_bool()), (Some("#fe0101"), Some(false), Some(true)));
|
||||
let clear = json!({"dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "transparent": ["#0000ff"]}});
|
||||
let v = preview(&mut s, clear.clone());
|
||||
assert!(v["colors"].as_array().unwrap().iter().all(|c| c["shifted"] == false), "{v}");
|
||||
assert_eq!(pixels(&one(&mut s, clear)).get_pixel(15, 5).0[3], 0);
|
||||
// The settings keep the shifts in lowercase, drop a color shifted to itself, a deleted one and
|
||||
// the web shift of a color shifted by hand.
|
||||
let table = json!({"shifted": {"#0000FF": "#FE0101", "#FF0000": "#ff0000", "#00ff00": "#000000"}, "webShift": ["#0000ff", "#00ff00"], "deleted": ["#00ff00"]});
|
||||
let r = run(&mut s, "webExport.settings", json!({ "colorTable": table }));
|
||||
let t = &r["settings"]["colorTable"];
|
||||
assert_eq!((&t["shifted"], &t["webShift"]), (&json!({"#0000ff": "#fe0101"}), &json!([])));
|
||||
// Another reduction keeps the shifts; a saved preset keeps them.
|
||||
let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"}));
|
||||
assert_eq!(r["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"}));
|
||||
run(&mut s, "webExport.presets.save", json!({"name": "Blue to red", "dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}}}));
|
||||
assert_eq!(entry(&preview(&mut s, json!({"preset": "Blue to red"})), "#0000ff")["color"], "#fe0101");
|
||||
// Bad shifts are refused and change nothing.
|
||||
let many: serde_json::Map<String, Value> = (0..257).map(|i| (format!("#{i:06x}"), json!("#000000"))).collect();
|
||||
for bad in [
|
||||
json!({"nope": "#000000"}),
|
||||
json!({"#ff0000": "nope"}),
|
||||
json!({"#ff0000": "#ff000080"}),
|
||||
json!({"#ff000080": "#000000"}),
|
||||
json!({"#ff0000": "#000000", "#FF0000": "#ffffff"}),
|
||||
json!({"#f00": "#000000", "#ff0000": "#ffffff"}),
|
||||
Value::Object(many),
|
||||
] {
|
||||
let p = json!({"colorTable": {"shifted": bad}});
|
||||
assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}");
|
||||
assert!(s.execute("document.exportForWeb.preview", &p).is_err(), "{p}");
|
||||
assert!(s.execute("webExport.settings", &p).is_err(), "{p}");
|
||||
}
|
||||
assert_eq!(run(&mut s, "webExport.settings", json!({}))["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"}));
|
||||
// Settings saved before shifts existed still read.
|
||||
let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"colorTable": {"locked": ["#ff0000"]}})).unwrap();
|
||||
assert!(old.color_table.shifted.is_empty());
|
||||
}
|
||||
|
||||
/// Lossy GIF compression leaves the pixels of a color shifted by hand alone, so a color shifted near
|
||||
/// another one does not take in that color's pixels.
|
||||
#[test]
|
||||
fn lossy_does_not_spread_a_shifted_color_into_another() {
|
||||
let mut s = session(30.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#0000ff");
|
||||
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#c80000");
|
||||
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#be0000"}}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(20, 5).0, img.get_pixel(29, 5).0), ([190, 0, 0, 255], [200, 0, 0, 255], [200, 0, 0, 255]));
|
||||
}
|
||||
|
||||
/// Lossy GIF compression moves no pixel into or out of a color shifted by hand: the colors next to
|
||||
/// a shifted one keep their own pixels, and the shifted color keeps all of its pixels.
|
||||
#[test]
|
||||
fn lossy_moves_no_pixel_into_or_out_of_a_shifted_color() {
|
||||
let mut s = session(30.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1414e6");
|
||||
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#0000ff");
|
||||
rect(&mut s, [20.0, 0.0, 30.0, 10.0], "#1414e6");
|
||||
let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#ff0000"}}});
|
||||
let img = pixels(&one(&mut s, p));
|
||||
let near_blue = [20, 20, 230, 255];
|
||||
for x in 0..30 {
|
||||
let want = if (10..20).contains(&x) { [255, 0, 0, 255] } else { near_blue };
|
||||
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Lossy GIF compression compares the pixels with the colors web snap writes, so a pixel does not
|
||||
/// take a color that snaps far from it.
|
||||
#[test]
|
||||
fn lossy_compares_pixels_with_the_snapped_colors() {
|
||||
let mut s = session(20.0, 10.0);
|
||||
rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1a1a1a");
|
||||
rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#000000");
|
||||
let img = pixels(&one(&mut s, json!({"format": "gif", "dither": "none", "webSnap": 100, "lossy": 50})));
|
||||
for x in 0..20 {
|
||||
let want = if x < 10 { [51, 51, 51, 255] } else { [0, 0, 0, 255] };
|
||||
assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_and_remembered_settings() {
|
||||
let mut s = two_colours();
|
||||
|
||||
@@ -515,6 +515,69 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() {
|
||||
assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}");
|
||||
}
|
||||
|
||||
/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant
|
||||
/// opposite ways, and 120 and 300 slant as -60 does.
|
||||
#[test]
|
||||
fn shear_angles_slant_by_their_tangent() {
|
||||
let run = 100.0 * 60f64.to_radians().tan();
|
||||
for (angle, want) in [
|
||||
(60.0, Rect::new(-run, 0.0, 100.0, 100.0)),
|
||||
(-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)),
|
||||
(-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)),
|
||||
] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap();
|
||||
assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a));
|
||||
}
|
||||
}
|
||||
|
||||
/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no
|
||||
/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded.
|
||||
#[test]
|
||||
fn shear_rejects_angles_with_no_shear_or_out_of_range() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
|
||||
let n = undo_len(&s);
|
||||
let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear");
|
||||
let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}");
|
||||
for (angle, msg) in [
|
||||
(90.0, none(90.0)),
|
||||
(-90.0, none(-90.0)),
|
||||
(270.0, none(270.0)),
|
||||
(-270.0, none(-270.0)),
|
||||
(90.0 + 1e-12, none(90.0 + 1e-12)),
|
||||
(360.0, range(360.0)),
|
||||
(-359.5, range(-359.5)),
|
||||
(1e300, range(1e300)),
|
||||
] {
|
||||
let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string());
|
||||
assert_eq!(e.to_string(), msg);
|
||||
}
|
||||
assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle");
|
||||
assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a));
|
||||
assert_eq!(undo_len(&s), n, "no undo step");
|
||||
}
|
||||
|
||||
/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact
|
||||
/// coordinates and no undo step is recorded.
|
||||
#[test]
|
||||
fn shear_by_0_and_180_changes_nothing() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0);
|
||||
let before = bounds(&s, a);
|
||||
let n = undo_len(&s);
|
||||
for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] {
|
||||
for axis in ["horizontal", "vertical"] {
|
||||
s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap();
|
||||
assert_eq!(bounds(&s, a), before, "{angle} {axis}");
|
||||
assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shear along an axis at an angle, counter-clockwise from horizontal on the page: each point
|
||||
/// slides along the axis by the tangent of the shear angle times its distance across the axis
|
||||
/// from the origin. -359° and 359° are taken, the shear is one undo step and Transform Again
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
//! Blend edits invalidate every pixel they change, including keys aligned to a curved spine.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
use vectorcraft_engine::Session;
|
||||
use vectorcraft_geom::Affine;
|
||||
use vectorcraft_render::{Changed, RenderOptions, Rendered, Renderer, view_pixels};
|
||||
|
||||
const WIDTH: u32 = 720;
|
||||
const HEIGHT: u32 = 480;
|
||||
|
||||
type Retained = (Renderer, Option<(Arc<Document>, Vec<u8>)>);
|
||||
|
||||
fn live(s: &Session, blend: NodeId, keys: [NodeId; 2], curved: bool) {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let NodeKind::Blend { children, spec } = &doc.node(blend).unwrap().kind else {
|
||||
panic!("INPUT: the fixture must remain a live blend");
|
||||
};
|
||||
assert_eq!(children.iter().map(|n| n.id).collect::<Vec<_>>(), keys.to_vec());
|
||||
assert_eq!(serde_json::to_value(spec).unwrap()["spacing"], json!({"steps": 3}));
|
||||
for key in keys {
|
||||
assert_eq!(doc.parent_of(key), Some(blend), "INPUT: key identity/parent changed");
|
||||
}
|
||||
if curved {
|
||||
let bounds = spec.spine.as_ref().expect("INPUT: Replace Spine did not set a spine").bounds().unwrap();
|
||||
assert!(!spec.no_spine && bounds.height() > 40.0 && bounds.width() > 250.0, "INPUT: a real curved spine is required");
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture() -> (Session, NodeId, [NodeId; 2]) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap();
|
||||
let mut rectangle = |x: f64, color: &str| {
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 120.0, "width": 64.0, "height": 48.0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": color})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
id
|
||||
};
|
||||
let keys = [rectangle(90.0, "#d52c38"), rectangle(430.0, "#25b453")];
|
||||
let blend = NodeId(
|
||||
s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(),
|
||||
);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
live(&s, blend, keys, false);
|
||||
(s, blend, keys)
|
||||
}
|
||||
|
||||
fn cpu() -> Renderer {
|
||||
let mut renderer = Renderer::new();
|
||||
renderer.threads = 0;
|
||||
renderer
|
||||
}
|
||||
|
||||
fn same_pixels(actual: &Rendered, expected: &Rendered) {
|
||||
assert_eq!((actual.width, actual.height), (WIDTH, HEIGHT));
|
||||
assert_eq!((expected.width, expected.height), (WIDTH, HEIGHT));
|
||||
assert_eq!(actual.pixels.len(), (WIDTH * HEIGHT * 4) as usize);
|
||||
assert!(actual.pixels == expected.pixels, "complete RGBA frames differ");
|
||||
}
|
||||
|
||||
fn damage_pixels(stage: &str, changed: Changed, before: &[u8], current: &[u8]) {
|
||||
let region = match changed {
|
||||
Changed::Everything => return,
|
||||
Changed::Nothing => None,
|
||||
Changed::Area(area) => view_pixels(area, Affine::IDENTITY, WIDTH, HEIGHT),
|
||||
};
|
||||
assert_eq!(before.len(), current.len());
|
||||
for (i, (old, new)) in before.as_chunks::<4>().0.iter().zip(current.as_chunks::<4>().0.iter()).enumerate() {
|
||||
let (x, y) = (i as u32 % WIDTH, i as u32 / WIDTH);
|
||||
if !region.is_some_and(|[x0, y0, x1, y1]| x >= x0 && x < x1 && y >= y0 && y < y1) {
|
||||
assert_eq!(old, new, "{stage}: pixel ({x}, {y}) changed outside {changed:?}, view pixels {region:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(s: &Session, retained: &mut Retained, stage: &str) -> Rendered {
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..Default::default() };
|
||||
// Ask for the edit's advertised damage before rendering the new full frame on this renderer.
|
||||
let changed = retained.1.as_ref().map(|(old, _)| retained.0.changed(old.as_ref(), doc.as_ref(), &opts));
|
||||
let actual = retained.0.render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts);
|
||||
let expected = cpu().render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts);
|
||||
same_pixels(&actual, &expected);
|
||||
let red = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] > 150 && p[1] < 100 && p[2] < 120 && p[3] == 255).count();
|
||||
let green = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] < 100 && p[1] > 120 && p[2] < 150 && p[3] == 255).count();
|
||||
assert!(red > 100 && green > 100, "INPUT: both original colored keys must really draw: red={red}, green={green}");
|
||||
if let (Some((_, previous)), Some(changed)) = (&retained.1, changed) {
|
||||
damage_pixels(stage, changed, previous, &expected.pixels);
|
||||
}
|
||||
retained.1 = Some((doc.clone(), expected.pixels));
|
||||
actual
|
||||
}
|
||||
|
||||
fn move_and_undo(s: &mut Session, retained: &mut Retained, blend: NodeId, keys: [NodeId; 2], curved: bool, before_frame: &Rendered) {
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
s.execute("object.transform", &json!({"matrix": [1.0, 0.0, 0.0, 1.0, 37.0, 29.0]})).unwrap();
|
||||
live(s, blend, keys, curved);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let moved = frame(s, retained, "moved");
|
||||
assert!(moved.pixels != before_frame.pixels, "INPUT: the fresh rendered fixture must actually move");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
live(s, blend, keys, curved);
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let restored = frame(s, retained, "undo-move");
|
||||
same_pixels(&restored, before_frame);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_5179_straight_move_undo_matches_fresh_cpu() {
|
||||
let (mut s, blend, keys) = fixture();
|
||||
let mut retained = (cpu(), None);
|
||||
let warm = frame(&s, &mut retained, "warm");
|
||||
move_and_undo(&mut s, &mut retained, blend, keys, false, &warm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_5179_replace_spine_move_undo_matches_fresh_cpu() {
|
||||
let (mut s, blend, keys) = fixture();
|
||||
let path = NodeId(s.execute("path.create", &json!({"d": "M122 144 C166 330 402 288 462 144"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap();
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
let nodes = s.doc().unwrap().doc.node_count();
|
||||
let mut retained = (cpu(), None);
|
||||
let warm = frame(&s, &mut retained, "before-replace");
|
||||
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
|
||||
live(&s, blend, keys, true);
|
||||
assert!(s.doc().unwrap().doc.node(path).is_none(), "Replace Spine consumes the original standalone path");
|
||||
assert_eq!(s.doc().unwrap().doc.node_count(), nodes - 1);
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let replaced = frame(&s, &mut retained, "replaced");
|
||||
assert!(replaced.pixels != warm.pixels, "INPUT: replacing the spine must visibly change the drawn fixture");
|
||||
move_and_undo(&mut s, &mut retained, blend, keys, true, &replaced);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
live(&s, blend, keys, false);
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
let restored = frame(&s, &mut retained, "undo-replace");
|
||||
same_pixels(&restored, &warm);
|
||||
}
|
||||
|
||||
// A fixed ordinary anisotropic Transform, evaluated after Align to Path turns the key.
|
||||
// 200% is the legitimate control; 400% is the single source-derived witness.
|
||||
fn rotated_transform_damage(scale_h: f64) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap();
|
||||
let mut rectangle = |x: f64, color: &str| {
|
||||
let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 200.0, "width": 8.0, "height": 80.0})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("paint.setFill", &json!({"color": color})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": scale_h, "scaleV": 100.0, "reference": 4}})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap();
|
||||
let b = n.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 8.0).abs() < 1e-8 && (b.height() - 80.0).abs() < 1e-8, "INPUT: the Transform must remain live on the narrow key");
|
||||
assert_eq!(n.appearance.effects.len(), 1);
|
||||
assert_eq!(n.appearance.effects[0].params["scaleH"], json!(scale_h));
|
||||
id
|
||||
};
|
||||
let keys = [rectangle(260.0, "#d52c38"), rectangle(460.0, "#25b453")];
|
||||
let blend = NodeId(
|
||||
s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(),
|
||||
);
|
||||
live(&s, blend, keys, false);
|
||||
let path = NodeId(s.execute("path.create", &json!({"d": "M264 160 L264 320"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap();
|
||||
let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap();
|
||||
let mut retained = (cpu(), None);
|
||||
let warm = frame(&s, &mut retained, "anisotropic-before-replace");
|
||||
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
|
||||
live(&s, blend, keys, false);
|
||||
assert!(s.doc().unwrap().doc.node(path).is_none());
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![blend]);
|
||||
let n = s.doc().unwrap().doc.node(blend).unwrap();
|
||||
let NodeKind::Blend { spec, .. } = &n.kind else { panic!("INPUT: the fixture must remain a live blend") };
|
||||
let spine = spec.spine.as_ref().unwrap().bounds().unwrap();
|
||||
assert!(spine.width().abs() < 1e-8 && (spine.height() - 160.0).abs() < 1e-8, "INPUT: this is the fixed vertical rail");
|
||||
let expanded = vectorcraft_render::expand_live(n);
|
||||
let placed = expanded.iter().find(|n| n.id == keys[0]).unwrap();
|
||||
let b = placed.geometric_bounds().unwrap();
|
||||
assert!((b.width() - 80.0).abs() < 1e-8 && (b.height() - 8.0).abs() < 1e-8, "INPUT: Align to Path must really turn the key by 90 degrees");
|
||||
assert_eq!(placed.appearance.effects.len(), 1);
|
||||
assert_eq!(placed.appearance.effects[0].params["scaleH"], json!(scale_h));
|
||||
let replaced = frame(&s, &mut retained, &format!("rotated-transform-{scale_h}-replace"));
|
||||
assert!(replaced.pixels != warm.pixels, "INPUT: the replacement must really change the painted frame");
|
||||
move_and_undo(&mut s, &mut retained, blend, keys, false, &replaced);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before);
|
||||
let restored = frame(&s, &mut retained, "anisotropic-undo-replace");
|
||||
same_pixels(&restored, &warm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_5179_rotated_transform_damage_contains_painted_pixels() {
|
||||
// The control completes every render, move and history check before the witness runs.
|
||||
rotated_transform_damage(200.0);
|
||||
rotated_transform_damage(400.0);
|
||||
}
|
||||
@@ -95,6 +95,29 @@ fn apply_to_all_restyles_every_dimension_in_one_undo_step() {
|
||||
assert!(s.execute("dimension.applyToAll", &json!({"id":line})).is_err(), "not a dimension");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() {
|
||||
use vectorcraft_doc::Arrowhead;
|
||||
let mut s = session();
|
||||
for (style, head) in
|
||||
[("filled", Some(Arrowhead::Triangle)), ("open", Some(Arrowhead::TriangleOpen)), ("tick", Some(Arrowhead::Slash)), ("none", None)]
|
||||
{
|
||||
let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":style}}))["id"].as_u64().unwrap();
|
||||
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap();
|
||||
let heads: Vec<_> = n
|
||||
.children()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone())))
|
||||
.filter(|(a, b)| a.is_some() || b.is_some())
|
||||
.collect();
|
||||
match head {
|
||||
Some(head) => assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style}: {heads:?}"),
|
||||
None => assert!(heads.is_empty(), "{style}: {heads:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimension_angles_circles_arcs_and_curves() {
|
||||
let mut s = session();
|
||||
@@ -1933,6 +1956,149 @@ fn an_anchor_beside_a_drawn_dimension_takes_the_point() {
|
||||
assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()]));
|
||||
}
|
||||
|
||||
/// The Smart Guide lines a pointer move at (`x`, `y`) shows, as their ends.
|
||||
fn guide_lines(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> Vec<(vectorcraft_geom::Point, vectorcraft_geom::Point)> {
|
||||
use vectorcraft_engine::tools::Overlay;
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap();
|
||||
s.overlays(view).into_iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some((a, b)) } else { None }).collect()
|
||||
}
|
||||
|
||||
/// An edge with anchors at x 100, 200 and 300, and a dimension from 100 to 200 placed 30 points
|
||||
/// above it, with the Dimension tool active and nothing selected: the session and the dimension.
|
||||
fn level_start(view: ViewInfo) -> (Session, u64) {
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let mut s = session();
|
||||
run(&mut s, "path.create", json!({"d": "M100 200 L200 200 L300 200 L300 300 L100 300 Z"}));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
s.select_tool("dimension", view).unwrap();
|
||||
linear_click(&mut s, view, 100.0, 200.0);
|
||||
linear_click(&mut s, view, 200.0, 200.0);
|
||||
linear_click(&mut s, view, 150.0, 170.0);
|
||||
let first = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
run(&mut s, "select.none", json!({}));
|
||||
(s, first)
|
||||
}
|
||||
|
||||
/// The next dimension, from 200 to 300, placed with the pointer at `y`: where its line lies.
|
||||
fn level_next(s: &mut Session, view: ViewInfo, y: f64) -> (vectorcraft_geom::Point, vectorcraft_geom::Point) {
|
||||
linear_click(s, view, 200.0, 200.0);
|
||||
linear_click(s, view, 300.0, 200.0);
|
||||
linear_click(s, view, 250.0, y);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
recipe(s, id).line_ends()
|
||||
}
|
||||
|
||||
/// A dimension placed next to another, with its line within the Smart Guides snapping tolerance of
|
||||
/// the level of the other's parallel line, has its line on that level. A level further off, Smart
|
||||
/// Guides off, a locked dimension or one that is not parallel leaves the line where the pointer
|
||||
/// puts it.
|
||||
#[test]
|
||||
fn a_dimension_line_placed_beside_another_lands_on_its_level() {
|
||||
let plain = ViewInfo::default();
|
||||
let off = ViewInfo { smart_guides: false, ..plain };
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
// 2.5 points below the first line's level, and 3.5 above it: on the level.
|
||||
for y in [172.5, 166.5] {
|
||||
let (mut s, _) = level_start(plain);
|
||||
assert_eq!(level_next(&mut s, plain, y), (pt(200.0, 170.0), pt(300.0, 170.0)), "pointer at y {y}");
|
||||
}
|
||||
// 10 points off: where the pointer is.
|
||||
let (mut s, _) = level_start(plain);
|
||||
assert_eq!(level_next(&mut s, plain, 180.0), (pt(200.0, 180.0), pt(300.0, 180.0)));
|
||||
// Smart Guides off: where the pointer is.
|
||||
let (mut s, _) = level_start(off);
|
||||
assert_eq!(level_next(&mut s, off, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5)));
|
||||
// A locked dimension does not pull the line.
|
||||
let (mut s, first) = level_start(plain);
|
||||
run(&mut s, "select.set", json!({"ids":[first]}));
|
||||
run(&mut s, "object.lock", json!({}));
|
||||
assert_eq!(level_next(&mut s, plain, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5)));
|
||||
// A dimension of the right edge has a vertical line, which is not parallel to the first: the
|
||||
// pointer 2.5 points below the first line's level places it where the pointer is.
|
||||
let (mut s, _) = level_start(plain);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 300.0);
|
||||
linear_click(&mut s, plain, 330.0, 172.5);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(330.0, 200.0), pt(330.0, 300.0)));
|
||||
}
|
||||
|
||||
/// While a dimension is placed with its line on the level of another, one alignment guide runs
|
||||
/// along the level across both lines. Off the level, after a dropped press and with Alignment
|
||||
/// Guides off, no guide shows.
|
||||
#[test]
|
||||
fn a_dimension_line_on_another_level_shows_one_guide_across_both() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (mut s, _) = level_start(plain);
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
let guides = guide_lines(&mut s, plain, 250.0, 172.5);
|
||||
assert!(guides.iter().any(|(a, b)| near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}");
|
||||
assert!(guide_lines(&mut s, plain, 250.0, 180.0).is_empty(), "no guide off the level");
|
||||
// A press on the level that the app drops cancels the preview, and its guide goes with it.
|
||||
assert!(!guide_lines(&mut s, plain, 250.0, 172.5).is_empty());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 172.5), plain).unwrap();
|
||||
s.drop_tool_press(plain).unwrap();
|
||||
assert!(s.overlays(plain).iter().all(|o| !matches!(o, vectorcraft_engine::tools::Overlay::Line { .. })), "{:?}", s.overlays(plain));
|
||||
// Alignment Guides off: the line still lands on the level, with no guide.
|
||||
let (mut s, _) = level_start(plain);
|
||||
run(&mut s, "prefs.set", json!({"key": "alignmentGuides", "value": false}));
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
assert!(guide_lines(&mut s, plain, 250.0, 172.5).is_empty());
|
||||
linear_click(&mut s, plain, 250.0, 172.5);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0)));
|
||||
}
|
||||
|
||||
/// A second dimension of the same two points as a dimension already drawn lands on its level too.
|
||||
/// Off every level, a pointer moved in small steps while it is placed puts the line at each step,
|
||||
/// with no pull from the preview of the dimension itself.
|
||||
#[test]
|
||||
fn a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
let (mut s, first) = level_start(plain);
|
||||
linear_click(&mut s, plain, 100.0, 200.0);
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 150.0, 172.5);
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_ne!(id, first);
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0)));
|
||||
let (mut s, _) = level_start(plain);
|
||||
linear_click(&mut s, plain, 200.0, 200.0);
|
||||
linear_click(&mut s, plain, 300.0, 200.0);
|
||||
for y in [190.0, 189.0, 188.0, 187.0, 186.0] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, y), plain).unwrap();
|
||||
}
|
||||
for kind in [PointerKind::Down, PointerKind::Up] {
|
||||
s.pointer(&PointerEvent::new(kind, 250.0, 186.0), plain).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 186.0), pt(300.0, 186.0)));
|
||||
}
|
||||
|
||||
/// A dimension dragged out from a segment, with its line within the Smart Guides snapping
|
||||
/// tolerance of the level of another dimension's parallel line, lands on that level.
|
||||
#[test]
|
||||
fn a_dimension_dragged_out_beside_another_lands_on_its_level() {
|
||||
let plain = ViewInfo::default();
|
||||
let pt = vectorcraft_geom::Point::new;
|
||||
// The bottom edge dragged out to 2 points below the level of the first line, 130 points
|
||||
// above the edge: on the level.
|
||||
let (mut s, _) = level_start(plain);
|
||||
for (kind, y) in
|
||||
[(PointerKind::Move, 300.0), (PointerKind::Down, 300.0), (PointerKind::Drag, 240.0), (PointerKind::Drag, 172.0), (PointerKind::Up, 172.0)]
|
||||
{
|
||||
s.pointer(&PointerEvent::new(kind, 160.0, y), plain).unwrap();
|
||||
}
|
||||
let id = s.doc().unwrap().selection.objects[0].0;
|
||||
let (a, b) = recipe(&s, id).line_ends();
|
||||
assert!(near(a, pt(300.0, 170.0)) && near(b, pt(100.0, 170.0)) || near(a, pt(100.0, 170.0)) && near(b, pt(300.0, 170.0)), "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
/// The page content streams of exported PDF `v`, inflated.
|
||||
fn pdf_content(v: &Value) -> String {
|
||||
let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap();
|
||||
|
||||
@@ -287,3 +287,107 @@ fn a_cancelled_export_stops_the_exporter() {
|
||||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||||
assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}");
|
||||
}
|
||||
|
||||
/// Every string in `v`, at any depth.
|
||||
fn strings_in(v: &Value, out: &mut Vec<String>) {
|
||||
match v {
|
||||
Value::String(s) => out.push(s.clone()),
|
||||
Value::Array(items) => items.iter().for_each(|v| strings_in(v, out)),
|
||||
Value::Object(map) => map.values().for_each(|v| strings_in(v, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A confined caller: an exporter, given the native document's JSON, is not run for a document
|
||||
/// that links a JavaScript file, a data set's image or a placed file outside the read roots. Every
|
||||
/// command that writes its format refuses, before any file or folder is written, with an error
|
||||
/// that names no file or folder, and the document keeps its links. A data set's image inside the
|
||||
/// roots is given to it, the JSON it is given leaves out an Export for Screens folder outside them,
|
||||
/// and the person's export gives it every path as stored.
|
||||
#[test]
|
||||
fn a_confined_exporter_is_refused_stored_paths_outside_the_read_roots() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine};
|
||||
|
||||
let away = tmp_dir("confined-away");
|
||||
let home = tmp_dir("confined-home");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("assets.add", &json!({"ids": [r["id"]]})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.confined", r#"["tsc"]"#, "{}"), Echo::Input));
|
||||
let format = "plugin.test.confined";
|
||||
let roots = AutomationRoots::new(&[home.as_path()], &[home.as_path()]).unwrap();
|
||||
let out = path_of(&home.join("out"));
|
||||
let outputs = [
|
||||
("document.serialize", json!({"format": format})),
|
||||
("document.export", json!({"format": format})),
|
||||
("document.export", json!({"format": format, "path": path_of(&home.join("export.tsc"))})),
|
||||
("document.exportSelection", json!({"format": format})),
|
||||
("document.exportForScreens", json!({"folder": out, "formats": [{"format": format}]})),
|
||||
("assets.export", json!({"folder": out, "formats": [{"format": format}]})),
|
||||
];
|
||||
let hidden = [path_of(&away), path_of(&home)];
|
||||
// `assets`: an asset's file is checked too (its document holds the asset's art and the
|
||||
// document's data sets, not other art).
|
||||
let refused = |s: &mut Session, why: &str, assets: bool| {
|
||||
for (cmd, p) in outputs.iter().filter(|(cmd, _)| assets || *cmd != "assets.export") {
|
||||
let e = confine(roots.as_ref(), || s.execute(cmd, p)).expect_err(&format!("{cmd} {p}: {why}"));
|
||||
assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}");
|
||||
let e = e.to_string();
|
||||
assert!(e.contains(why), "{cmd} {p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
|
||||
}
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(&home).unwrap().count(), 0, "nothing is written");
|
||||
};
|
||||
// The strings of the JSON the exporter is given.
|
||||
let given = |s: &mut Session, confined: bool| {
|
||||
let p = json!({"format": format});
|
||||
let r = if confined { confine(roots.as_ref(), || s.execute("document.export", &p)) } else { s.execute("document.export", &p) };
|
||||
let mut found = vec![];
|
||||
strings_in(&serde_json::from_slice(&exported(&r.unwrap())).unwrap(), &mut found);
|
||||
found
|
||||
};
|
||||
|
||||
let script = path_of(&away.join("menu.js"));
|
||||
s.execute("svgInteractivity.addFile", &json!({"file": script})).unwrap();
|
||||
refused(&mut s, "a linked JavaScript file is outside the read roots", true);
|
||||
assert!(given(&mut s, false).contains(&script), "the person's export");
|
||||
s.execute("svgInteractivity.removeFile", &json!({"file": script})).unwrap();
|
||||
|
||||
let set_image = |s: &mut Session, path: &str| {
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect();
|
||||
doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }];
|
||||
};
|
||||
let photo = path_of(&away.join("photo.png"));
|
||||
set_image(&mut s, &photo);
|
||||
refused(&mut s, "a linked image file is outside the read roots", true);
|
||||
assert!(given(&mut s, false).contains(&photo), "the person's export");
|
||||
let inside = path_of(&home.join("photo.png"));
|
||||
set_image(&mut s, &inside);
|
||||
assert!(given(&mut s, true).contains(&inside), "an image inside the read roots");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.clear();
|
||||
|
||||
let folder = path_of(&away.join("screens"));
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap();
|
||||
assert!(!given(&mut s, true).contains(&folder), "the export folder is left out");
|
||||
assert!(given(&mut s, false).contains(&folder), "the person's export");
|
||||
assert_eq!(s.doc().unwrap().doc.export_settings.get("folder"), Some(&json!(folder)), "the document keeps it");
|
||||
|
||||
let mut part = Session::new();
|
||||
part.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let placed = path_of(&away.join("part.vectorcraft"));
|
||||
part.execute("file.saveAs", &json!({"path": placed})).unwrap();
|
||||
s.execute("file.place", &json!({"path": placed, "link": true})).unwrap();
|
||||
refused(&mut s, "a linked image file is outside the read roots", false);
|
||||
// The asset's file holds the rectangle alone, without the placed file.
|
||||
let r = confine(roots.as_ref(), || s.execute("assets.export", &outputs[5].1)).unwrap();
|
||||
let mut found = vec![];
|
||||
strings_in(&serde_json::from_slice(&std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap(), &mut found);
|
||||
assert!(!found.contains(&placed), "{found:?}");
|
||||
let _ = std::fs::remove_dir_all(&away);
|
||||
let _ = std::fs::remove_dir_all(&home);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
//! Production preflight must find actual delivery problems and clear them after repairs.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
fn new() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({ "width": 500, "height": 400 })).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn check(s: &mut Session) -> Value {
|
||||
s.execute("document.preflight", &json!({})).unwrap()
|
||||
}
|
||||
|
||||
fn codes(report: &Value) -> Vec<&str> {
|
||||
report["findings"].as_array().unwrap().iter().map(|f| f["code"].as_str().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_finds_four_problems_and_repairs_clear_each_one() {
|
||||
let dir = Folder::new("preflight-four");
|
||||
let path = dir.file("picture.png");
|
||||
let bytes = png(40, 40, [200, 50, 10]);
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
let mut s = new();
|
||||
let text = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight Missing Family 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone();
|
||||
let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200], "link": true })).unwrap()["ids"][0].clone();
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
let before_doc = s.doc().unwrap().doc.clone();
|
||||
let before_sel = s.doc().unwrap().selection.clone();
|
||||
let revision = s.doc().unwrap().revision;
|
||||
let report = check(&mut s);
|
||||
for code in ["missingFont", "overflow", "missingLink", "lowResolution"] {
|
||||
assert!(codes(&report).contains(&code), "{code}: {report}");
|
||||
}
|
||||
assert_eq!(*before_doc, *s.doc().unwrap().doc);
|
||||
assert_eq!(before_sel, s.doc().unwrap().selection);
|
||||
assert_eq!(revision, s.doc().unwrap().revision, "checking doesn't edit the document");
|
||||
for f in report["findings"].as_array().unwrap() {
|
||||
assert!(f["ids"].as_array().unwrap().iter().all(|id| id == &text || id == &image), "{f}");
|
||||
}
|
||||
s.execute("text.areaOptions", &json!({ "ids": [text], "height": 150 })).unwrap();
|
||||
assert!(!codes(&check(&mut s)).contains(&"overflow"));
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
s.execute("links.update", &json!({ "ids": [image] })).unwrap();
|
||||
assert!(!codes(&check(&mut s)).contains(&"missingLink"));
|
||||
s.execute("select.set", &json!({ "ids": [image] })).unwrap();
|
||||
s.execute("object.setBounds", &json!({ "width": 7.2, "height": 7.2 })).unwrap();
|
||||
assert!(!codes(&check(&mut s)).contains(&"lowResolution"));
|
||||
// Deleting the missing-font object fixes the final delivery issue on any machine, including
|
||||
// builds with no optional craft-fonts checkout or installed fonts.
|
||||
s.execute("select.set", &json!({ "ids": [text] })).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
let clean = check(&mut s);
|
||||
assert!(codes(&clean).is_empty(), "{clean}");
|
||||
assert!(clean["checks"].as_array().unwrap().iter().all(|c| c["status"] == "passed"));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(codes(&check(&mut s)).contains(&"missingFont"), "undo is checked too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_reuses_link_probes_for_external_changes_without_an_edit() {
|
||||
let dir = Folder::new("preflight-modified");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200] })).unwrap()["ids"][0].clone();
|
||||
let rev = s.doc().unwrap().revision;
|
||||
std::fs::write(&path, png(41, 45, [10, 50, 200])).unwrap();
|
||||
assert!(codes(&check(&mut s)).contains(&"modifiedLink"));
|
||||
assert_eq!(rev, s.doc().unwrap().revision);
|
||||
s.execute("links.update", &json!({ "ids": [image] })).unwrap();
|
||||
assert!(!codes(&check(&mut s)).contains(&"modifiedLink"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_scopes_artboards_and_respects_hidden_and_nonprinting_layers() {
|
||||
let mut s = new();
|
||||
let id = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Scope 917" })).unwrap()["id"].clone();
|
||||
s.execute("artboard.new", &json!({ "x": 600, "y": 0, "width": 500, "height": 400 })).unwrap();
|
||||
let other = s.execute("document.preflight", &json!({ "artboards": [1] })).unwrap();
|
||||
assert!(codes(&other).is_empty(), "{other}");
|
||||
assert!(codes(&check(&mut s)).contains(&"missingFont"));
|
||||
s.execute("object.setProps", &json!({ "ids": [id], "visible": false })).unwrap();
|
||||
assert!(codes(&check(&mut s)).is_empty());
|
||||
s.execute("object.setProps", &json!({ "ids": [id], "visible": true, "locked": true })).unwrap();
|
||||
assert!(codes(&check(&mut s)).contains(&"missingFont"), "locked artwork still exports");
|
||||
let layer = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.setProps", &json!({ "id": layer.0, "printable": false })).unwrap();
|
||||
let print = s.execute("document.preflight", &json!({ "output": "print" })).unwrap();
|
||||
assert!(codes(&print).is_empty(), "{print}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resolution_follows_placed_size_and_both_axes() {
|
||||
let dir = Folder::new("preflight-resolution");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone();
|
||||
s.execute("select.set", &json!({ "ids": [id] })).unwrap();
|
||||
s.execute("object.setBounds", &json!({ "width": 24, "height": 72 })).unwrap();
|
||||
let r = check(&mut s);
|
||||
let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap();
|
||||
assert_eq!(f["effectivePpi"], json!([300.0, 100.0]));
|
||||
let screen = s.execute("document.preflight", &json!({ "output": "screen" })).unwrap();
|
||||
assert_eq!(screen["minPpi"], 96.0);
|
||||
assert!(codes(&screen).is_empty(), "{screen}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() {
|
||||
let dir = Folder::new("preflight-resolution-boundary");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap();
|
||||
for threshold in [31.0, 59.0, 300.0, 600.0, 9600.0] {
|
||||
let size = 40.0 * 72.0 / threshold;
|
||||
s.execute("object.setBounds", &json!({ "width": size, "height": size })).unwrap();
|
||||
let exact = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap();
|
||||
assert!(!codes(&exact).contains(&"lowResolution"), "exactly {threshold} ppi: {exact}");
|
||||
s.execute("object.setBounds", &json!({ "width": size * 1.000001, "height": size })).unwrap();
|
||||
let below = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap();
|
||||
let f = below["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap();
|
||||
assert_eq!(f["threshold"], threshold);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resolution_includes_the_print_jobs_scale() {
|
||||
let dir = Folder::new("preflight-print-scale");
|
||||
let path = dir.file("picture.png");
|
||||
std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap();
|
||||
let mut s = new();
|
||||
s.execute("file.place", &json!({ "path": path, "link": false, "at": [250, 200] })).unwrap();
|
||||
s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap();
|
||||
let doc = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap();
|
||||
assert!(codes(&doc).is_empty(), "{doc}");
|
||||
s.execute("print.setup", &json!({ "settings": { "scaling": "custom", "scale": { "width": 200, "height": 200 } } })).unwrap();
|
||||
let print = s.execute("document.preflight", &json!({ "output": "print", "minPpi": 200 })).unwrap();
|
||||
let f = print["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap();
|
||||
assert_eq!(f["effectivePpi"], json!([150.0, 150.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_reports_a_frame_that_cannot_show_even_its_first_line() {
|
||||
let mut s = new();
|
||||
let id = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Abc", "size": 30, "area": { "width": 100, "height": 1 } })).unwrap()["id"]
|
||||
.clone();
|
||||
let r = check(&mut s);
|
||||
assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_reports_type_that_cannot_place_a_glyph_on_a_horizontal_path() {
|
||||
let mut s = new();
|
||||
let path = s.execute("path.create", &json!({ "d": "M10 20 L11 20" })).unwrap()["id"].clone();
|
||||
let id = s.execute("text.createInPath", &json!({ "path": path, "mode": "onPath", "text": "Longer than the path" })).unwrap()["id"].clone();
|
||||
let r = check(&mut s);
|
||||
assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_bad_options_leave_document_and_selection_unchanged() {
|
||||
let mut s = new();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
for p in [
|
||||
json!({ "output": "unknown" }),
|
||||
json!({ "output": 1 }),
|
||||
json!({ "minPpi": 0 }),
|
||||
json!({ "minPpi": "300" }),
|
||||
json!({ "artboards": [] }),
|
||||
json!({ "artboards": [0.5] }),
|
||||
json!({ "artboards": [999] }),
|
||||
] {
|
||||
assert!(s.execute("document.preflight", &p).is_err(), "{p}");
|
||||
assert_eq!(*doc, *s.doc().unwrap().doc);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_resource_font_finding_locates_its_instance() {
|
||||
let mut s = new();
|
||||
let text = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Symbol 917" })).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({ "ids": [text] })).unwrap();
|
||||
s.execute("symbol.new", &json!({ "name": "Label" })).unwrap();
|
||||
let r = check(&mut s);
|
||||
let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "missingFont").unwrap();
|
||||
assert!(f["ids"].as_array().unwrap().iter().all(|id| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some()), "{r}");
|
||||
}
|
||||
|
||||
struct Folder(std::path::PathBuf);
|
||||
impl Folder {
|
||||
fn new(name: &str) -> Self {
|
||||
Self(vectorcraft_testkit::temp_dir(name))
|
||||
}
|
||||
fn file(&self, name: &str) -> String {
|
||||
self.0.join(name).to_string_lossy().into_owned()
|
||||
}
|
||||
}
|
||||
impl Drop for Folder {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec<u8> {
|
||||
let pixels = (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect();
|
||||
let image =
|
||||
craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap();
|
||||
craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &Default::default()).unwrap()
|
||||
}
|
||||
@@ -3431,6 +3431,133 @@ fn many_gradient_definitions_take_distinct_names_in_order() {
|
||||
assert_eq!(text, program(&doc));
|
||||
}
|
||||
|
||||
/// The program written from `doc`, with the gradient and pattern definitions found by comparing
|
||||
/// each in turn (`scanned`) or through their indexes.
|
||||
fn program_scanned(doc: &Document, scanned: bool) -> Vec<u8> {
|
||||
writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned));
|
||||
let out = export_ai_editing(doc, &opts());
|
||||
writer::SCANNED_DEFINITIONS.with(|s| s.set(false));
|
||||
out.unwrap().program
|
||||
}
|
||||
|
||||
/// [`gradients_and_patterns`] with more rectangles, each filled with a gradient: `distinct` with
|
||||
/// gradients of their own; `reused` with one of `ramps` gradients in turn; one for each of
|
||||
/// `swatches` new gradient swatches, linked to it, with the swatch's gradient for every other one
|
||||
/// and another gradient for the rest; one with the gradient of an object whose style isn't written
|
||||
/// (an even-odd fill with a drop shadow), after that object; and two whose gradients
|
||||
/// differ only in the sign of a zero offset.
|
||||
fn many_gradients(distinct: u16, reused: u16, ramps: u16, swatches: u16) -> Document {
|
||||
let mut doc = gradients_and_patterns();
|
||||
let two = |a: Color, b: Color| ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]);
|
||||
let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1));
|
||||
let swatch_gradient = |i: u16| two(Color::gray(shade(i, swatches)), Color::rgb(1.0, 0.0, 0.0));
|
||||
let more = (0..swatches)
|
||||
.map(|i| Swatch { name: format!("Ramp {i}"), paint: gradient_paint(swatch_gradient(i), None, None), global: false, spot: false })
|
||||
.collect();
|
||||
swatches_plus(&mut doc, more);
|
||||
let mut paints = vec![];
|
||||
for i in 0..distinct {
|
||||
paints.push(gradient_paint(two(Color::rgb(shade(i, distinct), 0.5, 0.0), Color::rgb(0.0, 0.0, 1.0)), None, None));
|
||||
}
|
||||
for i in 0..reused {
|
||||
paints.push(gradient_paint(two(Color::rgb(0.0, shade(i % ramps.max(1), ramps), 0.5), Color::WHITE), None, None));
|
||||
}
|
||||
for i in 0..swatches {
|
||||
let g = if i % 2 == 0 { swatch_gradient(i) } else { two(Color::gray(shade(i, swatches)), Color::rgb(0.0, 1.0, 0.0)) };
|
||||
paints.push(gradient_paint(g, None, Some(&format!("Ramp {i}"))));
|
||||
}
|
||||
// The reader wouldn't read an even-odd fill with the style, so the style isn't written.
|
||||
let unstyled = two(Color::WHITE, Color::BLACK);
|
||||
let ap = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(unstyled.clone(), None, None)))],
|
||||
effects: vec![fx("stylize.dropShadow", serde_json::json!({}))],
|
||||
contents_index: None,
|
||||
};
|
||||
let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap);
|
||||
if let NodeKind::Path { rule, .. } = &mut n.kind {
|
||||
*rule = FillRule::EvenOdd;
|
||||
}
|
||||
put(&mut doc, n);
|
||||
paints.push(gradient_paint(unstyled, None, None));
|
||||
let zero = |o: f32| ramp(GradientKind::Linear, &[(o, Color::rgb(0.2, 0.3, 0.4), 1.0, 0.5), (1.0, Color::BLACK, 1.0, 0.5)]);
|
||||
paints.extend([gradient_paint(zero(0.0), None, None), gradient_paint(zero(-0.0), None, None)]);
|
||||
for (i, p) in (0u16..).zip(paints) {
|
||||
let (x, y) = (f64::from(i % 60) * 5.0, f64::from(i / 60 % 40) * 5.0);
|
||||
let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), vec![AppearanceItem::Fill(FillLayer::new(p))]);
|
||||
put(&mut doc, n);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
/// Gradient and pattern definitions found through their indexes are those found by comparing each
|
||||
/// in turn: the program is the same, byte for byte. A swatch's definition serves a paint linked to
|
||||
/// it only with the swatch's gradient; a gradient defined for a style that isn't written leaves its
|
||||
/// name free; gradients that differ only in the sign of a zero share a definition.
|
||||
#[test]
|
||||
fn indexed_definitions_write_the_same_program() {
|
||||
let doc = many_gradients(300, 300, 7, 6);
|
||||
let (indexed, scanned) = (program_scanned(&doc, false), program_scanned(&doc, true));
|
||||
let differ = indexed.iter().zip(&scanned).position(|(a, b)| a != b);
|
||||
assert!(indexed == scanned, "the programs differ from byte {differ:?} ({} and {} bytes)", indexed.len(), scanned.len());
|
||||
let text = String::from_utf8(indexed).unwrap();
|
||||
let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect();
|
||||
// `gradients_and_patterns`'s 5, then 300 + 7 + 6 swatches' + 3 others linked to swatches + 1
|
||||
// after the style + 1 for both signs of zero.
|
||||
assert_eq!(names.len(), 5 + 300 + 7 + 6 + 3 + 1 + 1, "{names:?}");
|
||||
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len(), "{names:?}");
|
||||
assert_eq!(text.matches("%AI3_BeginPattern: (Dots)").count(), 1);
|
||||
}
|
||||
|
||||
/// A gradient paint is matched with the definitions of the same gradient, not with each
|
||||
/// definition: 1,000 gradients of their own and 1,000 paints of 10 others take a few comparisons
|
||||
/// each, where comparing each definition in turn takes hundreds of thousands.
|
||||
#[test]
|
||||
fn gradient_definitions_are_found_without_comparing_each() {
|
||||
let doc = many_gradients(1000, 1000, 10, 0);
|
||||
let comparisons = |scanned: bool| {
|
||||
writer::GRADIENT_COMPARISONS.with(|c| c.set(0));
|
||||
program_scanned(&doc, scanned);
|
||||
writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get)
|
||||
};
|
||||
let (indexed, scanned) = (comparisons(false), comparisons(true));
|
||||
assert!(indexed <= 2 * 2010, "{indexed} comparisons through the index");
|
||||
assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index");
|
||||
}
|
||||
|
||||
/// The time to write 5,000 rectangles with gradients of their own, 5,000 with 50 others and 20
|
||||
/// gradient swatches, with the definitions found by comparing each in turn and through their
|
||||
/// indexes: the median of 7 runs of each, alternating, with the programs compared. Run with
|
||||
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture gradient_definitions_timing`.
|
||||
#[test]
|
||||
#[ignore = "timing"]
|
||||
fn gradient_definitions_timing() {
|
||||
let doc = many_gradients(5000, 5000, 50, 20);
|
||||
let mut times = [vec![], vec![]];
|
||||
let mut programs: [Option<Vec<u8>>; 2] = [None, None];
|
||||
let mut how = "";
|
||||
for _ in 0..7 {
|
||||
for (k, scanned) in [true, false].into_iter().enumerate() {
|
||||
let (start, h) = thread_time();
|
||||
let program = program_scanned(&doc, scanned);
|
||||
times[k].push(thread_time().0.saturating_sub(start));
|
||||
how = h;
|
||||
programs[k].get_or_insert(program);
|
||||
}
|
||||
}
|
||||
assert_eq!(programs[0], programs[1]);
|
||||
for t in &mut times {
|
||||
t.sort();
|
||||
}
|
||||
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
|
||||
println!("median of 7 runs ({how}):");
|
||||
println!("| definitions found | median (ms) | runs (ms) |");
|
||||
println!("|---|---:|---|");
|
||||
for (k, label) in ["by comparing each", "through the indexes"].into_iter().enumerate() {
|
||||
let runs: Vec<String> = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect();
|
||||
println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
/// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop,
|
||||
/// and reads back with each stop on its side.
|
||||
#[test]
|
||||
|
||||
@@ -45,7 +45,8 @@ pub(super) use images::PAYLOAD;
|
||||
pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT};
|
||||
#[cfg(test)]
|
||||
pub(super) use paints::{
|
||||
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
|
||||
GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS,
|
||||
SWATCH_PLACEMENT, free_gradient_name,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
|
||||
@@ -200,11 +201,11 @@ pub(super) struct Writer<'a> {
|
||||
/// pattern's definition, the pattern's space turned y up.
|
||||
canvas: Affine,
|
||||
/// The gradient definitions, in the order they are first used.
|
||||
gradients: Vec<paints::GradientDef>,
|
||||
gradients: paints::GradientDefs,
|
||||
/// The number the next new gradient definition's name tries first (1 is `Gradient`).
|
||||
next_gradient: u64,
|
||||
/// The pattern definitions written, each after those its art uses.
|
||||
patterns: Vec<paints::PatternOut>,
|
||||
patterns: paints::PatternDefs,
|
||||
/// The patterns whose definitions are being written.
|
||||
defining: Vec<String>,
|
||||
/// Writing the palette: the definitions it adds are for its swatches only.
|
||||
@@ -357,9 +358,9 @@ impl<'a> Writer<'a> {
|
||||
grad_space: to_art,
|
||||
tile_grad_space: Affine::translate((-origin.0, origin.1)),
|
||||
canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art,
|
||||
gradients: vec![],
|
||||
gradients: paints::GradientDefs::default(),
|
||||
next_gradient: 1,
|
||||
patterns: vec![],
|
||||
patterns: paints::PatternDefs::default(),
|
||||
defining: vec![],
|
||||
in_palette: false,
|
||||
canvas_origin: origin,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Gradients and patterns: their definitions in the setup, gradient instances on paths and the
|
||||
//! pattern operators (see [`crate::ai_editing`] for the form).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use vectorcraft_color::gradient::GradientGeom;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
@@ -46,6 +48,134 @@ pub(super) struct PatternOut {
|
||||
used: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Whether [`GradientDefs`] and [`PatternDefs`] find definitions on this thread by comparing
|
||||
/// the gradient or name with each definition in turn.
|
||||
pub(in crate::ai_editing) static SCANNED_DEFINITIONS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// How many times [`GradientDefs::find`] has compared two gradients on this thread.
|
||||
pub(in crate::ai_editing) static GRADIENT_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Are gradients `a` and `b` the same?
|
||||
fn same_gradient(a: &Gradient, b: &Gradient) -> bool {
|
||||
#[cfg(test)]
|
||||
GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1));
|
||||
a == b
|
||||
}
|
||||
|
||||
/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its
|
||||
/// bits, with -0 as 0); different gradients may share one.
|
||||
fn gradient_key(g: &Gradient) -> u64 {
|
||||
let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() };
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
std::mem::discriminant(&g.kind).hash(&mut h);
|
||||
std::mem::discriminant(&g.method).hash(&mut h);
|
||||
(g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h);
|
||||
for s in &g.stops {
|
||||
let (model, c) = match s.color {
|
||||
Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]),
|
||||
Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]),
|
||||
Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]),
|
||||
Color::Lab { l, a, b } => (3, [l, a, b, 0.0]),
|
||||
};
|
||||
(model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h);
|
||||
(&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// The gradient definitions, in the order they are first used, found by name and by gradient
|
||||
/// without comparing each one.
|
||||
#[derive(Default)]
|
||||
pub(super) struct GradientDefs {
|
||||
list: Vec<GradientDef>,
|
||||
/// Each definition's place in `list`, by its name (no two definitions share one).
|
||||
names: HashMap<String, usize>,
|
||||
/// The places in `list` of the definitions no swatch names, in order, by their gradient's key
|
||||
/// ([`gradient_key`]).
|
||||
ramps: HashMap<u64, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl GradientDefs {
|
||||
/// Is `name` a definition's name?
|
||||
fn has_name(&self, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return self.list.iter().any(|d| d.name == name);
|
||||
}
|
||||
self.names.contains_key(name)
|
||||
}
|
||||
|
||||
/// The place of the definition of `g`: the swatch `swatch` names when it is a gradient swatch
|
||||
/// of the same gradient, else the first definition of the same gradient that no swatch names.
|
||||
fn find(&self, g: &Gradient, swatch: Option<&str>) -> Option<usize> {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return swatch
|
||||
.and_then(|s| self.list.iter().position(|d| d.swatch && d.name == s && same_gradient(&d.gradient, g)))
|
||||
.or_else(|| self.list.iter().position(|d| !d.swatch && same_gradient(&d.gradient, g)));
|
||||
}
|
||||
let held = |i: &usize, swatch: bool| self.list.get(*i).is_some_and(|d| d.swatch == swatch && same_gradient(&d.gradient, g));
|
||||
swatch
|
||||
.and_then(|s| self.names.get(s).copied().filter(|i| held(i, true)))
|
||||
.or_else(|| self.ramps.get(&gradient_key(g))?.iter().copied().find(|i| held(i, false)))
|
||||
}
|
||||
|
||||
/// Add `d`, whose name no definition has.
|
||||
fn push(&mut self, d: GradientDef) {
|
||||
let i = self.list.len();
|
||||
if !d.swatch {
|
||||
self.ramps.entry(gradient_key(&d.gradient)).or_default().push(i);
|
||||
}
|
||||
self.names.insert(d.name.clone(), i);
|
||||
self.list.push(d);
|
||||
}
|
||||
|
||||
/// Keep the first `len` definitions; the names of those removed are free again.
|
||||
fn truncate(&mut self, len: usize) {
|
||||
while self.list.len() > len {
|
||||
let Some(d) = self.list.pop() else { break };
|
||||
self.names.remove(&d.name);
|
||||
if !d.swatch {
|
||||
// Places are added in order, so the removed definition's is the last of its key's.
|
||||
let key = gradient_key(&d.gradient);
|
||||
if let Some(places) = self.ramps.get_mut(&key) {
|
||||
places.pop();
|
||||
if places.is_empty() {
|
||||
self.ramps.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern definitions written, each after those its art uses, found by name.
|
||||
#[derive(Default)]
|
||||
pub(super) struct PatternDefs {
|
||||
list: Vec<PatternOut>,
|
||||
/// Each definition's place in `list`, by its name (no two definitions share one).
|
||||
names: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl PatternDefs {
|
||||
/// The place of pattern `name`'s definition.
|
||||
fn find(&self, name: &str) -> Option<usize> {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return self.list.iter().position(|p| p.name == name);
|
||||
}
|
||||
self.names.get(name).copied()
|
||||
}
|
||||
|
||||
/// Add `p`, whose name no definition has.
|
||||
fn push(&mut self, p: PatternOut) {
|
||||
self.names.insert(p.name.clone(), self.list.len());
|
||||
self.list.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::ai_editing) const DIAMOND: &str =
|
||||
"diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps";
|
||||
@@ -118,7 +248,7 @@ impl Writer<'_> {
|
||||
&& let stops = curve_as_stops(&g.gradient)
|
||||
&& let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS)
|
||||
&& writable_gradient(&gradient)
|
||||
&& !self.gradients.iter().any(|d| d.name == sw.name)
|
||||
&& !self.gradients.has_name(&sw.name)
|
||||
{
|
||||
self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false });
|
||||
}
|
||||
@@ -131,17 +261,14 @@ impl Writer<'_> {
|
||||
/// swatch or a pattern).
|
||||
fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String {
|
||||
let used = !self.in_palette;
|
||||
let found = swatch
|
||||
.and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g))
|
||||
.or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g));
|
||||
if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) {
|
||||
let found = self.gradients.find(g, swatch);
|
||||
if let Some(d) = found.and_then(|i| self.gradients.list.get_mut(i)) {
|
||||
d.used |= used;
|
||||
return d.name.clone();
|
||||
}
|
||||
let (doc, gradients) = (self.doc, &self.gradients);
|
||||
let name = free_gradient_name(&mut self.next_gradient, |name| {
|
||||
gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()
|
||||
});
|
||||
let name =
|
||||
free_gradient_name(&mut self.next_gradient, |name| gradients.has_name(name) || doc.swatch(name).is_some() || doc.pattern(name).is_some());
|
||||
self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used });
|
||||
name
|
||||
}
|
||||
@@ -149,14 +276,14 @@ impl Writer<'_> {
|
||||
/// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the
|
||||
/// art uses, and the next name's number.
|
||||
pub(super) fn gradient_mark(&self) -> (usize, Vec<bool>, u64) {
|
||||
(self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient)
|
||||
(self.gradients.list.len(), self.gradients.list.iter().map(|d| d.used).collect(), self.next_gradient)
|
||||
}
|
||||
|
||||
/// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]).
|
||||
pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec<bool>, u64)) {
|
||||
let (len, used, next) = mark;
|
||||
self.gradients.truncate(len);
|
||||
for (d, u) in self.gradients.iter_mut().zip(used) {
|
||||
for (d, u) in self.gradients.list.iter_mut().zip(used) {
|
||||
d.used = u;
|
||||
}
|
||||
self.next_gradient = next;
|
||||
@@ -476,7 +603,7 @@ impl Writer<'_> {
|
||||
if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol {
|
||||
return false;
|
||||
}
|
||||
if self.patterns.iter().any(|p| p.name == name) {
|
||||
if self.patterns.find(name).is_some() {
|
||||
return true;
|
||||
}
|
||||
self.doc.pattern(name).is_some_and(tile_holds_art)
|
||||
@@ -492,7 +619,7 @@ impl Writer<'_> {
|
||||
return false;
|
||||
}
|
||||
let used = !self.in_palette;
|
||||
if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) {
|
||||
if let Some(p) = self.patterns.find(name).and_then(|i| self.patterns.list.get_mut(i)) {
|
||||
p.used |= used;
|
||||
return true;
|
||||
}
|
||||
@@ -582,7 +709,7 @@ impl Writer<'_> {
|
||||
/// uses).
|
||||
pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) {
|
||||
let defs = std::mem::take(&mut self.gradients);
|
||||
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used);
|
||||
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.list.iter().partition(|d| d.used);
|
||||
let _ = writeln!(s, "{} Bn", used.len());
|
||||
for d in &used {
|
||||
self.gradient_def(s, d);
|
||||
@@ -595,12 +722,12 @@ impl Writer<'_> {
|
||||
s.push_str("%AI5_End_NonPrinting--\n");
|
||||
}
|
||||
self.gradients = defs;
|
||||
for p in self.patterns.iter().filter(|p| p.used) {
|
||||
for p in self.patterns.list.iter().filter(|p| p.used) {
|
||||
s.push_str(&p.text);
|
||||
}
|
||||
if self.patterns.iter().any(|p| !p.used) {
|
||||
if self.patterns.list.iter().any(|p| !p.used) {
|
||||
s.push_str("%AI5_Begin_NonPrinting\nNp\n");
|
||||
for p in self.patterns.iter().filter(|p| !p.used) {
|
||||
for p in self.patterns.list.iter().filter(|p| !p.used) {
|
||||
s.push_str(&p.text);
|
||||
}
|
||||
s.push_str("%AI5_End_NonPrinting--\n");
|
||||
@@ -729,3 +856,94 @@ fn tile_holds_art(def: &PatternDef) -> bool {
|
||||
b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn two(a: f32, b: Color) -> Gradient {
|
||||
Gradient::new(GradientKind::Linear, vec![GradientStop::new(a, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, b)])
|
||||
}
|
||||
|
||||
fn def(name: &str, gradient: Gradient, swatch: bool) -> GradientDef {
|
||||
GradientDef { name: name.into(), gradient, swatch, used: true }
|
||||
}
|
||||
|
||||
/// The same gradients have the same key, a zero of either sign included.
|
||||
#[test]
|
||||
fn a_zero_of_either_sign_gives_the_same_key() {
|
||||
assert_eq!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(-0.0, Color::BLACK)));
|
||||
assert_eq!(two(0.0, Color::BLACK), two(-0.0, Color::BLACK));
|
||||
assert_ne!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(0.0, Color::WHITE)));
|
||||
}
|
||||
|
||||
/// Definitions whose gradients share a key are told apart by their gradients, the first of the
|
||||
/// same gradient found; a gradient that isn't equal to itself is found in none.
|
||||
#[test]
|
||||
fn definitions_that_share_a_key_are_told_apart() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Gradient", white.clone(), false));
|
||||
defs.push(def("Gradient 2", black.clone(), false));
|
||||
defs.push(def("Gradient 3", black.clone(), false));
|
||||
// Every definition under the black gradient's key, as if the keys of both were the same.
|
||||
defs.ramps = HashMap::from([(gradient_key(&black), vec![0, 1, 2])]);
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, None), None);
|
||||
defs.ramps.insert(gradient_key(&white), vec![0, 1, 2]);
|
||||
assert_eq!(defs.find(&white, None), Some(0));
|
||||
let nan = two(f32::NAN, Color::BLACK);
|
||||
defs.push(def("Gradient 4", nan.clone(), false));
|
||||
assert_eq!(defs.find(&nan, None), None);
|
||||
}
|
||||
|
||||
/// A swatch's definition is found by the swatch's name and gradient; a definition that no
|
||||
/// swatch names, for the same gradient without the name or with another.
|
||||
#[test]
|
||||
fn a_swatch_definition_is_found_by_its_name_and_gradient() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Ramp", black.clone(), true));
|
||||
assert_eq!(defs.find(&black, Some("Ramp")), Some(0));
|
||||
assert_eq!(defs.find(&black, None), None);
|
||||
assert_eq!(defs.find(&white, Some("Ramp")), None);
|
||||
defs.push(def("Gradient", black.clone(), false));
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
assert_eq!(defs.find(&black, Some("Ramp")), Some(0));
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, Some("Ramp")), Some(2));
|
||||
assert_eq!(defs.find(&black, Some("Other")), Some(1));
|
||||
}
|
||||
|
||||
/// Definitions removed leave their names free and are no longer found; those kept still are.
|
||||
#[test]
|
||||
fn removed_definitions_free_their_names() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Ramp", white.clone(), true));
|
||||
defs.push(def("Gradient", black.clone(), false));
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
defs.push(def("Gradient 3", black.clone(), false));
|
||||
defs.truncate(2);
|
||||
assert!(defs.has_name("Ramp") && defs.has_name("Gradient"));
|
||||
assert!(!defs.has_name("Gradient 2") && !defs.has_name("Gradient 3"));
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, None), None);
|
||||
assert_eq!(defs.ramps.values().map(Vec::len).sum::<usize>(), 1);
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
assert_eq!(defs.find(&white, None), Some(2));
|
||||
defs.truncate(0);
|
||||
assert!(defs.list.is_empty() && defs.names.is_empty() && defs.ramps.is_empty());
|
||||
}
|
||||
|
||||
/// A pattern's definition is found by its name.
|
||||
#[test]
|
||||
fn pattern_definitions_are_found_by_name() {
|
||||
let mut defs = PatternDefs::default();
|
||||
assert_eq!(defs.find("Dots"), None);
|
||||
for name in ["Dots", "Checks"] {
|
||||
defs.push(PatternOut { name: name.into(), text: String::new(), used: false });
|
||||
}
|
||||
assert_eq!((defs.find("Dots"), defs.find("Checks"), defs.find("Stripes")), (Some(0), Some(1), None));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,8 @@ mod tests_native;
|
||||
#[cfg(test)]
|
||||
mod tests_reads;
|
||||
#[cfg(test)]
|
||||
mod tests_strings;
|
||||
#[cfg(test)]
|
||||
mod tests_type1;
|
||||
#[cfg(test)]
|
||||
mod tests_type42;
|
||||
|
||||
@@ -146,13 +146,21 @@ impl Interp<'_> {
|
||||
fn token(&mut self) -> Res {
|
||||
match self.pop()? {
|
||||
Obj::Str(s) => {
|
||||
let bytes = s.to_vec();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
let Some(o) = lex.next()? else { return self.push(Obj::Bool(false)) };
|
||||
let o = self.scanned(o, lex.immediate)?;
|
||||
// The whitespace after the token is read with it.
|
||||
let used = bytes.len() - lex.data().len();
|
||||
self.push_interval(Obj::Str(s), used, bytes.len() - used)?;
|
||||
// The scanner reads the string in place. The borrow ends before `scanned`, which
|
||||
// can fail or charge the budget, and before the results are pushed.
|
||||
let read = {
|
||||
let bytes = s.borrow();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
// The whitespace after the token is read with it.
|
||||
lex.next()?.map(|o| {
|
||||
let immediate = lex.immediate;
|
||||
let rest = lex.data().len();
|
||||
(o, immediate, bytes.len() - rest, rest)
|
||||
})
|
||||
};
|
||||
let Some((o, immediate, used, rest)) = read else { return self.push(Obj::Bool(false)) };
|
||||
let o = self.scanned(o, immediate)?;
|
||||
self.push_interval(Obj::Str(s), used, rest)?;
|
||||
self.push(o)?;
|
||||
}
|
||||
Obj::File { stream: f, .. } => {
|
||||
|
||||
@@ -753,21 +753,25 @@ impl<'a> Interp<'a> {
|
||||
}
|
||||
|
||||
fn search_string(&mut self, op: Op) -> Res {
|
||||
let seek = self.pop_str()?.to_vec();
|
||||
let seek = self.pop_str()?;
|
||||
let s = self.pop_str()?;
|
||||
let text = s.to_vec();
|
||||
self.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
// Both strings are read in place, and the borrows end before the results are pushed.
|
||||
let (len, n, at) = {
|
||||
let (text, seek) = (s.borrow(), seek.borrow());
|
||||
self.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
(text.len(), seek.len(), at)
|
||||
};
|
||||
match at {
|
||||
Some(i) => {
|
||||
let o = Obj::Str(s);
|
||||
if op == Op::Search {
|
||||
self.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?;
|
||||
self.push_interval(o.clone(), i, seek.len())?;
|
||||
self.push_interval(o.clone(), i + n, len - i - n)?;
|
||||
self.push_interval(o.clone(), i, n)?;
|
||||
self.push_interval(o, 0, i)?;
|
||||
} else {
|
||||
self.push_interval(o.clone(), seek.len(), text.len() - seek.len())?;
|
||||
self.push_interval(o, 0, seek.len())?;
|
||||
self.push_interval(o.clone(), n, len - n)?;
|
||||
self.push_interval(o, 0, n)?;
|
||||
}
|
||||
self.push(Obj::Bool(true))?;
|
||||
}
|
||||
|
||||
@@ -49,6 +49,8 @@ thread_local! {
|
||||
/// Tests: the arrays of the list last released on this thread that were still alive after it
|
||||
/// (the ones the interpreter itself still held).
|
||||
pub(crate) static ARRAYS_LEFT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many values [`Shared::to_vec`] has copied on this thread.
|
||||
pub(crate) static VALUES_COPIED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
@@ -340,7 +342,10 @@ impl<T: Clone + Held> Shared<T> {
|
||||
}
|
||||
|
||||
pub fn to_vec(&self) -> Vec<T> {
|
||||
self.borrow().to_vec()
|
||||
let v = self.borrow().to_vec();
|
||||
#[cfg(test)]
|
||||
VALUES_COPIED.with(|n| n.set(n.get() + v.len()));
|
||||
v
|
||||
}
|
||||
|
||||
/// `n` values from `at`, sharing the storage (`getinterval`); `None` past the end.
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
//! `token` on a string, `search` and `anchorsearch` (PLRM 3rd ed., pp. 702-703, 655 and 529) read
|
||||
//! their strings in place. The tests run them next to reference readers that copy the strings
|
||||
//! first, on the same operands in the same interpreter state: the operand stack, the error and the
|
||||
//! operations spent must agree.
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::graphics::{GState, Out};
|
||||
use super::interp::Interp;
|
||||
use super::lex::Lexer;
|
||||
use super::obj::{Obj, Op, PsError, Res, Shared, VALUES_COPIED};
|
||||
|
||||
/// An interpreter that has run `src`, with the operands it left.
|
||||
fn after(src: &[u8]) -> Interp<'_> {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.layers.clear();
|
||||
let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]);
|
||||
let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0)));
|
||||
assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src));
|
||||
it
|
||||
}
|
||||
|
||||
/// The reference `token`: the string copied before it is scanned.
|
||||
fn token_by_copy(it: &mut Interp) -> Res {
|
||||
match it.pop()? {
|
||||
Obj::Str(s) => {
|
||||
let bytes = s.to_vec();
|
||||
let mut lex = Lexer::new(&bytes);
|
||||
let Some(o) = lex.next()? else { return it.push(Obj::Bool(false)) };
|
||||
let o = it.scanned(o, lex.immediate)?;
|
||||
let used = bytes.len() - lex.data().len();
|
||||
it.push_interval(Obj::Str(s), used, bytes.len() - used)?;
|
||||
it.push(o)?;
|
||||
}
|
||||
Obj::File { stream: f, .. } => {
|
||||
let (o, immediate) = it.next_in(&f)?;
|
||||
let Some(o) = o else { return it.push(Obj::Bool(false)) };
|
||||
let o = it.scanned(o, immediate)?;
|
||||
it.push(o)?;
|
||||
}
|
||||
_ => return Err(PsError::Ps("typecheck", "token".into())),
|
||||
}
|
||||
it.push(Obj::Bool(true))
|
||||
}
|
||||
|
||||
/// The reference `search` and `anchorsearch`: both strings copied before they are compared.
|
||||
fn search_by_copy(it: &mut Interp, op: Op) -> Res {
|
||||
let seek = it.pop_str()?.to_vec();
|
||||
let s = it.pop_str()?;
|
||||
let text = s.to_vec();
|
||||
it.spend((text.len() / 64) as u64)?;
|
||||
let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) };
|
||||
match at {
|
||||
Some(i) => {
|
||||
let o = Obj::Str(s);
|
||||
if op == Op::Search {
|
||||
it.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?;
|
||||
it.push_interval(o.clone(), i, seek.len())?;
|
||||
it.push_interval(o, 0, i)?;
|
||||
} else {
|
||||
it.push_interval(o.clone(), seek.len(), text.len() - seek.len())?;
|
||||
it.push_interval(o, 0, seek.len())?;
|
||||
}
|
||||
it.push(Obj::Bool(true))?;
|
||||
}
|
||||
None => {
|
||||
it.push(Obj::Str(s))?;
|
||||
it.push(Obj::Bool(false))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn by_copy(it: &mut Interp, op: Op) -> Res {
|
||||
if op == Op::Token { token_by_copy(it) } else { search_by_copy(it, op) }
|
||||
}
|
||||
|
||||
/// The error's name, or the limit reached.
|
||||
fn outcome(r: Res) -> Result<(), String> {
|
||||
r.map_err(|e| match e {
|
||||
PsError::Ps(name, _) => name.to_string(),
|
||||
e => format!("{e:?}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Everything the operator left: the operand stack with each string's storage, offset and length,
|
||||
/// and the operations spent.
|
||||
fn state(it: &Interp) -> (String, u64) {
|
||||
(format!("{:?}", it.stack), it.ops_left())
|
||||
}
|
||||
|
||||
/// Run `op` on the operands `src` leaves, in place and by copy, `steps` times (a walk that feeds
|
||||
/// each call the string the last one left), and check that the two agree after every call.
|
||||
fn agree(src: &str, op: Op, steps: usize) {
|
||||
let (mut new, mut old) = (after(src.as_bytes()), after(src.as_bytes()));
|
||||
// `search` and `anchorsearch` look for the same string on each call.
|
||||
let seeks = [new.stack.last().cloned(), old.stack.last().cloned()];
|
||||
for step in 0..steps {
|
||||
let (a, b) = (outcome(new.op(op)), outcome(by_copy(&mut old, op)));
|
||||
assert_eq!(a, b, "{src} {op:?}, call {step}");
|
||||
assert_eq!(state(&new), state(&old), "{src} {op:?}, call {step}");
|
||||
// Keep walking while the operator answered true, with the string it left.
|
||||
let more = matches!(new.stack.last(), Some(Obj::Bool(true)));
|
||||
if a.is_err() || !more {
|
||||
break;
|
||||
}
|
||||
for (it, seek) in [&mut new, &mut old].into_iter().zip(&seeks) {
|
||||
it.stack.pop();
|
||||
// `token` leaves the rest under the object; `search` leaves it under match and pre
|
||||
// (and `anchorsearch` under the match).
|
||||
let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 };
|
||||
it.stack.truncate(keep);
|
||||
// The string to look for again, or the file `token` reads on from.
|
||||
if op != Op::Token || matches!(seek, Some(Obj::File { .. })) {
|
||||
it.stack.extend(seek.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
new.release();
|
||||
old.release();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_and_search_agree_with_copying_readers() {
|
||||
let tokens = [
|
||||
"()",
|
||||
"( )",
|
||||
"(\r\n\t )",
|
||||
"(12)",
|
||||
"(12 34)",
|
||||
"(12 34)",
|
||||
"(12\r\n34)",
|
||||
"(/x {a b} (s) <41> 1.5 x)",
|
||||
"(1 {)",
|
||||
"( [ 1 ] )",
|
||||
"/x 7 def (//x {//x} y)",
|
||||
"(xx12 34 56) 2 7 getinterval",
|
||||
"(%comment only)",
|
||||
"5",
|
||||
"(12 /x {a}) /ReusableStreamDecode filter",
|
||||
"currentfile",
|
||||
];
|
||||
for src in tokens {
|
||||
agree(src, Op::Token, 16);
|
||||
}
|
||||
let searches = [
|
||||
"(abcabc) (bc)",
|
||||
"(abc) (x)",
|
||||
"(abc) ()",
|
||||
"() ()",
|
||||
"() (a)",
|
||||
"(ab) (abc)",
|
||||
"(a\nb\nc\n) (\n)",
|
||||
"/s (aa) def s s",
|
||||
"(xxab cd ef) 2 8 getinterval ( )",
|
||||
"(abc) 5",
|
||||
"5 (abc)",
|
||||
];
|
||||
for src in searches {
|
||||
agree(src, Op::Search, 8);
|
||||
agree(src, Op::AnchorSearch, 8);
|
||||
}
|
||||
// Over the operation budget: the same error, with the same operands popped.
|
||||
let big = "/h 65536 string def h (\\001)";
|
||||
let (mut new, mut old) = (after(big.as_bytes()), after(big.as_bytes()));
|
||||
for it in [&mut new, &mut old] {
|
||||
let left = it.ops_left();
|
||||
assert_eq!(it.spend(left.saturating_sub(10)), Ok(()));
|
||||
}
|
||||
let (a, b) = (outcome(new.op(Op::Search)), outcome(by_copy(&mut old, Op::Search)));
|
||||
assert!(a.as_ref().is_err_and(|e| e.contains("too long")), "{a:?}");
|
||||
assert_eq!((a, state(&new)), (b, state(&old)));
|
||||
new.release();
|
||||
old.release();
|
||||
}
|
||||
|
||||
/// The results share the string's storage: a write to the string after `token` or `search` shows
|
||||
/// in what they left.
|
||||
#[test]
|
||||
fn token_and_search_results_see_later_writes() {
|
||||
let check = super::tests::check;
|
||||
check("/s (12 34) def s token pop pop /post exch def s 3 57 put post token pop exch pop 94 eq");
|
||||
check("/s (ab cd) def s ( ) search pop /pre exch def pop /post exch def s 0 120 put s 4 121 put pre (xb) eq post (cy) eq and");
|
||||
check("/s (ab cd) def s (ab) anchorsearch pop pop /post exch def s 4 122 put post ( cz) eq");
|
||||
check("/s (xx12 34) def s 2 5 getinterval token pop pop /post exch def s 5 57 put post token pop exch pop 94 eq");
|
||||
}
|
||||
|
||||
/// `token` on a string, `search` and `anchorsearch` copy neither string.
|
||||
#[test]
|
||||
fn token_and_search_copy_no_string() {
|
||||
for (src, op) in [
|
||||
("(12 34 56 78)", Op::Token),
|
||||
("(abc def ghi) ( )", Op::Search),
|
||||
("(abc def ghi) (xyz)", Op::Search),
|
||||
("(abc def ghi) (abc)", Op::AnchorSearch),
|
||||
("(abc def ghi) (def)", Op::AnchorSearch),
|
||||
] {
|
||||
let mut it = after(src.as_bytes());
|
||||
VALUES_COPIED.with(|n| n.set(0));
|
||||
assert_eq!(it.op(op), Ok(()), "{src} {op:?}");
|
||||
assert_eq!(VALUES_COPIED.with(std::cell::Cell::get), 0, "{src} {op:?}");
|
||||
it.release();
|
||||
}
|
||||
}
|
||||
|
||||
/// The median of `runs`.
|
||||
fn median(runs: &[Duration]) -> Duration {
|
||||
let mut sorted = runs.to_vec();
|
||||
sorted.sort();
|
||||
sorted.get(sorted.len() / 2).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What a walk records of each result: a string's length and first bytes, any other object whole.
|
||||
fn mark(o: &Obj, h: &mut impl Hasher) {
|
||||
match o {
|
||||
Obj::Str(s) => {
|
||||
s.len().hash(h);
|
||||
s.borrow().iter().take(16).for_each(|b| b.hash(h));
|
||||
}
|
||||
o => format!("{o:?}").hash(h),
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk `data` with `op` and `seek` (none for `token`) until the operator answers false, by copy
|
||||
/// or in place: how long it took, the calls made, and a hash of every result and of the operations
|
||||
/// spent. The interpreter is made before the clock starts.
|
||||
fn walk(data: &[u8], op: Op, seek: Option<&[u8]>, copy: bool) -> (Duration, usize, u64) {
|
||||
let mut it = after(b"");
|
||||
it.stack.push(Obj::Str(Shared::new(data.to_vec())));
|
||||
let mut calls = 0;
|
||||
let mut h = DefaultHasher::new();
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if let Some(seek) = seek {
|
||||
it.stack.push(Obj::Str(Shared::new(seek.to_vec())));
|
||||
}
|
||||
let r = if copy { by_copy(&mut it, op) } else { it.op(op) };
|
||||
assert_eq!(r, Ok(()));
|
||||
calls += 1;
|
||||
if !matches!(it.stack.pop(), Some(Obj::Bool(true))) {
|
||||
break;
|
||||
}
|
||||
let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 };
|
||||
it.stack.iter().for_each(|o| mark(o, &mut h));
|
||||
it.stack.truncate(keep);
|
||||
}
|
||||
let took = start.elapsed();
|
||||
it.stack.iter().for_each(|o| mark(o, &mut h));
|
||||
it.ops_left().hash(&mut h);
|
||||
it.release();
|
||||
(took, calls, h.finish())
|
||||
}
|
||||
|
||||
/// Time both readers on `data` in 7 runs, alternating which goes first, check that they leave the
|
||||
/// same, and print every run and the medians.
|
||||
fn compare(what: &str, data: &[u8], op: Op, seek: Option<&[u8]>) {
|
||||
let (mut old, mut new) = (vec![], vec![]);
|
||||
let mut calls = 0;
|
||||
for run in 0..7 {
|
||||
let order: [bool; 2] = if run % 2 == 0 { [true, false] } else { [false, true] };
|
||||
let mut got = vec![];
|
||||
for copy in order {
|
||||
let (took, n, last) = walk(data, op, seek, copy);
|
||||
if copy {
|
||||
old.push(took)
|
||||
} else {
|
||||
new.push(took)
|
||||
}
|
||||
calls = n;
|
||||
got.push((n, last));
|
||||
}
|
||||
assert!(got.first() == got.get(1), "{what}: the readers differ");
|
||||
}
|
||||
let ms = |d: &Duration| format!("{:.2}", d.as_secs_f64() * 1000.0);
|
||||
println!("{what}: {} bytes, {calls} calls", data.len());
|
||||
println!(" by copy, ms: {}", old.iter().map(ms).collect::<Vec<_>>().join(" "));
|
||||
println!(" in place, ms: {}", new.iter().map(ms).collect::<Vec<_>>().join(" "));
|
||||
let (o, w) = (median(&old), median(&new));
|
||||
println!(" median: by copy {} ms, in place {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9));
|
||||
}
|
||||
|
||||
/// Times `token` and `search` walking a string by what each call leaves, against the copying
|
||||
/// reference readers, in one process: strings of 4 KiB, 64 KiB and 512 KiB, of numbers and names
|
||||
/// for `token` and of 128-byte lines for `search`. Run it in release:
|
||||
/// `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn string_walks_timed() {
|
||||
for kib in [4, 64, 512] {
|
||||
let size = kib * 1024;
|
||||
let mut words = Vec::with_capacity(size + 16);
|
||||
let mut i = 0u32;
|
||||
while words.len() < size {
|
||||
let w = if i.is_multiple_of(2) { format!("{} ", i.wrapping_mul(2_654_435_761) % 100_000) } else { format!("/n{i} ") };
|
||||
words.extend_from_slice(w.as_bytes());
|
||||
i += 1;
|
||||
}
|
||||
compare(&format!("token, {kib} KiB"), &words, Op::Token, None);
|
||||
let lines: Vec<u8> = (0..size / 128).flat_map(|i| format!("{:<127}\n", format!("line {i}")).into_bytes()).collect();
|
||||
compare(&format!("search, {kib} KiB"), &lines, Op::Search, Some(b"\n"));
|
||||
}
|
||||
}
|
||||
@@ -1636,6 +1636,64 @@ fn doc_json(s: &mut Server) -> Value {
|
||||
serde_json::from_str(&text_of(&r)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_refused_by_a_later_operation_changes_nothing() {
|
||||
let mut s = server();
|
||||
let count = |s: &mut Server| -> u64 {
|
||||
let r = call(s, 90, "inspect_document", json!({}));
|
||||
serde_json::from_str::<Value>(&text_of(&r)).unwrap()["objects"].as_u64().unwrap()
|
||||
};
|
||||
let base = count(&mut s);
|
||||
let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50})));
|
||||
let before = doc_json(&mut s);
|
||||
for (id, args, says) in [
|
||||
(2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"),
|
||||
(3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"),
|
||||
(4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"),
|
||||
(5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"),
|
||||
(6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"),
|
||||
] {
|
||||
let t = call(&mut s, id, "transform", args.clone());
|
||||
assert_eq!(t["isError"], true, "{args}: {t}");
|
||||
assert!(text_of(&t).contains(says), "{args}: {t}");
|
||||
assert_eq!(doc_json(&mut s), before, "{args}");
|
||||
}
|
||||
// No undo step was recorded: one undo removes the rectangle.
|
||||
assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false);
|
||||
assert_eq!(count(&mut s), base, "one undo removes the rectangle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing() {
|
||||
let inspect = |s: &mut Server, id| serde_json::from_str::<Value>(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap();
|
||||
let mut s = server();
|
||||
let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"})));
|
||||
let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"})));
|
||||
let before = inspect(&mut s, 3);
|
||||
let cases = [
|
||||
("object.reflect", json!({"dx": 10, "reflect": 42, "copy": true})),
|
||||
("object.reflect", json!({"dx": 10, "reflect": true})),
|
||||
("copy", json!({"dx": 10, "copy": "yes"})),
|
||||
("origin", json!({"dx": 10, "rotate": 30, "origin": "center", "copy": true})),
|
||||
("origin", json!({"dx": 10, "rotate": 30, "origin": [5]})),
|
||||
("origin", json!({"dx": 10, "rotate": 30, "origin": [5, "a"]})),
|
||||
];
|
||||
for (index, (says, mut args)) in cases.into_iter().enumerate() {
|
||||
args["ids"] = json!([first]);
|
||||
let request_id = 4 + index as u64 * 2;
|
||||
let rejected = call(&mut s, request_id, "transform", args.clone());
|
||||
assert_eq!(rejected["isError"], true, "{args}: {rejected}");
|
||||
assert!(text_of(&rejected).contains(says), "{args}: {rejected}");
|
||||
// The document, the selection and the undo history are as they were.
|
||||
assert_eq!(inspect(&mut s, request_id + 1), before, "{args}");
|
||||
}
|
||||
// A null `reflect`, `copy` or `origin` is left out.
|
||||
let applied = call(&mut s, 20, "transform", json!({"ids": [second], "dx": 10, "reflect": null, "copy": null, "origin": null}));
|
||||
assert_eq!(applied["isError"], false, "{applied}");
|
||||
let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap();
|
||||
assert_eq!(applied["applied"], json!(["move"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_text_rejects_invalid_path_effects_before_editing() {
|
||||
let mut s = server();
|
||||
|
||||
@@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
tool(
|
||||
"transform",
|
||||
"Transform",
|
||||
"Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.",
|
||||
"Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection center; `copy` transforms a copy. A scale, reflect or shear its command refuses, or an argument of the wrong type, returns that error before any step runs, and nothing changes.",
|
||||
obj(
|
||||
json!({
|
||||
"ids": {"type": "array", "items": {"type": "integer"}},
|
||||
|
||||
@@ -302,9 +302,42 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
}
|
||||
|
||||
pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String> {
|
||||
// Each operation is its own command: check the params the later ones refuse before the first
|
||||
// runs, so a refused request changes nothing. The `transform` arm of `dispatch` has already
|
||||
// refused a `dx`, `dy`, `rotate`, `scale`, `scaleX`, `scaleY` or `shear` that is not a number.
|
||||
fn bad(cmd: &'static str) -> impl Fn(String) -> String {
|
||||
move |e| format!("invalid parameters for `{cmd}`: {e}")
|
||||
}
|
||||
let s = a.get("scale").and_then(Value::as_f64);
|
||||
let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s));
|
||||
if sx.is_some() || sy.is_some() {
|
||||
vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?;
|
||||
}
|
||||
// A null `reflect`, `copy` or `origin` is left out.
|
||||
let reflect = match a.get("reflect") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(axis)) => Some(axis.as_str()),
|
||||
Some(v) => return Err(format!("invalid parameters for `object.reflect`: axis must be \"vertical\" or \"horizontal\", not `{v}`")),
|
||||
};
|
||||
if let Some(axis) = reflect {
|
||||
vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?;
|
||||
}
|
||||
let shear = a.get("shear").and_then(Value::as_f64);
|
||||
if let Some(sh) = shear {
|
||||
vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?;
|
||||
}
|
||||
let copy = match a.get("copy") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| format!("`copy` must be true or false, not {v}"))?,
|
||||
};
|
||||
if let Some(o) = a.get("origin").filter(|o| !o.is_null())
|
||||
&& !o.as_array().is_some_and(|xy| xy.len() == 2 && xy.iter().all(Value::is_number))
|
||||
{
|
||||
return Err(format!("`origin` must be [x, y], not {o}"));
|
||||
}
|
||||
select_ids(b, a)?;
|
||||
// With `copy`, the first operation duplicates and the rest transform the copy (the new selection).
|
||||
let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false));
|
||||
let copy = std::cell::Cell::new(copy);
|
||||
let with = |mut p: Value| {
|
||||
if let Some(o) = a.get("origin") {
|
||||
p["origin"] = o.clone();
|
||||
@@ -322,17 +355,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result<Value, String>
|
||||
exec(b, "object.rotate", with(json!({"angle": r})))?;
|
||||
done.push("rotate");
|
||||
}
|
||||
let s = a.get("scale").and_then(Value::as_f64);
|
||||
let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s));
|
||||
if sx.is_some() || sy.is_some() {
|
||||
exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?;
|
||||
done.push("scale");
|
||||
}
|
||||
if let Some(axis) = a.get("reflect").and_then(Value::as_str) {
|
||||
if let Some(axis) = reflect {
|
||||
exec(b, "object.reflect", with(json!({"axis": axis})))?;
|
||||
done.push("reflect");
|
||||
}
|
||||
if let Some(sh) = a.get("shear").and_then(Value::as_f64) {
|
||||
if let Some(sh) = shear {
|
||||
exec(b, "object.shear", with(json!({"angle": sh})))?;
|
||||
done.push("shear");
|
||||
}
|
||||
|
||||
@@ -688,7 +688,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"window.panel.float",
|
||||
"Float Panel",
|
||||
"",
|
||||
"{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}",
|
||||
"{panel: id or \"tools\", x?, y?, width?, height?, group?: bool, column?: bool or n, onto?: id, above?: id, below?: id, collapsed?: bool} float a panel (with `group`, its whole group; with `column`, its whole dock column or floating window) as a floating window with its top-left corner at x, y in window points (default: inside the dock area, cascaded), as dragging its tab out does; a whole floating window keeps its rect unless given one. Supplied geometry also moves or resizes an existing native window; omitted components keep their current values. `onto` makes it a tab of the floating group holding that panel instead; `above` / `below` a group of its own above or below the group holding that panel, in its floating window or dock column. `collapsed` then minimizes (true) or restores (false) its window or group. A hidden panel shows first. \"tools\" floats the Tools panel at x, y. Returns {layout, closed, floating}",
|
||||
),
|
||||
(
|
||||
"window.panel.dock",
|
||||
@@ -1026,7 +1026,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.symbolOptions",
|
||||
"Symbol Options…",
|
||||
"F8",
|
||||
"{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}",
|
||||
"{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error",
|
||||
),
|
||||
(
|
||||
"tool.options",
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
//! Both are found as roots over the normal's angle: sampled, then refined by bisection, with
|
||||
//! sampled minima refined too so that a double root (outlines that touch) or two roots between
|
||||
//! neighboring samples are kept.
|
||||
//!
|
||||
//! One of the two may be a point instead ([`Outline::point`]): its support value is `p · n`, and
|
||||
//! the tangents are the lines through it that touch the other outline.
|
||||
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
@@ -60,7 +63,7 @@ pub enum OutlineError {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Coincide;
|
||||
|
||||
/// A convex closed outline that [`common_tangents`] takes.
|
||||
/// A convex closed outline, or a point, that [`common_tangents`] takes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Outline {
|
||||
/// The unit circle under an affine map: the center is the map's translation, `m` its linear
|
||||
@@ -70,9 +73,19 @@ pub enum Outline {
|
||||
/// when the segments run counter-clockwise (y up); the segment where `p · n` is largest then
|
||||
/// comes later in the list as the angle of `n` grows.
|
||||
Convex { segments: Vec<CubicBez>, center: Point, size: f64, ccw: bool },
|
||||
/// A single point.
|
||||
Point { at: Point },
|
||||
}
|
||||
|
||||
impl Outline {
|
||||
/// The point `at`, whose tangents are the lines through it.
|
||||
pub fn point(at: Point) -> Result<Self, OutlineError> {
|
||||
if !at.x.is_finite() || !at.y.is_finite() {
|
||||
return Err(OutlineError::Empty);
|
||||
}
|
||||
Ok(Outline::Point { at })
|
||||
}
|
||||
|
||||
/// The ellipse that `unit` maps the unit circle onto.
|
||||
pub fn ellipse(unit: Affine) -> Result<Self, OutlineError> {
|
||||
let [a, b, c, d, e, f] = unit.as_coeffs();
|
||||
@@ -183,6 +196,7 @@ impl Outline {
|
||||
size: *size,
|
||||
ccw: *ccw,
|
||||
},
|
||||
Outline::Point { at } => Outline::Point { at: *at + d },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,7 +217,7 @@ impl Outline {
|
||||
/// The support value at `n` and the segment it is reached on, from every segment.
|
||||
fn support_scan(&self, n: Vec2) -> (f64, usize) {
|
||||
match self {
|
||||
Outline::Ellipse { .. } => (self.support(n), 0),
|
||||
Outline::Ellipse { .. } | Outline::Point { .. } => (self.support(n), 0),
|
||||
Outline::Convex { segments, .. } => {
|
||||
let mut best = (f64::MIN, 0);
|
||||
for (i, s) in segments.iter().enumerate() {
|
||||
@@ -222,7 +236,7 @@ impl Outline {
|
||||
/// where the support value was reached at a normal angle a little less than `n`'s.
|
||||
fn support_from(&self, n: Vec2, from: usize) -> (f64, usize) {
|
||||
match self {
|
||||
Outline::Ellipse { .. } => (self.support(n), 0),
|
||||
Outline::Ellipse { .. } | Outline::Point { .. } => (self.support(n), 0),
|
||||
Outline::Convex { segments, ccw, .. } => {
|
||||
let len = segments.len();
|
||||
if len == 0 {
|
||||
@@ -251,14 +265,20 @@ impl Outline {
|
||||
}
|
||||
}
|
||||
|
||||
/// The center: an ellipse's, or a path's center of area.
|
||||
/// The center: an ellipse's, a path's center of area, or the point itself.
|
||||
pub fn center(&self) -> Point {
|
||||
match self {
|
||||
Outline::Ellipse { center, .. } | Outline::Convex { center, .. } => *center,
|
||||
Outline::Point { at } => *at,
|
||||
}
|
||||
}
|
||||
|
||||
/// The diagonal of the bounds (an ellipse's: of the box its axes span).
|
||||
/// Whether this is a point.
|
||||
pub fn is_point(&self) -> bool {
|
||||
matches!(self, Outline::Point { .. })
|
||||
}
|
||||
|
||||
/// The diagonal of the bounds (an ellipse's: of the box its axes span; a point's: 0).
|
||||
pub fn size(&self) -> f64 {
|
||||
match self {
|
||||
Outline::Ellipse { m, .. } => {
|
||||
@@ -266,6 +286,7 @@ impl Outline {
|
||||
2.0 * (a.hypot(c).powi(2) + b.hypot(d).powi(2)).sqrt()
|
||||
}
|
||||
Outline::Convex { size, .. } => *size,
|
||||
Outline::Point { .. } => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -280,6 +301,7 @@ impl Outline {
|
||||
}
|
||||
best
|
||||
}
|
||||
Outline::Point { at } => at.to_vec2().dot(n),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +342,7 @@ impl Outline {
|
||||
let Some(&(peak, _)) = all.iter().max_by(|x, y| x.1.total_cmp(&y.1)) else { return vec![] };
|
||||
all.into_iter().filter(|(p, v)| h - v <= tol + slope * (*p - peak).hypot()).map(|(p, _)| p).collect()
|
||||
}
|
||||
Outline::Point { at } => vec![*at],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -406,7 +429,14 @@ fn dir(angle: f64) -> Vec2 {
|
||||
/// the angle of its normal. Separate outlines have two of each; overlapping ones only external
|
||||
/// ones (two for ellipses, possibly more for paths whose outlines cross more often); one inside the
|
||||
/// other none; outlines that touch share one tangent where they touch.
|
||||
///
|
||||
/// When one of them is a point, its external and internal tangents are the same lines, and they
|
||||
/// come back as external ones: two when the point lies outside the other outline, one when it lies
|
||||
/// on it, none inside. Two points have none.
|
||||
pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincide> {
|
||||
if a.is_point() && b.is_point() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
// Worked out about the point between the two centers.
|
||||
let origin = (a.center().to_vec2() + b.center().to_vec2()) / 2.0;
|
||||
let (a, b) = (&a.shifted(-origin), &b.shifted(-origin));
|
||||
@@ -434,7 +464,11 @@ pub fn common_tangents(a: &Outline, b: &Outline) -> Result<Vec<Tangent>, Coincid
|
||||
let (ha, hb, hb_back) = (hints(a, 1.0), hints(b, 1.0), hints(b, -1.0));
|
||||
let hint = |h: &[usize], k: usize| h.get(k).copied().unwrap_or(0);
|
||||
let external = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 - b.support_from(dir(t), hint(&hb, k)).0, tol)?;
|
||||
let internal = roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?;
|
||||
let internal = if a.is_point() || b.is_point() {
|
||||
vec![]
|
||||
} else {
|
||||
roots(&at, &|t, k| a.support_from(dir(t), hint(&ha, k)).0 + b.support_from(-dir(t), hint(&hb_back, k)).0, tol)?
|
||||
};
|
||||
let (a, b) = (Hinted { o: a, at: &at, hints: &ha }, Hinted { o: b, at: &at, hints: &hb });
|
||||
let mut out = Vec::with_capacity(external.len() + internal.len());
|
||||
for (kind, list) in [(TangentKind::External, external), (TangentKind::Internal, internal)] {
|
||||
@@ -506,8 +540,13 @@ fn tangent_at(a: &Hinted, b: &Hinted, kind: TangentKind, angle: f64, double: boo
|
||||
// A double root's angle is found less exactly than a simple one's, so touching points may
|
||||
// stand a little apart.
|
||||
let (from, to) = if double && hi - lo <= 1e-6 * size {
|
||||
// Touching at one point: the narrower outline's width along the line, centered there.
|
||||
let width = [a, b].map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0).into_iter().fold(f64::MAX, f64::min);
|
||||
// Touching at one point: the narrower outline's width along the line, centered there. A
|
||||
// point on the other outline takes that outline's width.
|
||||
let width = [a, b]
|
||||
.into_iter()
|
||||
.filter(|o| !o.o.is_point())
|
||||
.map(|o| o.support(angle + TAU / 4.0).0 + o.support(angle - TAU / 4.0).0)
|
||||
.fold(f64::MAX, f64::min);
|
||||
let mid = (lo + hi) / 2.0;
|
||||
(mid - width / 2.0, mid + width / 2.0)
|
||||
} else if mean(&on_a) <= mean(&on_b) {
|
||||
@@ -975,6 +1014,127 @@ mod tests {
|
||||
assert!((best - 0.25).abs() < 1e-12, "{best}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_outside_a_turned_ellipse_has_two_tangents_through_it() {
|
||||
let m = ellipse_map(100.0, 50.0, 40.0, 15.0, 30.0);
|
||||
let (oval, p) = (Outline::ellipse(m).unwrap(), Point::new(-60.0, 120.0));
|
||||
let samples = sample_ellipse(m, 5_000);
|
||||
for point_first in [true, false] {
|
||||
let point = Outline::point(p).unwrap();
|
||||
let all = if point_first { common_tangents(&point, &oval) } else { common_tangents(&oval, &point) }.unwrap();
|
||||
assert_eq!(all.len(), 2, "{all:?}");
|
||||
for t in &all {
|
||||
assert_eq!(t.kind, TangentKind::External);
|
||||
// Each runs from the first outline given to the second: from the point when it
|
||||
// comes first.
|
||||
let (at_point, on_oval) = if point_first { (t.from, t.to) } else { (t.to, t.from) };
|
||||
assert!((at_point - p).hypot() < 1e-9, "{t:?}");
|
||||
// Taken back to the unit circle, the far end lies on it and the line runs square to
|
||||
// its radius there.
|
||||
let inv = m.inverse();
|
||||
let (q, d) = ((inv * on_oval).to_vec2(), (inv * on_oval) - (inv * at_point));
|
||||
assert!((q.hypot() - 1.0).abs() < 1e-9, "{q:?}");
|
||||
assert!((q.dot(d) / d.hypot()).abs() < 1e-7, "{q:?} {d:?}");
|
||||
// The whole ellipse lies on one side of the line.
|
||||
let dir = on_oval - at_point;
|
||||
let n = Vec2::new(-dir.y, dir.x) / dir.hypot();
|
||||
let side: Vec<f64> = samples.iter().map(|s| (*s - at_point).dot(n)).collect();
|
||||
let (lo, hi) = side.iter().fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
|
||||
assert!(lo > -1e-6 || hi < 1e-6, "crosses: {lo} .. {hi}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_on_inside_and_beside_a_path() {
|
||||
// On a circle: the one tangent there, centered on the point and as long as the circle is
|
||||
// wide.
|
||||
let on = common_tangents(&Outline::point(Point::new(10.0, 0.0)).unwrap(), &circle(0.0, 0.0, 10.0)).unwrap();
|
||||
assert_eq!(on.len(), 1, "{on:?}");
|
||||
assert!(ends_within(&on[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{on:?}");
|
||||
// Inside, and two points: none.
|
||||
assert!(common_tangents(&Outline::point(Point::new(3.0, 4.0)).unwrap(), &circle(0.0, 0.0, 10.0)).unwrap().is_empty());
|
||||
let two = (Outline::point(Point::new(0.0, 0.0)).unwrap(), Outline::point(Point::new(5.0, 0.0)).unwrap());
|
||||
assert!(common_tangents(&two.0, &two.1).unwrap().is_empty());
|
||||
// Beside a square, in line with its bottom side: that tangent covers the whole side, and
|
||||
// the other one touches the corner at (10, 10).
|
||||
let square = SubPath::polyline(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(Point::from), true);
|
||||
let sq = Outline::convex(&square).unwrap();
|
||||
let p = Point::new(20.0, 0.0);
|
||||
let all = common_tangents(&Outline::point(p).unwrap(), &sq).unwrap();
|
||||
assert_eq!(all.len(), 2, "{all:?}");
|
||||
assert!(all.iter().any(|t| ends_at(t, p, Point::new(0.0, 0.0))), "{all:?}");
|
||||
assert!(all.iter().any(|t| ends_at(t, p, Point::new(10.0, 10.0))), "{all:?}");
|
||||
assert!(all.iter().all(|t| (t.from - p).hypot() < 1e-9), "from the point: {all:?}");
|
||||
// On a straight side, off its middle: the one tangent is that side, covered whole.
|
||||
let side = common_tangents(&Outline::point(Point::new(2.0, 0.0)).unwrap(), &sq).unwrap();
|
||||
assert_eq!(side.len(), 1, "{side:?}");
|
||||
assert!(ends_at(&side[0], Point::new(0.0, 0.0), Point::new(10.0, 0.0)), "{side:?}");
|
||||
// At a corner of the square: one line through the corner, at the middle of the directions
|
||||
// that touch there, as long as the square is wide along it.
|
||||
let corner = common_tangents(&Outline::point(Point::new(10.0, 10.0)).unwrap(), &sq).unwrap();
|
||||
assert_eq!(corner.len(), 1, "{corner:?}");
|
||||
// The diagonal is 10√2 long, so each end lies 5√2 from the corner, along (1, -1).
|
||||
assert!(ends_within(&corner[0], Point::new(15.0, 5.0), Point::new(5.0, 15.0), 1e-5), "{corner:?}");
|
||||
// A point that is not finite is refused.
|
||||
assert_eq!(Outline::point(Point::new(f64::NAN, 0.0)).err(), Some(OutlineError::Empty));
|
||||
assert_eq!(Outline::point(Point::new(0.0, f64::INFINITY)).err(), Some(OutlineError::Empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_placed_on_a_turned_outline_has_one_tangent() {
|
||||
// A point worked out on the outline lies a rounding error inside or outside it, and still
|
||||
// gets the one line there, as long as the outline is wide along it.
|
||||
let one = |p: Point, o: &Outline, samples: &[Point]| {
|
||||
let all = common_tangents(&Outline::point(p).unwrap(), o).unwrap();
|
||||
assert_eq!(all.len(), 1, "{p:?}: {all:?}");
|
||||
// The line runs through the point.
|
||||
let (a, d) = (all[0].from, all[0].to - all[0].from);
|
||||
assert!(d.hypot() > 1.0 && ((p - a).cross(d) / d.hypot()).abs() < 1e-6, "{p:?}: {all:?}");
|
||||
// Its length is the outline's width along it, measured on dense samples.
|
||||
let u = d / d.hypot();
|
||||
let (lo, hi) = samples.iter().map(|s| s.to_vec2().dot(u)).fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(v), hi.max(v)));
|
||||
assert!((d.hypot() - (hi - lo)).abs() < 1e-3, "{p:?}: {} against {}", d.hypot(), hi - lo);
|
||||
};
|
||||
let m = ellipse_map(100.0, 50.0, 40.0, 15.0, 30.0);
|
||||
let (oval, oval_samples) = (Outline::ellipse(m).unwrap(), sample_ellipse(m, 20_000));
|
||||
for k in 0..37 {
|
||||
let a = 0.17 + k as f64 * TAU / 37.0;
|
||||
one(m * Point::new(a.cos(), a.sin()), &oval, &oval_samples);
|
||||
}
|
||||
// A closed Bézier circle, turned and moved: on each anchor and partway along each segment.
|
||||
let turned = shapes::ellipse(Rect::new(-60.0, -60.0, 60.0, 60.0)).transformed(Affine::translate((37.3, -12.9)) * Affine::rotate(0.7));
|
||||
let sp = turned.subpaths[0].clone();
|
||||
let (path, path_samples) = (Outline::convex(&sp).unwrap(), sample_path(&sp, 5_000));
|
||||
for an in sp.anchors.iter() {
|
||||
one(an.p, &path, &path_samples);
|
||||
}
|
||||
for k in 0..sp.segment_count() {
|
||||
for t in [0.21, 0.5, 0.83] {
|
||||
one(sp.segment(k).eval(t), &path, &path_samples);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_point_within_the_touching_tolerance_counts_as_on_the_outline() {
|
||||
// The tolerance is a billionth of the larger of the circle's size and the point's distance
|
||||
// from its center: closer than that, inside or outside, the point gets the one line there.
|
||||
let round = circle(0.0, 0.0, 10.0);
|
||||
let tol = 1e-9 * round.size().max(10.0);
|
||||
let at = |dx: f64| common_tangents(&Outline::point(Point::new(10.0 + dx, 0.0)).unwrap(), &round).unwrap();
|
||||
for dx in [-0.5 * tol, 0.5 * tol] {
|
||||
let on = at(dx);
|
||||
assert_eq!(on.len(), 1, "{dx}: {on:?}");
|
||||
assert!(ends_within(&on[0], Point::new(10.0, -10.0), Point::new(10.0, 10.0), 1e-5), "{dx}: {on:?}");
|
||||
}
|
||||
// Farther than that, a point inside gets none and a point outside gets two.
|
||||
assert!(at(-100.0 * tol).is_empty());
|
||||
assert_eq!(at(100.0 * tol).len(), 2);
|
||||
assert!(at(-1e-6).is_empty());
|
||||
assert_eq!(at(1e-6).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_concave_empty_and_identical_outlines_are_refused() {
|
||||
let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false);
|
||||
|
||||
+104
-27
@@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash ";
|
||||
/// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it
|
||||
/// keeps every offset.
|
||||
const PLACEHOLDER: &str = "0000000000000000";
|
||||
/// Deepest name tree searched for the editing file.
|
||||
const MAX_DEPTH: usize = 16;
|
||||
/// The most name tree nodes searched for the editing file.
|
||||
const MAX_NODES: usize = 1 << 16;
|
||||
|
||||
/// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -77,12 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option<Editing> {
|
||||
editing_in(&crate::pages::open(bytes, password).ok()?)
|
||||
}
|
||||
|
||||
/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]).
|
||||
struct Search<'a> {
|
||||
/// The editing file's file specification, if one was found.
|
||||
spec: Option<Dict<'a>>,
|
||||
/// A name tree key searched names the editing file (set also when its file specification
|
||||
/// can't be read).
|
||||
keyed: bool,
|
||||
/// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched.
|
||||
cut: bool,
|
||||
}
|
||||
|
||||
/// The search of a parsed PDF's attachments for the editing file.
|
||||
fn editing_file_spec(pdf: &Pdf) -> Search<'_> {
|
||||
let xref = pdf.xref();
|
||||
let Some(tree) = xref
|
||||
.get::<Dict<'_>>(xref.root_id())
|
||||
.and_then(|catalog| catalog.get::<Dict<'_>>(b"Names"))
|
||||
.and_then(|names| names.get::<Dict<'_>>(b"EmbeddedFiles"))
|
||||
else {
|
||||
return Search { spec: None, keyed: false, cut: false };
|
||||
};
|
||||
let (mut keyed, mut cut) = (false, false);
|
||||
let spec = editing_spec(tree, &mut keyed, &mut cut, xref);
|
||||
Search { spec, keyed, cut }
|
||||
}
|
||||
|
||||
/// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't
|
||||
/// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be
|
||||
/// resolved)? Also true when the name tree is too large to search to its end.
|
||||
pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool {
|
||||
let search = editing_file_spec(pdf);
|
||||
search.spec.is_some() || search.keyed || search.cut
|
||||
}
|
||||
|
||||
/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`]
|
||||
/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it
|
||||
/// reads.
|
||||
pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool {
|
||||
editing_file_spec(pdf).cut
|
||||
}
|
||||
|
||||
/// [`editing`] of a parsed PDF.
|
||||
pub(crate) fn editing_in(pdf: &Pdf) -> Option<Editing> {
|
||||
let xref = pdf.xref();
|
||||
let catalog = xref.get::<Dict<'_>>(xref.root_id())?;
|
||||
let tree = catalog.get::<Dict<'_>>(b"Names")?.get::<Dict<'_>>(b"EmbeddedFiles")?;
|
||||
let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?;
|
||||
let spec = editing_file_spec(pdf).spec?;
|
||||
let files = spec.get::<Dict<'_>>(b"EF")?;
|
||||
let stream = files.get::<Stream<'_>>(b"F").or_else(|| files.get::<Stream<'_>>(b"UF"))?;
|
||||
let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default();
|
||||
@@ -96,10 +134,59 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option<Editing> {
|
||||
Some(Editing { data, intact })
|
||||
}
|
||||
|
||||
/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect
|
||||
/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path.
|
||||
fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet<ObjectIdentifier>, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
/// The first file specification of the editing file in the name tree `tree`, searched in order at
|
||||
/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the
|
||||
/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is
|
||||
/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is
|
||||
/// set when a key searched names the editing file, and `cut` when nodes are left unsearched.
|
||||
fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
let mut seen = HashSet::<ObjectIdentifier>::new();
|
||||
let mut nodes = vec![tree];
|
||||
let mut found = None;
|
||||
// Nodes still to be searched, counting the ones waiting in `nodes`.
|
||||
let mut left = MAX_NODES - 1;
|
||||
while let Some(node) = nodes.pop() {
|
||||
// Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut.
|
||||
if found.is_none() {
|
||||
found = node_spec(&node, keyed, xref);
|
||||
}
|
||||
let Some(kids) = node.get::<Array<'a>>(b"Kids") else { continue };
|
||||
// Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The
|
||||
// reference is checked before the kid is read, so a shared kid is read once.
|
||||
let mut kids: Vec<Dict<'a>> = items(&kids)
|
||||
.filter_map(|raw| match raw {
|
||||
MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::<Dict<'a>>(r.into()),
|
||||
MaybeRef::NotRef(Object::Dict(kid)) => Some(kid),
|
||||
_ => None,
|
||||
})
|
||||
.take(left.saturating_add(1))
|
||||
.collect();
|
||||
if kids.len() > left {
|
||||
*cut = true;
|
||||
kids.truncate(left);
|
||||
}
|
||||
left -= kids.len();
|
||||
nodes.extend(kids.into_iter().rev());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The file specification of the editing file among the name tree node `node`'s own `Names`.
|
||||
/// `keyed` is set when a key names the editing file.
|
||||
fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option<Dict<'a>> {
|
||||
if let Some(names) = node.get::<Array<'a>>(b"Names") {
|
||||
// The keys read as written, so a value that can't be resolved doesn't shift the pairs.
|
||||
let mut raw = items(&names);
|
||||
while let (Some(key), Some(_)) = (raw.next(), raw.next()) {
|
||||
let key = match key {
|
||||
MaybeRef::NotRef(Object::String(key)) => Some(key),
|
||||
MaybeRef::Ref(r) => xref.get::<PdfString<'a>>(r.into()),
|
||||
MaybeRef::NotRef(_) => None,
|
||||
};
|
||||
if key.is_some_and(|key| is_editing_name(&key)) {
|
||||
*keyed = true;
|
||||
}
|
||||
}
|
||||
let mut items = names.iter::<Object<'a>>();
|
||||
while let (Some(_), Some(spec)) = (items.next(), items.next()) {
|
||||
if let Object::Dict(spec) = spec
|
||||
@@ -109,29 +196,19 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet<ObjectIden
|
||||
}
|
||||
}
|
||||
}
|
||||
if depth >= MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let kids = node.get::<Array<'a>>(b"Kids")?;
|
||||
// Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The
|
||||
// reference is checked before the kid is read, so a shared kid is read once.
|
||||
items(&kids).find_map(|raw| {
|
||||
let kid = match raw {
|
||||
MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::<Dict<'a>>(r.into())?,
|
||||
MaybeRef::NotRef(Object::Dict(kid)) => kid,
|
||||
_ => return None,
|
||||
};
|
||||
editing_spec(&kid, depth + 1, seen, xref)
|
||||
})
|
||||
None
|
||||
}
|
||||
|
||||
/// A file specification naming the editing file (current or legacy name), in any text string
|
||||
/// encoding.
|
||||
fn is_editing_file(spec: &Dict<'_>) -> bool {
|
||||
[&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::<PdfString<'_>>(k)).any(|name| {
|
||||
let name = text_string(name.as_bytes());
|
||||
name == EDITING_FILE || name == LEGACY_EDITING_FILE
|
||||
})
|
||||
[&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::<PdfString<'_>>(k)).any(|name| is_editing_name(&name))
|
||||
}
|
||||
|
||||
/// A text string that is the editing file's name (current or legacy), in any encoding.
|
||||
fn is_editing_name(name: &PdfString<'_>) -> bool {
|
||||
let name = text_string(name.as_bytes());
|
||||
name == EDITING_FILE || name == LEGACY_EDITING_FILE
|
||||
}
|
||||
|
||||
/// The most decoded page content [`page_hash`] reads in all (bytes).
|
||||
|
||||
@@ -64,8 +64,8 @@ pub(crate) struct Sheet<'a> {
|
||||
|
||||
impl Writer {
|
||||
/// A PDF with `set`'s version, standard, compression and colour output, and `doc`'s metadata
|
||||
/// under `title`, created at `created` (Unix seconds). With `cmyk`, transparency blends in
|
||||
/// CMYK (unless the colours are converted to RGB).
|
||||
/// and language under `title`, created at `created` (Unix seconds). With `cmyk`, transparency
|
||||
/// blends in CMYK (unless the colours are converted to RGB).
|
||||
pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option<i64>, cmyk: bool) -> Result<Self, PdfError> {
|
||||
let out = ColorOut::new(doc, set)?;
|
||||
let mut warnings = out.profile_notes.clone();
|
||||
@@ -111,7 +111,11 @@ impl Writer {
|
||||
created: created.map(date_time),
|
||||
modified: None,
|
||||
};
|
||||
let pdf = write::Writer::new(settings, metadata);
|
||||
// The document language (Document Setup) as the catalog's `Lang` and the XMP packet's
|
||||
// `dc:language` (ISO 32000-1, 14.9.2): its BCP 47 tag. A language without a tag writes
|
||||
// none rather than a guess.
|
||||
let language = vectorcraft_doc::setup::language_tag(&doc.setup.language).map(str::to_string);
|
||||
let pdf = write::Writer::new_with_language(settings, metadata, language);
|
||||
Ok(Self {
|
||||
pdf,
|
||||
cmyk: out.blends_cmyk(cmyk),
|
||||
|
||||
@@ -261,6 +261,18 @@ impl Opened {
|
||||
crate::editing::editing_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// Does the PDF list the editing file among its attachments, also when
|
||||
/// [`editing`](Self::editing) can't read it?
|
||||
pub fn has_editing_file(&self) -> bool {
|
||||
crate::editing::has_editing_file_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// Is the PDF's attachment name tree too large to search to its end? It may then list an
|
||||
/// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads.
|
||||
pub fn editing_search_cut(&self) -> bool {
|
||||
crate::editing::editing_search_cut_in(&self.pdf)
|
||||
}
|
||||
|
||||
/// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it.
|
||||
pub fn illustrator_data(&self) -> Option<Vec<u8>> {
|
||||
private_data(&self.pdf)
|
||||
|
||||
@@ -1449,6 +1449,41 @@ fn empty_and_populated_file_info_preserve_key_presence() {
|
||||
assert!(s.contains("/ViewerPreferences<</DisplayDocTitle true>>"), "viewers should show the document title (#3646)");
|
||||
}
|
||||
|
||||
/// The text of the `/Lang` entry of the catalog of `pdf` (a literal string), if any.
|
||||
fn catalog_lang(pdf: &[u8]) -> Option<String> {
|
||||
let xref = crate::patch::Xref::read(pdf).expect("a cross-reference table");
|
||||
let root = xref.trailer_ref(pdf, b"/Root").expect("a catalog");
|
||||
let (start, end) = xref.dict(pdf, root).expect("the catalog's dictionary");
|
||||
let catalog = String::from_utf8_lossy(&pdf[start..end]).into_owned();
|
||||
let at = catalog.find("/Lang")? + "/Lang".len();
|
||||
let rest = catalog[at..].trim_start().strip_prefix('(').expect("a literal string");
|
||||
Some(rest[..rest.find(')').expect("a closed string")].to_string())
|
||||
}
|
||||
|
||||
/// The catalog gives the document language chosen in Document Setup as its BCP 47 tag, in
|
||||
/// exported and printed PDFs, and the XMP packet says it too (#3644).
|
||||
#[test]
|
||||
fn the_catalog_gives_the_document_language() {
|
||||
let mut d = doc(100.0, 100.0);
|
||||
for (language, tag) in [(None, "en-US"), (Some("French"), "fr"), (Some("German: Swiss"), "de-CH")] {
|
||||
if let Some(language) = language {
|
||||
d.setup.language = language.into();
|
||||
}
|
||||
for opts in [PdfOptions::uncompressed(), PdfOptions::default()] {
|
||||
let bytes = export(&d, &opts).unwrap();
|
||||
assert_eq!(catalog_lang(&bytes).as_deref(), Some(tag), "{language:?}");
|
||||
}
|
||||
// Print to PDF writes its file with the same writer.
|
||||
let printed = print(&d, &PrintOptions { created: Some(1_700_000_000), ..Default::default() }).unwrap();
|
||||
assert_eq!(catalog_lang(&printed.bytes).as_deref(), Some(tag), "{language:?}: printed");
|
||||
let s = uncompressed(&d);
|
||||
assert!(s.contains(&format!("<dc:language><rdf:Bag><rdf:li>{tag}</rdf:li></rdf:Bag></dc:language>")), "{language:?}: {s}");
|
||||
}
|
||||
// A language without a tag (from a file) writes none rather than a guess.
|
||||
d.setup.language = "Klingon".into();
|
||||
assert_eq!(catalog_lang(&export(&d, &PdfOptions::uncompressed()).unwrap()), None);
|
||||
}
|
||||
|
||||
/// A function or colour space built on itself is refused before the interpreter builds it (by
|
||||
/// recursion, with no cap: a stack overflow), and those of real files are read.
|
||||
#[test]
|
||||
|
||||
@@ -237,3 +237,104 @@ fn a_file_name_written_as_utf16_is_found() {
|
||||
assert_eq!(e.data, b"hello", "/{key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() {
|
||||
// No `EF` dictionary, an `EF` without `F` or `UF`, and an `F` naming no object.
|
||||
for ef in ["", "/EF << >>", "/EF << /F 9 0 R >>"] {
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [5 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Names [(a) 4 0 R] >>".to_string(),
|
||||
format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
];
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing(), None, "{ef:?}");
|
||||
assert!(opened.has_editing_file(), "{ef:?}");
|
||||
}
|
||||
// A name tree key naming it, with a file specification that names no object or isn't one.
|
||||
for spec in ["9 0 R", "(not a file specification)"] {
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(),
|
||||
format!("<< /Names [(a) 9 0 R ({EDITING_FILE}) {spec}] >>"),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
];
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing(), None, "{spec}");
|
||||
assert!(opened.has_editing_file(), "{spec}");
|
||||
}
|
||||
// The key written as an indirect string.
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Names [5 0 R 9 0 R] >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
format!("({EDITING_FILE})"),
|
||||
];
|
||||
assert!(open_pdf(&raw_pdf(&objects), None).unwrap().has_editing_file());
|
||||
// A PDF without the editing file, and one with it.
|
||||
assert!(!open_pdf(&export(&doc(), &PdfOptions::default()).unwrap(), None).unwrap().has_editing_file());
|
||||
let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap();
|
||||
assert!(opened.editing().is_some() && opened.has_editing_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_editing_file_deep_in_the_name_tree_is_found() {
|
||||
// Objects 4..=203 are a chain of 200 name tree nodes, each listing the next one; the editing
|
||||
// file sits in the leaf (object 204), with its data or naming data that can't be resolved.
|
||||
for ef in ["/EF << /F 206 0 R >>", "/EF << /F 999 0 R >>"] {
|
||||
let mut objects = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [207 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Kids [4 0 R] >>".to_string(),
|
||||
];
|
||||
for node in 4..=203 {
|
||||
objects.push(format!("<< /Kids [{} 0 R] >>", node + 1));
|
||||
}
|
||||
objects.push("<< /Names [(a) 205 0 R] >>".to_string());
|
||||
objects.push(format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"));
|
||||
objects.push("<< /Length 5 >>\nstream\nhello\nendstream".to_string());
|
||||
objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string());
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert!(opened.has_editing_file(), "{ef}");
|
||||
let data = opened.editing().map(|e| e.data);
|
||||
assert_eq!(data.as_deref(), ef.contains("206").then_some(&b"hello"[..]), "{ef}");
|
||||
}
|
||||
// A name tree with more nodes than are searched may list it.
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(),
|
||||
format!("<< /Kids [{}] >>", "<< /Names [] >> ".repeat(70_000)),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
];
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing(), None);
|
||||
assert!(opened.has_editing_file() && opened.editing_search_cut());
|
||||
// One that lists a readable editing file before the nodes left unsearched and another after
|
||||
// them: the first is read, and the search reads as cut short.
|
||||
let leaf = |stream: u32| format!("<< /Names [({EDITING_FILE}) << /Type /Filespec /UF ({EDITING_FILE}) /EF << /F {stream} 0 R >> >>] >>");
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(),
|
||||
"<< /Type /Pages /Kids [8 0 R] /Count 1 >>".to_string(),
|
||||
format!("<< /Kids [4 0 R {}5 0 R] >>", "<< /Names [] >> ".repeat(70_000)),
|
||||
leaf(6),
|
||||
leaf(7),
|
||||
"<< /Length 5 >>\nstream\nfirst\nendstream".to_string(),
|
||||
"<< /Length 6 >>\nstream\nsecond\nendstream".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(),
|
||||
];
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..]));
|
||||
assert!(opened.has_editing_file() && opened.editing_search_cut());
|
||||
// The same, with the nodes past the limit in a subtree after the one holding the first.
|
||||
let mut objects = objects;
|
||||
objects[2] = format!("<< /Kids [4 0 R << /Kids [{}5 0 R] >>] >>", "<< /Names [] >> ".repeat(70_000));
|
||||
let opened = open_pdf(&raw_pdf(&objects), None).unwrap();
|
||||
assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..]));
|
||||
assert!(opened.has_editing_file() && opened.editing_search_cut());
|
||||
// A tree searched to its end.
|
||||
let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap();
|
||||
assert!(opened.editing().is_some() && !opened.editing_search_cut());
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ pub mod wat;
|
||||
pub use dialog::ParamUi;
|
||||
pub use host::{LogLevel, LogLine, Report};
|
||||
pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms};
|
||||
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms};
|
||||
#[doc(hidden)]
|
||||
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
|
||||
|
||||
|
||||
@@ -35,6 +35,11 @@ pub const HEAVY_FUEL: u64 = 1_000_000_000;
|
||||
/// Wall-clock budget of a heavy filter's run, in milliseconds.
|
||||
pub const HEAVY_WALL_TIME_MS: u64 = 300_000;
|
||||
|
||||
/// Instructions a filter's run may use besides [`Limits::fuel_per_byte`] for each byte of input
|
||||
/// when Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget is Large
|
||||
/// ([`Plugin::large_limits`]): 5 times the default.
|
||||
pub const LARGE_FUEL: u64 = 250_000_000;
|
||||
|
||||
/// The limit a run reports when its input and parameters together are past half its memory.
|
||||
pub(crate) const SELECTION_TOO_LARGE: &str = "memory budget (the selection is too large to hand over)";
|
||||
|
||||
@@ -215,6 +220,12 @@ impl Plugin {
|
||||
pub fn limits(&self) -> &Limits {
|
||||
&self.limits
|
||||
}
|
||||
/// Its limits with the Large instruction budget: at least [`LARGE_FUEL`] instructions besides
|
||||
/// those for each byte of input, and every other limit, the time budget included, as it is. A
|
||||
/// heavy filter keeps its larger budget.
|
||||
pub fn large_limits(&self) -> Limits {
|
||||
Limits { fuel_base: self.limits.fuel_base.max(LARGE_FUEL), ..self.limits.clone() }
|
||||
}
|
||||
/// Module size in bytes.
|
||||
pub fn size(&self) -> usize {
|
||||
self.size
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_plugins::storage::{Meter, Storage, StorageError};
|
||||
use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, Limits, Plugin, Report, heavy_terms, registry, wat as tpl};
|
||||
use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl};
|
||||
|
||||
/// The example Desaturate plug-in, built from `crates/plugins/example`.
|
||||
const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm");
|
||||
@@ -259,6 +259,23 @@ fn a_heavy_filter_finishes_what_a_light_one_cannot() {
|
||||
assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes());
|
||||
}
|
||||
|
||||
/// The Large instruction budget gives a light filter 5 times the instructions besides those for
|
||||
/// each byte of input, so it finishes 20 million steps of a loop that its own budget can't, in the
|
||||
/// same time budget. A heavy filter keeps its larger budget, and every other limit stays.
|
||||
#[test]
|
||||
fn the_large_budget_finishes_what_a_light_one_cannot_and_keeps_a_heavy_one() {
|
||||
let light = Plugin::load(&build(&tpl::spinning(MANIFEST, 20_000_000, INPUT)), Limits::default()).unwrap();
|
||||
assert_eq!(light.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into())));
|
||||
let large = light.large_limits();
|
||||
assert_eq!(large, Limits { fuel_base: LARGE_FUEL, ..Limits::default() });
|
||||
assert_eq!(LARGE_FUEL, 5 * Limits::default().fuel_base);
|
||||
assert_eq!(light.run_limited(INPUT.as_bytes(), b"{}", &large).unwrap(), INPUT.as_bytes());
|
||||
let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#;
|
||||
let heavy = Plugin::load(&build(&tpl::spinning(heavy, 1, INPUT)), Limits::default()).unwrap();
|
||||
assert_eq!(heavy.large_limits(), *heavy.limits());
|
||||
assert_eq!((heavy.large_limits().fuel_base, heavy.large_limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exporter_returns_its_file_with_an_export_s_budget() {
|
||||
use vectorcraft_plugins::export::{self, Target};
|
||||
|
||||
@@ -203,6 +203,21 @@ pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pal
|
||||
finish(px, &colors, width, height, &palette, o, o.dither)
|
||||
}
|
||||
|
||||
/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures
|
||||
/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a
|
||||
/// pixel that becomes transparent, and for every pixel when `palette` is empty.
|
||||
pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec<Option<usize>> {
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
let colors = opaque_colors(px, o, false);
|
||||
let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect();
|
||||
let index = PaletteIndex::new(&pal, o.reduction.weights());
|
||||
colors
|
||||
.iter()
|
||||
.zip(px)
|
||||
.map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The color of each pixel when opaque: blended over the matte, and gray when `gray`.
|
||||
fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> {
|
||||
let matte = o.matte.unwrap_or([255; 3]);
|
||||
|
||||
@@ -80,14 +80,19 @@ fn lossy_makes_runs_and_smaller_gifs() {
|
||||
let px = image(96, 64, |x, y| [(x * 2 + y) as u8, (y * 3) as u8, ((x * y) % 255) as u8]);
|
||||
let ix = quantize(&px, 96, 64, &PaletteOptions { colors: 64, dither: Dither::Diffusion, ..Default::default() });
|
||||
let mut lossy_ix = ix.clone();
|
||||
lossy(&mut lossy_ix, &px, 80);
|
||||
lossy(&mut lossy_ix, &px, 80, &[]);
|
||||
let runs = |ix: &Indexed| ix.indices.windows(2).filter(|w| w[0] != w[1]).count();
|
||||
assert!(runs(&lossy_ix) < runs(&ix));
|
||||
let size = |ix: &Indexed| gif::encode(ix, false).unwrap().len();
|
||||
assert!(size(&lossy_ix) < size(&ix), "{} vs {}", size(&lossy_ix), size(&ix));
|
||||
let mut none = ix.clone();
|
||||
lossy(&mut none, &px, 0);
|
||||
lossy(&mut none, &px, 0, &[]);
|
||||
assert_eq!(none, ix);
|
||||
// A fixed entry keeps its pixels and takes no others.
|
||||
let fixed: Vec<u8> = (0..ix.palette.len()).filter_map(|i| u8::try_from(i).ok()).collect();
|
||||
let mut kept = ix.clone();
|
||||
lossy(&mut kept, &px, 100, &fixed);
|
||||
assert_eq!(kept, ix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -83,19 +83,24 @@ pub fn to_transparent(ix: &mut Indexed, mapped: impl Fn(usize) -> bool) -> Vec<O
|
||||
|
||||
/// Lossy GIF compression: a pixel takes the entry of the pixel left of it when that entry is
|
||||
/// within `amount` (0–100) of its own colour in `rgba` (the straight pixels it was reduced from).
|
||||
/// Longer runs of one index compress better in a GIF, at the cost of some noise.
|
||||
pub fn lossy(ix: &mut Indexed, rgba: &[u8], amount: u8) {
|
||||
/// Longer runs of one index compress better in a GIF, at the cost of some noise. No pixel moves
|
||||
/// into or out of the transparent entry or an entry in `fixed`.
|
||||
pub fn lossy(ix: &mut Indexed, rgba: &[u8], amount: u8, fixed: &[u8]) {
|
||||
let w = ix.width as usize;
|
||||
if amount == 0 || w == 0 || rgba.len() != ix.indices.len() * 4 {
|
||||
return;
|
||||
}
|
||||
// Up to 64 levels apart in each channel at 100.
|
||||
let limit = (f32::from(amount.min(100)) / 100.0 * 64.0).powi(2) * 3.0;
|
||||
let mut held = [false; 256];
|
||||
for i in fixed.iter().chain(&ix.transparent) {
|
||||
held[usize::from(*i)] = true;
|
||||
}
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
for (row, src) in ix.indices.chunks_mut(w).zip(px.chunks(w)) {
|
||||
for x in 1..row.len() {
|
||||
let (prev, cur) = (row[x - 1], row[x]);
|
||||
if prev == cur || ix.transparent.is_some_and(|t| t == prev || t == cur) {
|
||||
if prev == cur || held[usize::from(prev)] || held[usize::from(cur)] {
|
||||
continue;
|
||||
}
|
||||
let (Some(c), Some(p)) = (src.get(x), ix.palette.get(prev as usize)) else { continue };
|
||||
|
||||
@@ -726,6 +726,12 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b
|
||||
let a = art_effects_reach(symbols, n);
|
||||
Some(b.inflate(a, a))
|
||||
}
|
||||
// A spine can rotate a blend's keys and steps past their unrotated visual bounds.
|
||||
NodeKind::Blend { .. } => {
|
||||
let b = n.reach_bounds_with(symbols)?;
|
||||
let a = live_content_reach(symbols, n);
|
||||
vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_blend_effect_bounds(symbols, n))
|
||||
}
|
||||
_ => {
|
||||
let b = n.visual_bounds_with(symbols)?;
|
||||
let b = match &n.kind {
|
||||
@@ -804,16 +810,43 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) ->
|
||||
b.inflate(o, o)
|
||||
}
|
||||
|
||||
/// `n`'s own visual box, type's grown to hold its glyphs ([`glyphs_box`]): what it draws when its
|
||||
/// object effects leave it as it is (Revolve builds no art from type).
|
||||
/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its
|
||||
/// spine-placed keys and steps: what it draws when its object effects leave it as it is
|
||||
/// (Revolve builds no art from type).
|
||||
fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let b = n.visual_bounds_with(symbols)?;
|
||||
let b = match &n.kind {
|
||||
NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_blend_effect_bounds(symbols, n)),
|
||||
_ => n.visual_bounds_with(symbols),
|
||||
}?;
|
||||
Some(match &n.kind {
|
||||
NodeKind::Text(t) => vectorcraft_geom::union_opt(Some(b), glyphs_box(t, n.appearance.outset())).unwrap_or(b),
|
||||
_ => b,
|
||||
})
|
||||
}
|
||||
|
||||
/// A rotated blend's effect-bearing content, measured after spine placement. Geometry effects
|
||||
/// run on the placed shapes, so their reach on the original keys need not cover what they paint.
|
||||
/// Effect-free blends keep the quick rail envelope without evaluating their steps.
|
||||
fn placed_blend_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let NodeKind::Blend { spec, .. } = &n.kind else { return None };
|
||||
if spec.orientation != vectorcraft_doc::BlendOrientation::AlignToPath {
|
||||
return None;
|
||||
}
|
||||
let mut has_effects = false;
|
||||
n.walk(&mut |c| {
|
||||
has_effects |= has_fx(c)
|
||||
|| has_object_fx(c)
|
||||
|| match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol),
|
||||
_ => false,
|
||||
};
|
||||
});
|
||||
if !has_effects {
|
||||
return None;
|
||||
}
|
||||
effects::expand_live(Some(symbols.document()), n).iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, cull_bounds(symbols, c)))
|
||||
}
|
||||
|
||||
/// The box of type `t`'s glyphs as laid out (its layout bounds, else laid out now), grown by its
|
||||
/// characters' strokes, miter spikes included, and by `outset`: on a path they stand above it and
|
||||
/// run past its ends, in an area they can hang past its frame, where its own box
|
||||
|
||||
@@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool {
|
||||
let symbols = cx.doc.symbol_boxes();
|
||||
let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten();
|
||||
let mut ids = if let Some(region) = region {
|
||||
enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline)
|
||||
enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline, !cx.guides)
|
||||
.into_iter()
|
||||
.filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion)))
|
||||
.collect()
|
||||
|
||||
@@ -76,6 +76,12 @@ pub struct DimensionTool {
|
||||
/// for that click (a snap or Shift can move the point away from it): placed with the pointer
|
||||
/// still at either, it is aligned.
|
||||
second: Option<(Point, Point)>,
|
||||
/// While a Linear dimension is placed with its line on the level of another dimension's line:
|
||||
/// the ends of that other line. A Smart Guide runs along the level across both lines.
|
||||
level_guide: Option<(Point, Point)>,
|
||||
/// While a dimension is placed: the lines of the visible, unlocked linear dimensions in the
|
||||
/// document before its first preview ([`dimension_lines`]), which its line can line up with.
|
||||
levels: Vec<DimensionLine>,
|
||||
}
|
||||
|
||||
/// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is
|
||||
@@ -285,6 +291,58 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> {
|
||||
best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false)))
|
||||
}
|
||||
|
||||
/// The line of a linear dimension already drawn: its ends and its direction.
|
||||
type DimensionLine = ((Point, Point), Vec2);
|
||||
|
||||
/// The lines of the visible, unlocked linear dimensions in the document. Bounded work, as in
|
||||
/// [`on_dimensions`].
|
||||
fn dimension_lines(cx: &ToolContext) -> Vec<DimensionLine> {
|
||||
fn visit(n: &Node, budget: &mut usize, out: &mut Vec<DimensionLine>) {
|
||||
if *budget == 0 || !n.visible || n.locked {
|
||||
return;
|
||||
}
|
||||
*budget -= 1;
|
||||
if let Some(d) = &n.extras().dimension {
|
||||
if d.mode == DimensionMode::Linear {
|
||||
out.push((d.line_ends(), d.direction()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in n.children().into_iter().flatten().rev() {
|
||||
visit(c, budget, out);
|
||||
}
|
||||
}
|
||||
let (mut budget, mut out) = (20_000usize, vec![]);
|
||||
for n in cx.doc.layers.iter().rev() {
|
||||
visit(n, &mut budget, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where the line of the linear dimension `d`, placed through `p`, lands on the level of one of
|
||||
/// the `levels` that runs parallel to it, within `reach` of `p` across the line: the point to
|
||||
/// place `d` through, and the ends of that other line. The nearest level wins, then the line
|
||||
/// nearest `p` along it (none nearer than a line that `p` lies across).
|
||||
fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> Option<(Point, (Point, Point))> {
|
||||
if d.mode != DimensionMode::Linear {
|
||||
return None;
|
||||
}
|
||||
let (u, normal) = (d.direction(), d.normal());
|
||||
let mut best: Option<(f64, f64, f64, (Point, Point))> = None;
|
||||
for &(ends, direction) in levels {
|
||||
if u.cross(direction).abs() > 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let shift = (ends.0 - p).dot(normal);
|
||||
let (s0, s1) = ((ends.0 - p).dot(u), (ends.1 - p).dot(u));
|
||||
let along = if s0 * s1 <= 0.0 { 0.0 } else { s0.abs().min(s1.abs()) };
|
||||
if shift.is_finite() && along.is_finite() && shift.abs() <= reach && best.is_none_or(|(s, a, _, _)| (shift.abs(), along) < (s, a)) {
|
||||
best = Some((shift.abs(), along, shift, ends));
|
||||
}
|
||||
}
|
||||
best.map(|(_, _, shift, ends)| (p + normal * shift, ends))
|
||||
}
|
||||
|
||||
/// The point of `edge` closest to `p`.
|
||||
fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
|
||||
use vectorcraft_geom::kurbo::ParamCurveNearest;
|
||||
@@ -435,6 +493,7 @@ impl DimensionTool {
|
||||
p
|
||||
}
|
||||
fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
|
||||
self.level_guide = None;
|
||||
let Some(d) = &mut self.pending else { return vec![] };
|
||||
if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter)
|
||||
&& let Some(Target::Radial { center, radius, .. }) = self.press.as_ref().and_then(|(_, t)| t.as_ref())
|
||||
@@ -462,10 +521,18 @@ impl DimensionTool {
|
||||
if d.resolve(cx.doc).is_err() {
|
||||
return vec![];
|
||||
}
|
||||
d.place(p);
|
||||
// With Smart Guides on, a linear dimension's line lands on the level of a parallel
|
||||
// dimension line already drawn within the Smart Guides snapping tolerance. The lines are
|
||||
// read before the first preview, so the preview of this dimension is not one of them.
|
||||
if !self.began {
|
||||
self.levels = dimension_lines(cx);
|
||||
}
|
||||
let level = if cx.smart_guides { line_level(&self.levels, d, p, cx.snap_tol()) } else { None };
|
||||
d.place(level.map_or(p, |(on_level, _)| on_level));
|
||||
if d.validate().is_err() {
|
||||
return vec![];
|
||||
}
|
||||
self.level_guide = level.map(|(_, ends)| ends);
|
||||
let mut actions = vec![];
|
||||
if !self.began {
|
||||
actions.push(Action::Begin("Create Dimension".into()));
|
||||
@@ -495,6 +562,8 @@ impl DimensionTool {
|
||||
self.snap.clear();
|
||||
self.snapped = None;
|
||||
self.second = None;
|
||||
self.level_guide = None;
|
||||
self.levels.clear();
|
||||
}
|
||||
/// A plain click: picks a point or a line, or measures a circle's radius.
|
||||
fn click(&mut self, cx: &ToolContext, p: Point, target: Option<Target>, mods: Mods) -> Vec<Action> {
|
||||
@@ -664,6 +733,7 @@ impl Tool for DimensionTool {
|
||||
self.press = None;
|
||||
if self.pending.is_some() && self.began {
|
||||
self.began = false;
|
||||
self.level_guide = None;
|
||||
vec![Action::Cancel]
|
||||
} else {
|
||||
vec![]
|
||||
@@ -741,6 +811,21 @@ impl Tool for DimensionTool {
|
||||
if linear_pick {
|
||||
out.extend(self.snap.guides().iter().cloned());
|
||||
}
|
||||
// A dimension line placed on the level of another: one alignment guide across both lines,
|
||||
// unless Alignment Guides are off.
|
||||
if cx.alignment_guides
|
||||
&& let (Some(d), Some((c, e))) = (&self.pending, self.level_guide)
|
||||
{
|
||||
let (a, b) = d.line_ends();
|
||||
let u = d.direction();
|
||||
let along = |q: &Point| q.to_vec2().dot(u);
|
||||
let ends = [a, b, c, e];
|
||||
if let (Some(lo), Some(hi)) =
|
||||
(ends.iter().min_by(|p, q| along(p).total_cmp(&along(q))), ends.iter().max_by(|p, q| along(p).total_cmp(&along(q))))
|
||||
{
|
||||
out.push(Overlay::Line { a: *lo, b: *hi, color: cx.smart_guide_color, dashed: false });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
@@ -778,6 +863,21 @@ mod tests {
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 60.0)).is_empty(), "the release places nothing");
|
||||
}
|
||||
|
||||
/// Of two dimension lines on one level, a line the pointer lies across wins over a line whose
|
||||
/// end is nearer the pointer.
|
||||
#[test]
|
||||
fn a_line_the_pointer_lies_across_wins_on_one_level() {
|
||||
let pt = Point::new;
|
||||
let d = DimensionTool::default().recipe(DimensionMode::Linear, pt(200.0, 200.0), pt(300.0, 200.0), pt(250.0, 200.0), None);
|
||||
let across = ((pt(0.0, 170.0), pt(400.0, 170.0)), Vec2::new(1.0, 0.0));
|
||||
let beside = ((pt(100.0, 170.0), pt(200.0, 170.0)), Vec2::new(1.0, 0.0));
|
||||
for levels in [[beside, across], [across, beside]] {
|
||||
let (at, ends) = line_level(&levels, &d, pt(250.0, 172.0), 4.0).expect("on the level");
|
||||
assert!(at.distance(pt(250.0, 170.0)) < 1e-9, "{at:?}");
|
||||
assert_eq!(ends, across.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_placement_press_does_not_commit_the_dimension() {
|
||||
let (d, _) = doc_with_rect();
|
||||
|
||||
@@ -1674,7 +1674,7 @@ impl DirectSelectionTool {
|
||||
// marquee or an Alt-marquee, every object it touches, each whole (#8047).
|
||||
if enclosed || whole || self.group {
|
||||
(self.spine, self.spine_more) = (None, vec![]);
|
||||
let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline);
|
||||
let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline, !cx.guides);
|
||||
let editable = cx.doc.editable();
|
||||
touched.retain(|id| editable(*id));
|
||||
let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched };
|
||||
@@ -1684,8 +1684,11 @@ impl DirectSelectionTool {
|
||||
}
|
||||
// Anchors inside the rect, on editable paths inside isolation mode.
|
||||
let mut sel: Vec<(NodeId, Vec<AnchorRef>)> = vec![];
|
||||
// Guide paths only while guides can be picked: not while they are locked or hidden (#8538).
|
||||
walk_pickable(cx.doc, cx.isolation, |n| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
if let NodeKind::Path { path, guide, .. } = &n.kind
|
||||
&& (cx.guides || !*guide)
|
||||
{
|
||||
let v: Vec<AnchorRef> = path.anchors().filter(|(_, _, a)| r.contains(a.p)).map(|(s, i, _)| (s, i)).collect();
|
||||
if !v.is_empty() {
|
||||
sel.push((n.id, v));
|
||||
@@ -1773,7 +1776,7 @@ impl DirectSelectionTool {
|
||||
}
|
||||
// Objects without anchors to pick (type, images, symbols…) are selected whole when
|
||||
// the marquee touches them, as with the Selection tool (#927).
|
||||
for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) {
|
||||
for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline, !cx.guides) {
|
||||
let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }));
|
||||
if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) && spined != Some(id) {
|
||||
sel.push((id, vec![]));
|
||||
@@ -1785,7 +1788,8 @@ impl DirectSelectionTool {
|
||||
let mut crossed: Vec<(NodeId, Vec<AnchorRef>)> = vec![];
|
||||
if !self.group {
|
||||
walk_pickable(cx.doc, cx.isolation, |n| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind
|
||||
if let NodeKind::Path { path, guide, .. } = &n.kind
|
||||
&& (cx.guides || !*guide)
|
||||
&& editable(n.id)
|
||||
{
|
||||
let segs = crossed_segments(path, r);
|
||||
|
||||
@@ -2767,3 +2767,30 @@ fn outline_view_marquees_measure_clipped_art_by_the_plain_clipping_path() {
|
||||
let a = marquee(false);
|
||||
assert!(!selects(&a), "preview: {a:?}");
|
||||
}
|
||||
|
||||
/// #8538: while guides are locked or hidden (`guides` off), a Direct Selection marquee takes
|
||||
/// neither the anchors nor the crossed segments of a guide path; while guides can be picked, it
|
||||
/// takes them as on any path.
|
||||
#[test]
|
||||
fn a_marquee_skips_the_anchors_and_segments_of_guides_that_cannot_be_picked() {
|
||||
let (mut d, id) = doc_with_rect();
|
||||
if let Some(NodeKind::Path { guide, .. }) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
*guide = true;
|
||||
}
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let marquee = |guides: bool, from: (f64, f64), to: (f64, f64)| {
|
||||
let cx = ToolContext { guides, ..cx(&d, &s, &p) };
|
||||
let mut t = DirectSelectionTool::new(false);
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, from.0, from.1));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1))
|
||||
};
|
||||
let anchors = |items: Value| vec![Action::Exec("select.anchorsMany".into(), json!({"items": items, "mode": "set"}))];
|
||||
// Over the corner at (200, 100).
|
||||
assert_eq!(marquee(false, (150.0, 50.0), (250.0, 150.0)), anchors(json!([])), "locked or hidden: no anchor");
|
||||
assert_eq!(marquee(true, (150.0, 50.0), (250.0, 150.0)), anchors(json!([{"id": id.0, "anchors": [[0, 1]]}])), "shown and unlocked");
|
||||
// Across the middle of the top edge.
|
||||
let crossed = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.segments"));
|
||||
assert!(!crossed(&marquee(false, (140.0, 80.0), (160.0, 120.0))), "locked or hidden: no segment");
|
||||
assert!(crossed(&marquee(true, (140.0, 80.0), (160.0, 120.0))), "shown and unlocked");
|
||||
}
|
||||
|
||||
@@ -525,10 +525,12 @@ impl Tool for PenTool {
|
||||
&& let (Some((id, _, _, last, out)), Some(h)) = (self.active(cx), self.hover)
|
||||
{
|
||||
if cx.pen_rubber_band {
|
||||
// The segment a click at `h` adds: it leaves the last anchor along its outgoing
|
||||
// handle and arrives at the new corner anchor without a handle.
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to(last);
|
||||
if out.distance(last) > 1e-9 {
|
||||
bp.quad_to(out, h);
|
||||
bp.curve_to(out, h, h);
|
||||
} else {
|
||||
bp.line_to(h);
|
||||
}
|
||||
|
||||
@@ -865,6 +865,27 @@ fn anchors_snap_to_smart_guides() {
|
||||
assert_eq!(a[1], Action::Preview("path.create".into(), json!({"anchors": [{"x": 100.0, "y": 100.0}]})));
|
||||
}
|
||||
|
||||
/// The rubber band after a smooth anchor is the curve the click then adds: it leaves along the
|
||||
/// anchor's outgoing handle and arrives at the new corner anchor without a handle, so the segment
|
||||
/// keeps its shape when the anchor goes down (#8296).
|
||||
#[test]
|
||||
fn rubber_band_is_the_segment_a_click_adds() {
|
||||
let (last, out) = (Point::new(60.0, 300.0), Point::new(110.0, 250.0));
|
||||
let sub = vectorcraft_geom::SubPath::new(vec![Anchor::corner(Point::new(10.0, 300.0)), Anchor::smooth(last, out)], false);
|
||||
let (d, id, s) = drawing(sub);
|
||||
let p = paint();
|
||||
let cx = ToolContext { zoom: 1.0, smart_guides: false, snap_to_point: false, snap_to_pixel: false, snap_to_grid: false, ..cx(&d, &s, &p) };
|
||||
let h = Point::new(237.0, 361.0);
|
||||
let mut t = PenTool { drawing: true, ..PenTool::default() };
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Move, h.x, h.y));
|
||||
let band: Vec<_> =
|
||||
t.overlays(&cx).into_iter().filter_map(|o| if let Overlay::Path { path, .. } = o { Some(path.elements().to_vec()) } else { None }).collect();
|
||||
assert_eq!(band, vec![vec![vectorcraft_geom::PathEl::MoveTo(last), vectorcraft_geom::PathEl::CurveTo(out, h, h)]]);
|
||||
// The click adds a corner anchor there: the segment drawn is the one previewed.
|
||||
let a = click(&mut t, &cx, h.x, h.y, Mods::default());
|
||||
assert_eq!(a[1], Action::Preview("path.appendAnchor".into(), json!({"id": id.0, "x": h.x, "y": h.y, "subpath": 0})));
|
||||
}
|
||||
|
||||
/// With Enable Rubber Band off, the preview segment is hidden but Measurement Labels still shows
|
||||
/// the D / Angle / dX / dY readout at the snapped point before the next click.
|
||||
#[test]
|
||||
|
||||
@@ -599,7 +599,12 @@ fn with_object_bounds<R>(cx: &ToolContext, walk: impl FnOnce(&mut dyn FnMut(Node
|
||||
pub(crate) fn inside(cx: &ToolContext, r: Rect, ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
let symbols = cx.doc.symbol_boxes();
|
||||
let within = |b: Rect| r.min_x() <= b.min_x() && b.max_x() <= r.max_x() && r.min_y() <= b.min_y() && b.max_y() <= r.max_y();
|
||||
ids.into_iter().filter(|id| cx.doc.node(*id).and_then(|n| n.geometric_bounds_with(&symbols)).is_some_and(within)).collect()
|
||||
// Locked or hidden guides, which the marquee leaves out, don't count toward a group's box (#8538).
|
||||
let measure = |n: &vectorcraft_doc::Node| match n.without_guides().filter(|_| !cx.guides) {
|
||||
Some(art) => art.geometric_bounds_with(&symbols),
|
||||
None => n.geometric_bounds_with(&symbols),
|
||||
};
|
||||
ids.into_iter().filter(|id| cx.doc.node(*id).and_then(measure).is_some_and(within)).collect()
|
||||
}
|
||||
|
||||
/// What of the bounding box is under the pointer.
|
||||
@@ -1222,7 +1227,7 @@ impl Tool for SelectionTool {
|
||||
if r.width() < Self::drag_threshold(cx) && r.height() < Self::drag_threshold(cx) {
|
||||
return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] };
|
||||
}
|
||||
let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline);
|
||||
let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline, !cx.guides);
|
||||
let enclosed = marquee_enclosed(cx, enclosed, marquee_direction(cx, start, p, directional_inside));
|
||||
let ids = if enclosed { inside(cx, r, touched) } else { touched };
|
||||
let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": json_ids(&ids) }));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::*;
|
||||
use crate::testutil::*;
|
||||
use vectorcraft_doc::Selection;
|
||||
use vectorcraft_doc::{Document, NodeKind, Selection};
|
||||
|
||||
/// While an opacity mask is edited, a press on a selected Shaper original shape moves it, over the
|
||||
/// art the group shows and over a part of the shape the group does not show. A press on an original
|
||||
@@ -146,6 +146,66 @@ fn a_press_where_a_mask_hides_a_selected_object_drags_it() {
|
||||
assert!(a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([front.0]))), "{a:?}");
|
||||
}
|
||||
|
||||
/// #8538: while guides are locked or hidden (`guides` off), a Selection tool marquee that touches
|
||||
/// only a guide path in a group selects nothing, so a drag can't move the guide; one that touches
|
||||
/// the group's other member selects the group. With guides unlocked, the guide takes the group.
|
||||
#[test]
|
||||
fn a_marquee_over_a_locked_guide_in_a_group_selects_nothing() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let l = d.layers[0].id;
|
||||
let (gid, guide_id, art_id) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let mut guide = vectorcraft_doc::Node::path(
|
||||
guide_id,
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 120.0, 120.0)),
|
||||
vectorcraft_doc::Appearance::default_art(),
|
||||
);
|
||||
if let NodeKind::Path { guide, .. } = &mut guide.kind {
|
||||
*guide = true;
|
||||
}
|
||||
let art = vectorcraft_doc::Node::path(
|
||||
art_id,
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 100.0, 320.0, 120.0)),
|
||||
vectorcraft_doc::Appearance::default_art(),
|
||||
);
|
||||
d.insert(Some(l), 0, vectorcraft_doc::Node::group(gid, vec![std::sync::Arc::new(guide), std::sync::Arc::new(art)])).unwrap();
|
||||
let (none, p) = (Selection::default(), paint());
|
||||
let marquee = |guides: bool, x0: f64, x1: f64| {
|
||||
let c = ToolContext { guides, ..cx(&d, &none, &p) };
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, x0, 50.0));
|
||||
t.pointer(&c, &ev(PointerKind::Drag, x1, 110.0));
|
||||
let up = t.pointer(&c, &ev(PointerKind::Up, x1, 110.0));
|
||||
up.iter().find_map(|a| match a {
|
||||
Action::Exec(c, v) if c == "select.set" => Some(v["ids"].clone()),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
assert_eq!(marquee(false, 90.0, 130.0), Some(json!([])), "locked: only the guide");
|
||||
assert_eq!(marquee(false, 290.0, 330.0), Some(json!([gid.0])), "locked: the group's art");
|
||||
assert_eq!(marquee(true, 90.0, 130.0), Some(json!([gid.0])), "unlocked: the guide");
|
||||
}
|
||||
|
||||
/// #8538: an enclosing marquee measures a group without the locked or hidden guides in it, as the
|
||||
/// marquee leaves them out: a group whose art lies inside is taken though a guide in it reaches
|
||||
/// past the marquee. While guides can be picked, the guide counts.
|
||||
#[test]
|
||||
fn an_enclosing_marquee_measures_a_group_without_its_locked_guides() {
|
||||
let mut d = Document::new(800.0, 600.0);
|
||||
let l = d.layers[0].id;
|
||||
let (gid, guide_id, art_id) = (d.alloc_id(), d.alloc_id(), d.alloc_id());
|
||||
let square = |id, r| vectorcraft_doc::Node::path(id, vectorcraft_geom::shapes::rectangle(r), vectorcraft_doc::Appearance::default_art());
|
||||
let mut guide = square(guide_id, Rect::new(500.0, 100.0, 520.0, 120.0));
|
||||
if let NodeKind::Path { guide, .. } = &mut guide.kind {
|
||||
*guide = true;
|
||||
}
|
||||
let art = square(art_id, Rect::new(100.0, 100.0, 120.0, 120.0));
|
||||
d.insert(Some(l), 0, vectorcraft_doc::Node::group(gid, vec![std::sync::Arc::new(guide), std::sync::Arc::new(art)])).unwrap();
|
||||
let (none, p) = (Selection::default(), paint());
|
||||
let r = Rect::new(50.0, 50.0, 200.0, 200.0);
|
||||
assert_eq!(crate::select::inside(&ToolContext { guides: false, ..cx(&d, &none, &p) }, r, vec![gid]), [gid], "locked or hidden");
|
||||
assert!(crate::select::inside(&ToolContext { guides: true, ..cx(&d, &none, &p) }, r, vec![gid]).is_empty(), "shown and unlocked");
|
||||
}
|
||||
|
||||
/// #955: grabbed by an anchor and dropped near another object's anchor, the anchor lands
|
||||
/// exactly on it with Smart Guides, even where lining the bounds up would leave it beside it.
|
||||
#[test]
|
||||
|
||||
@@ -329,3 +329,45 @@ fn common_tangents_previews_cancels_and_runs_on_ok() {
|
||||
assert_eq!((steps(&app), count(&app)), (n, nodes));
|
||||
assert!(app.ui.status.contains("inside the other"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
/// Common Tangents… on a point and an ellipse: every Tangents choice previews the same two lines
|
||||
/// from the point, OK keeps them as one step, and a point inside the ellipse changes nothing and
|
||||
/// says why.
|
||||
#[test]
|
||||
fn common_tangents_on_a_point_gives_the_same_lines_for_every_choice() {
|
||||
let mut app = app();
|
||||
let oval = app.run("shape.ellipse", json!({"x": 180.0, "y": 120.0, "width": 80.0, "height": 60.0})).unwrap()["id"].as_u64().unwrap();
|
||||
let point =
|
||||
|app: &mut VectorcraftApp, x: f64, y: f64| app.run("path.create", json!({"anchors": [{"x": x, "y": y}]})).unwrap()["id"].as_u64().unwrap();
|
||||
let dot = point(&mut app, 40.0, 150.0);
|
||||
app.run("select.set", json!({"ids": [oval, dot]})).unwrap();
|
||||
let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count();
|
||||
let (n, nodes) = (steps(&app), count(&app));
|
||||
let open = |app: &mut VectorcraftApp| {
|
||||
let entries = menus::menu_entries(app);
|
||||
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Common Tangents…").unwrap();
|
||||
assert!(item.enabled);
|
||||
let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params);
|
||||
menus::invoke(app, &cmd, p);
|
||||
};
|
||||
|
||||
open(&mut app);
|
||||
crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true));
|
||||
for (_, kind) in super::TANGENT_KINDS {
|
||||
crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "tangents".into(), json!(kind));
|
||||
painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx()));
|
||||
assert_eq!(count(&app), nodes + 2, "{kind}: the two lines from the point");
|
||||
}
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 2), "one undo step");
|
||||
|
||||
// A point inside the ellipse: nothing changes, and a message says why.
|
||||
let inside = point(&mut app, 220.0, 150.0);
|
||||
app.run("select.set", json!({"ids": [oval, inside]})).unwrap();
|
||||
let (n, nodes) = (steps(&app), count(&app));
|
||||
open(&mut app);
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!((steps(&app), count(&app)), (n, nodes));
|
||||
assert!(app.ui.status.contains("The point lies inside the path"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ impl VectorcraftApp {
|
||||
slices: None,
|
||||
print_tiling: None,
|
||||
live_paint_gaps: None,
|
||||
find_font: None,
|
||||
hidden_chars: Default::default(),
|
||||
spelling: Default::default(),
|
||||
selection_marks: Default::default(),
|
||||
|
||||
@@ -42,6 +42,10 @@ pub struct CanvasCache {
|
||||
pub print_tiling: Option<PrintTilingCache>,
|
||||
/// The gap lines View → Show Live Paint Gaps draws for (document uid, revision).
|
||||
pub live_paint_gaps: Option<LivePaintGapsCache>,
|
||||
/// Type → Find Font's list of the document's fonts and whether the document misses one, for a
|
||||
/// version of the document's content and of the available fonts: the dialog reads them every
|
||||
/// frame.
|
||||
pub find_font: Option<FindFontCache>,
|
||||
/// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame
|
||||
/// that does not draw them drops them ([`canvas::show`]).
|
||||
pub hidden_chars: canvas::HiddenChars,
|
||||
@@ -117,6 +121,32 @@ pub type SliceCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_doc::SliceArea
|
||||
/// uid, revision).
|
||||
pub type LivePaintGapsCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_tools::Overlay>>);
|
||||
|
||||
/// [`CanvasCache::find_font`]: the document's fonts as `text.fonts` lists them, and whether
|
||||
/// [`vectorcraft_engine::cmd::fontfiles::missing_fonts`] finds any (`None` until it is asked).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FindFontCache {
|
||||
/// The document and the content and fonts the answers were worked out from.
|
||||
pub key: FontsKey,
|
||||
pub fonts: std::sync::Arc<Vec<serde_json::Value>>,
|
||||
pub missing: Option<bool>,
|
||||
}
|
||||
|
||||
/// A document's uid, a version of its content (compared by identity) and the font database's
|
||||
/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's
|
||||
/// allocation, so a later version is never placed at the same address while the key is kept.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FontsKey {
|
||||
pub uid: u64,
|
||||
pub doc: std::sync::Weak<vectorcraft_doc::Document>,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
impl PartialEq for FontsKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.uid == other.uid && self.generation == other.generation && std::sync::Weak::ptr_eq(&self.doc, &other.doc)
|
||||
}
|
||||
}
|
||||
|
||||
/// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they
|
||||
/// agree and `None` when they differ, with whether every one can be aligned.
|
||||
pub type PixelAligned = (Option<bool>, bool);
|
||||
|
||||
@@ -1121,6 +1121,7 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
ui.add_space((middle - BUTTON / 2.0 * row.len() as f32 - ui.cursor().min.x).max(0.0));
|
||||
for &(s, slot) in row {
|
||||
let Some((rect, shown)) = slot_button(ui, &t, &press, slot, &mut actions) else { continue };
|
||||
crate::palette::note_spot(ui, rect, || crate::palette::SpotAt::Slot(Some(bar.name.clone()), slot.clone()));
|
||||
if edit_this {
|
||||
buttons.push((s, rect));
|
||||
}
|
||||
|
||||
@@ -547,8 +547,9 @@ fn hidden_controls(d: &Dialog) -> &'static [&'static str] {
|
||||
}
|
||||
// The selected rows and Randomize's seed.
|
||||
Some(DialogKind::Recolor) => &["__seed", "__sel"],
|
||||
// The view, zoom, download speed, selected color table entries and the preset name being typed.
|
||||
Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__kbps", "__presetName", "__view", "__zoom"],
|
||||
// The view, zoom, download speed, selected color table entries, the color table entry whose
|
||||
// Color Picker opens and the preset name being typed.
|
||||
Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__editColor", "__kbps", "__presetName", "__view", "__zoom"],
|
||||
// The link that keeps width and height in proportion.
|
||||
Some(DialogKind::Shape | DialogKind::TransformEach) => &["__constrain"],
|
||||
// The attention filter, the Keys section, the search text and the key being recorded.
|
||||
@@ -846,6 +847,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
let focus_first = focus_first && !clicked;
|
||||
let spec = spec(&d.kind);
|
||||
// Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to.
|
||||
if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) {
|
||||
modal::over_parent(ctx);
|
||||
}
|
||||
if let Some(window) = spec.window {
|
||||
return window(app, ctx);
|
||||
}
|
||||
@@ -888,14 +893,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if focus_first {
|
||||
ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true));
|
||||
}
|
||||
// When the dialog is taller than the window, its body scrolls, and the heading and the
|
||||
// buttons stay in view.
|
||||
if let Some(body) = spec.body_with_actions {
|
||||
match body(app, ui, &mut d) {
|
||||
match modal::body_rows(ui, |ui| body(app, ui, &mut d)) {
|
||||
DialogAction::None => {}
|
||||
DialogAction::Confirm => ok = true,
|
||||
DialogAction::Cancel => cancel = true,
|
||||
}
|
||||
} else {
|
||||
cancel = (spec.body)(app, ui, &mut d);
|
||||
cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d));
|
||||
}
|
||||
// Taken (the flag is gone): done. Still there (the window's measuring frame): next frame.
|
||||
if focus_first && ui.data_mut(|m| m.remove_temp::<bool>(widgets::dialog_focus_flag())).is_none() {
|
||||
@@ -1076,6 +1083,9 @@ mod tests_perspective;
|
||||
#[cfg(test)]
|
||||
mod tests_modal;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_scroll;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests_rectangular_grid;
|
||||
|
||||
|
||||
@@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id {
|
||||
/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether
|
||||
/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`).
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
super::modal::fits_itself(ui);
|
||||
let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height());
|
||||
let content = ui.ctx().data(|m| m.get_temp::<f32>(content_id(ui))).unwrap_or(0.0);
|
||||
let rest = (window - content).max(0.0);
|
||||
|
||||
@@ -384,6 +384,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction {
|
||||
let p = picked(d);
|
||||
let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color);
|
||||
let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color);
|
||||
super::modal::fits_itself(ui);
|
||||
let (side, values_w, button_w, stacked) = layout_size(ui);
|
||||
let field_w = side + SLIDER_GAP + SLIDER_W;
|
||||
let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w };
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::DialogSpec;
|
||||
use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets};
|
||||
use egui::{RichText, Ui};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::dimension::DimensionOptions;
|
||||
use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions};
|
||||
|
||||
pub const KIND: &str = "dimensionOptions";
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
@@ -32,6 +32,10 @@ const UNITS: Choices = &[
|
||||
];
|
||||
const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")];
|
||||
const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")];
|
||||
/// The style of each `ARROWS` entry, in the same order.
|
||||
const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None];
|
||||
/// The size of an Arrow Style preview: a line with the head at its right end.
|
||||
const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0);
|
||||
const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")];
|
||||
const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")];
|
||||
|
||||
@@ -69,6 +73,29 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, key: &str, l
|
||||
});
|
||||
changed
|
||||
}
|
||||
/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in
|
||||
/// the open list and in the closed field.
|
||||
fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, id: &str) -> bool {
|
||||
const KEY: &str = "arrowStyle";
|
||||
let mut changed = false;
|
||||
widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| {
|
||||
let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default();
|
||||
let shown = ARROWS.iter().position(|(v, _)| *v == current);
|
||||
let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect();
|
||||
let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| {
|
||||
if let Some(style) = ARROW_STYLES.get(i) {
|
||||
crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink);
|
||||
}
|
||||
};
|
||||
if let Some((value, _)) =
|
||||
widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i))
|
||||
{
|
||||
fields.insert(KEY.into(), json!(value));
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
fn number(ui: &mut Ui, fields: &mut serde_json::Map<String, Value>, key: &str, label: &str, range: (f64, f64), suffix: &str) -> bool {
|
||||
let mut changed = false;
|
||||
widgets::label_row(ui, tl!(label), 96.0, |ui| {
|
||||
@@ -160,7 +187,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
color(ui, f, "lineColor");
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
choose(ui, f, "arrowStyle", "Arrow Style:", ARROWS);
|
||||
arrow_style(ui, f, "arrowStyle");
|
||||
number(ui, f, "arrowScale", "Arrow Scale:", (1.0, 1000.0), "%");
|
||||
});
|
||||
});
|
||||
@@ -310,7 +337,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
changed |= number(ui, &mut f, "lineWeight", "Line Weight:", (0.1, 100.0), "pt");
|
||||
changed |= color(ui, &mut f, "lineColor");
|
||||
});
|
||||
ui.horizontal(|ui| changed |= choose(ui, &mut f, "arrowStyle", "Arrow Style:", ARROWS));
|
||||
ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle"));
|
||||
ui.horizontal(|ui| {
|
||||
changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt");
|
||||
changed |= color(ui, &mut f, "textColor");
|
||||
@@ -377,4 +404,56 @@ mod tests {
|
||||
assert!(text.contains(label), "{label}: {text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a frame drew a picture (a textured mesh) just before the text `name` on its line.
|
||||
fn picture_before(out: &egui::FullOutput, name: &str) -> bool {
|
||||
fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, pictures: &mut Vec<egui::Rect>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.visual_bounding_rect())),
|
||||
egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => pictures.push(m.calc_bounds()),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, pictures)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (mut texts, mut pictures) = (vec![], vec![]);
|
||||
for c in &out.shapes {
|
||||
collect(&c.shape, &mut texts, &mut pictures);
|
||||
}
|
||||
texts
|
||||
.iter()
|
||||
.filter(|(t, _)| t == name)
|
||||
.any(|(_, r)| pictures.iter().any(|p| p.max.x <= r.min.x + 1.0 && r.min.x - p.max.x < 16.0 && p.min.y < r.max.y && p.max.y > r.min.y))
|
||||
}
|
||||
|
||||
/// The frame `f` draws, once its previews are loaded.
|
||||
fn frame(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &mut Ui)) -> egui::FullOutput {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear();
|
||||
ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui))
|
||||
}
|
||||
|
||||
/// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead,
|
||||
/// drawn, before its name (#8049).
|
||||
#[test]
|
||||
fn arrow_style_shows_a_drawn_arrowhead() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.run("tool.options", json!({"tool":"dimension"})).unwrap();
|
||||
let out = frame(&mut app, |app, ui| super::super::show(app, ui.ctx()));
|
||||
assert!(picture_before(&out, "Filled"), "Tool Options");
|
||||
app.ui.dialog = None;
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowStyle":"tick"}})).unwrap();
|
||||
let out = frame(&mut app, properties_section);
|
||||
assert!(picture_before(&out, "Tick"), "Properties");
|
||||
}
|
||||
|
||||
/// Each Arrow Style entry previews the style its value names.
|
||||
#[test]
|
||||
fn arrow_previews_follow_the_listed_styles() {
|
||||
assert_eq!(ARROWS.len(), ARROW_STYLES.len());
|
||||
for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) {
|
||||
assert_eq!(serde_json::to_value(style).unwrap(), json!(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! window with no title bar that opens centred and moves by dragging its heading (the band from its
|
||||
//! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where
|
||||
//! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows
|
||||
//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons
|
||||
//! stay in view.
|
||||
//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its
|
||||
//! heading and buttons stay in view. A window without such rows that is still too tall or too wide
|
||||
//! for the screen scrolls as a whole on that axis.
|
||||
|
||||
use egui::{Id, Rect, Vec2};
|
||||
|
||||
@@ -35,11 +36,97 @@ pub(crate) fn show_at<R>(ctx: &egui::Context, title: &str, id: Id, initial: Vec2
|
||||
.title_bar(false)
|
||||
.anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial))
|
||||
.frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin)))
|
||||
.show(ctx, add)?;
|
||||
keep_rest(ctx, id, shown.response.rect.height());
|
||||
.show(ctx, |ui| {
|
||||
// Just opened: what scrolls in the window starts at its top, wherever it was left when
|
||||
// the window last closed.
|
||||
if opened(ctx, id) {
|
||||
ctx.data_mut(|m| {
|
||||
m.insert_temp(id.with(TOP_ROWS_KEY), true);
|
||||
m.insert_temp(id.with(TOP_WHOLE_KEY), true);
|
||||
});
|
||||
}
|
||||
// A window whose contents are wider than the screen has room for, or taller without
|
||||
// rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis,
|
||||
// so none of it is out of reach. The contents keep their ids whether the window scrolls
|
||||
// or not, so a field being edited keeps its text when that changes.
|
||||
let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default();
|
||||
let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents"));
|
||||
let (r, contents) = if wide || tall {
|
||||
let room = whole_room(ctx, margin);
|
||||
let mut area = egui::ScrollArea::new([wide, tall]);
|
||||
if ctx.data_mut(|m| m.remove_temp::<bool>(id.with(TOP_WHOLE_KEY))).is_some() {
|
||||
area = area.scroll_offset(Vec2::ZERO);
|
||||
}
|
||||
let out = area
|
||||
.id_salt("modal-whole")
|
||||
.max_width(room.x)
|
||||
.max_height(room.y)
|
||||
.min_scrolled_width(room.x)
|
||||
.min_scrolled_height(room.y)
|
||||
.show(ui, |ui| ui.scope_builder(scope, add).inner);
|
||||
(out.inner, out.content_size)
|
||||
} else {
|
||||
let r = ui.scope_builder(scope, add).inner;
|
||||
(r, ui.min_rect().size())
|
||||
};
|
||||
ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents));
|
||||
r
|
||||
})?;
|
||||
keep_rest(ctx, id, shown.response.rect.height(), margin);
|
||||
shown.inner
|
||||
}
|
||||
|
||||
/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before,
|
||||
/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard
|
||||
/// Shortcuts). The window under it keeps where it was scrolled to.
|
||||
pub(crate) fn over_parent(ctx: &egui::Context) {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass));
|
||||
}
|
||||
|
||||
/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before,
|
||||
/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]).
|
||||
fn opened(ctx: &egui::Context, id: Id) -> bool {
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
ctx.data_mut(|m| {
|
||||
// The windows drawn in this pass so far and in the pass before.
|
||||
let (at, now, prev) = m.get_temp::<(u64, Vec<Id>, Vec<Id>)>(Id::unique(LAST_KEY)).unwrap_or_default();
|
||||
let (mut now, prev) = if at == pass {
|
||||
(now, prev)
|
||||
} else if at.saturating_add(1) == pass {
|
||||
(vec![], now)
|
||||
} else {
|
||||
(vec![], vec![])
|
||||
};
|
||||
let before: Vec<Id> = prev.iter().copied().filter(|&other| other != id).collect();
|
||||
now.push(id);
|
||||
m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev));
|
||||
let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass);
|
||||
if last != u64::MAX && last.saturating_add(1) >= pass {
|
||||
return false;
|
||||
}
|
||||
// Shown again as the window opened over it closed.
|
||||
if before.iter().any(|over| m.get_temp::<Id>(over.with(HOLDS_KEY)) == Some(id)) {
|
||||
return false;
|
||||
}
|
||||
// Opened over the window drawn last in the pass before, it holds that one; otherwise none.
|
||||
match before.last().copied().filter(|_| m.get_temp::<u64>(Id::unique(OVER_KEY)) == Some(pass)) {
|
||||
Some(under) => {
|
||||
m.insert_temp(id.with(HOLDS_KEY), under);
|
||||
}
|
||||
None => {
|
||||
m.remove::<Id>(id.with(HOLDS_KEY));
|
||||
}
|
||||
}
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// The room for the contents of a modal window with `margin` inside its frame.
|
||||
fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 {
|
||||
(ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO)
|
||||
}
|
||||
|
||||
/// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of
|
||||
/// the app would get.
|
||||
pub(crate) fn backdrop() -> egui::LayerId {
|
||||
@@ -86,34 +173,158 @@ pub(super) fn handle(id: Id) -> Id {
|
||||
id.with("modal-drag")
|
||||
}
|
||||
|
||||
/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall
|
||||
/// the rest of it was when last drawn.
|
||||
/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this
|
||||
/// frame, and how tall the rest of it was when last drawn.
|
||||
const ROWS_KEY: &str = "modal-rows";
|
||||
const REST_KEY: &str = "modal-rest";
|
||||
/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to
|
||||
/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`).
|
||||
const OWN_ROWS_KEY: &str = "modal-own-rows";
|
||||
const OWN_BEFORE_KEY: &str = "modal-own-before";
|
||||
/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame.
|
||||
const BODY_KEY: &str = "modal-body";
|
||||
/// Under a modal window's id: how large its contents would be without scrolling as a whole, this
|
||||
/// frame.
|
||||
const CONTENTS_KEY: &str = "modal-contents";
|
||||
/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on
|
||||
/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`).
|
||||
const TALL_KEY: &str = "modal-tall";
|
||||
const WHOLE_KEY: &str = "modal-whole";
|
||||
/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened,
|
||||
/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so
|
||||
/// they start at the top when they first do.
|
||||
const SHOWN_KEY: &str = "modal-shown";
|
||||
const TOP_ROWS_KEY: &str = "modal-top-rows";
|
||||
const TOP_WHOLE_KEY: &str = "modal-top-whole";
|
||||
/// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass
|
||||
/// and of those drawn in the pass before it (`LAST_KEY`), and the pass
|
||||
/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`).
|
||||
/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`).
|
||||
const LAST_KEY: &str = "modal-last";
|
||||
const OVER_KEY: &str = "modal-over";
|
||||
const HOLDS_KEY: &str = "modal-holds";
|
||||
|
||||
/// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window
|
||||
/// would be taller than the screen. Their height is the screen's less the rest of the window as
|
||||
/// last drawn (a frame late, as only the drawn window knows its height).
|
||||
/// Rows that fit are as tall as they are.
|
||||
pub(crate) fn scrolled_rows<R>(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let id = ui.layer_id().id;
|
||||
let rest = ui.ctx().data(|m| m.get_temp::<f32>(id.with(REST_KEY))).unwrap_or(0.0);
|
||||
let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0);
|
||||
// As tall as the room at once: by itself a scroll area grows a frame at a time with the window.
|
||||
let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner);
|
||||
ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height()));
|
||||
rows.inner
|
||||
fits_itself(ui);
|
||||
let (r, drawn, _) = rows(ui, salt, true, add);
|
||||
ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn));
|
||||
r
|
||||
}
|
||||
|
||||
/// After modal window `id` is drawn `height` tall: keep the height of all of it but its
|
||||
/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just
|
||||
/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit
|
||||
/// without waiting for input.
|
||||
fn keep_rest(ctx: &egui::Context, id: Id, height: f32) {
|
||||
let Some(rows) = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(ROWS_KEY))) else { return };
|
||||
let rest = (height - rows).max(0.0);
|
||||
let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest));
|
||||
if (used - rest).abs() > 0.5 {
|
||||
/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing
|
||||
/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window
|
||||
/// scroll them again.
|
||||
pub(crate) fn fits_itself(ui: &egui::Ui) {
|
||||
ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true));
|
||||
}
|
||||
|
||||
/// The body of a shared dialog window. While the window would be taller than the screen has room
|
||||
/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view;
|
||||
/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is.
|
||||
pub(crate) fn body_rows<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let id = ui.layer_id().id;
|
||||
let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add);
|
||||
if !ui.ctx().data(|m| m.get_temp::<bool>(id.with(OWN_ROWS_KEY))).unwrap_or(false) {
|
||||
ui.ctx().data_mut(|m| {
|
||||
m.insert_temp(id.with(ROWS_KEY), drawn);
|
||||
m.insert_temp(id.with(BODY_KEY), body);
|
||||
});
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Whether the [`body_rows`] of modal window `id` scroll in this frame.
|
||||
fn body_scrolls(ctx: &egui::Context, id: Id) -> bool {
|
||||
let own = ctx.data(|m| m.get_temp::<bool>(id.with(OWN_BEFORE_KEY))).unwrap_or(false);
|
||||
!own && ctx.data(|m| m.get_temp::<bool>(id.with(TALL_KEY))).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn.
|
||||
pub(crate) fn body_view(ui: &egui::Ui) -> Option<f32> {
|
||||
let id = ui.layer_id().id;
|
||||
body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id))
|
||||
}
|
||||
|
||||
/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on
|
||||
/// which axes ([wide, tall]) the window scrolls as a whole.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option<f32>, [bool; 2]) {
|
||||
let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id));
|
||||
(body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`]
|
||||
/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so
|
||||
/// the list and its bar can be scrolled into view whole.
|
||||
pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 {
|
||||
body_view(ui).map_or(height, |view| view.min(height))
|
||||
}
|
||||
|
||||
/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the
|
||||
/// window as last drawn.
|
||||
fn rows_room(ctx: &egui::Context, id: Id) -> f32 {
|
||||
let rest = ctx.data(|m| m.get_temp::<f32>(id.with(REST_KEY))).unwrap_or(0.0);
|
||||
(ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0)
|
||||
}
|
||||
|
||||
/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their
|
||||
/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling.
|
||||
/// Rows that do not `scroll` are as tall as they are, with no
|
||||
/// scroll area (which would take the scroll requests of their fields from the window's). The rows
|
||||
/// keep their ids either way, so a field being edited keeps its text when they start or stop
|
||||
/// scrolling.
|
||||
fn rows<R>(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) {
|
||||
let id = ui.layer_id().id;
|
||||
let room = rows_room(ui.ctx(), id);
|
||||
let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows"));
|
||||
if !scroll {
|
||||
let rows = ui.scope_builder(scope, add);
|
||||
let height = rows.response.rect.height();
|
||||
return (rows.inner, height, height);
|
||||
}
|
||||
// As tall as the room at once: by itself a scroll area grows a frame at a time with the window.
|
||||
let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room);
|
||||
if ui.ctx().data_mut(|m| m.remove_temp::<bool>(id.with(TOP_ROWS_KEY))).is_some() {
|
||||
area = area.scroll_offset(Vec2::ZERO);
|
||||
}
|
||||
let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner));
|
||||
(rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y)
|
||||
}
|
||||
|
||||
/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height
|
||||
/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different
|
||||
/// one (the window just opened, or what is around them changed), the next frame is drawn at once,
|
||||
/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll
|
||||
/// while the window would be taller than the screen has room for without them scrolling; a window
|
||||
/// without rows that scroll scrolls as a whole while its contents would be taller than the room,
|
||||
/// and any window scrolls sideways while its contents would be wider.
|
||||
fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) {
|
||||
let rows = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(ROWS_KEY)));
|
||||
let body = ctx.data_mut(|m| m.remove_temp::<f32>(id.with(BODY_KEY)));
|
||||
let contents = ctx.data_mut(|m| m.remove_temp::<Vec2>(id.with(CONTENTS_KEY))).unwrap_or_default();
|
||||
let own = ctx.data_mut(|m| m.remove_temp::<bool>(id.with(OWN_ROWS_KEY))).unwrap_or(false);
|
||||
ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own));
|
||||
let room = whole_room(ctx, margin);
|
||||
let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP;
|
||||
let tall = match (rows, body) {
|
||||
(Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5,
|
||||
_ => false,
|
||||
};
|
||||
// A window that fits itself to the screen's height can still be too wide for it.
|
||||
let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5];
|
||||
let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall));
|
||||
let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole));
|
||||
let mut repaint = tall != was_tall || whole != was_whole;
|
||||
if let Some(rows) = rows {
|
||||
let rest = (height - rows).max(0.0);
|
||||
let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest));
|
||||
repaint |= (used - rest).abs() > 0.5;
|
||||
}
|
||||
if repaint {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
@@ -159,4 +370,159 @@ mod tests {
|
||||
// Larger than the screen: its top left stays in view.
|
||||
assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0));
|
||||
}
|
||||
|
||||
/// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal
|
||||
/// windows named in `open` open, in that order: the first a heading and 60 rows, in
|
||||
/// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is
|
||||
/// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in
|
||||
/// the last frame (inside the screen and its clip).
|
||||
fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec<egui::Event>, time: &mut f64, frames: usize) -> bool {
|
||||
let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0));
|
||||
let add = |ui: &mut egui::Ui| {
|
||||
for i in 0..60 {
|
||||
ui.label(format!("Row {i}"));
|
||||
}
|
||||
};
|
||||
let mut events = Some(events);
|
||||
let mut seen = false;
|
||||
for _ in 0..frames {
|
||||
*time += 1.0 / 60.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
for (i, &name) in open.iter().enumerate() {
|
||||
if name.starts_with("over ") {
|
||||
over_parent(ui.ctx());
|
||||
}
|
||||
show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| {
|
||||
heading(ui, "Top");
|
||||
if i > 0 {
|
||||
ui.label("Alert");
|
||||
} else if in_rows {
|
||||
scrolled_rows(ui, "rows", add);
|
||||
} else {
|
||||
add(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
seen = out.shapes.iter().any(|c| match &c.shape {
|
||||
egui::Shape::Text(t) => {
|
||||
let r = t.visual_bounding_rect();
|
||||
t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r)
|
||||
}
|
||||
_ => false,
|
||||
});
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// A wheel turn far down, at the middle of the 400×300 screen.
|
||||
fn wheel_down() -> Vec<egui::Event> {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(0.0, -3000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_scrolled_opens_again_at_its_top() {
|
||||
for in_rows in [false, true] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let mut time = 0.0;
|
||||
assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top");
|
||||
assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away");
|
||||
first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2);
|
||||
assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() {
|
||||
// As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it
|
||||
// did not close. A window that another replaced did close. Either may have shown an alert
|
||||
// of its own, drawn after it in the same passes.
|
||||
let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)];
|
||||
let mut wrong = vec![];
|
||||
for in_rows in [false, true] {
|
||||
for (other, kept) in others {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let mut time = 0.0;
|
||||
first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4);
|
||||
if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) {
|
||||
wrong.push(format!("rows {in_rows}: the wheel does not scroll A"));
|
||||
}
|
||||
if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) {
|
||||
wrong.push(format!("rows {in_rows}: {other:?} does not open at its top"));
|
||||
}
|
||||
if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept {
|
||||
wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" }));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() {
|
||||
// A field's edit state and the keyboard focus are kept under its id, so typing goes on into
|
||||
// the same field when the screen's height changes whether the body or the window scrolls.
|
||||
let mut wrong = vec![];
|
||||
for in_body in [false, true] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let window = Id::unique("modal-field-id-test");
|
||||
let mut text = String::from("12");
|
||||
let mut time = 0.0;
|
||||
let mut field = None;
|
||||
let mut focus_given = false;
|
||||
let mut seen = vec![];
|
||||
for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] {
|
||||
let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height));
|
||||
for i in 0..4 {
|
||||
time += 1.0 / 60.0;
|
||||
// Typed once the window has settled at this height.
|
||||
let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] };
|
||||
let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
show(ui.ctx(), "Test", window, 0.0, 8, |ui| {
|
||||
heading(ui, "Top");
|
||||
let mut add = |ui: &mut egui::Ui| {
|
||||
let r = ui.text_edit_singleline(&mut text);
|
||||
for i in 0..30 {
|
||||
ui.label(format!("Row {i}"));
|
||||
}
|
||||
r.id
|
||||
};
|
||||
field = Some(if in_body { body_rows(ui, add) } else { add(ui) });
|
||||
});
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
// The field is given the focus once, after the first frame; a resize that took it
|
||||
// away would leave the keys typed after it untaken.
|
||||
if let Some(id) = field.filter(|_| !focus_given) {
|
||||
ctx.memory_mut(|m| m.request_focus(id));
|
||||
focus_given = true;
|
||||
}
|
||||
}
|
||||
let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) };
|
||||
let scrolls = ctx.data(|m| m.get_temp::<bool>(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1]));
|
||||
seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some()));
|
||||
}
|
||||
let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)];
|
||||
let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect();
|
||||
if seen != want {
|
||||
wrong.push((in_body, seen));
|
||||
}
|
||||
}
|
||||
// Only the short screen scrolls, and the field keeps its focus and takes each key.
|
||||
assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id {
|
||||
/// (as drawn last frame). The section list stays put while the content scrolls. Returns whether
|
||||
/// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`).
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
super::modal::fits_itself(ui);
|
||||
let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height());
|
||||
let content = ui.ctx().data(|m| m.get_temp::<f32>(content_id(ui))).unwrap_or(0.0);
|
||||
let rest = (window - content).max(0.0);
|
||||
|
||||
@@ -251,7 +251,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(500.0);
|
||||
ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong));
|
||||
egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
let list_h = super::modal::list_height(ui, 360.0);
|
||||
egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
"Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d),
|
||||
"Output" => output(ui, d, &preview),
|
||||
"Graphics" => graphics(ui, d),
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
//! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views,
|
||||
//! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8,
|
||||
//! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap,
|
||||
//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color
|
||||
//! and Restore Generated Table), image size and anti-aliasing, Clip to Artboard, sRGB, metadata,
|
||||
//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color,
|
||||
//! Restore Generated Table, a double-click that shifts a color to one picked in the Color Picker,
|
||||
//! and Unshift All Colors), image size and anti-aliasing, Clip to Artboard, sRGB, metadata,
|
||||
//! slices and HTML output, and presets.
|
||||
//!
|
||||
//! Fields are the `document.exportForWeb` settings (`webExport.settings` gives them; set one with
|
||||
@@ -11,7 +12,8 @@
|
||||
//! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed),
|
||||
//! `__color` (the colour table's selected colour, by source: the one Lock, Transparent and Web
|
||||
//! Shift edit, and where a Shift-click range starts), `__colors` (every selected color, by source,
|
||||
//! which Delete Color deletes; when it is empty, `__color` alone), `__presetName` (shown while saving a
|
||||
//! which Delete Color deletes; when it is empty, `__color` alone), `__editColor` (a source color:
|
||||
//! the Color Picker opens on it, as a double-click on its swatch opens it), `__presetName` (shown while saving a
|
||||
//! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K),
|
||||
//! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`,
|
||||
//! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and
|
||||
@@ -55,6 +57,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec {
|
||||
|
||||
/// The preview area (panes and their captions) and the settings column.
|
||||
const PREVIEW_W: f32 = 620.0;
|
||||
/// The narrowest the panes get in a narrow window.
|
||||
const MIN_PREVIEW_W: f32 = 240.0;
|
||||
const PREVIEW_H: f32 = 470.0;
|
||||
const SIDE_W: f32 = 296.0;
|
||||
const GAP: f32 = 16.0;
|
||||
@@ -533,12 +537,22 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
take_shift(d);
|
||||
let settings = settings_of(app, d);
|
||||
let mut browser = false;
|
||||
ui.horizontal_top(|ui| {
|
||||
// In a window too narrow for both, the panes are narrower, so the settings beside them and the
|
||||
// buttons below stay in view. The room is the screen's (the window's own width follows what it
|
||||
// drew last), less a column for the bar of the body while it scrolls; the settings column is as
|
||||
// wide as it was drawn last.
|
||||
let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 };
|
||||
let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar;
|
||||
let rest_id = egui::Id::unique("save-for-web-beside-panes");
|
||||
let rest = ui.ctx().data(|m| m.get_temp::<f32>(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W);
|
||||
let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W);
|
||||
let row = ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(PREVIEW_W);
|
||||
browser = preview_area(app, ui, d, &settings);
|
||||
ui.set_width(preview_w);
|
||||
browser = preview_area(app, ui, d, &settings, preview_w);
|
||||
});
|
||||
ui.add_space(GAP);
|
||||
ui.vertical(|ui| {
|
||||
@@ -546,23 +560,33 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
side(app, ui, d, settings.as_ref().ok());
|
||||
});
|
||||
});
|
||||
let drawn = row.response.rect.width() - preview_w;
|
||||
if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
optimize_on_enter(ui.ctx(), d);
|
||||
if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) {
|
||||
app.status(e);
|
||||
}
|
||||
// A double-clicked swatch (or an agent's `__editColor`) opens the Color Picker last, over the
|
||||
// dialog as it now is.
|
||||
if let Some(source) = d.fields.remove("__editColor").and_then(|v| v.as_str().map(String::from)) {
|
||||
let start = d.fields.remove("__editStart").and_then(|v| v.as_str().map(String::from)).unwrap_or_else(|| source.clone());
|
||||
edit_color(d, &source, &start);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was
|
||||
/// clicked.
|
||||
fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result<WebSettings, String>) -> bool {
|
||||
/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in
|
||||
/// Browser was clicked.
|
||||
fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result<WebSettings, String>, width: f32) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2);
|
||||
if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) {
|
||||
d.fields.insert("__view".into(), json!(VIEWS[i]));
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag());
|
||||
let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag());
|
||||
let pan_id = egui::Id::unique("save-for-web-pan");
|
||||
let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default();
|
||||
if resp.dragged() {
|
||||
@@ -607,6 +631,17 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
let mut browser = false;
|
||||
// Preview in Browser goes on a row of its own when the panes are too narrow for it beside the
|
||||
// two lists (its width as `widgets::secondary_button` draws it).
|
||||
let label = tl!("Preview in Browser");
|
||||
let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0);
|
||||
let mut beside = false;
|
||||
let mut button = |ui: &mut egui::Ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, label));
|
||||
browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked();
|
||||
});
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
let z = ZOOMS.iter().position(|z| *z == d.str("__zoom")).unwrap_or(2);
|
||||
let zoom = ui.name_inputs(tl!("Zoom"), |ui| widgets::dropdown(ui, "sfw-zoom", ZOOM_LABELS[z], &ZOOM_LABELS, 110.0));
|
||||
@@ -623,11 +658,15 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set
|
||||
{
|
||||
d.fields.insert("__kbps".into(), json!(s));
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Preview in Browser")));
|
||||
browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked();
|
||||
});
|
||||
beside = ui.available_width() >= button_w;
|
||||
if beside {
|
||||
button(ui);
|
||||
}
|
||||
});
|
||||
if !beside {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(button);
|
||||
}
|
||||
browser
|
||||
}
|
||||
|
||||
@@ -732,7 +771,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<&
|
||||
presets_row(app, ui, d, s);
|
||||
optimize_rows(ui, d, s, &art_key(app));
|
||||
widgets::divider(ui);
|
||||
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| {
|
||||
let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0);
|
||||
egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| {
|
||||
let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| {
|
||||
form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options);
|
||||
};
|
||||
@@ -1057,7 +1097,9 @@ fn matte_row(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
/// ones with a square, web-safe ones with a diamond, transparent ones over the grid), the buttons
|
||||
/// that edit the selected colour, Delete Color and the table's menu, plus the sort order. A click
|
||||
/// selects one color, a Shift-click the colors from the anchor, and a Ctrl-click
|
||||
/// (Command-click on macOS) adds or removes one. Returns an error for a deletion that would leave
|
||||
/// (Command-click on macOS) adds or removes one; a double-click on an opaque color asks for the
|
||||
/// Color Picker (`__editColor`), and a color shifted by hand shows its source color at the upper
|
||||
/// left and its new color at the lower right. Returns an error for a deletion that would leave
|
||||
/// no color.
|
||||
fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Result<(), String> {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
@@ -1086,15 +1128,20 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re
|
||||
.colors
|
||||
.iter()
|
||||
.map(|c| (*c, false))
|
||||
.chain(shot.mapped.iter().map(|c| (TableColor { color: *c, source: *c, transparent: true, locked: false, web_shifted: false }, true)))
|
||||
.chain(
|
||||
shot.mapped
|
||||
.iter()
|
||||
.map(|c| (TableColor { color: *c, source: *c, transparent: true, locked: false, web_shifted: false, shifted: false }, true)),
|
||||
)
|
||||
.collect();
|
||||
const CELL: f32 = 15.0;
|
||||
let per_row = ((SIDE_W - 8.0) / (CELL + 2.0)).floor().max(1.0) as usize;
|
||||
let lines = rows.len().div_ceil(per_row).max(1);
|
||||
let (area, resp) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::click());
|
||||
let (area, _) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::hover());
|
||||
// The colors that can be selected, in table order (for Shift-click ranges).
|
||||
let order: Vec<String> = rows.iter().filter(|(c, mapped)| !c.transparent || *mapped).map(|(c, _)| hex(c.source)).collect();
|
||||
let mut clicked = None;
|
||||
let mut edit = None;
|
||||
let p = ui.painter();
|
||||
for (i, (c, mapped)) in rows.iter().enumerate() {
|
||||
let r = egui::Rect::from_min_size(
|
||||
@@ -1113,6 +1160,15 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re
|
||||
}
|
||||
} else {
|
||||
p.rect_filled(r, 0.0, fill);
|
||||
if c.shifted {
|
||||
// Shifted by hand: the source color at the upper left, the new one at the lower right.
|
||||
let [red, g, b] = c.source;
|
||||
p.add(egui::Shape::convex_polygon(
|
||||
vec![r.left_top(), r.right_top(), r.left_bottom()],
|
||||
egui::Color32::from_rgb(red, g, b),
|
||||
egui::Stroke::NONE,
|
||||
));
|
||||
}
|
||||
}
|
||||
let mark = if c.color.iter().map(|v| u32::from(*v)).sum::<u32>() > 380 { egui::Color32::BLACK } else { egui::Color32::WHITE };
|
||||
if c.locked {
|
||||
@@ -1130,18 +1186,37 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re
|
||||
let pickable = !c.transparent || *mapped;
|
||||
let ringed = pickable && picked.iter().any(|h| h.eq_ignore_ascii_case(&hex(c.source)));
|
||||
p.rect_stroke(r, 0.0, egui::Stroke::new(if ringed { 2.0 } else { 1.0 }, if ringed { t.accent } else { t.border }), egui::StrokeKind::Outside);
|
||||
if pickable && resp.clicked() && resp.interact_pointer_pos().is_some_and(|pos| r.contains(pos)) {
|
||||
if !pickable {
|
||||
continue;
|
||||
}
|
||||
let resp = ui.interact(r, swatch_id(&hex(c.source)), egui::Sense::click());
|
||||
if resp.clicked() {
|
||||
clicked = Some(hex(c.source));
|
||||
}
|
||||
// A double-click edits an opaque color: the picker opens on the color as shown, or on the
|
||||
// source color for a color already shifted by hand.
|
||||
if resp.double_clicked() && !c.transparent {
|
||||
edit = Some((hex(c.source), hex(if c.shifted { c.source } else { c.color })));
|
||||
}
|
||||
}
|
||||
if let Some(c) = clicked {
|
||||
let m = ui.input(|i| i.modifiers);
|
||||
pick(d, &order, &c, m.shift, m.command);
|
||||
}
|
||||
if let Some((source, start)) = edit {
|
||||
d.fields.insert("__editColor".into(), json!(source));
|
||||
d.fields.insert("__editStart".into(), json!(start));
|
||||
}
|
||||
let shifted = |c: &str| table.shifted.keys().any(|k| k.eq_ignore_ascii_case(c));
|
||||
// The colors the table shows, by source: Lock, Transparent, Web Shift and Delete Color act only
|
||||
// on these.
|
||||
let palette: Vec<String> =
|
||||
shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect();
|
||||
let shown = palette.iter().any(|p| p.eq_ignore_ascii_case(&selected));
|
||||
ui.add_space(4.0);
|
||||
let on = |list: &[String]| list.iter().any(|h| h.eq_ignore_ascii_case(&selected));
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_enabled_ui(!selected.is_empty(), |ui| {
|
||||
ui.add_enabled_ui(shown, |ui| {
|
||||
for (list, on_label, off_label) in [
|
||||
("transparent", tl!("Restore"), tl!("Transparent")),
|
||||
("webShift", tl!("Unshift"), tl!("Web Shift")),
|
||||
@@ -1152,21 +1227,30 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re
|
||||
"webShift" => &table.web_shift,
|
||||
_ => &table.locked,
|
||||
};
|
||||
let is_on = on(current);
|
||||
if widgets::flat_button(ui, if is_on { on_label } else { off_label }, 88.0).clicked() {
|
||||
// A color shifted by hand stays locked until it is unshifted.
|
||||
let fixed = list == "locked" && shifted(&selected);
|
||||
let is_on = on(current) || fixed;
|
||||
let label = if is_on { on_label } else { off_label };
|
||||
if ui.add_enabled(!fixed, |ui: &mut egui::Ui| widgets::flat_button(ui, label, 88.0)).clicked() {
|
||||
toggle(d, list, &selected, !is_on);
|
||||
// Web Shift replaces a shift by hand.
|
||||
if list == "webShift" && !is_on {
|
||||
unshift(d, &selected);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
// Delete Color (the button and the table's menu) and Restore Generated Table.
|
||||
let (mut delete, mut restore) = (false, false);
|
||||
// Delete Color (the button and the table's menu) and Restore Generated Table. Delete Color
|
||||
// takes only selected colors the table shows (`palette`, by source).
|
||||
let deletable = !selected_in(d, &palette).is_empty();
|
||||
let (mut delete, mut restore, mut unshift_all) = (false, false, false);
|
||||
ui.horizontal(|ui| {
|
||||
delete |= widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Color"), false, !picked.is_empty(), 24.0).clicked();
|
||||
delete |= widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Color"), false, deletable, 24.0).clicked();
|
||||
let menu = widgets::icon_button(ui, "menu", tl!("Color Table"), false, 24.0);
|
||||
let open = menu.clicked();
|
||||
let _ = widgets::popover(&menu, open, |ui| {
|
||||
if widgets::menu_item(ui, tl!("Delete Color"), !picked.is_empty(), false) {
|
||||
if widgets::menu_item(ui, tl!("Delete Color"), deletable, false) {
|
||||
delete = true;
|
||||
ui.close();
|
||||
}
|
||||
@@ -1174,6 +1258,10 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re
|
||||
restore = true;
|
||||
ui.close();
|
||||
}
|
||||
if widgets::menu_item(ui, tl!("Unshift All Colors"), !table.shifted.is_empty() || !table.web_shift.is_empty(), false) {
|
||||
unshift_all = true;
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
let sort = table.sort;
|
||||
@@ -1188,14 +1276,20 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re
|
||||
if restore {
|
||||
restore_table(d);
|
||||
}
|
||||
if unshift_all {
|
||||
unshift_all_colors(d);
|
||||
}
|
||||
if delete {
|
||||
let palette: Vec<String> =
|
||||
shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect();
|
||||
delete_colors(d, &palette)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The selected colors (by source) that `palette`, the colors the table shows, holds.
|
||||
pub(super) fn selected_in(d: &Dialog, palette: &[String]) -> Vec<String> {
|
||||
selection(d).into_iter().filter(|c| palette.iter().any(|p| p.eq_ignore_ascii_case(c))).collect()
|
||||
}
|
||||
|
||||
/// The colour table's selected colors, by source: `__colors`, else `__color`.
|
||||
pub(super) fn selection(d: &Dialog) -> Vec<String> {
|
||||
let many: Vec<String> =
|
||||
@@ -1245,11 +1339,14 @@ pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, c
|
||||
/// Delete Color: the selected colors join the color table's `deleted` list and leave its other
|
||||
/// lists. The first deletion fixes the palette (`customPalette`) to `palette`, the table's colors
|
||||
/// (by source) with the deleted ones, so the colors left do not change. A deletion that leaves no
|
||||
/// color, or only colors mapped to transparent, is refused with nothing changed. The selection is
|
||||
/// cleared.
|
||||
/// color, or only colors mapped to transparent, is refused with nothing changed. Only selected
|
||||
/// colors that `palette` holds are deleted; when it holds none of them, the table is left as it is
|
||||
/// and the selection is cleared. The selection is cleared after a deletion too.
|
||||
pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), String> {
|
||||
let picked = selection(d);
|
||||
let picked = selected_in(d, palette);
|
||||
if picked.is_empty() {
|
||||
d.fields.remove("__colors");
|
||||
d.fields.remove("__color");
|
||||
return Ok(());
|
||||
}
|
||||
let list = |d: &Dialog, key: &str| -> Vec<String> {
|
||||
@@ -1285,6 +1382,9 @@ pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), St
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in &picked {
|
||||
unshift(d, c);
|
||||
}
|
||||
set_table(d, "customPalette", json!(custom));
|
||||
set_table(d, "deleted", json!(deleted));
|
||||
d.fields.remove("__colors");
|
||||
@@ -1299,6 +1399,71 @@ pub(super) fn restore_table(d: &mut Dialog) {
|
||||
set_table(d, "customPalette", json!([]));
|
||||
}
|
||||
|
||||
/// The id of the color table's swatch for the source color `source` (`#rrggbb`).
|
||||
pub(super) fn swatch_id(source: &str) -> egui::Id {
|
||||
egui::Id::unique(("sfw-swatch", source.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
/// The field of the Color Picker's OK over Save for Web: the color the edited swatch shifts to.
|
||||
const SHIFT_TO: &str = "__shiftTo";
|
||||
|
||||
/// The Color Picker over the dialog for the color table's source color `source`, on `start`; its
|
||||
/// OK shifts the color ([`shift_color`]) and its Cancel leaves the table as it was. Nothing opens
|
||||
/// when either is not a color.
|
||||
pub(super) fn edit_color(d: &mut Dialog, source: &str, start: &str) {
|
||||
let (Some(_), Some(c)) = (vectorcraft_color::Color::from_hex(source), vectorcraft_color::Color::from_hex(start)) else { return };
|
||||
d.fields.insert("__shiftSource".into(), json!(source));
|
||||
*d = super::color_picker::over_effect(d, SHIFT_TO, c);
|
||||
}
|
||||
|
||||
/// Back from the Color Picker: its OK's color shifts the color it was opened for.
|
||||
fn take_shift(d: &mut Dialog) {
|
||||
let source = d.fields.remove("__shiftSource");
|
||||
if let (Some(to), Some(source)) = (d.fields.remove(SHIFT_TO), source)
|
||||
&& let (Some(to), Some(source)) = (to.as_str(), source.as_str())
|
||||
{
|
||||
shift_color(d, source, to);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shift the source color `source` to `to` (`colorTable.shifted`), wherever it is in the image; it
|
||||
/// is no longer web-shifted. Picking the source color itself takes the shift away. The color
|
||||
/// becomes the selection. Nothing changes when either is not a color.
|
||||
pub(super) fn shift_color(d: &mut Dialog, source: &str, to: &str) {
|
||||
let hex = |h: &str| vectorcraft_color::Color::from_hex(h).map(|c| c.to_hex());
|
||||
let (Some(source), Some(to)) = (hex(source), hex(to)) else { return };
|
||||
unshift(d, &source);
|
||||
if to != source {
|
||||
let mut map = shifts(d);
|
||||
map.insert(source.clone(), json!(to));
|
||||
set_table(d, "shifted", Value::Object(map));
|
||||
}
|
||||
toggle(d, "webShift", &source, false);
|
||||
d.fields.insert("__colors".into(), json!([source]));
|
||||
d.fields.insert("__color".into(), json!(source));
|
||||
}
|
||||
|
||||
/// The `colorTable.shifted` field.
|
||||
fn shifts(d: &Dialog) -> Map<String, Value> {
|
||||
d.fields.get("colorTable").and_then(|t| t.get("shifted")).and_then(Value::as_object).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Take the shift by hand of the source color `source` away.
|
||||
pub(super) fn unshift(d: &mut Dialog, source: &str) {
|
||||
let mut map = shifts(d);
|
||||
let before = map.len();
|
||||
map.retain(|k, _| !k.eq_ignore_ascii_case(source));
|
||||
if map.len() != before {
|
||||
set_table(d, "shifted", Value::Object(map));
|
||||
}
|
||||
}
|
||||
|
||||
/// Unshift All Colors: no color is shifted by hand or web-shifted.
|
||||
pub(super) fn unshift_all_colors(d: &mut Dialog) {
|
||||
set_table(d, "shifted", json!({}));
|
||||
set_table(d, "webShift", json!([]));
|
||||
}
|
||||
|
||||
/// Add `color` to the colour table's `list`, or take it out.
|
||||
pub(super) fn toggle(d: &mut Dialog, list: &str, color: &str, add: bool) {
|
||||
let mut v: Vec<Value> = d.fields.get("colorTable").and_then(|t| t.get(list)).and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
|
||||
@@ -429,7 +429,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(500.0);
|
||||
ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong));
|
||||
egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
let list_h = super::modal::list_height(ui, 360.0);
|
||||
egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section {
|
||||
"Compression" => compression(ui, d),
|
||||
"Marks and Bleeds" => marks_and_bleeds(app, ui, d),
|
||||
"Output" => output(ui, d),
|
||||
|
||||
@@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open);
|
||||
let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0);
|
||||
crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| {
|
||||
crate::dialogs::modal::fits_itself(ui);
|
||||
ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0);
|
||||
crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set"));
|
||||
ui.add_space(10.0);
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` |
|
||||
//! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid;
|
||||
//! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an
|
||||
//! existing symbol). Help:
|
||||
//! existing symbol), `__keepArt` (true when a new symbol leaves the selection as ordinary art).
|
||||
//! Help:
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html>.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -69,15 +70,23 @@ const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic"
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM };
|
||||
|
||||
/// Open Symbol Options to name a new symbol made from the selection.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
/// Open Symbol Options to name a new symbol made from the selection. With `keep_art`, OK leaves
|
||||
/// the selection as ordinary art instead of replacing it with an instance.
|
||||
pub fn open(app: &mut VectorcraftApp, keep_art: bool) -> Result<Value, String> {
|
||||
let st = app.session.active().ok_or("no document open")?;
|
||||
if st.selection.is_empty() {
|
||||
return Err("nothing selected".into());
|
||||
}
|
||||
let name = st.doc.unique_symbol_name("New Symbol");
|
||||
let mut fields =
|
||||
json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false });
|
||||
let mut fields = json!({
|
||||
"name": name,
|
||||
"exportType": "movieClip",
|
||||
"type": "dynamic",
|
||||
"registration": 4,
|
||||
"alignToPixelGrid": false,
|
||||
"__edit": false,
|
||||
"__keepArt": keep_art,
|
||||
});
|
||||
if let Some(o) = fields.as_object_mut() {
|
||||
o.extend(slice_fields(None));
|
||||
}
|
||||
@@ -193,6 +202,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
} else {
|
||||
let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel });
|
||||
merge(&mut params, slice_params(d));
|
||||
if d.bool("__keepArt") {
|
||||
params["keepArt"] = json!(true);
|
||||
}
|
||||
app.run("symbol.new", params)
|
||||
};
|
||||
if r.is_ok() {
|
||||
|
||||
@@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId
|
||||
egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None })
|
||||
}
|
||||
|
||||
/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out.
|
||||
/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out.
|
||||
fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) {
|
||||
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
|
||||
screen.run(app, vec![]);
|
||||
let out = screen.run(app, vec![]);
|
||||
let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes;
|
||||
let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)));
|
||||
// W is left of H on their row (the tree lists its nodes in no particular order).
|
||||
let w = nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown)))
|
||||
.min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0)));
|
||||
screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]);
|
||||
screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]);
|
||||
screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]);
|
||||
|
||||
@@ -783,6 +783,177 @@ fn colour_table_selection_and_delete_color() {
|
||||
assert_eq!((&d.fields["colorTable"]["deleted"], &d.fields["colorTable"]["customPalette"]), (&json!([]), &json!([])));
|
||||
}
|
||||
|
||||
/// Delete Color takes only selected colors the table shows: a selection the table no longer holds
|
||||
/// (after a change of reduction or color count, or set through `ui.dialog.set`) deletes nothing,
|
||||
/// fixes no palette and is cleared, and a selection partly in the table deletes only what it shows.
|
||||
#[test]
|
||||
fn delete_color_skips_selected_colors_the_table_does_not_show() {
|
||||
let mut d = Dialog::new(save_for_web::KIND, json!({}));
|
||||
let shown: Vec<String> = ["#000000", "#111111"].map(String::from).to_vec();
|
||||
let table = |d: &Dialog, key: &str| d.fields.get("colorTable").and_then(|t| t.get(key)).cloned();
|
||||
d.fields.insert("__colors".into(), json!(["#ABCDEF"]));
|
||||
d.fields.insert("__color".into(), json!("#abcdef"));
|
||||
assert!(save_for_web::selected_in(&d, &shown).is_empty());
|
||||
save_for_web::delete_colors(&mut d, &shown).unwrap();
|
||||
assert_eq!((table(&d, "customPalette"), table(&d, "deleted")), (None, None));
|
||||
assert!(!d.fields.contains_key("__colors") && !d.fields.contains_key("__color"));
|
||||
d.fields.insert("__colors".into(), json!(["#abcdef", "#111111"]));
|
||||
assert_eq!(save_for_web::selected_in(&d, &shown), ["#111111"]);
|
||||
save_for_web::delete_colors(&mut d, &shown).unwrap();
|
||||
assert_eq!((table(&d, "customPalette"), table(&d, "deleted")), (Some(json!(shown)), Some(json!(["#111111"]))));
|
||||
}
|
||||
|
||||
/// A shift by hand replaces a web shift and selects the color; a shift to the color itself takes it
|
||||
/// away; Unshift All Colors clears both kinds; Delete Color takes a deleted color's shift away.
|
||||
#[test]
|
||||
fn colour_table_shift_unshift_and_unshift_all() {
|
||||
let mut d = Dialog::new(save_for_web::KIND, json!({}));
|
||||
save_for_web::toggle(&mut d, "webShift", "#123456", true);
|
||||
save_for_web::shift_color(&mut d, "#123456", "#FF8800");
|
||||
assert_eq!(d.fields["colorTable"], json!({"webShift": [], "shifted": {"#123456": "#ff8800"}}));
|
||||
assert_eq!(save_for_web::selection(&d), ["#123456"]);
|
||||
// Not a color: nothing changes.
|
||||
let before = d.fields.clone();
|
||||
save_for_web::shift_color(&mut d, "nope", "#000000");
|
||||
save_for_web::shift_color(&mut d, "#123456", "nope");
|
||||
assert_eq!(d.fields, before);
|
||||
save_for_web::shift_color(&mut d, "#ABCDEF", "#00ff00");
|
||||
save_for_web::shift_color(&mut d, "#123456", "#123456");
|
||||
assert_eq!(d.fields["colorTable"]["shifted"], json!({"#abcdef": "#00ff00"}));
|
||||
save_for_web::toggle(&mut d, "webShift", "#222222", true);
|
||||
save_for_web::unshift_all_colors(&mut d);
|
||||
assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["webShift"]), (&json!({}), &json!([])));
|
||||
let order: Vec<String> = ["#000000", "#222222"].map(String::from).to_vec();
|
||||
save_for_web::shift_color(&mut d, "#222222", "#ffffff");
|
||||
save_for_web::delete_colors(&mut d, &order).unwrap();
|
||||
assert_eq!((&d.fields["colorTable"]["shifted"], &d.fields["colorTable"]["deleted"]), (&json!({}), &json!(["#222222"])));
|
||||
}
|
||||
|
||||
/// One frame of `app` in `ctx`, 50 ms after the last.
|
||||
fn tick(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) {
|
||||
let time = ctx.input(|i| i.time) + 0.05;
|
||||
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)));
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
/// Double-click the color table's swatch of the source color `source`.
|
||||
fn double_click_swatch(app: &mut VectorcraftApp, ctx: &egui::Context, source: &str) {
|
||||
for _ in 0..3 {
|
||||
tick(app, ctx, vec![]);
|
||||
}
|
||||
let pos = ctx.read_response(save_for_web::swatch_id(source)).unwrap_or_else(|| panic!("no swatch for {source}")).rect.center();
|
||||
let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
tick(app, ctx, vec![egui::Event::PointerMoved(pos), button(true)]);
|
||||
tick(app, ctx, vec![button(false)]);
|
||||
tick(app, ctx, vec![button(true)]);
|
||||
tick(app, ctx, vec![button(false)]);
|
||||
tick(app, ctx, vec![]);
|
||||
}
|
||||
|
||||
/// The color the open Color Picker shows.
|
||||
fn picker_color(app: &VectorcraftApp) -> Option<String> {
|
||||
let d = app.ui.dialog.as_ref()?;
|
||||
assert_eq!(d.kind, "colorPicker", "the Color Picker is open");
|
||||
d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value).map(|c| c.to_hex())
|
||||
}
|
||||
|
||||
/// A double-click on a swatch opens the Color Picker on its color. Cancel changes nothing; OK
|
||||
/// shifts the color in the table and the saved file. A double-click on a shifted swatch opens the
|
||||
/// picker on the source color, and Web Shift replaces the shift by hand.
|
||||
#[test]
|
||||
fn double_clicking_a_swatch_shifts_its_color() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-shift-color");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] {
|
||||
set(&mut app, k, v);
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let shifted = |app: &VectorcraftApp| app.ui.dialog.as_ref().map(|d| d.fields["colorTable"]["shifted"].clone());
|
||||
double_click_swatch(&mut app, &ctx, "#0000ff");
|
||||
assert_eq!(picker_color(&app).as_deref(), Some("#0000ff"));
|
||||
crate::dialogs::cancel(&mut app);
|
||||
tick(&mut app, &ctx, vec![]);
|
||||
assert_eq!((kind(&app), shifted(&app)), (Some(save_for_web::KIND), Some(json!({}))), "Cancel shifts nothing");
|
||||
double_click_swatch(&mut app, &ctx, "#0000ff");
|
||||
set(&mut app, "color", json!("#00ff00"));
|
||||
confirm(&mut app).unwrap();
|
||||
tick(&mut app, &ctx, vec![]);
|
||||
assert_eq!((kind(&app), shifted(&app)), (Some(save_for_web::KIND), Some(json!({"#0000ff": "#00ff00"}))), "OK shifts the color");
|
||||
// The shifted swatch opens on its source color.
|
||||
double_click_swatch(&mut app, &ctx, "#0000ff");
|
||||
assert_eq!(picker_color(&app).as_deref(), Some("#0000ff"));
|
||||
crate::dialogs::cancel(&mut app);
|
||||
// Web Shift replaces the shift by hand.
|
||||
click_text(&mut app, "Web Shift");
|
||||
let t = app.ui.dialog.as_ref().unwrap().fields["colorTable"].clone();
|
||||
assert_eq!((&t["shifted"], &t["webShift"]), (&json!({}), &json!(["#0000ff"])));
|
||||
// Shifted again, the color reaches the saved file and is remembered.
|
||||
double_click_swatch(&mut app, &ctx, "#0000ff");
|
||||
set(&mut app, "color", json!("#00ff00"));
|
||||
confirm(&mut app).unwrap();
|
||||
tick(&mut app, &ctx, vec![]);
|
||||
let r = confirm(&mut app).unwrap();
|
||||
let image = image::open(r["path"].as_str().unwrap()).unwrap().to_rgba8();
|
||||
assert_eq!((image.get_pixel(50, 20).0, image.get_pixel(20, 14).0), ([0, 255, 0, 255], [204, 51, 0, 255]));
|
||||
let remembered = app.session.last_web_settings().color_table;
|
||||
assert_eq!((remembered.shifted.get("#0000ff").map(String::as_str), remembered.web_shift.len()), (Some("#00ff00"), 0));
|
||||
}
|
||||
|
||||
/// `ui.dialog.set` accepts `__editColor`, and the next frame opens the Color Picker on that color,
|
||||
/// whose OK shifts it.
|
||||
#[test]
|
||||
fn dialog_set_edit_color_opens_the_color_picker() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-edit-color-set");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
set(&mut app, "format", json!("gif"));
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": "__editColor", "value": "#0000ff"}));
|
||||
let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") };
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
tick(&mut app, &ctx, vec![]);
|
||||
assert_eq!(picker_color(&app).as_deref(), Some("#0000ff"));
|
||||
set(&mut app, "color", json!("#00ff00"));
|
||||
confirm(&mut app).unwrap();
|
||||
tick(&mut app, &ctx, vec![]);
|
||||
let shifted = app.ui.dialog.as_ref().map(|d| d.fields["colorTable"]["shifted"].clone());
|
||||
assert_eq!((kind(&app), shifted), (Some(save_for_web::KIND), Some(json!({"#0000ff": "#00ff00"}))));
|
||||
}
|
||||
|
||||
/// Lock, Transparent and Web Shift are off while the selected color (`__color`) is one the table
|
||||
/// no longer shows, so a click adds it to no list; with a color the table shows, Lock locks it.
|
||||
#[test]
|
||||
fn table_buttons_skip_a_selected_color_the_table_does_not_show() {
|
||||
let dir = vectorcraft_testkit::temp_dir("sfw-stale-anchor");
|
||||
let (mut app, _) = app(&dir, false);
|
||||
app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
|
||||
app.run("file.saveForWeb", json!({})).unwrap();
|
||||
for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] {
|
||||
set(&mut app, k, v);
|
||||
}
|
||||
let table = |app: &VectorcraftApp| app.ui.dialog.as_ref().and_then(|d| d.fields.get("colorTable").cloned()).unwrap_or_default();
|
||||
let has = |app: &VectorcraftApp, list: &str, c: &str| table(app)[list].as_array().is_some_and(|l| l.iter().any(|v| v == c));
|
||||
set(&mut app, "__color", json!("#abcdef"));
|
||||
for label in ["Lock", "Transparent", "Web Shift"] {
|
||||
click_text(&mut app, label);
|
||||
}
|
||||
for list in ["locked", "transparent", "webShift"] {
|
||||
assert!(!has(&app, list, "#abcdef"), "{list}: {}", table(&app));
|
||||
}
|
||||
set(&mut app, "__color", json!("#0000ff"));
|
||||
click_text(&mut app, "Lock");
|
||||
assert!(has(&app, "locked", "#0000ff"), "{}", table(&app));
|
||||
}
|
||||
|
||||
/// Click the dialog's text `label` with the pointer (frames a quarter second apart).
|
||||
fn click_text(app: &mut VectorcraftApp, label: &str) {
|
||||
let ctx = egui::Context::default();
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
//! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of
|
||||
//! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests
|
||||
//! can find it.
|
||||
|
||||
use egui::{Pos2, Rect, Shape, vec2};
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
type Open = fn(&mut VectorcraftApp);
|
||||
|
||||
/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls
|
||||
/// ([`modal::scrolling`]).
|
||||
struct Shown {
|
||||
shapes: Vec<egui::epaint::ClippedShape>,
|
||||
window: Rect,
|
||||
body: Option<f32>,
|
||||
whole: [bool; 2],
|
||||
}
|
||||
|
||||
/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away
|
||||
/// from the dialog), and draw it until it settles. With `scroll`, then scroll far down and right
|
||||
/// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists
|
||||
/// inside it) and draw it until it settles again.
|
||||
fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
ctx.global_style_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid());
|
||||
open(&mut app);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, size);
|
||||
let window = |ctx: &egui::Context| {
|
||||
ctx.memory(|m| {
|
||||
m.areas()
|
||||
.visible_layer_ids()
|
||||
.into_iter()
|
||||
.filter(|l| l.order == egui::Order::Foreground)
|
||||
.filter_map(|l| Some((l.id, m.area_rect(l.id)?)))
|
||||
.max_by(|a, b| a.1.area().total_cmp(&b.1.area()))
|
||||
})
|
||||
.unwrap_or((egui::Id::NULL, Rect::NOTHING))
|
||||
};
|
||||
let mut time = 0.0;
|
||||
let mut frames = |app: &mut VectorcraftApp, first: Vec<egui::Event>| {
|
||||
let mut first = Some(first);
|
||||
let mut shapes = vec![];
|
||||
for _ in 0..12 {
|
||||
time += 1.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: first.take().unwrap_or_default(), time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
shapes = std::mem::take(&mut out.shapes);
|
||||
}
|
||||
shapes
|
||||
};
|
||||
let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]);
|
||||
if scroll {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(-5000.0, -5000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
let (id, w) = window(&ctx);
|
||||
let (body, whole) = modal::scrolling(&ctx, id);
|
||||
let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole };
|
||||
// On the window's upright bar, else on its body's bar, else on its sideways bar, else at
|
||||
// its right edge.
|
||||
let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width());
|
||||
let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center());
|
||||
shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]);
|
||||
}
|
||||
let (id, window) = window(&ctx);
|
||||
let (body, whole) = modal::scrolling(&ctx, id);
|
||||
Shown { shapes, window, body, whole }
|
||||
}
|
||||
|
||||
/// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or
|
||||
/// (`sideways`) flat, inside the dialog window; with `seen`, only those inside their clip.
|
||||
fn bars(shown: &Shown, sideways: bool, seen: bool) -> Vec<Rect> {
|
||||
fn walk(s: &Shape, clip: Rect, sideways: bool, seen: bool, out: &mut Vec<Rect>) {
|
||||
match s {
|
||||
Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => {
|
||||
let (across, along) = if sideways { (r.rect.height(), r.rect.width()) } else { (r.rect.width(), r.rect.height()) };
|
||||
if (4.0..=10.0).contains(&across) && along > 12.0 && (!seen || clip.contains_rect(r.rect)) {
|
||||
out.push(r.rect);
|
||||
}
|
||||
}
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, sideways, seen, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, sideways, seen, &mut out));
|
||||
out.retain(|r| shown.window.expand(0.5).contains_rect(*r));
|
||||
out
|
||||
}
|
||||
|
||||
/// The bar of a shared dialog's scrolling body: the rightmost upright bar as tall as the body is
|
||||
/// drawn (a list inside the body draws its bar further left).
|
||||
fn body_bar(shown: &Shown) -> Option<Rect> {
|
||||
let view = shown.body?;
|
||||
bars(shown, false, true).into_iter().filter(|r| (r.height() - view).abs() <= 1.0).max_by(|a, b| a.right().total_cmp(&b.right()))
|
||||
}
|
||||
|
||||
/// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that
|
||||
/// runs most of the window's height (lists inside it are shorter).
|
||||
fn whole_bar(shown: &Shown) -> Option<Rect> {
|
||||
let w = shown.window;
|
||||
bars(shown, false, true)
|
||||
.into_iter()
|
||||
.filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height())
|
||||
.max_by(|a, b| a.height().total_cmp(&b.height()))
|
||||
}
|
||||
|
||||
/// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and
|
||||
/// its clip).
|
||||
fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> {
|
||||
texts(shown)
|
||||
.into_iter()
|
||||
.filter(|(s, ..)| labels.contains(&s.as_str()))
|
||||
.map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() {
|
||||
let opens: [(&str, Open, &[&str]); 7] = [
|
||||
("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]),
|
||||
("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]),
|
||||
("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]),
|
||||
(
|
||||
"Save PDF",
|
||||
|app| {
|
||||
save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap();
|
||||
},
|
||||
&["Cancel"],
|
||||
),
|
||||
(
|
||||
"Save for Web",
|
||||
|app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
},
|
||||
&["Cancel", "Done"],
|
||||
),
|
||||
("Export for Screens", export_for_screens::open, &["Cancel"]),
|
||||
(
|
||||
"Print",
|
||||
|app| {
|
||||
print::open(app).unwrap();
|
||||
},
|
||||
&["Cancel", "Done"],
|
||||
),
|
||||
];
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0));
|
||||
for (name, open, labels) in opens {
|
||||
let tall = show_in(open, vec2(1280.0, 900.0), false);
|
||||
assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window);
|
||||
assert_eq!((tall.body, tall.whole), (None, [false; 2]), "{name}: in a tall window nothing scrolls");
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window);
|
||||
let found = buttons(&shown, screen, labels);
|
||||
assert_eq!(found.len(), labels.len(), "{name}: {found:?}");
|
||||
assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}");
|
||||
assert_eq!(shown.whole, [false; 2], "{name}: the window does not scroll as a whole");
|
||||
let bar = body_bar(&shown);
|
||||
assert!(bar.is_some(), "{name}: the body scrolls ({:?}) and its bar is drawn: {:?}", shown.body, bars(&shown, false, true));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_list_in_a_scrolling_body_is_no_taller_than_the_body() {
|
||||
// The settings of Save for Web and the sections of Print and Save PDF scroll in lists of their
|
||||
// own; in a short window those lists are no taller than the body shows, so each list and its
|
||||
// bar can be scrolled into view whole.
|
||||
let opens: [(&str, Open); 3] = [
|
||||
("Save for Web", |app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
}),
|
||||
("Print", |app| {
|
||||
print::open(app).unwrap();
|
||||
if let Some(d) = app.ui.dialog.as_mut() {
|
||||
d.fields.insert("__section".into(), json!("Marks and Bleed"));
|
||||
}
|
||||
}),
|
||||
("Save PDF", |app| {
|
||||
save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap();
|
||||
if let Some(d) = app.ui.dialog.as_mut() {
|
||||
d.fields.insert("__section".into(), json!("Marks and Bleeds"));
|
||||
}
|
||||
}),
|
||||
];
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 400.0));
|
||||
let mut wrong = vec![];
|
||||
for (name, open) in opens {
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
let Some(body) = body_bar(&shown) else {
|
||||
wrong.push(format!("{name}: the body does not scroll ({:?}): {:?}", shown.body, bars(&shown, false, false)));
|
||||
continue;
|
||||
};
|
||||
// The tracks of the lists' bars, seen or not: left of the body's bar and inside the window
|
||||
// (a list taller than the body runs past the window's bottom).
|
||||
let lists: Vec<Rect> = bars(&shown, false, false).into_iter().filter(|r| r.right() < body.left()).collect();
|
||||
let tallest = lists.iter().map(|r| r.height()).fold(0.0, f32::max);
|
||||
if tallest == 0.0 || tallest > body.height() + 0.5 {
|
||||
wrong.push(format!("{name}: no list bar no taller than the body ({}): {:?}", body.height(), bars(&shown, false, false)));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() {
|
||||
let open: Open = |app| {
|
||||
save_for_web::open(app).unwrap();
|
||||
};
|
||||
// The app window's smallest size, 800 by 500 pixels, at a UI scale of 100%, 110% and 125%.
|
||||
let mut wrong = vec![];
|
||||
for size in [vec2(800.0, 500.0), vec2(727.0, 454.0), vec2(640.0, 400.0)] {
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, size);
|
||||
let shown = show_in(open, size, false);
|
||||
let labels = ["Format:", "Optimize to File Size…", "Cancel", "Done"];
|
||||
let found = buttons(&shown, screen, &labels);
|
||||
if !screen.contains_rect(shown.window) || found.len() != labels.len() || !found.iter().all(|(_, seen)| *seen) {
|
||||
wrong.push(format!("{size:?}: the dialog ({:?}) leaves its settings and buttons in view: {found:?}", shown.window));
|
||||
}
|
||||
if body_bar(&shown).is_none() || shown.whole != [false; 2] {
|
||||
wrong.push(format!("{size:?}: only the body scrolls ({:?}, {:?})", shown.body, shown.whole));
|
||||
}
|
||||
// The controls under the narrower panes stay in their column, left of the settings.
|
||||
let controls = text_rects(&shown, "Preview in Browser").first().map(|r| r.right());
|
||||
let settings = text_rects(&shown, "Format:").first().map(|r| r.left());
|
||||
if !matches!((controls, settings), (Some(c), Some(s)) if c < s) {
|
||||
wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})"));
|
||||
}
|
||||
// Preview in Browser is right of the download speed list or on a row below it, not over it.
|
||||
let button = text_rects(&shown, "Preview in Browser").first().copied();
|
||||
let speed = text_rects(&shown, "56.6 Kbps").first().copied();
|
||||
if !matches!((button, speed), (Some(b), Some(s)) if b.left() > s.right() + 16.0 || b.top() > s.bottom() + 8.0) {
|
||||
wrong.push(format!("{size:?}: Preview in Browser ({button:?}) clears the download speed list ({speed:?})"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// The rectangles of the texts `label` the dialog drew.
|
||||
fn text_rects(shown: &Shown, label: &str) -> Vec<Rect> {
|
||||
fn walk(s: &Shape, label: &str, out: &mut Vec<Rect>) {
|
||||
match s {
|
||||
Shape::Text(t) if t.galley.text() == label => out.push(t.visual_bounding_rect()),
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, label, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, label, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_too_large_for_the_screen_scrolls_as_a_whole() {
|
||||
let opens: [(&str, Open, &[&str]); 4] = [
|
||||
("Preferences", |app| crate::prefs_dialog::open(app, None), &["OK", "Cancel"]),
|
||||
("Keyboard Shortcuts", crate::shortcut_editor::open, &["OK", "Cancel"]),
|
||||
("New Document", new_document::open, &["Create", "Close"]),
|
||||
("Find Font", crate::find_font::open, &["Done"]),
|
||||
];
|
||||
// The app window's smallest size.
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
|
||||
for (name, open, labels) in opens {
|
||||
let tall = show_in(open, vec2(1280.0, 900.0), false);
|
||||
assert!(
|
||||
tall.window.height() > screen.height() || tall.window.width() > screen.width(),
|
||||
"{name}: the dialog is larger than the small window ({:?})",
|
||||
tall.window
|
||||
);
|
||||
assert_eq!(tall.whole, [false; 2], "{name}: in a large window the dialog does not scroll as a whole");
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window);
|
||||
assert!(shown.whole[1], "{name}: the dialog scrolls as a whole");
|
||||
assert!(whole_bar(&shown).is_some(), "{name}: the window's bar is drawn: {:?}", bars(&shown, false, true));
|
||||
// The buttons can sit outside the part in view; each is in view at the top or scrolled to
|
||||
// the end.
|
||||
let scrolled = show_in(open, screen.size(), true);
|
||||
let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels));
|
||||
for label in labels {
|
||||
let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen);
|
||||
assert!(seen(&top) || seen(&end), "{name}: {label} can be scrolled into view: {top:?} {end:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() {
|
||||
// Scrolled down in the smallest window, Keyboard Shortcuts is where it was left when Import
|
||||
// Shortcut Set, opened over it, is canceled; closed and opened again, it starts at its top.
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
|
||||
let mut time = 0.0;
|
||||
// Draws 12 frames, the first with `events`; returns whether the heading can be seen.
|
||||
let mut heading_seen = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let mut events = Some(events);
|
||||
let mut seen = false;
|
||||
for _ in 0..12 {
|
||||
time += 1.0;
|
||||
let input =
|
||||
egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] };
|
||||
seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen);
|
||||
}
|
||||
seen
|
||||
};
|
||||
let wheel = |at: Pos2| {
|
||||
let wheel = egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -5000.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
vec![egui::Event::PointerMoved(at), wheel]
|
||||
};
|
||||
crate::shortcut_editor::open(&mut app);
|
||||
assert!(heading_seen(&mut app, vec![]), "Keyboard Shortcuts opens at its top");
|
||||
// On the window's bar, inside its 20 pt margin.
|
||||
let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-shortcuts"))).unwrap_or(screen);
|
||||
assert!(!heading_seen(&mut app, wheel(egui::pos2(window.right() - 23.0, window.center().y))), "the wheel scrolls the heading away");
|
||||
let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n}\n";
|
||||
crate::io::open_bytes(&mut app, "Keys.kys", kys.as_bytes(), None).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(shortcut_import::KIND));
|
||||
heading_seen(&mut app, vec![]);
|
||||
cancel(&mut app);
|
||||
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "Cancel shows Keyboard Shortcuts again");
|
||||
assert!(!heading_seen(&mut app, vec![]), "shown again, Keyboard Shortcuts is where it was scrolled to");
|
||||
cancel(&mut app);
|
||||
heading_seen(&mut app, vec![]);
|
||||
crate::shortcut_editor::open(&mut app);
|
||||
assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top");
|
||||
}
|
||||
|
||||
/// Open Import Shortcut Set on a set of two shortcuts.
|
||||
fn open_shortcut_import(app: &mut VectorcraftApp) {
|
||||
let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n";
|
||||
crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() {
|
||||
// Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An
|
||||
// 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt.
|
||||
let wide = show_in(open_shortcut_import, vec2(1280.0, 900.0), false);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0));
|
||||
assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window);
|
||||
assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll");
|
||||
let shown = show_in(open_shortcut_import, screen.size(), false);
|
||||
assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window);
|
||||
assert_eq!(shown.whole, [true, false], "it scrolls sideways only");
|
||||
let sideways: Vec<Rect> = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect();
|
||||
assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() {
|
||||
// In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right
|
||||
// edge, the text drawn furthest right in a large window can be seen.
|
||||
let opens: [(&str, Open); 3] = [
|
||||
("Import Shortcut Set", open_shortcut_import),
|
||||
("Keyboard Shortcuts", crate::shortcut_editor::open),
|
||||
("Preferences", |app| crate::prefs_dialog::open(app, None)),
|
||||
];
|
||||
let mut wrong = vec![];
|
||||
for (name, open) in opens {
|
||||
let wide = show_in(open, vec2(1600.0, 1000.0), false);
|
||||
let Some((right, _)) = texts(&wide)
|
||||
.into_iter()
|
||||
.filter(|(_, r, _)| wide.window.contains_rect(*r))
|
||||
.map(|(s, r, _)| (s, r.right()))
|
||||
.max_by(|a, b| a.1.total_cmp(&b.1))
|
||||
else {
|
||||
wrong.push(format!("{name}: no text in the large window"));
|
||||
continue;
|
||||
};
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2((0.7 * wide.window.width()).round(), 1000.0));
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
let scrolled = show_in(open, screen.size(), true);
|
||||
// Within 1 pt: a text's drawn box can reach a fraction of a point past the content's edge.
|
||||
let seen =
|
||||
|shown: &Shown| texts(shown).iter().any(|(s, r, clip)| *s == right && screen.contains_rect(*r) && clip.expand(1.0).contains_rect(*r));
|
||||
let sideways = bars(&shown, true, true).into_iter().any(|r| r.width() >= 0.5 * shown.window.width());
|
||||
if !screen.contains_rect(shown.window) || !shown.whole[0] || !sideways || seen(&shown) || !seen(&scrolled) {
|
||||
let at = |shown: &Shown| texts(shown).into_iter().filter(|(s, ..)| *s == right).collect::<Vec<_>>();
|
||||
wrong.push(format!(
|
||||
"{name} in {:?}: window {:?}, scrolls {:?}, sideways bar {sideways}, {right:?} seen at first {} {:?}, scrolled {} {:?}, bars {:?}",
|
||||
screen.size(),
|
||||
shown.window,
|
||||
shown.whole,
|
||||
seen(&shown),
|
||||
at(&shown),
|
||||
seen(&scrolled),
|
||||
at(&scrolled),
|
||||
bars(&shown, true, true)
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// Every text the dialog drew, with its rectangle and its clip.
|
||||
fn texts(shown: &Shown) -> Vec<(String, Rect, Rect)> {
|
||||
fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) {
|
||||
match s {
|
||||
Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)),
|
||||
Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut out));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dialog_with_buttons_in_its_body_scrolls_them_with_the_body() {
|
||||
// Check Spelling draws its buttons inside its body: in a window too short for it, the heading
|
||||
// stays in view and the buttons scroll with the body.
|
||||
let open: Open = |app| {
|
||||
check_spelling::open(app).unwrap();
|
||||
};
|
||||
let tall = show_in(open, vec2(1280.0, 900.0), false);
|
||||
let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, (0.6 * tall.window.height()).round()));
|
||||
let shown = show_in(open, screen.size(), false);
|
||||
let scrolled = show_in(open, screen.size(), true);
|
||||
let seen = |shown: &Shown, label: &str| buttons(shown, screen, &[label]).iter().any(|(_, seen)| *seen);
|
||||
assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window);
|
||||
assert!(body_bar(&shown).is_some() && shown.whole == [false; 2], "only the body scrolls ({:?}, {:?})", shown.body, shown.whole);
|
||||
assert!(seen(&shown, "Check Spelling") && seen(&scrolled, "Check Spelling"), "the heading stays in view");
|
||||
assert!(!seen(&shown, "Cancel") && seen(&scrolled, "Cancel"), "Cancel is out of view until the body is scrolled down");
|
||||
}
|
||||
@@ -4,10 +4,13 @@
|
||||
//! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). Find In limits Find
|
||||
//! to the active artboard or the selected layers.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::Ui;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::caches::{FindFontCache, FontsKey};
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets;
|
||||
@@ -20,7 +23,7 @@ pub fn open(app: &mut VectorcraftApp) {
|
||||
/// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find
|
||||
/// Fonts).
|
||||
pub fn open_on_missing(app: &mut VectorcraftApp) {
|
||||
let first = fonts(app).iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute")));
|
||||
let first = document_fonts(app, false).0.iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute")));
|
||||
open_at(app, first.unwrap_or(0));
|
||||
}
|
||||
|
||||
@@ -28,7 +31,7 @@ pub fn open_on_missing(app: &mut VectorcraftApp) {
|
||||
/// System's font ([`system_family`]) to change to, and the last Find In choice (Document at first).
|
||||
fn open_at(app: &mut VectorcraftApp, selected: usize) {
|
||||
let find_in = FIND_IN.iter().find(|f| **f == app.ui.find_font_in).copied().unwrap_or("document");
|
||||
let used = fonts(app);
|
||||
let (used, _) = document_fonts(app, false);
|
||||
let source = "system";
|
||||
let rows = replacement_rows(app, source, &used);
|
||||
let family = system_family();
|
||||
@@ -252,6 +255,30 @@ fn fonts(app: &mut VectorcraftApp) -> Vec<Value> {
|
||||
app.session.execute("text.fonts", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The active document's fonts ([`fonts`]) and, when `missing` is asked for, whether it misses a
|
||||
/// font ([`vectorcraft_engine::cmd::fontfiles::missing_fonts`]; `false` when it is not asked
|
||||
/// for). Both are kept in [`crate::CanvasCache::find_font`] and worked out again only for another
|
||||
/// document, another version of its content or another font generation. No document: no fonts.
|
||||
fn document_fonts(app: &mut VectorcraftApp, missing: bool) -> (Arc<Vec<Value>>, bool) {
|
||||
let Some(st) = app.session.active() else { return (Arc::default(), false) };
|
||||
// The generation is read first: fonts loaded while the answers are worked out leave the entry
|
||||
// under the older generation, so the next frame works them out again.
|
||||
let key = FontsKey { uid: st.uid, doc: Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() };
|
||||
if app.canvas.find_font.as_ref().is_none_or(|c| c.key != key) {
|
||||
let fonts = Arc::new(fonts(app));
|
||||
app.canvas.find_font = Some(FindFontCache { key, fonts, missing: None });
|
||||
}
|
||||
if missing
|
||||
&& let Some(c) = app.canvas.find_font.as_mut()
|
||||
&& c.missing.is_none()
|
||||
&& let Some(st) = app.session.active()
|
||||
{
|
||||
c.missing = Some(!vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
|
||||
}
|
||||
let c = app.canvas.find_font.as_ref();
|
||||
(c.map(|c| c.fonts.clone()).unwrap_or_default(), missing && c.and_then(|c| c.missing).unwrap_or(false))
|
||||
}
|
||||
|
||||
pub fn confirm(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
if let Some(ctx) = app.ui_ctx.clone() {
|
||||
clear_search(&ctx);
|
||||
@@ -279,10 +306,9 @@ fn change(app: &mut VectorcraftApp, d: &Dialog, from: &Value, all: bool) -> Resu
|
||||
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(mut d) = app.ui.dialog.clone() else { return };
|
||||
let t = Tokens::get(ctx);
|
||||
let list = fonts(app);
|
||||
// Find in Folder… shows when the document misses fonts, fonts used only in its symbols included.
|
||||
let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder)
|
||||
&& app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
|
||||
let can_pick = crate::picks::can(app, &crate::picks::PickRequest::Folder);
|
||||
let (list, offer_folder) = document_fonts(app, can_pick);
|
||||
let mut close = false;
|
||||
let mut find_in_folder = false;
|
||||
let mut act: Option<&str> = None;
|
||||
@@ -416,7 +442,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
match run_button(app, &d, a, from) {
|
||||
// The rows are a snapshot: the document's fonts and the recent fonts have moved on.
|
||||
Ok(_) if a != "find" => {
|
||||
let used = fonts(app);
|
||||
let (used, _) = document_fonts(app, false);
|
||||
d.fields.insert("rows".into(), rows_json(&replacement_rows(app, &d.str("replaceFrom"), &used)));
|
||||
}
|
||||
Ok(_) => {}
|
||||
@@ -1421,4 +1447,231 @@ mod tests {
|
||||
let (note, color) = font_note(&row("exact", 2));
|
||||
assert!(note.contains("2 characters") && color.is_some());
|
||||
}
|
||||
|
||||
/// The font list the dialog keeps for the active document.
|
||||
fn kept_list(app: &VectorcraftApp) -> Arc<Vec<Value>> {
|
||||
app.canvas.find_font.as_ref().expect("the dialog kept the document's fonts").fonts.clone()
|
||||
}
|
||||
|
||||
/// The kept list and Find in Folder… are what `text.fonts` and `missing_fonts` give now.
|
||||
fn assert_current(app: &mut VectorcraftApp, shown: &str, why: &str) {
|
||||
let listed = fonts(app);
|
||||
assert_eq!(*kept_list(app), listed, "{why}: the list");
|
||||
let missing = app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
|
||||
let picks = crate::picks::can(app, &crate::picks::PickRequest::Folder);
|
||||
assert_eq!(shown.contains("Find in Folder…"), picks && missing, "{why}: Find in Folder… {shown}");
|
||||
}
|
||||
|
||||
/// A document set in a missing family and in Inter, with a folder picker.
|
||||
fn missing_font_document() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
for (y, font) in [(20, "Missing Family"), (40, "Inter")] {
|
||||
app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap();
|
||||
}
|
||||
app.services.pick_folder = Some(Box::new(|| None));
|
||||
app
|
||||
}
|
||||
|
||||
/// Frames that change nothing in the document, a new selection included, keep the font list
|
||||
/// and the missing-font answer worked out on the first; the answer is worked out only once a
|
||||
/// folder picker is there.
|
||||
#[test]
|
||||
fn the_font_list_is_worked_out_once_per_document_version() {
|
||||
let mut app = missing_font_document();
|
||||
let picker = app.services.pick_folder.take();
|
||||
open(&mut app);
|
||||
assert!(kept_over_frames(&mut app, "no folder picker"), "frames of one document version keep its list");
|
||||
assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), None, "no picker: the document is not searched for missing fonts");
|
||||
app.services.pick_folder = picker;
|
||||
assert!(kept_over_frames(&mut app, "a folder picker"), "a picker alone keeps the list");
|
||||
assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), Some(true));
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
assert!(kept_over_frames(&mut app, "a new selection"), "a new selection keeps the list");
|
||||
}
|
||||
|
||||
/// Draws frames of the dialog and tells whether they kept the list kept before them. Another
|
||||
/// test thread that changes the available fonts meanwhile makes the dialog work the list out
|
||||
/// again, so the frames are drawn again until the fonts stay as they are.
|
||||
fn kept_over_frames(app: &mut VectorcraftApp, why: &str) -> bool {
|
||||
for _ in 0..20 {
|
||||
// The generation the kept list was worked out under: the database's generation only
|
||||
// counts up, so the same one after the frames means no fonts changed in between.
|
||||
let before = kept_list(app);
|
||||
let generation = app.canvas.find_font.as_ref().map(|c| c.key.generation);
|
||||
let shown = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(app, &shown, why);
|
||||
if Some(vectorcraft_text::FontDb::global().generation()) == generation {
|
||||
return Arc::ptr_eq(&before, &kept_list(app));
|
||||
}
|
||||
}
|
||||
panic!("{why}: the available fonts kept changing")
|
||||
}
|
||||
|
||||
/// An edit, its undo and a Change All each give the list of the document as it is then.
|
||||
#[test]
|
||||
fn an_edit_works_the_font_list_out_again() {
|
||||
let mut app = missing_font_document();
|
||||
open(&mut app);
|
||||
crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
let first = kept_list(&app);
|
||||
app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Inter"}})).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "after the replacement");
|
||||
assert!(!shown.contains("Find in Folder…"), "nothing is missing: {shown}");
|
||||
assert_eq!(kept_list(&app).len(), 1, "{:?}", kept_list(&app));
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "after the undo");
|
||||
assert_eq!(*kept_list(&app), *first, "the undo brings back the first list");
|
||||
let mut d = app.ui.dialog.clone().unwrap();
|
||||
d.fields.insert("family".into(), json!("Source Serif 4"));
|
||||
d.fields.insert("style".into(), json!(""));
|
||||
let from = first.iter().find(|f| f["family"] == "Inter").unwrap().clone();
|
||||
change(&mut app, &d, &from, true).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "after Change All");
|
||||
assert!(kept_list(&app).iter().any(|f| f["family"] == "Source Serif 4"), "{:?}", kept_list(&app));
|
||||
}
|
||||
|
||||
/// Fonts that become available, a composite font defined among them, give the list and the
|
||||
/// missing-font answer as they are with those fonts.
|
||||
#[test]
|
||||
fn other_available_fonts_work_the_font_list_out_again() {
|
||||
const FAMILY: &str = "Find Font Kept List CF";
|
||||
let mut app = missing_font_document();
|
||||
app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Ab12", "font": FAMILY})).unwrap();
|
||||
open(&mut app);
|
||||
crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
// The same document under another generation of the font database: what is kept for it no
|
||||
// longer counts.
|
||||
let entry = app.canvas.find_font.as_mut().unwrap();
|
||||
entry.key.generation = u64::MAX;
|
||||
entry.fonts = Arc::default();
|
||||
entry.missing = Some(false);
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "another font generation");
|
||||
let row = |app: &VectorcraftApp| kept_list(app).iter().find(|f| f["family"] == FAMILY).cloned().unwrap();
|
||||
assert_eq!(row(&app)["status"], "missing");
|
||||
let generation = vectorcraft_text::FontDb::global().generation();
|
||||
let parts = json!({"name": FAMILY, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono"}, "numerals": {"font": "Inter"}}});
|
||||
app.run("type.compositeFonts.set", json!({"fonts": [parts]})).unwrap();
|
||||
assert_ne!(vectorcraft_text::FontDb::global().generation(), generation, "defining a composite font is a new generation");
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "the composite font defined");
|
||||
assert_eq!(row(&app)["status"], "exact");
|
||||
app.run("type.compositeFonts.set", json!({"fonts": []})).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "the composite font taken out");
|
||||
assert_eq!(row(&app)["status"], "missing");
|
||||
}
|
||||
|
||||
/// Another document in front, and pattern editing entered and canceled, each give the list of
|
||||
/// the document in front as it is then.
|
||||
#[test]
|
||||
fn the_font_list_follows_the_document_in_front() {
|
||||
let mut app = missing_font_document();
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Serif 4"})).unwrap()["id"].clone();
|
||||
app.services.pick_folder = Some(Box::new(|| None));
|
||||
open(&mut app);
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "the second document");
|
||||
app.session.set_active(0);
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "the first document");
|
||||
assert!(shown.contains("Find in Folder…"), "{shown}");
|
||||
app.session.set_active(1);
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.run("object.pattern.make", json!({"name": "Kept List"})).unwrap();
|
||||
assert!(app.session.active().unwrap().doc.pattern_edit.is_some(), "pattern editing");
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "pattern editing");
|
||||
app.run("object.pattern.cancel", json!({})).unwrap();
|
||||
let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
|
||||
assert_current(&mut app, &shown, "pattern editing canceled");
|
||||
}
|
||||
|
||||
/// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`.
|
||||
fn thread_cpu_ns() -> Option<u128> {
|
||||
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Time the font list and the missing-font answer a Find Font frame reads, for a document of
|
||||
/// 2,000 point-type objects of 50 characters each and one of 20, set in five installed faces
|
||||
/// and a missing family, with a folder picker: worked out on every frame as `text.fonts` and
|
||||
/// `missing_fonts` (each frame before they were kept), on the first frame of a document version
|
||||
/// ([`document_fonts`] with nothing kept) and on later frames. Per run, the large document
|
||||
/// draws 120 frames and the small one 12,000 (so the thread's CPU clock, which advances in
|
||||
/// steps of a few milliseconds, sees them), and later frames number 1,000,000; the sides
|
||||
/// alternate, and the median time per frame of 7 runs is printed.
|
||||
/// Run with `cargo test --release -p vectorcraft-ui-egui --lib find_font_list_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; performance depends on machine load"]
|
||||
fn find_font_list_timing() {
|
||||
const KEPT: u32 = 1_000_000;
|
||||
const FACES: [(&str, &str); 6] = [
|
||||
("Inter", "Regular"),
|
||||
("Inter", "Medium"),
|
||||
("Source Sans 3", "Bold"),
|
||||
("Source Serif 4", "Regular"),
|
||||
("JetBrains Mono", "Regular"),
|
||||
("Missing Family", "Regular"),
|
||||
];
|
||||
for (objects, frames) in [(2_000, 120), (20, 12_000)] {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap();
|
||||
for i in 0..objects {
|
||||
let (family, style) = FACES[i % FACES.len()];
|
||||
let text: String = (0..50).map(|c| char::from(b'a' + ((i + c) % 26) as u8)).collect();
|
||||
let (x, y) = ((i % 20 * 90) as f64, (i / 20 * 18) as f64 + 20.0);
|
||||
app.session.execute("text.create", &json!({"x": x, "y": y, "text": text, "font": family, "style": style})).unwrap();
|
||||
}
|
||||
app.services.pick_folder = Some(Box::new(|| None));
|
||||
let every_frame = |app: &mut VectorcraftApp| {
|
||||
let list = fonts(app);
|
||||
let offer = crate::picks::can(app, &crate::picks::PickRequest::Folder)
|
||||
&& app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
|
||||
(list, offer)
|
||||
};
|
||||
let expected = every_frame(&mut app);
|
||||
assert!(expected.1 && expected.0.len() == FACES.len(), "{expected:?}");
|
||||
let kept = document_fonts(&mut app, true);
|
||||
assert_eq!((kept.0.to_vec(), kept.1), expected, "the kept answers are the ones worked out every frame");
|
||||
// Each side's answers for one frame: the number of fonts listed and Find in Folder….
|
||||
let time = |app: &mut VectorcraftApp, frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> (usize, bool)| {
|
||||
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
|
||||
for _ in 0..frames {
|
||||
assert_eq!(f(app), (FACES.len(), true));
|
||||
}
|
||||
let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a);
|
||||
ns as f64 / f64::from(frames) / 1000.0
|
||||
};
|
||||
let (mut full, mut first, mut later) = (vec![], vec![], vec![]);
|
||||
for _ in 0..7 {
|
||||
full.push(time(&mut app, frames, &mut |app| {
|
||||
let (list, offer) = every_frame(app);
|
||||
(list.len(), offer)
|
||||
}));
|
||||
first.push(time(&mut app, frames, &mut |app| {
|
||||
app.canvas.find_font = None;
|
||||
let (list, offer) = document_fonts(app, true);
|
||||
(list.len(), offer)
|
||||
}));
|
||||
later.push(time(&mut app, KEPT, &mut |app| {
|
||||
let (list, offer) = document_fonts(app, true);
|
||||
(list.len(), offer)
|
||||
}));
|
||||
}
|
||||
let median = |v: &mut Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" };
|
||||
eprintln!("{objects} text objects of 50 characters; {clock} per frame, median of 7 runs");
|
||||
eprintln!("worked out every frame ({frames} frames a run): {:>12.3} us {full:.3?}", median(&mut full));
|
||||
eprintln!("first frame of a version ({frames} a run): {:>12.3} us {first:.3?}", median(&mut first));
|
||||
eprintln!("later frames of the version ({KEPT} a run): {:>12.4} us {later:.4?}", median(&mut later));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user