mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 13:08:32 +00:00
Merge main into feat/symbols-drag-to-delete
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
//! Placed documents: another VectorCraft file, or a page of a PDF or `.ai` file, placed linked
|
||||
//! ([`PlacedDocument`]).
|
||||
//! Placed documents: another VectorCraft file, a page of a PDF or `.ai` file, or an EPS file,
|
||||
//! placed linked ([`PlacedDocument`]).
|
||||
//!
|
||||
//! The object keeps the link to the file and the file's bytes, stored like image data in
|
||||
//! [`Document::images`] (with a small preview a save writes instead, as for linked images), so the
|
||||
@@ -7,9 +7,9 @@
|
||||
//! joins the object tree, so editing can't reach it: it is locked by design. Drawing and exporting
|
||||
//! expand it like a live object ([`crate::live::expanded`]).
|
||||
//!
|
||||
//! The file is read by the engine's loader (native documents, PDF and `.ai` pages), which lives
|
||||
//! above this crate and registers itself ([`set_loader`]); the art read is kept in a small cache
|
||||
//! by content. Before exporting,
|
||||
//! The file is read by the engine's loader (native documents, PDF and `.ai` pages, EPS files),
|
||||
//! which lives above this crate and registers itself ([`set_loader`]); the art read is kept in a
|
||||
//! small cache by content. Before exporting,
|
||||
//! every exporter calls [`Document::with_placed_art`], which adds the resources the art uses
|
||||
//! (images, symbols, patterns) under names of their own ([`RESOURCE_PREFIX`]) to a temporary copy
|
||||
//! of the document, so they never meet the user's or show in panels. Placed documents inside a
|
||||
@@ -27,8 +27,8 @@ use vectorcraft_color::Paint;
|
||||
|
||||
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
|
||||
|
||||
/// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai` file,
|
||||
/// shown as one locked object.
|
||||
/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or
|
||||
/// an EPS file's art, shown as one locked object.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PlacedDocument {
|
||||
/// The file (its `page` is the artboard or page shown, 1-based).
|
||||
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket (Stroke)",
|
||||
[],
|
||||
None,
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; also paints every edge of the group, hidden edges skipped, that the polyline crosses or comes within 0.0001 pt of), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
has_doc,
|
||||
lp_stroke_edge
|
||||
),
|
||||
|
||||
@@ -409,43 +409,61 @@ fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result<Option
|
||||
serde_json::from_value::<super::Paint>(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
|
||||
}
|
||||
|
||||
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.fill";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
|
||||
/// The drag path of `livePaint.fill` or `livePaint.strokeEdge` (command `c`) pressed at `start`:
|
||||
/// `points` followed by each chunk of `continuation`, where every chunk holds 1 to
|
||||
/// [`b::LP_FILL_CHUNK_POINTS`] finite canvas points and starts at the last point of the chunk
|
||||
/// before it (`points` at `start`). None when `points` is left out. With a `scope` other than
|
||||
/// `one`, `points` is an error.
|
||||
fn path_param(p: &Value, c: &str, start: Point, scope: LpScope) -> Result<Option<Vec<Vec<Point>>>> {
|
||||
if scope != LpScope::One && p.get("points").is_some() {
|
||||
return Err(bad(C, "scope applies to a click: leave out points"));
|
||||
return Err(bad(c, "scope applies to a click: leave out points"));
|
||||
}
|
||||
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
|
||||
let values = input
|
||||
.as_array()
|
||||
.filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS)
|
||||
.ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?;
|
||||
.ok_or_else(|| bad(c, "each path chunk must contain 1 to 4096 points"))?;
|
||||
let points: Vec<_> = values
|
||||
.iter()
|
||||
.map(|point| {
|
||||
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?;
|
||||
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?;
|
||||
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?;
|
||||
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(c, "points must be [x,y] pairs"))?;
|
||||
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(c, "point x must be a number"))?;
|
||||
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(c, "point y must be a number"))?;
|
||||
let point = Point::new(x, y);
|
||||
if !finite(point) {
|
||||
return Err(bad(C, "points must be finite canvas points"));
|
||||
return Err(bad(c, "points must be finite canvas points"));
|
||||
}
|
||||
Ok(point)
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if points.first() != Some(&start) {
|
||||
return Err(bad(C, "path chunks must share their boundary point"));
|
||||
return Err(bad(c, "path chunks must share their boundary point"));
|
||||
}
|
||||
Ok(points)
|
||||
};
|
||||
let points = p.get("points");
|
||||
let Some(points) = p.get("points") else {
|
||||
return if p.get("continuation").is_some() { Err(bad(c, "continuation requires points")) } else { Ok(None) };
|
||||
};
|
||||
let continuation = match p.get("continuation") {
|
||||
None => &[][..],
|
||||
Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(),
|
||||
Some(_) => return Err(bad(C, "continuation requires points")),
|
||||
Some(input) => input.as_array().ok_or_else(|| bad(c, "continuation must be an array of path chunks"))?.as_slice(),
|
||||
};
|
||||
let mut chunks: Vec<Vec<Point>> = Vec::with_capacity(continuation.len() + 1);
|
||||
let mut last = start;
|
||||
for input in std::iter::once(points).chain(continuation) {
|
||||
let chunk = parse_chunk(input, last)?;
|
||||
last = chunk.last().copied().unwrap_or(last);
|
||||
chunks.push(chunk);
|
||||
}
|
||||
Ok(Some(chunks))
|
||||
}
|
||||
|
||||
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.fill";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
|
||||
let path = path_param(p, C, pt, scope)?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
|
||||
let group = object_param(p, "group", C)?;
|
||||
@@ -472,7 +490,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
|
||||
}
|
||||
}
|
||||
if let Some(points) = points {
|
||||
if let Some(chunks) = &path {
|
||||
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
|
||||
// Use the existing region-crossing probes, so even a face narrower than the distance
|
||||
// between pointer events is filled. Reversing matches visible_face_at's front first.
|
||||
@@ -488,11 +506,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let map = b::BuilderMap { regions, ..Default::default() };
|
||||
let mut last = pt;
|
||||
for input in std::iter::once(points).chain(continuation) {
|
||||
let chunk = parse_chunk(input, last)?;
|
||||
last = chunk.last().copied().unwrap_or(last);
|
||||
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
|
||||
for chunk in chunks {
|
||||
targets.extend(map.hits_along(chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
|
||||
}
|
||||
}
|
||||
Ok((fid, targets))
|
||||
@@ -567,6 +582,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
|
||||
let path = path_param(p, C, pt, scope)?;
|
||||
let through: Vec<NodeId> = match p.get("through") {
|
||||
None => vec![],
|
||||
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
|
||||
@@ -590,7 +606,18 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let eid = start.id;
|
||||
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
|
||||
let targets = match scope {
|
||||
LpScope::One => vec![eid],
|
||||
// A drag also reaches every edge of the group that is not hidden and that its path
|
||||
// crosses or touches.
|
||||
LpScope::One => std::iter::once(eid)
|
||||
.chain(
|
||||
path.as_deref()
|
||||
.map(|chunks| b::visible_edges_along(n, chunks))
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|e| e.id)
|
||||
.filter(|id| *id != eid),
|
||||
)
|
||||
.collect(),
|
||||
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
|
||||
LpScope::SamePaint => std::iter::once(eid)
|
||||
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
|
||||
|
||||
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Arc",
|
||||
[],
|
||||
None,
|
||||
"{x1, y1, x2, y2, closed?, slope?} or {x, y, lengthX, lengthY, reference?, baseAlong?: x|y, slope?, closed?, fillArc?} → {id}",
|
||||
"{x1, y1, x2, y2, closed?, slope?: −100…100 (default 100), rotation?: deg clockwise about (x1, y1)} or {x, y, lengthX, lengthY, reference?: 0–8 (default 0), baseAlong?: x|y (either case; default x), slope?: −100…100 (default 50), closed?, fillArc?, rotation?: deg clockwise about the reference point (x, y)} (0: upright); a reference or baseAlong given as anything else (null included) or a slope outside its range is an error and draws nothing → {id}",
|
||||
has_doc,
|
||||
arc
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Rectangular Grid",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, rows=5, columns=5, rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
"{x, y, width, height, rows=5, columns=5 (whole numbers; at most 999), rowSkew=0, columnSkew=0 (−500…500 %: + crowds the horizontal dividers toward the top, the vertical ones toward the right), frame=true (the outside as one rectangle, else its four sides), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
has_doc,
|
||||
rect_grid
|
||||
),
|
||||
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Polar Grid",
|
||||
[],
|
||||
None,
|
||||
"{x, y, width, height, concentric=5, radial=5, concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
"{x, y, width, height, concentric=5, radial=5 (whole numbers; at most 999), concentricSkew=0, radialSkew=0 (−500…500 %: + crowds the ellipses toward the outside, the radial dividers clockwise of the top one), compound=false (the ellipses pair up into compound-path rings), fill=false (the current fill, else none), rotation?: deg clockwise about the centre (0: upright)} → {id}",
|
||||
has_doc,
|
||||
polar_grid
|
||||
),
|
||||
@@ -299,7 +299,8 @@ fn path_kind(path: PathData, live: Option<LiveShape>) -> NodeKind {
|
||||
/// (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>):
|
||||
/// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog
|
||||
/// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays
|
||||
/// put; a polygon or star turns its base orientation about its centre. The params as they are at
|
||||
/// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog
|
||||
/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at
|
||||
/// 0° or a whole turn, for other commands and when they already carry a `rotation`.
|
||||
pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value {
|
||||
let base = s.prefs.constrain_angle;
|
||||
@@ -318,6 +319,9 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point)
|
||||
"shape.polygon" | "shape.star" => {
|
||||
o.insert("rotation".into(), json!(rotation));
|
||||
}
|
||||
"shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => {
|
||||
o.insert("rotation".into(), json!(rotation));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
params
|
||||
@@ -590,26 +594,56 @@ fn spiral(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.arc")? } else { 0.0 };
|
||||
if !rotation.is_finite() {
|
||||
return Err(bad("shape.arc", "rotation must be finite"));
|
||||
}
|
||||
let closed = switch_or(p, "closed", false, "shape.arc")?;
|
||||
let fill_arc = switch_or(p, "fillArc", false, "shape.arc")?;
|
||||
let base_x = !matches!(p.get("baseAlong").and_then(Value::as_str), Some("y" | "Y"));
|
||||
let path = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
|
||||
// Given values are checked in both forms, null included; only a left-out key takes its default.
|
||||
let base_x = match p.get("baseAlong") {
|
||||
None => true,
|
||||
Some(Value::String(v)) if v.eq_ignore_ascii_case("x") || v.eq_ignore_ascii_case("y") => v.eq_ignore_ascii_case("x"),
|
||||
Some(_) => return Err(bad("shape.arc", "`baseAlong` must be one of x, y")),
|
||||
};
|
||||
let reference = match p.get("reference") {
|
||||
None => 0,
|
||||
Some(v) => match (v.as_u64(), v.as_f64()) {
|
||||
(Some(n), _) if n <= 8 => n as usize,
|
||||
(None, Some(x)) if (0.0..=8.0).contains(&x) && x.fract() == 0.0 => x as usize,
|
||||
_ => return Err(bad("shape.arc", "`reference` must be a whole number from 0 to 8")),
|
||||
},
|
||||
};
|
||||
let slope = |default: f64| {
|
||||
let (key, lo, hi) = ("slope", -100.0, 100.0);
|
||||
let v = number_or(p, key, default, "shape.arc")?;
|
||||
if (lo..=hi).contains(&v) { Ok(v) } else { Err(bad("shape.arc", format!("`{key}` must be from {lo} to {hi}, not {v}"))) }
|
||||
};
|
||||
// The upright path, and the point `rotation` turns it about.
|
||||
let (path, pivot) = if p.get("lengthX").is_some() || p.get("lengthY").is_some() {
|
||||
let anchor = Point::new(f64_req(p, "x", "shape.arc")?, f64_req(p, "y", "shape.arc")?);
|
||||
let reference = p.get("reference").and_then(Value::as_u64).unwrap_or(0) as usize;
|
||||
shapes::arc_segment(
|
||||
let path = shapes::arc_segment(
|
||||
anchor,
|
||||
reference,
|
||||
number_or(p, "lengthX", 100.0, "shape.arc")?,
|
||||
number_or(p, "lengthY", 100.0, "shape.arc")?,
|
||||
base_x,
|
||||
number_or(p, "slope", 50.0, "shape.arc")?,
|
||||
slope(50.0)?,
|
||||
closed,
|
||||
)
|
||||
);
|
||||
(path, anchor)
|
||||
} else {
|
||||
let a = Point::new(f64_req(p, "x1", "shape.arc")?, f64_req(p, "y1", "shape.arc")?);
|
||||
let b = Point::new(f64_req(p, "x2", "shape.arc")?, f64_req(p, "y2", "shape.arc")?);
|
||||
let slope = number_or(p, "slope", 100.0, "shape.arc")?;
|
||||
shapes::arc(a, b, slope, closed, base_x)
|
||||
(shapes::arc(a, b, slope(100.0)?, closed, base_x), a)
|
||||
};
|
||||
// 0 and whole turns leave the path as it is; quarter turns are exact.
|
||||
let bbox_angle = bbox_turn(rotation);
|
||||
let path = if bbox_angle == 0.0 {
|
||||
path
|
||||
} else {
|
||||
let c = pivot.to_vec2();
|
||||
path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c))
|
||||
};
|
||||
let fill = if fill_arc { s.paint.fill.clone() } else { vectorcraft_color::Paint::None };
|
||||
let look = s.new_art_look(
|
||||
@@ -617,7 +651,7 @@ fn arc(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() },
|
||||
s.paint.stroke_width.max(0.1),
|
||||
);
|
||||
add_look(s, "Arc", path_kind(path, None), look, None)
|
||||
insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle)
|
||||
}
|
||||
|
||||
/// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the
|
||||
@@ -655,13 +689,11 @@ fn grid_group(s: &mut Session, label: &str, (paths, bbox_angle): (Vec<PathData>,
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// A grid's divider count `count` (an error unless it is a number or null; 5 unless it is a JSON
|
||||
/// whole number of 0 or more, so 4.0 gives 4 and 2.5 gives 5; at most 999) with its skew `key` in percent (0 when
|
||||
/// absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
|
||||
/// A grid's divider count `count` (5 when absent or null; a whole number of 0 or more, so 4.0 gives
|
||||
/// 4, and anything else, such as 2.5, -1 or `"3"`, is an error; at most 999) with its skew `key` in
|
||||
/// percent (0 when absent, clamped to ±[`shapes::GRID_SKEW_MAX`]).
|
||||
fn dividers(p: &Value, count: &str, key: &str, cmd: &str) -> Result<(u32, f64)> {
|
||||
check_numbers(p, &[count], cmd)?;
|
||||
let whole = |v: &Value| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0 && f.fract() == 0.0).map(|f| f as u64));
|
||||
let n = p.get(count).and_then(whole).unwrap_or(5).min(999) as u32;
|
||||
let n = count_or(p, count, 5, cmd)?.min(999) as u32;
|
||||
let skew = match p.get(key) {
|
||||
None | Some(Value::Null) => 0.0,
|
||||
Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?,
|
||||
|
||||
@@ -509,7 +509,16 @@ pub(crate) fn linked_files(d: &Document, base: LinkBase) -> Vec<LinkedFile> {
|
||||
.filter(|g| seen.insert(g.link.path.clone()))
|
||||
.map(|g| {
|
||||
let named = fileio::format_for_name(g.link.name()).or_else(|| fileio::readable_format_for_name(g.link.name()));
|
||||
let own = |b: &&ImageBlob| !b.is_proxy() && named.is_some_and(|f| f.mime == b.mime);
|
||||
// A placed document's PostScript bytes are its file's own only when its name is one that
|
||||
// PostScript is read from (`.eps`, `.epsf`, `.ps`, a PostScript `.ai` or `.ait`).
|
||||
let postscript_name = matches!(fileio::extension(g.link.name()).as_str(), "eps" | "epsf" | "ps" | "ai" | "ait");
|
||||
let postscript = |b: &ImageBlob| {
|
||||
g.document.is_some()
|
||||
&& postscript_name
|
||||
&& b.mime == super::place::document::POSTSCRIPT
|
||||
&& super::place::document::is_postscript(&b.bytes)
|
||||
};
|
||||
let own = |b: &&ImageBlob| !b.is_proxy() && (named.is_some_and(|f| f.mime == b.mime) || postscript(b));
|
||||
let found = locate(&g.link, base);
|
||||
let found_path = found.as_ref().map(|f| f.path.clone());
|
||||
let bytes = found.and_then(|mut f| f.read().ok()).or_else(|| d.images.get(&g.key).filter(own).map(|b| b.bytes.to_vec()));
|
||||
@@ -2361,12 +2370,20 @@ fn format_label(d: &Document, im: &ImageObject) -> &'static str {
|
||||
.map_or("Image", |f| f.label)
|
||||
}
|
||||
|
||||
/// A placed document's `links.list` fields: `format` (`VectorCraft`, or the PDF or `.ai` file's
|
||||
/// format), `document: true` and its artboard's or page's size (`pageWidth`, `pageHeight`, pt)
|
||||
/// instead of pixels.
|
||||
fn document_row(p: &PlacedDocument) -> Value {
|
||||
let pdf = fileio::format_for_name(p.link.name()).filter(|f| matches!(f.id, "pdf" | "ai" | "ait"));
|
||||
json!({ "format": pdf.map_or("VectorCraft", |f| f.label), "document": true, "pageWidth": p.width, "pageHeight": p.height })
|
||||
/// A placed document's `links.list` fields (of `d`): `format` (`VectorCraft`, the PDF or `.ai`
|
||||
/// file's format, or for an EPS or PostScript file `EPS` or `PostScript`), `document: true` and its
|
||||
/// artboard's or page's size (`pageWidth`, `pageHeight`, pt) instead of pixels. A PostScript `.ai`
|
||||
/// is told by its stored bytes or, when a save kept only its preview, by its key.
|
||||
fn document_row(d: &Document, p: &PlacedDocument) -> Value {
|
||||
use super::place::document::{POSTSCRIPT, is_postscript_ai_key};
|
||||
let postscript = d.images.get(&p.key).is_some_and(|b| b.mime == POSTSCRIPT) || is_postscript_ai_key(&p.key);
|
||||
let format = match fileio::format_for_name(p.link.name()) {
|
||||
Some(f) if matches!(f.id, "eps" | "ps") => f.label,
|
||||
_ if postscript => "PostScript",
|
||||
Some(f) if matches!(f.id, "pdf" | "ai" | "ait") => f.label,
|
||||
_ => "VectorCraft",
|
||||
};
|
||||
json!({ "format": format, "document": true, "pageWidth": p.width, "pageHeight": p.height })
|
||||
}
|
||||
|
||||
/// The size in bytes of the file that link `l` (of `st`) names, as Link Info shows it: the file's
|
||||
@@ -2488,7 +2505,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
(im.link.as_ref(), row)
|
||||
}
|
||||
NodeKind::PlacedDocument(p) => (Some(&p.link), document_row(p)),
|
||||
NodeKind::PlacedDocument(p) => (Some(&p.link), document_row(&doc, p)),
|
||||
_ => continue,
|
||||
};
|
||||
let name = link.map_or_else(|| n.display_name(), |l| l.name().to_string());
|
||||
@@ -2766,7 +2783,7 @@ fn placed_info(st: &crate::DocState, doc: &Document, id: NodeId) -> Result<Value
|
||||
let NodeKind::PlacedDocument(pl) = &n.kind else { return Err(bad("links.info", format!("object {} is not a placed document", id.0))) };
|
||||
let size = n.geometric_bounds().unwrap_or_default();
|
||||
let (scale, rotation) = scale_rotation(pl.xf, (1.0, 1.0));
|
||||
let mut out = document_row(pl);
|
||||
let mut out = document_row(doc, pl);
|
||||
let fields = [
|
||||
("id", json!(id.0)),
|
||||
("name", json!(n.display_name())),
|
||||
|
||||
@@ -9,7 +9,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer};
|
||||
use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
use vectorcraft_geom::{FillRule, PathData, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_pathops::{BoolOp, PathfinderOp};
|
||||
|
||||
@@ -352,6 +352,94 @@ pub(crate) fn pf_leaves(d: &Document, n: &Node, out: &mut Vec<Node>) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The region a clip group's members show through: its clipping path's outline
|
||||
/// ([`vectorcraft_render::effects::clip_outline`]), cut by the clip groups around it.
|
||||
struct Clip {
|
||||
path: PathData,
|
||||
rule: FillRule,
|
||||
}
|
||||
|
||||
/// Does `path` have an anchor or handle that isn't a finite number?
|
||||
fn has_invalid_coordinates(path: &PathData) -> bool {
|
||||
path.subpaths.iter().flat_map(|sp| &sp.anchors).any(|a| [a.p, a.h_in, a.h_out].iter().any(|q| !(q.x.is_finite() && q.y.is_finite())))
|
||||
}
|
||||
|
||||
/// A Pathfinder operation's leaf shape ([`pf_leaves`]) with the region its clip groups show it
|
||||
/// through, `None` outside any clip group.
|
||||
type ClippedLeaf = (Node, Option<Arc<Clip>>);
|
||||
|
||||
/// [`pf_leaves`], each with the region the clip groups it is in show it through (#8093). A clip
|
||||
/// group's clipping path is not a leaf, and the members of one whose clipping path clips by nothing
|
||||
/// are hidden, as on the canvas: their region is empty.
|
||||
fn clipped_pf_leaves(d: &Document, n: &Node, clip: Option<&Arc<Clip>>, precision: f64, out: &mut Vec<ClippedLeaf>) -> Result<()> {
|
||||
let (NodeKind::Group { children, clip: clips } | NodeKind::Layer { children, clip: clips, .. }) = &n.kind else {
|
||||
let mut lv = vec![];
|
||||
leaves(n, &mut lv);
|
||||
out.extend(lv.into_iter().map(|l| (l, clip.cloned())));
|
||||
return Ok(());
|
||||
};
|
||||
let hook = |c: &Node| vectorcraft_render::effects::outline_object(Some(d), c);
|
||||
if let Some(art) = vectorcraft_render::effects::compound_shape_art(Some(d), n, Some(&hook)) {
|
||||
out.push((art, clip.cloned()));
|
||||
return Ok(());
|
||||
}
|
||||
if !*clips {
|
||||
return children.iter().try_for_each(|c| clipped_pf_leaves(d, c, clip, precision, out));
|
||||
}
|
||||
let Some((first, rest)) = children.split_first() else { return Ok(()) };
|
||||
let mut region = match vectorcraft_render::effects::clip_outline(first) {
|
||||
Some((outline, rule)) => Clip { path: PathData::from_bezpath(&outline), rule },
|
||||
None => Clip { path: PathData::default(), rule: FillRule::NonZero },
|
||||
};
|
||||
if has_invalid_coordinates(®ion.path) {
|
||||
return Err(EngineError::Other("paths contain invalid coordinates".into()));
|
||||
}
|
||||
if let Some(outer) = clip.filter(|_| !region.path.is_empty()) {
|
||||
let path = po::try_boolean(®ion.path, region.rule, &outer.path, outer.rule, BoolOp::Intersect, precision)
|
||||
.map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
region = Clip { path, rule: FillRule::NonZero };
|
||||
}
|
||||
let region = Arc::new(region);
|
||||
rest.iter().try_for_each(|c| clipped_pf_leaves(d, c, Some(®ion), precision, out))
|
||||
}
|
||||
|
||||
/// `path`, filled by `rule`, where `clip` shows it: its area intersected with the region, filled
|
||||
/// non-zero, and with `lines` (Divide, whose open contours cut) its open contours' parts inside the
|
||||
/// region, so their hidden parts cut nothing.
|
||||
fn clipped(path: PathData, rule: FillRule, clip: &Clip, lines: bool, precision: f64) -> Result<(PathData, FillRule)> {
|
||||
if has_invalid_coordinates(&path) {
|
||||
// Left as it is for the operation to refuse ("paths contain invalid coordinates").
|
||||
return Ok((path, rule));
|
||||
}
|
||||
let (Some(within), Some(bounds)) = (clip.path.control_bounds(), path.control_bounds()) else { return Ok((PathData::default(), rule)) };
|
||||
if within.intersect(bounds).is_zero_area() && !bounds.is_zero_area() {
|
||||
// Wholly outside the region (a line's bounds may be flat, so only an area's are trusted).
|
||||
return Ok((PathData::default(), rule));
|
||||
}
|
||||
let (open, closed): (Vec<SubPath>, Vec<SubPath>) =
|
||||
if lines { path.subpaths.into_iter().partition(|sp| !sp.closed) } else { (vec![], path.subpaths) };
|
||||
let mut subs = vec![];
|
||||
if !closed.is_empty() {
|
||||
let area = po::try_boolean(&PathData::new(closed), rule, &clip.path, clip.rule, BoolOp::Intersect, precision)
|
||||
.map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
subs.extend(area.subpaths);
|
||||
}
|
||||
if !open.is_empty() {
|
||||
let open = PathData::new(open);
|
||||
// Each segment is sampled at least every 1/16 of the region's shorter side (and 24 times),
|
||||
// and the crossings found are refined: a part of the region narrower than that, which a
|
||||
// line crosses between two samples, can be missed.
|
||||
let step = (within.width().min(within.height()) / 16.0).max(precision);
|
||||
let outline = clip.path.to_bezpath();
|
||||
let outside = |q| !vectorcraft_geom::hit::fill_contains(&outline, clip.rule, q);
|
||||
match super::draw2::erase_outline(&open, step, &outside) {
|
||||
Some(pieces) => subs.extend(pieces.into_iter().flat_map(|p| p.subpaths)),
|
||||
None => subs.extend(open.subpaths),
|
||||
}
|
||||
}
|
||||
Ok((PathData::new(subs), FillRule::NonZero))
|
||||
}
|
||||
|
||||
/// How many shapes a Pathfinder operation takes from `n` selected alone: its leaf shapes, however
|
||||
/// deep its groups nest (an expanded stroke is a group inside the group, #1635). Inside a compound
|
||||
/// shape, a blend, an envelope or another live object and a symbol instance count as one shape
|
||||
@@ -591,6 +679,10 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
}
|
||||
let shape_mode =
|
||||
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
|
||||
// An operand its clipping masks hide altogether is an empty shape for the operations whose
|
||||
// result it changes (Intersect gives nothing, Minus Front loses its back object, Minus Back its
|
||||
// front one, Crop its cropping shape); the others leave it out, which gives the same art.
|
||||
let keeps_hidden = matches!(op, PathfinderOp::Intersect | PathfinderOp::MinusFront | PathfinderOp::MinusBack | PathfinderOp::Crop);
|
||||
let label = pf_label(op);
|
||||
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
@@ -598,63 +690,95 @@ fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
let mut styles: Vec<Style> = vec![];
|
||||
let mut shapes: Vec<po::Shape> = vec![];
|
||||
let mut names: Vec<Option<String>> = vec![];
|
||||
let mut push = |mut path: PathData, rule: FillRule, mut st: Style, name: Option<String>| {
|
||||
if path.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Trim, Merge and Crop remove any strokes (and Merge then merges by fill alone), as the
|
||||
// public Pathfinder documentation describes.
|
||||
if matches!(op, PathfinderOp::Trim | PathfinderOp::Merge | PathfinderOp::Crop) {
|
||||
st.appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_)));
|
||||
}
|
||||
if op == PathfinderOp::Divide && st.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if !f.paint.is_none())) {
|
||||
// Filled open contours keep their implicit closing edge. A zero-area line
|
||||
// stays a cutter; normalised area also catches zero-signed-area self crossings.
|
||||
for sub in path.subpaths.iter_mut().filter(|sp| !sp.closed) {
|
||||
sub.closed = po::encloses_area(sub) || po::area(&PathData::single(sub.clone()), rule) > 0.0;
|
||||
// `hidden`: the masks hide the operand altogether, and its empty path stands for it.
|
||||
let mut push =
|
||||
|mut path: PathData, mut rule: FillRule, mut st: Style, name: Option<String>, clip: Option<&Clip>, hidden: bool| -> Result<()> {
|
||||
if path.is_empty() && !(hidden && keeps_hidden) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let key = match styles.iter().position(|x| *x == st) {
|
||||
Some(k) => k,
|
||||
None => {
|
||||
styles.push(st);
|
||||
styles.len() - 1
|
||||
// Trim, Merge and Crop remove any strokes (and Merge then merges by fill alone), as the
|
||||
// public Pathfinder documentation describes.
|
||||
if matches!(op, PathfinderOp::Trim | PathfinderOp::Merge | PathfinderOp::Crop) {
|
||||
st.appearance.items.retain(|i| !matches!(i, AppearanceItem::Stroke(_)));
|
||||
}
|
||||
if op == PathfinderOp::Divide && st.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if !f.paint.is_none())) {
|
||||
// Filled open contours keep their implicit closing edge. A zero-area line
|
||||
// stays a cutter; normalised area also catches zero-signed-area self crossings.
|
||||
for sub in path.subpaths.iter_mut().filter(|sp| !sp.closed) {
|
||||
sub.closed = po::encloses_area(sub) || po::area(&PathData::single(sub.clone()), rule) > 0.0;
|
||||
}
|
||||
}
|
||||
if let Some(clip) = clip {
|
||||
(path, rule) = clipped(path, rule, clip, op == PathfinderOp::Divide, options.precision)?;
|
||||
if path.is_empty() && !keeps_hidden {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let key = match styles.iter().position(|x| *x == st) {
|
||||
Some(k) => k,
|
||||
None => {
|
||||
styles.push(st);
|
||||
styles.len() - 1
|
||||
}
|
||||
};
|
||||
shapes.push(po::Shape::new(path, rule, key as u64));
|
||||
names.push(name);
|
||||
Ok(())
|
||||
};
|
||||
shapes.push(po::Shape::new(path, rule, key as u64));
|
||||
names.push(name);
|
||||
};
|
||||
// Whether a clip group was among the selection, for the error when its mask hides it all.
|
||||
let mut masked = false;
|
||||
for id in &roots {
|
||||
let n = d.node(*id).ok_or(EngineError::NoNode(*id))?;
|
||||
let mut lv = vec![];
|
||||
pf_leaves(d, n, &mut lv);
|
||||
clipped_pf_leaves(d, n, None, options.precision, &mut lv)?;
|
||||
masked |= lv.iter().any(|(_, clip)| clip.is_some());
|
||||
if lv.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if shape_mode
|
||||
&& roots.len() > 1
|
||||
&& lv.len() > 1
|
||||
&& let Some(top) = lv.last()
|
||||
{
|
||||
// Among other objects, a group acts as one shape (the union of its leaves) with
|
||||
// its top leaf's style. Selected alone, its members are the shapes (#1450).
|
||||
let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(node_path).collect();
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
|
||||
let name = n.name.clone().or_else(|| lv.iter().find_map(|l| l.name.clone()));
|
||||
if shape_mode && roots.len() > 1 && lv.len() > 1 {
|
||||
// Among other objects, a group acts as one shape (the union of its leaves, each
|
||||
// where its clip groups show it) with the style of its top leaf that shows.
|
||||
// Selected alone, its members are the shapes (#1450).
|
||||
let mut parts: Vec<(&Node, PathData, FillRule)> = vec![];
|
||||
for (l, clip) in &lv {
|
||||
let Some((p, r)) = node_path(l) else { continue };
|
||||
let (p, r) = match clip {
|
||||
Some(clip) => clipped(p, r, clip, false, options.precision)?,
|
||||
None => (p, r),
|
||||
};
|
||||
if !p.is_empty() {
|
||||
parts.push((l, p, r));
|
||||
}
|
||||
}
|
||||
let name = n.name.clone().or_else(|| parts.iter().find_map(|(l, ..)| l.name.clone()));
|
||||
let Some((top, ..)) = parts.last() else {
|
||||
// The masks hide the whole group.
|
||||
if let Some((top, _)) = lv.last() {
|
||||
push(PathData::default(), FillRule::NonZero, style_of(top), name, None, true)?;
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let top = *top;
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, p, r)| (p, *r)).collect();
|
||||
push(
|
||||
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
|
||||
FillRule::NonZero,
|
||||
style_of(top),
|
||||
name,
|
||||
);
|
||||
None,
|
||||
false,
|
||||
)?;
|
||||
} else {
|
||||
for l in &lv {
|
||||
for (l, clip) in &lv {
|
||||
if let Some((p, r)) = node_path(l) {
|
||||
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()));
|
||||
push(p, r, style_of(l), n.name.clone().or_else(|| l.name.clone()), clip.as_deref(), clip.is_some())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if shapes.is_empty() && masked {
|
||||
return Err(EngineError::Other(format!("{label}: the clipping masks hide the selected art")));
|
||||
}
|
||||
if shapes.is_empty() {
|
||||
return Err(EngineError::Other(format!("{label}: select paths, compound paths, groups or text")));
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
//! Placed documents (`file.place` of a VectorCraft document, a PDF or a `.ai` file from a file,
|
||||
//! with `link`): one locked object showing an artboard of the document or a page of the PDF, a
|
||||
//! [`PlacedDocument`].
|
||||
//! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file
|
||||
//! from a file, with `link`): one locked object showing an artboard of the document, a page of the
|
||||
//! PDF or the EPS file's art, a [`PlacedDocument`].
|
||||
//!
|
||||
//! The object keeps the file's bytes (in the document's images, like image data) and the link; the
|
||||
//! art it shows is read from them the way placing the file without Link reads it
|
||||
@@ -33,6 +33,16 @@ pub(crate) const MAX_FILE: usize = 256 << 20;
|
||||
const NATIVE: [&str; 2] = ["vectorcraft", "template"];
|
||||
/// The type a placed VectorCraft document's bytes are stored with (a PDF's: its format's).
|
||||
const MIME: &str = "application/json";
|
||||
/// The type a placed EPS or PostScript file's bytes are stored with.
|
||||
pub(crate) const POSTSCRIPT: &str = "application/postscript";
|
||||
/// What follows the hash in the key of a placed PostScript `.ai` file ([`key_for`]).
|
||||
const AI_MARK: &str = "-ai";
|
||||
|
||||
/// Is `key` (of a placed document) a PostScript `.ai` file's ([`AI_MARK`])? Hashes are hex, so
|
||||
/// only the mark puts `-ai-` in a key.
|
||||
pub(crate) fn is_postscript_ai_key(key: &str) -> bool {
|
||||
key.contains(&format!("{AI_MARK}-"))
|
||||
}
|
||||
|
||||
/// Is `name` with `bytes` a VectorCraft document?
|
||||
pub(crate) fn is_native(name: &str, bytes: &[u8]) -> bool {
|
||||
@@ -44,6 +54,12 @@ pub(crate) fn is_pdf(name: &str, bytes: &[u8]) -> bool {
|
||||
fileio::detect(name, bytes).is_some_and(|f| matches!(f.id, "pdf" | "ai" | "ait")) && !vectorcraft_pdf::is_postscript(bytes)
|
||||
}
|
||||
|
||||
/// Is `bytes` an EPS file, a PostScript file or a PostScript `.ai` or `.ait` file, read by the EPS
|
||||
/// importer (not a DCS file, which is placed as a linked image)?
|
||||
pub(crate) fn is_postscript(bytes: &[u8]) -> bool {
|
||||
vectorcraft_pdf::is_postscript(bytes) && !super::dcs::is_dcs(bytes)
|
||||
}
|
||||
|
||||
/// The editing data of the `.ai` file `name` (`bytes`) when its PDF part is only a placeholder, or
|
||||
/// can't be read:
|
||||
/// the document its pages are read from ([`super::pdf_art`]), with the files it links. `None` for
|
||||
@@ -60,9 +76,12 @@ pub(crate) fn editing_data(name: &str, bytes: &[u8]) -> Option<Document> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The type the bytes of placed file `name` (`bytes`) are stored with: a PDF's format's, else
|
||||
/// [`MIME`].
|
||||
/// The type the bytes of placed file `name` (`bytes`) are stored with: a PDF's format's,
|
||||
/// [`POSTSCRIPT`] for an EPS or PostScript file, else [`MIME`].
|
||||
fn mime(name: &str, bytes: &[u8]) -> &'static str {
|
||||
if is_postscript(bytes) {
|
||||
return POSTSCRIPT;
|
||||
}
|
||||
fileio::detect(name, bytes).filter(|_| is_pdf(name, bytes)).map_or(MIME, |f| f.mime)
|
||||
}
|
||||
|
||||
@@ -108,7 +127,9 @@ pub(crate) struct DocumentArt {
|
||||
/// Artboard `page` (1-based) of the VectorCraft document `name` (`bytes`, read from `path` when
|
||||
/// there is one, so its linked images are found), clipped to the artboard unless `bounding`; or
|
||||
/// page `page` of the PDF or `.ai` file `name`, clipped to its box `page_box` unless `bounding`
|
||||
/// ([`super::pdf_art`]).
|
||||
/// ([`super::pdf_art`]); or the art of the EPS or PostScript file `name` ([`is_postscript`]) on
|
||||
/// its page `page`, clipped to its bounding box unless `bounding`, as placing it without Link reads
|
||||
/// it.
|
||||
pub(crate) fn document_art(
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
@@ -135,7 +156,7 @@ fn opened_document_art(
|
||||
) -> Result<DocumentArt> {
|
||||
let file = fileio::file_name(name);
|
||||
let pdf = is_pdf(name, bytes);
|
||||
if !pdf && !is_native(name, bytes) {
|
||||
if !pdf && !is_native(name, bytes) && !is_postscript(bytes) {
|
||||
return Err(bad(cmd, format!("`{file}` isn't a VectorCraft document, a PDF or a PDF-compatible .ai file")));
|
||||
}
|
||||
if bytes.len() > MAX_FILE {
|
||||
@@ -145,6 +166,8 @@ fn opened_document_art(
|
||||
let o = fileio::LoadOptions { crop: crop_to(page_box), ..Default::default() };
|
||||
return super::pdf_art(name, (bytes, opened), path, page as usize, o, bounding, cmd);
|
||||
}
|
||||
// A VectorCraft document, or an EPS or PostScript file: the document our EPS files carry, else
|
||||
// what its PostScript draws.
|
||||
let mut l = fileio::load(name, bytes)?;
|
||||
// Its linked images show their files; its placed documents stay as they are, unless their
|
||||
// stored bytes are lost, when resolving reads their files, which can place this one again.
|
||||
@@ -292,6 +315,10 @@ fn read_source(
|
||||
let hash = shared.map_or_else(|| hash_bytes(bytes), |f| f.hash.to_string());
|
||||
let opened = shared.map(|f| f.opened);
|
||||
let shared = shared.map(|f| f.bytes);
|
||||
// A PostScript `.ai` is read with the artboard its header gives, an EPS file on its page: the
|
||||
// same bytes under the two names show different art, so they have keys of their own.
|
||||
let ai = is_postscript(bytes) && fileio::detect(name, bytes).is_some_and(|f| matches!(f.id, "ai" | "ait"));
|
||||
let hash = if ai { format!("{hash}{AI_MARK}") } else { hash };
|
||||
// The same document placed the same way is read once (placing it again is free).
|
||||
let key = key_for(&hash, page, bounding, page_box);
|
||||
// Resolving its links depends on where the file is and on what the caller may read, so a hit
|
||||
|
||||
@@ -122,6 +122,7 @@ mod panelcmds;
|
||||
mod paragraphs;
|
||||
mod params;
|
||||
mod path_menu_enabled;
|
||||
mod pathfinder_clip;
|
||||
mod pathops;
|
||||
mod pathtype;
|
||||
mod pattern;
|
||||
|
||||
@@ -5198,6 +5198,137 @@ fn live_paint_bucket_drag_rejects_invalid_points_atomically() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The edge of `g` through (`x`, 25), halfway up the squares of [`live_squares`].
|
||||
fn vertical_edge(s: &Session, g: NodeId, x: f64) -> NodeId {
|
||||
vectorcraft_tools::builder::edge_near(&node(s, g), Point::new(x, 25.0), 0.5).map(|e| e.id).unwrap_or_else(|| panic!("an edge at x {x}"))
|
||||
}
|
||||
|
||||
/// A Shift-drag from an edge strokes every visible edge of that group the drag crosses, between
|
||||
/// pointer events and on the release too, as one undo step that Escape cancels; hidden edges and
|
||||
/// another group's edges keep their strokes.
|
||||
#[test]
|
||||
fn live_paint_bucket_drag_strokes_crossed_edges_as_one_undo() {
|
||||
for cancel in [false, true] {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0, 200.0]);
|
||||
let other = live_squares(&mut s, &[300.0]);
|
||||
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all: Vec<NodeId> = [g, other].iter().flat_map(|g| edges_in(&s, *g, Rect::new(-1.0, -1.0, 351.0, 51.0))).collect();
|
||||
paint_parts(&mut s, &all, &black, &[]);
|
||||
let hidden = vertical_edge(&s, g, 100.0);
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(hidden).unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let depth = s.doc().unwrap().history.undo.len();
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.stroke = green.clone();
|
||||
s.paint.stroke_width = 3.0;
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 25.0).with_mods(shift), v).unwrap();
|
||||
// Past the hidden edge and the edge at 150, then back across it, between pointer events.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 160.0, 25.0).with_mods(shift), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 140.0, 30.0).with_mods(shift), v).unwrap();
|
||||
if cancel {
|
||||
assert!(s.tool_busy());
|
||||
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
|
||||
assert!(!s.tool_busy());
|
||||
}
|
||||
// The release crosses the edges at 200 and 250 and goes on into the other group.
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 325.0, 25.0).with_mods(shift), v).unwrap();
|
||||
if cancel {
|
||||
assert!(s.doc().unwrap().doc == before, "Escape cancels the whole drag");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
|
||||
continue;
|
||||
}
|
||||
let stroke = |s: &Session, id: NodeId| {
|
||||
let n = node(s, id);
|
||||
(n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width))
|
||||
};
|
||||
for x in [50.0, 150.0, 200.0, 250.0] {
|
||||
assert_eq!(stroke(&s, vertical_edge(&s, g, x)), (green.clone(), Some(3.0)), "edge at {x}");
|
||||
}
|
||||
for (group, x) in [(g, 0.0), (g, 100.0), (other, 300.0), (other, 350.0)] {
|
||||
assert_eq!(stroke(&s, vertical_edge(&s, group, x)), (black.clone(), Some(1.0)), "edge at {x}");
|
||||
}
|
||||
for e in edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 1.0)) {
|
||||
assert_eq!(stroke(&s, e).0, black, "a top edge is not crossed");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1, "one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before, "one Undo restores every edge");
|
||||
}
|
||||
}
|
||||
|
||||
/// A stroke drag over edges that already have the stroke records no undo step and keeps the redo
|
||||
/// steps.
|
||||
#[test]
|
||||
fn live_paint_bucket_stroke_drag_no_op_keeps_history() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0]);
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
|
||||
paint_parts(&mut s, &all, &green, &[]);
|
||||
paint_parts(&mut s, &all, &green, &[]);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len());
|
||||
assert_eq!(redo, 1);
|
||||
let v = ViewInfo::default();
|
||||
s.select_tool("livePaintBucket", v).unwrap();
|
||||
s.paint.stroke = green;
|
||||
s.paint.stroke_width = 1.0;
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 0.0, 25.0).with_mods(shift), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 60.0, 25.0).with_mods(shift), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 25.0).with_mods(shift), v).unwrap();
|
||||
assert!(s.doc().unwrap().doc == before);
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len()), (undo, redo));
|
||||
}
|
||||
|
||||
/// `livePaint.strokeEdge` with `points` paints the crossed edges, counting the edge at the point;
|
||||
/// a malformed path or a scope other than "one" with `points` is an error that changes nothing.
|
||||
#[test]
|
||||
fn live_paint_stroke_drag_rejects_invalid_points_atomically() {
|
||||
let mut s = session();
|
||||
let g = live_squares(&mut s, &[0.0, 50.0, 100.0]);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let stroke = |s: &mut Session, extra: Value| {
|
||||
let mut p = json!({"group": g.0, "point": [50.0, 25.0], "color": "#00ff00"});
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
s.execute("livePaint.strokeEdge", &p)
|
||||
};
|
||||
for points in
|
||||
[json!([]), json!([[51.0, 25.0]]), json!([[50.0, 25.0], [null, 0]]), json!([[50.0, 25.0], [1e30, 0]]), json!(vec![[50.0, 25.0]; 4097])]
|
||||
{
|
||||
assert!(stroke(&mut s, json!({ "points": points })).is_err(), "{points}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
for continuation in [json!(null), json!([[[51.0, 25.0], [125.0, 25.0]]]), json!([vec![[50.0, 25.0]; 4097]])] {
|
||||
assert!(stroke(&mut s, json!({ "points": [[50.0, 25.0]], "continuation": continuation })).is_err(), "{continuation}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
assert!(stroke(&mut s, json!({ "continuation": [[[50.0, 25.0]]] })).is_err());
|
||||
for scope in ["connected", "samePaint"] {
|
||||
assert!(stroke(&mut s, json!({ "points": [[50.0, 25.0], [125.0, 25.0]], "scope": scope })).is_err(), "{scope}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
// A path in two chunks reaches the edges at 50, 100 and 150, not the one at 0.
|
||||
let r = stroke(&mut s, json!({ "points": [[50.0, 25.0], [90.0, 25.0]], "continuation": [[[90.0, 25.0], [160.0, 25.0]]] })).unwrap();
|
||||
assert_eq!(r["count"], 3);
|
||||
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
|
||||
for x in [50.0, 100.0, 150.0] {
|
||||
assert_eq!(node(&s, vertical_edge(&s, g, x)).appearance.stroke_paint(), green, "edge at {x}");
|
||||
}
|
||||
assert_ne!(node(&s, vertical_edge(&s, g, 0.0)).appearance.stroke_paint(), green);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_paint_bucket_tool_fills_face() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -412,3 +412,97 @@ fn constrain_angle_turns_a_click_made_grid_about_its_reference_point() {
|
||||
let b = bounds(&s, id);
|
||||
assert_eq!((b.x0, b.y0, b.x1, b.y1), (175.0, 150.0, 225.0, 250.0), "turned about the click: {b:?}");
|
||||
}
|
||||
|
||||
/// The anchor points of the path `id`.
|
||||
fn path_points(s: &Session, id: NodeId) -> Vec<Point> {
|
||||
match &s.doc().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect(),
|
||||
other => panic!("a path: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The direction (degrees, counter-clockwise on the page) of the arc `id`'s first handle.
|
||||
fn first_handle_angle(s: &Session, id: NodeId) -> f64 {
|
||||
let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("a path") };
|
||||
let a = &path.subpaths[0].anchors[0];
|
||||
let v = a.h_out - a.p;
|
||||
(-v.y).atan2(v.x).to_degrees()
|
||||
}
|
||||
|
||||
fn near(p: Point, x: f64, y: f64) -> bool {
|
||||
close(p.x, x) && close(p.y, y)
|
||||
}
|
||||
|
||||
/// An arc dragged out runs along the turned axes: at 30° it still runs from the drag's start to
|
||||
/// its end, its base leaves the start along the turned x axis and its bounding box turns 30°; at
|
||||
/// 0° it is as before.
|
||||
#[test]
|
||||
fn constrain_angle_draws_a_dragged_arc_along_the_turned_axes() {
|
||||
let mut s = new_doc();
|
||||
for (deg, handle) in [(0.0, 0.0), (30.0, 30.0)] {
|
||||
set_angle(&mut s, deg);
|
||||
s.select_tool("arc", ViewInfo::default()).unwrap();
|
||||
gesture(&mut s, Mods::default(), &[(Down, 100.0, 100.0), (Drag, 130.0, 110.0), (Drag, 160.0, 120.0), (Up, 160.0, 120.0)]);
|
||||
let id = last_id(&s);
|
||||
let pts = path_points(&s, id);
|
||||
assert!(near(pts[0], 100.0, 100.0) && near(pts[1], 160.0, 120.0), "{deg}°: {pts:?}");
|
||||
assert!(close(first_handle_angle(&s, id), handle), "{deg}°: {}", first_handle_angle(&s, id));
|
||||
if deg == 0.0 {
|
||||
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits());
|
||||
} else {
|
||||
assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An arc placed by the click dialog keeps its reference point at the click and runs its lengths
|
||||
/// along the turned axes: at 30° from the top-left reference point, and at 90° about the center
|
||||
/// one; at 0° the dialog's params are unchanged.
|
||||
#[test]
|
||||
fn constrain_angle_turns_a_click_made_arc_about_its_reference_point() {
|
||||
let mut s = new_doc();
|
||||
let params = |reference: u64, x: f64, y: f64| json!({"x": x, "y": y, "lengthX": 100, "lengthY": 50, "reference": reference, "baseAlong": "x", "slope": 50, "closed": false, "fillArc": false});
|
||||
let click = Point::new(200.0, 200.0);
|
||||
let p = params(0, 200.0, 200.0);
|
||||
assert_eq!(constrain_click(&s, "shape.arc", p.clone(), click), p, "0°");
|
||||
set_angle(&mut s, 30.0);
|
||||
let turned = constrain_click(&s, "shape.arc", p, click);
|
||||
assert_eq!(turned["rotation"], json!(-30.0));
|
||||
let id = NodeId(s.execute("shape.arc", &turned).unwrap()["id"].as_u64().unwrap());
|
||||
let pts = path_points(&s, id);
|
||||
let r = 30f64.to_radians();
|
||||
let end = (200.0 + 100.0 * r.cos() + 50.0 * r.sin(), 200.0 - 100.0 * r.sin() + 50.0 * r.cos());
|
||||
assert!(near(pts[0], 200.0, 200.0) && near(pts[1], end.0, end.1), "{pts:?} vs {end:?}");
|
||||
assert!(close(bbox_angle(&s, id), 30.0));
|
||||
set_angle(&mut s, 90.0);
|
||||
let p = constrain_click(&s, "shape.arc", params(4, 200.0, 200.0), click);
|
||||
let id = NodeId(s.execute("shape.arc", &p).unwrap()["id"].as_u64().unwrap());
|
||||
// The ends at opposite corners of the 100 × 50 box centered on the click, turned exactly.
|
||||
assert_eq!(path_points(&s, id), vec![Point::new(175.0, 250.0), Point::new(225.0, 150.0)]);
|
||||
let b = bounds(&s, id);
|
||||
assert!(close(b.x0, 175.0) && close(b.y0, 150.0) && close(b.x1, 225.0) && close(b.y1, 250.0), "turned about the click: {b:?}");
|
||||
assert_eq!(bbox_angle(&s, id), 90.0);
|
||||
}
|
||||
|
||||
/// `shape.arc` turns by an explicit `rotation` (clockwise) about `x1`, `y1` or about its reference
|
||||
/// point; a `rotation` that is not a number is refused and adds nothing.
|
||||
#[test]
|
||||
fn arc_rotation_turns_it_and_must_be_a_number() {
|
||||
let mut s = new_doc();
|
||||
let id = NodeId(s.execute("shape.arc", &json!({"x1": 0, "y1": 0, "x2": 10, "y2": 20, "rotation": 90})).unwrap()["id"].as_u64().unwrap());
|
||||
let pts = path_points(&s, id);
|
||||
assert!(near(pts[0], 0.0, 0.0) && near(pts[1], -20.0, 10.0), "{pts:?}");
|
||||
assert_eq!(bbox_angle(&s, id), -90.0, "a quarter turn clockwise");
|
||||
let id =
|
||||
NodeId(s.execute("shape.arc", &json!({"x": 50, "y": 50, "lengthX": 10, "lengthY": 20, "rotation": 360})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!(path_points(&s, id), vec![Point::new(50.0, 50.0), Point::new(60.0, 70.0)], "a whole turn leaves it upright");
|
||||
assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits());
|
||||
for bad in [json!("x"), Value::Null] {
|
||||
for p in
|
||||
[json!({"x1": 0, "y1": 0, "x2": 10, "y2": 20, "rotation": bad}), json!({"x": 0, "y": 0, "lengthX": 10, "lengthY": 20, "rotation": bad})]
|
||||
{
|
||||
assert!(s.execute("shape.arc", &p).is_err(), "{p}");
|
||||
assert_eq!(last_id(&s), id, "nothing added for {p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2658,6 +2658,66 @@ fn shape_arc_closed_along_y_closes_through_the_top_left_corner() {
|
||||
assert!((area - std::f64::consts::FRAC_PI_4).abs() < 0.01, "{area}");
|
||||
}
|
||||
|
||||
/// A `reference` that is not a whole number from 0 to 8, a `baseAlong` other than x or y, and a
|
||||
/// `slope` outside -100 to 100 are errors naming the key in both forms of `shape.arc`, null
|
||||
/// included, and nothing is drawn and no undo step is added.
|
||||
#[test]
|
||||
fn shape_arc_rejects_an_invalid_reference_base_along_or_slope() {
|
||||
let mut s = session();
|
||||
let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len();
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let (before, steps) = (objects(&s), undo(&s));
|
||||
let sized = json!({"x": 100, "y": 50, "lengthX": 80, "lengthY": 40});
|
||||
let ends = json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50});
|
||||
let mut cases = vec![];
|
||||
for v in [json!("4"), json!(-1), json!(4.5), json!(9), json!(9.0), json!(true), json!(null), json!([0])] {
|
||||
cases.push(("reference", "`reference` must be a whole number from 0 to 8".to_string(), v));
|
||||
}
|
||||
for v in [json!("z"), json!("yes"), json!(""), json!(1), json!(false), json!(null), json!({"axis": "y"})] {
|
||||
cases.push(("baseAlong", "`baseAlong` must be one of x, y".to_string(), v));
|
||||
}
|
||||
for (v, shown) in [(json!(150), "150"), (json!(-100.5), "-100.5")] {
|
||||
cases.push(("slope", format!("`slope` must be from -100 to 100, not {shown}"), v));
|
||||
}
|
||||
for form in [&sized, &ends] {
|
||||
for (key, want, v) in &cases {
|
||||
let mut p = form.clone();
|
||||
p[*key] = v.clone();
|
||||
let r = s.execute("shape.arc", &p);
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}");
|
||||
assert_eq!((objects(&s), undo(&s)), (before, steps), "{p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `shape.arc` takes each of the nine reference points (`4.0` as 4) and x or y in either case for
|
||||
/// `baseAlong`; a left-out `reference` is 0 and a left-out `baseAlong` is x.
|
||||
#[test]
|
||||
fn shape_arc_takes_every_reference_point_and_either_base_axis() {
|
||||
let mut s = session();
|
||||
let arc = |s: &mut Session, extra: serde_json::Value| {
|
||||
let mut p = json!({"x": 100, "y": 50, "lengthX": 80, "lengthY": 40});
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
let id = NodeId(s.execute("shape.arc", &p).unwrap()["id"].as_u64().unwrap());
|
||||
s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone()
|
||||
};
|
||||
let start = |path: &PathData| path.subpaths[0].anchors[0].p;
|
||||
for r in 0..=8u64 {
|
||||
let p = start(&arc(&mut s, json!({ "reference": r })));
|
||||
let (col, row) = ((r % 3) as f64, (r / 3) as f64);
|
||||
assert_eq!(p, Point::new(100.0 - 40.0 * col, 50.0 - 20.0 * row), "reference {r}");
|
||||
}
|
||||
assert_eq!(arc(&mut s, json!({"reference": 4.0})), arc(&mut s, json!({"reference": 4})));
|
||||
assert_eq!(arc(&mut s, json!({})), arc(&mut s, json!({"reference": 0, "baseAlong": "x"})));
|
||||
assert_eq!(arc(&mut s, json!({"baseAlong": "X"})), arc(&mut s, json!({"baseAlong": "x"})));
|
||||
assert_eq!(arc(&mut s, json!({"baseAlong": "Y"})), arc(&mut s, json!({"baseAlong": "y"})));
|
||||
assert_ne!(arc(&mut s, json!({"baseAlong": "y"})), arc(&mut s, json!({"baseAlong": "x"})));
|
||||
let ends = json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50, "slope": -100});
|
||||
assert!(s.execute("shape.arc", &ends).is_ok());
|
||||
}
|
||||
|
||||
/// A spiral dragged out with Alt pressed part way gets four more segments per wind as its outer end
|
||||
/// moves out. Ctrl/Cmd pressed part way fits the decay so the inner end keeps its distance from the
|
||||
/// center. The Spiral tool keeps both values for the next spiral.
|
||||
@@ -2822,7 +2882,7 @@ fn polar_grid_options_compound_fill_and_skew() {
|
||||
assert!(tips(&inward)[1..].iter().all(|t| t.x < 50.0), "counterclockwise of the top: {:?}", tips(&inward));
|
||||
}
|
||||
|
||||
/// A divider count written as a whole float (`3.0`) is the same as `3`; a fraction gives the default 5.
|
||||
/// A divider count written as a whole float (`3.0`) is the same as `3`.
|
||||
#[test]
|
||||
fn grid_divider_counts_accept_whole_floats() {
|
||||
let mut s = session();
|
||||
@@ -2834,8 +2894,30 @@ fn grid_divider_counts_accept_whole_floats() {
|
||||
let float = grid(&mut s, "shape.polarGrid", with(&size, json!({"concentric": 2.0, "radial": 3.0})));
|
||||
let int = grid(&mut s, "shape.polarGrid", with(&size, json!({"concentric": 2, "radial": 3})));
|
||||
assert_eq!(float.len(), int.len());
|
||||
let frac = grid(&mut s, "shape.rectangularGrid", with(&size, json!({"rows": 2.5, "columns": 2.5})));
|
||||
assert_eq!(frac.len(), 11);
|
||||
}
|
||||
|
||||
/// A divider count that is not a whole number of 0 or more (a fraction, a negative) is an error
|
||||
/// naming the key, and no grid is made; a left-out or null count is 5.
|
||||
#[test]
|
||||
fn grid_divider_counts_reject_fractions_and_negatives() {
|
||||
let mut s = session();
|
||||
let size = json!({"x": 0, "y": 0, "width": 100, "height": 100});
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let before = undo(&s);
|
||||
for (cmd, key, value, shown) in [
|
||||
("shape.rectangularGrid", "rows", json!(2.5), "2.5"),
|
||||
("shape.rectangularGrid", "columns", json!(-1), "-1"),
|
||||
("shape.polarGrid", "concentric", json!(0.5), "0.5"),
|
||||
("shape.polarGrid", "radial", json!(-3.0), "-3"),
|
||||
] {
|
||||
let r = s.execute(cmd, &with(&size, json!({ key: value })));
|
||||
let want = format!("`{key}` must be a whole number of at least 0, not {shown}");
|
||||
assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {key}={value}: {r:?}");
|
||||
assert_eq!(undo(&s), before, "{cmd} {key}={value}");
|
||||
}
|
||||
let omitted = grid(&mut s, "shape.rectangularGrid", size.clone());
|
||||
let null = grid(&mut s, "shape.rectangularGrid", with(&size, json!({"rows": null, "columns": null})));
|
||||
assert_eq!((omitted.len(), null.len()), (11, 11));
|
||||
}
|
||||
|
||||
/// The grid options are checked: a divider count or a skew is a number and a switch true or false,
|
||||
|
||||
@@ -746,6 +746,87 @@ fn package_copies_a_linked_pdf_page_as_it_is() {
|
||||
assert!(s.doc().unwrap().doc.has_placed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_copies_a_linked_eps_file_as_it_is() {
|
||||
let dir = Folder::new("package-placed-eps");
|
||||
let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n1 0 0 setrgbcolor\nnewpath 0 0 moveto 100 0 lineto 100 50 lineto 0 50 lineto closepath fill\nshowpage\n%%EOF\n";
|
||||
let src = dir.file("art/seal.eps");
|
||||
write(&src, eps);
|
||||
let mut s = session();
|
||||
let placed = run(&mut s, "file.place", json!({"path": src}));
|
||||
assert_eq!(placed["linked"], true, "{placed}");
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
|
||||
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone(), r["warnings"].clone()), (Some(1), json!([]), json!([])), "{r}");
|
||||
let root = dir.0.join("out/poster Folder");
|
||||
assert_eq!(std::fs::read(root.join("Links/seal.eps")).unwrap(), eps, "copied as it is");
|
||||
// The packaged document shows the copy.
|
||||
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
|
||||
let opened = open(&mut s, &root.join("poster.vectorcraft").to_string_lossy());
|
||||
assert_eq!(opened["missingLinks"], json!([]), "{opened}");
|
||||
assert!(s.doc().unwrap().doc.has_placed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_copies_a_linked_postscript_ai_file_the_document_holds_after_it_is_gone() {
|
||||
let dir = Folder::new("package-placed-ps-ai");
|
||||
let ai = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor\nnewpath 0 0 moveto 100 0 lineto 100 50 lineto 0 50 lineto closepath fill\nshowpage\n%%EOF\n";
|
||||
let src = dir.file("art/badge.ai");
|
||||
write(&src, ai);
|
||||
let mut s = session();
|
||||
let placed = run(&mut s, "file.place", json!({"path": src}));
|
||||
assert_eq!(placed["linked"], true, "{placed}");
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
|
||||
assert_eq!((r["links"].as_u64(), r["missingLinks"].clone()), (Some(1), json!([])), "{r}");
|
||||
let root = dir.0.join("out/poster Folder");
|
||||
assert_eq!(std::fs::read(root.join("Links/badge.ai")).unwrap(), ai, "the bytes the document holds");
|
||||
}
|
||||
|
||||
/// The PostScript bytes a document holds are copied for a placed document whose file name is one
|
||||
/// PostScript is read from, and not under any other name or for a linked image.
|
||||
#[test]
|
||||
fn package_copies_held_postscript_only_for_a_placed_document_with_a_postscript_name() {
|
||||
let dir = Folder::new("package-placed-ps-names");
|
||||
let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n1 0 0 setrgbcolor\nnewpath 0 0 moveto 100 0 lineto 100 50 lineto 0 50 lineto closepath fill\nshowpage\n%%EOF\n";
|
||||
let ai = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor\nnewpath 0 0 moveto 100 0 lineto 100 50 lineto 0 50 lineto closepath fill\nshowpage\n%%EOF\n";
|
||||
write(&dir.file("art/seal.eps"), eps);
|
||||
write(&dir.file("art/badge.ai"), ai);
|
||||
write(&dir.file("art/logo.png"), &png(8, 8, RED));
|
||||
let mut s = session();
|
||||
let seal = run(&mut s, "file.place", json!({"path": dir.file("art/seal.eps")}));
|
||||
assert_eq!(seal["linked"], true, "{seal}");
|
||||
let seal = vectorcraft_doc::NodeId(seal["ids"][0].as_u64().unwrap());
|
||||
run(&mut s, "file.place", json!({"path": dir.file("art/badge.ai")}));
|
||||
let logo = place(&mut s, &dir.file("art/logo.png"));
|
||||
let (tool, logo_ai) = (dir.file("art/tool.exe"), dir.file("art/logo.ai"));
|
||||
s.edit("names", |d, _| {
|
||||
let vectorcraft_doc::NodeKind::PlacedDocument(p) = &mut d.node_mut(seal).unwrap().kind else { panic!("not a placed document") };
|
||||
p.link.path = tool.clone();
|
||||
p.link.relative = None;
|
||||
let vectorcraft_doc::NodeKind::Image(im) = &mut d.node_mut(logo).unwrap().kind else { panic!("not an image") };
|
||||
im.link.as_mut().unwrap().path = logo_ai.clone();
|
||||
im.link.as_mut().unwrap().relative = None;
|
||||
let key = im.key.clone();
|
||||
d.images
|
||||
.insert(key, vectorcraft_doc::ImageBlob { mime: "application/postscript".into(), bytes: std::sync::Arc::new(eps.to_vec()), proxy: None });
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
std::fs::remove_dir_all(dir.0.join("art")).unwrap();
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out")}));
|
||||
assert_eq!(r["links"].as_u64(), Some(1), "{r}");
|
||||
let mut missing: Vec<&str> = r["missingLinks"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
missing.sort_unstable();
|
||||
assert_eq!(missing, ["logo.ai", "tool.exe"], "{r}");
|
||||
let links = dir.0.join("out/poster Folder/Links");
|
||||
assert_eq!(std::fs::read(links.join("badge.ai")).unwrap(), ai, "a PostScript .ai under its own name");
|
||||
assert!(!links.join("tool.exe").exists(), "PostScript under a name it isn't read from");
|
||||
assert!(!links.join("logo.ai").exists(), "PostScript held for a linked image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_copies_the_fonts_of_the_type_on_a_linked_pdf_page() {
|
||||
let dir = Folder::new("package-placed-pdf-type");
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
//! Pathfinder on clip groups (#8093): a clip group's members take part only where its clipping
|
||||
//! path shows them, so Divide and the other operations leave out the hidden art.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_geom::{FillRule, PathData, Rect};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn id(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}")))
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64, fill: Color) -> NodeId {
|
||||
let r = id(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap());
|
||||
s.edit("fill", |d, _| {
|
||||
d.node_mut(r).unwrap().appearance.set_fill(Paint::solid(fill));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
fn clip(s: &mut Session, ids: &[NodeId]) -> NodeId {
|
||||
id(&s.execute("object.clippingMask.make", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap())
|
||||
}
|
||||
|
||||
fn red() -> Color {
|
||||
Color::rgb(1.0, 0.0, 0.0)
|
||||
}
|
||||
|
||||
fn blue() -> Color {
|
||||
Color::rgb(0.0, 0.0, 1.0)
|
||||
}
|
||||
|
||||
fn green() -> Color {
|
||||
Color::rgb(0.0, 1.0, 0.0)
|
||||
}
|
||||
|
||||
/// A red square at (0, 0) and a blue one at (50, 50), both 100 pt, clipped by a 100 pt square
|
||||
/// mask at (25, 25): the clip group. The mask shows 8750 pt² of them.
|
||||
fn clipped_pair(s: &mut Session) -> NodeId {
|
||||
let a = rect(s, 0.0, 0.0, 100.0, 100.0, red());
|
||||
let b = rect(s, 50.0, 50.0, 100.0, 100.0, blue());
|
||||
let mask = rect(s, 25.0, 25.0, 100.0, 100.0, green());
|
||||
clip(s, &[a, b, mask])
|
||||
}
|
||||
|
||||
/// The shapes `op` makes of the selection, the members of the group it makes or the one shape:
|
||||
/// (fill, path, rule) each.
|
||||
fn pieces(s: &mut Session, op: &str) -> Vec<(Paint, PathData, FillRule)> {
|
||||
let r = s.execute(op, &json!({})).unwrap();
|
||||
let g = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).cloned().unwrap();
|
||||
let shape = |n: &vectorcraft_doc::Node| match &n.kind {
|
||||
NodeKind::Path { path, rule, .. } => (n.appearance.fill_paint(), path.clone(), *rule),
|
||||
NodeKind::Compound { children, rule } => {
|
||||
let subs = children.iter().flat_map(|c| c.path_data().unwrap().subpaths.clone()).collect();
|
||||
(n.appearance.fill_paint(), PathData::new(subs), *rule)
|
||||
}
|
||||
k => panic!("not a path: {k:?}"),
|
||||
};
|
||||
match &g.kind {
|
||||
NodeKind::Group { children, .. } => children.iter().map(|c| shape(c)).collect(),
|
||||
_ => vec![shape(&g)],
|
||||
}
|
||||
}
|
||||
|
||||
fn area(p: &(Paint, PathData, FillRule)) -> f64 {
|
||||
vectorcraft_pathops::area(&p.1, p.2)
|
||||
}
|
||||
|
||||
fn bounds(ps: &[(Paint, PathData, FillRule)]) -> Rect {
|
||||
ps.iter().filter_map(|p| p.1.bounds()).reduce(|a, b| a.union(b)).unwrap()
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, ids: &[NodeId]) {
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
}
|
||||
|
||||
fn assert_inside(r: Rect, within: Rect) {
|
||||
assert!(within.inflate(1e-6, 1e-6).contains_rect(r), "{r:?} reaches out of {within:?}");
|
||||
}
|
||||
|
||||
/// The issue's case: Divide on a clip group gives the pieces the mask shows, cut along it, and the
|
||||
/// hidden art goes.
|
||||
#[test]
|
||||
fn divide_on_a_clip_group_keeps_only_what_the_mask_shows() {
|
||||
let mut s = session();
|
||||
let g = clipped_pair(&mut s);
|
||||
select(&mut s, &[g]);
|
||||
let ps = pieces(&mut s, "object.pathfinder.divide");
|
||||
assert_eq!(ps.len(), 3, "red alone, the overlap and blue alone: {ps:?}");
|
||||
let total: f64 = ps.iter().map(area).sum();
|
||||
assert!((total - 8750.0).abs() < 1.0, "the visible area, not the whole art: {total}");
|
||||
assert_inside(bounds(&ps), Rect::new(25.0, 25.0, 125.0, 125.0));
|
||||
let blue: f64 = ps.iter().filter(|p| p.0 == Paint::solid(blue())).map(area).sum();
|
||||
assert!((blue - 5625.0).abs() < 1.0, "the overlap takes the front (blue) fill: {blue}");
|
||||
assert!(ps.iter().all(|p| p.0 != Paint::solid(green())), "the clipping path adds no piece: {ps:?}");
|
||||
}
|
||||
|
||||
/// An irregular mask: a square clipped by a circle divides into a disc.
|
||||
#[test]
|
||||
fn divide_cuts_along_a_curved_clipping_path() {
|
||||
let mut s = session();
|
||||
let square = rect(&mut s, 100.0, 100.0, 300.0, 300.0, red());
|
||||
let circle = id(&s.execute("shape.ellipse", &json!({"x": 150, "y": 150, "width": 200, "height": 200})).unwrap());
|
||||
let g = clip(&mut s, &[square, circle]);
|
||||
select(&mut s, &[g]);
|
||||
let ps = pieces(&mut s, "object.pathfinder.divide");
|
||||
assert_eq!(ps.len(), 1, "{ps:?}");
|
||||
let disc = std::f64::consts::PI * 100.0 * 100.0;
|
||||
assert!((area(&ps[0]) - disc).abs() < disc * 1e-3, "{} vs {disc}", area(&ps[0]));
|
||||
assert_inside(bounds(&ps), Rect::new(150.0, 150.0, 350.0, 350.0));
|
||||
}
|
||||
|
||||
/// A clip group inside a clip group: its members show only where both masks do.
|
||||
#[test]
|
||||
fn nested_clip_groups_cut_by_both_masks() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 200.0, 200.0, red());
|
||||
let inner_mask = rect(&mut s, 0.0, 0.0, 100.0, 200.0, green());
|
||||
let inner = clip(&mut s, &[a, inner_mask]);
|
||||
let outer_mask = rect(&mut s, 0.0, 50.0, 200.0, 100.0, green());
|
||||
let outer = clip(&mut s, &[inner, outer_mask]);
|
||||
select(&mut s, &[outer]);
|
||||
let ps = pieces(&mut s, "object.pathfinder.divide");
|
||||
assert_eq!(ps.len(), 1, "{ps:?}");
|
||||
assert!((area(&ps[0]) - 10000.0).abs() < 1.0, "100 × 100 shows: {}", area(&ps[0]));
|
||||
assert_inside(bounds(&ps), Rect::new(0.0, 50.0, 100.0, 150.0));
|
||||
}
|
||||
|
||||
/// A member the mask hides altogether gives no piece.
|
||||
#[test]
|
||||
fn a_member_the_mask_hides_gives_no_piece() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
|
||||
let b = rect(&mut s, 300.0, 300.0, 100.0, 100.0, blue());
|
||||
let mask = rect(&mut s, 0.0, 0.0, 150.0, 150.0, green());
|
||||
let g = clip(&mut s, &[a, b, mask]);
|
||||
select(&mut s, &[g]);
|
||||
let ps = pieces(&mut s, "object.pathfinder.divide");
|
||||
assert_eq!(ps.len(), 1, "only the red square shows: {ps:?}");
|
||||
assert_eq!(ps[0].0, Paint::solid(red()));
|
||||
}
|
||||
|
||||
/// A cutting line in a clip group cuts only where the mask shows it: its hidden part leaves the
|
||||
/// other selected art alone.
|
||||
#[test]
|
||||
fn a_clipped_cutting_line_cuts_only_where_it_shows() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
|
||||
let line = id(&s.execute("shape.line", &json!({"x1": 50, "y1": -50, "x2": 50, "y2": 400})).unwrap());
|
||||
let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0, green());
|
||||
let g = clip(&mut s, &[a, line, mask]);
|
||||
let other = rect(&mut s, 0.0, 200.0, 100.0, 100.0, blue());
|
||||
select(&mut s, &[g, other]);
|
||||
let ps = pieces(&mut s, "object.pathfinder.divide");
|
||||
let red = ps.iter().filter(|p| p.0 == Paint::solid(red())).count();
|
||||
let blue = ps.iter().filter(|p| p.0 == Paint::solid(blue())).count();
|
||||
assert_eq!((red, blue), (2, 1), "the line halves the red square, not the blue one: {ps:?}");
|
||||
}
|
||||
|
||||
/// Every Shape Mode and Pathfinder button takes the members as the mask shows them (#3367 asks
|
||||
/// this of Merge). The mask, 100 × 60 pt at (25, 25), cuts through the squares' overlap: it shows
|
||||
/// 4500 pt² of red, 2625 pt² of blue and 1750 pt² of their overlap.
|
||||
#[test]
|
||||
fn every_operation_takes_only_what_the_mask_shows() {
|
||||
for (op, want) in [
|
||||
("unite", Some(5375.0)),
|
||||
("minusFront", Some(2750.0)),
|
||||
("minusBack", Some(875.0)),
|
||||
("intersect", Some(1750.0)),
|
||||
("exclude", Some(3625.0)),
|
||||
("trim", Some(5375.0)),
|
||||
("merge", Some(5375.0)),
|
||||
("crop", Some(1750.0)),
|
||||
("outline", None),
|
||||
] {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
|
||||
let b = rect(&mut s, 50.0, 50.0, 100.0, 100.0, blue());
|
||||
let mask = rect(&mut s, 25.0, 25.0, 100.0, 60.0, green());
|
||||
let g = clip(&mut s, &[a, b, mask]);
|
||||
select(&mut s, &[g]);
|
||||
let ps = pieces(&mut s, &format!("object.pathfinder.{op}"));
|
||||
assert_inside(bounds(&ps), Rect::new(25.0, 25.0, 125.0, 85.0));
|
||||
if let Some(want) = want {
|
||||
let total: f64 = ps.iter().map(area).sum();
|
||||
assert!((total - want).abs() < 1.0, "{op}: {total}, want {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Among other objects a clip group acts as one shape: the union of what its mask shows.
|
||||
#[test]
|
||||
fn a_clip_group_among_other_objects_is_the_area_its_mask_shows() {
|
||||
let mut s = session();
|
||||
let g = clipped_pair(&mut s);
|
||||
let other = rect(&mut s, 300.0, 0.0, 50.0, 50.0, blue());
|
||||
select(&mut s, &[g, other]);
|
||||
let ps = pieces(&mut s, "object.pathfinder.unite");
|
||||
let total: f64 = ps.iter().map(area).sum();
|
||||
assert!((total - (8750.0 + 2500.0)).abs() < 1.0, "{total}");
|
||||
}
|
||||
|
||||
/// Among other objects a clip group takes the style of its top member that shows: a member the
|
||||
/// mask hides paints nothing.
|
||||
#[test]
|
||||
fn a_hidden_top_member_gives_no_style() {
|
||||
let mut s = session();
|
||||
// Below the clip group, so the result takes the group's style.
|
||||
let other = rect(&mut s, 50.0, 50.0, 100.0, 100.0, green());
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
|
||||
let b = rect(&mut s, 300.0, 300.0, 100.0, 100.0, blue());
|
||||
let mask = rect(&mut s, 0.0, 0.0, 150.0, 150.0, green());
|
||||
let g = clip(&mut s, &[a, b, mask]);
|
||||
select(&mut s, &[other, g]);
|
||||
let ps = pieces(&mut s, "object.pathfinder.unite");
|
||||
assert_eq!(ps.len(), 1, "{ps:?}");
|
||||
assert_eq!(ps[0].0, Paint::solid(red()), "not the hidden blue member's fill");
|
||||
assert!((area(&ps[0]) - 17500.0).abs() < 1.0, "{}", area(&ps[0]));
|
||||
}
|
||||
|
||||
/// A selection the masks hide altogether says so.
|
||||
#[test]
|
||||
fn art_the_masks_hide_altogether_is_refused_with_a_reason() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 300.0, 300.0, 100.0, 100.0, red());
|
||||
let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0, green());
|
||||
let g = clip(&mut s, &[a, mask]);
|
||||
select(&mut s, &[g]);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("clipping masks hide"), "{e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing changes");
|
||||
}
|
||||
|
||||
/// A clip group its mask hides altogether, selected with a red square at (0, 0) and a blue one at
|
||||
/// (50, 50), each 100 pt, at `position` in the stacking order (0: at the back).
|
||||
fn with_a_hidden_clip_group(s: &mut Session, position: usize) {
|
||||
let mut ids = vec![];
|
||||
for i in 0..3 {
|
||||
if i == position {
|
||||
// Two members, so among other objects the group is one shape: their union.
|
||||
let a = rect(s, 300.0, 300.0, 100.0, 100.0, green());
|
||||
let b = rect(s, 450.0, 300.0, 100.0, 100.0, green());
|
||||
let mask = rect(s, 0.0, 0.0, 100.0, 100.0, green());
|
||||
ids.push(clip(s, &[a, b, mask]));
|
||||
} else {
|
||||
let at = if ids.len() == usize::from(position == 0) { 0.0 } else { 50.0 };
|
||||
ids.push(rect(s, at, at, 100.0, 100.0, if at == 0.0 { red() } else { blue() }));
|
||||
}
|
||||
}
|
||||
select(s, &ids);
|
||||
}
|
||||
|
||||
/// A selected object its masks hide altogether is an empty operand: Intersect, Minus Front with
|
||||
/// it at the back, Minus Back with it in front and Crop with it on top give nothing, and the other
|
||||
/// operations make what they make without it.
|
||||
#[test]
|
||||
fn a_hidden_operand_is_an_empty_shape_where_it_changes_the_result() {
|
||||
for (op, position) in [("intersect", 1), ("minusFront", 0), ("minusBack", 2), ("crop", 2)] {
|
||||
let mut s = session();
|
||||
with_a_hidden_clip_group(&mut s, position);
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute(&format!("object.pathfinder.{op}"), &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("empty result"), "{op}: {e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{op}: nothing changes");
|
||||
}
|
||||
for (op, position, want) in [("unite", 2, 17500.0), ("exclude", 2, 15000.0), ("minusFront", 2, 7500.0), ("minusBack", 0, 7500.0)] {
|
||||
let mut s = session();
|
||||
with_a_hidden_clip_group(&mut s, position);
|
||||
let ps = pieces(&mut s, &format!("object.pathfinder.{op}"));
|
||||
let total: f64 = ps.iter().map(area).sum();
|
||||
assert!((total - want).abs() < 1.0, "{op}: {total}, want {want}");
|
||||
assert!(ps.iter().all(|p| p.0 != Paint::solid(green())), "{op}: the hidden group's style: {ps:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A clip group whose clipping path clips by nothing (here an empty group) hides its members, as on
|
||||
/// the canvas: they are a hidden operand too, not left out of the selection.
|
||||
#[test]
|
||||
fn a_clipping_path_that_clips_by_nothing_hides_the_members() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0, red());
|
||||
let b = rect(&mut s, 50.0, 50.0, 100.0, 100.0, blue());
|
||||
let m1 = rect(&mut s, 300.0, 300.0, 100.0, 100.0, green());
|
||||
let m2 = rect(&mut s, 450.0, 300.0, 100.0, 100.0, green());
|
||||
let mask = rect(&mut s, 300.0, 300.0, 300.0, 100.0, green());
|
||||
let g = clip(&mut s, &[m1, m2, mask]);
|
||||
s.edit("empty clipping path", |d, _| {
|
||||
let empty = vectorcraft_doc::Node::group(d.alloc_id(), vec![]);
|
||||
let NodeKind::Group { children, .. } = &mut d.node_mut(g).unwrap().kind else { panic!("not a group") };
|
||||
children[0] = std::sync::Arc::new(empty);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
select(&mut s, &[a, b, g]);
|
||||
let e = s.execute("object.pathfinder.intersect", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("empty result"), "not the squares' overlap: {e}");
|
||||
select(&mut s, &[g]);
|
||||
let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("clipping masks hide"), "{e}");
|
||||
}
|
||||
@@ -926,6 +926,190 @@ fn a_pdf_compatible_ai_file_places_linked_like_a_pdf() {
|
||||
assert_eq!(images, 0);
|
||||
}
|
||||
|
||||
/// An EPS file written by hand at `path`: a 100×50 bounding box holding a 40×20 rectangle of `rgb`
|
||||
/// from (20, 10), and `extra` comment lines (which change the file's size).
|
||||
fn eps_source(path: &str, rgb: [u8; 3], extra: usize) {
|
||||
let [r, g, b] = rgb.map(|c| c as f64 / 255.0);
|
||||
let mut ps = format!(
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n{r} {g} {b} setrgbcolor\nnewpath 20 10 moveto 60 10 lineto 60 30 lineto 20 30 lineto closepath fill\n"
|
||||
);
|
||||
for i in 0..extra {
|
||||
ps.push_str(&format!("% line {i}\n"));
|
||||
}
|
||||
ps.push_str("showpage\n%%EOF\n");
|
||||
write(path, ps.as_bytes());
|
||||
}
|
||||
|
||||
/// An EPS file at `path` written by VectorCraft's EPS export: a 100×50 artboard filled with `rgb`
|
||||
/// (`extra` more rectangles change the file's size).
|
||||
fn exported_eps(path: &str, rgb: [u8; 3], extra: usize) {
|
||||
let mut d = Document::new(100.0, 50.0);
|
||||
let layer = d.layers[0].id;
|
||||
for _ in 0..=extra {
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(layer), usize::MAX, Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)), look(rgb))).unwrap();
|
||||
}
|
||||
write(path, &cmd::fileio::encode_all(&d, "eps", &json!({})).unwrap().files[0].1);
|
||||
}
|
||||
|
||||
/// The kinds of `n` and everything inside it, in order.
|
||||
fn kinds(n: &Node) -> Vec<&'static str> {
|
||||
let mut k = vec![];
|
||||
n.walk(&mut |c| k.push(c.kind_label()));
|
||||
k
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_link_an_eps_file_places_linked_framed_as_without_link() {
|
||||
let dir = Folder::new("placed-eps-linked");
|
||||
let src = dir.file("badge.eps");
|
||||
eps_source(&src, RED, 0);
|
||||
let mut s = session();
|
||||
let embedded = |s: &mut Session, crop: &str| {
|
||||
let r = s.execute("file.place", &json!({"path": src, "link": false, "crop": crop, "at": [200, 150]})).unwrap();
|
||||
assert_eq!(r["linked"], false, "{r}");
|
||||
let n = s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).unwrap().clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
n
|
||||
};
|
||||
let copy = embedded(&mut s, "crop");
|
||||
let id = place(&mut s, &src);
|
||||
let p = placed(&s, id);
|
||||
assert_eq!((p.link.path.as_str(), p.link.page, p.bounding), (src.as_str(), Some(1), false), "{p:?}");
|
||||
assert!((p.width - 100.0).abs() < 1e-6 && (p.height - 50.0).abs() < 1e-6, "{p:?}");
|
||||
assert_eq!(Some(bounds(&s, id)), copy.geometric_bounds(), "the bounding box, as without Link");
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
let row = &s.execute("links.list", &json!({})).unwrap()["links"][0];
|
||||
assert_eq!((row["format"].as_str(), row["document"].as_bool(), row["status"].as_str()), (Some("EPS"), Some(true), Some("ok")), "{row}");
|
||||
assert_eq!(s.doc().unwrap().doc.images[&p.key].mime, "application/postscript");
|
||||
// Break Link gives the group placing it without Link gives.
|
||||
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!(r["embedded"], json!([id.0]), "{r}");
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert_eq!((kinds(&n), n.geometric_bounds()), (kinds(©), copy.geometric_bounds()));
|
||||
assert!(!s.doc().unwrap().doc.has_placed() && near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Bounding Box: the art's bounds, as without Link.
|
||||
let copy = embedded(&mut s, "bounding");
|
||||
let r = s.execute("file.place", &json!({"path": src, "crop": "bounding", "at": [200, 150]})).unwrap();
|
||||
assert_eq!(r["linked"], true, "{r}");
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let p = placed(&s, id);
|
||||
assert!(p.bounding && (p.width - 40.0).abs() < 1e-6 && (p.height - 20.0).abs() < 1e-6, "{p:?}");
|
||||
assert_eq!(Some(bounds(&s, id)), copy.geometric_bounds());
|
||||
// Object › Expand gives it too (the placed object is selected).
|
||||
let r = s.execute("object.expand", &json!({})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
assert_eq!((kinds(&n), n.geometric_bounds()), (kinds(©), copy.geometric_bounds()), "{r}");
|
||||
// Placed from its bytes, it is embedded.
|
||||
let data = vectorcraft_format::base64_encode(&std::fs::read(&src).unwrap());
|
||||
let r = s.execute("file.place", &json!({"name": "badge.eps", "dataBase64": data})).unwrap();
|
||||
assert_eq!(r["linked"], false, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_eps_file_is_modified_and_update_links_reads_it_again() {
|
||||
let dir = Folder::new("placed-eps-update");
|
||||
let src = dir.file("flyer.eps");
|
||||
exported_eps(&src, RED, 0);
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &src);
|
||||
exported_eps(&src, BLUE, 1);
|
||||
assert_eq!(s.execute("links.check", &json!({})).unwrap()["links"][0]["status"], "modified");
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "shows the file as it read it");
|
||||
let u = s.execute("links.update", &json!({})).unwrap();
|
||||
assert_eq!(u["updated"], json!([id.0]), "{u}");
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
assert_eq!(s.execute("links.check", &json!({})).unwrap()["modified"], 0);
|
||||
// Relinked to another EPS file, it shows that file's art.
|
||||
let other = dir.file("other.eps");
|
||||
eps_source(&other, RED, 0);
|
||||
let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other})).unwrap();
|
||||
assert_eq!(r["relinked"], json!([id.0]), "{r}");
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
// A file it can't show is refused.
|
||||
let notes = dir.file("notes.txt");
|
||||
write(¬es, b"not a page");
|
||||
let e = s.execute("links.relink", &json!({"ids": [id.0], "path": notes})).unwrap_err().to_string();
|
||||
assert!(e.contains("isn't a VectorCraft document"), "{e}");
|
||||
assert_eq!(placed(&s, id).link.path, other);
|
||||
// Its file replaced by one that isn't PostScript: updating keeps the art it shows.
|
||||
write(&other, b"not a page");
|
||||
let _ = s.execute("links.update", &json!({}));
|
||||
assert_eq!(placed(&s, id).link.path, other);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_linked_eps_file_outputs_as_vectors_and_shows_its_preview_without_its_file() {
|
||||
let dir = Folder::new("placed-eps-outputs");
|
||||
let src = dir.file("seal.eps");
|
||||
// Content of its own: files read are cached by content, and this one is removed.
|
||||
eps_source(&src, RED, 3);
|
||||
let bytes = std::fs::read(&src).unwrap();
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &src);
|
||||
let doc_path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &doc_path);
|
||||
// Without its file: missing, shown and output as its preview, and not embedded.
|
||||
std::fs::remove_file(&src).unwrap();
|
||||
open(&mut s, &doc_path);
|
||||
let key = placed(&s, id).key;
|
||||
assert!(s.doc().unwrap().doc.images[&key].is_proxy(), "opened with the preview only");
|
||||
let row = &s.execute("links.list", &json!({})).unwrap()["links"][0];
|
||||
assert_eq!((row["format"].as_str(), row["status"].as_str()), (Some("EPS"), Some("missing")), "{row}");
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED), "the preview");
|
||||
let pdf = s.execute("document.serialize", &json!({"format": "pdf"})).unwrap();
|
||||
assert!(pdf["warnings"].to_string().contains("1 placed document output as its preview"), "{}", pdf["warnings"]);
|
||||
let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
||||
assert_eq!((r["embedded"].clone(), r["missing"].clone()), (json!([]), json!([id.0])), "{r}");
|
||||
assert!(s.doc().unwrap().doc.has_placed());
|
||||
// The file back: output reads it again, its paths and not the preview.
|
||||
write(&src, &bytes);
|
||||
assert_eq!(s.execute("links.check", &json!({})).unwrap()["links"][0]["status"], "ok");
|
||||
let pdf = s.execute("document.serialize", &json!({"format": "pdf"})).unwrap();
|
||||
assert_eq!(pdf["warnings"], json!([]), "{}", pdf["warnings"]);
|
||||
let (images, paths) = pdf_contents(&decode(&pdf));
|
||||
assert_eq!(images, 0, "no image in the PDF");
|
||||
assert!(paths > 0);
|
||||
// Include Linked Files keeps the EPS file itself.
|
||||
let full = file_json(&decode(&s.execute("document.serialize", &json!({"format": "vectorcraft", "includeLinked": true})).unwrap()));
|
||||
assert_eq!((full["images"][&key]["proxy"].clone(), full["images"][&key]["mime"].as_str()), (Value::Null, Some("application/postscript")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_postscript_ai_file_places_linked_like_an_eps_file() {
|
||||
let dir = Folder::new("placed-ps-ai-linked");
|
||||
let src = dir.file("badge.ai");
|
||||
eps_source(&src, RED, 0);
|
||||
let mut s = session();
|
||||
let id = place(&mut s, &src);
|
||||
assert_eq!(placed(&s, id).link.path, src);
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
|
||||
let row = &s.execute("links.list", &json!({})).unwrap()["links"][0];
|
||||
assert_eq!(row["format"], "PostScript", "{row}");
|
||||
eps_source(&src, BLUE, 5);
|
||||
let u = s.execute("links.update", &json!({})).unwrap();
|
||||
assert_eq!(u["updated"], json!([id.0]), "{u}");
|
||||
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
|
||||
// Saved with its preview only and reopened without its file, it is still listed as PostScript.
|
||||
let bytes = std::fs::read(&src).unwrap();
|
||||
let doc_path = dir.file("poster.vectorcraft");
|
||||
save(&mut s, &doc_path);
|
||||
std::fs::remove_file(&src).unwrap();
|
||||
open(&mut s, &doc_path);
|
||||
assert!(s.doc().unwrap().doc.images[&placed(&s, id).key].is_proxy(), "opened with the preview only");
|
||||
let row = &s.execute("links.list", &json!({})).unwrap()["links"][0];
|
||||
assert_eq!((row["format"].as_str(), row["status"].as_str()), (Some("PostScript"), Some("missing")), "{row}");
|
||||
write(&src, &bytes);
|
||||
// The same bytes named .eps are read as an EPS file: a file of their own, not the .ai's art.
|
||||
let eps = dir.file("badge.eps");
|
||||
write(&eps, &std::fs::read(&src).unwrap());
|
||||
let other = place(&mut s, &eps);
|
||||
assert_ne!(placed(&s, other).key, placed(&s, id).key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_document_inside_a_placed_document_outputs_from_its_own_file() {
|
||||
let dir = Folder::new("placed-nested");
|
||||
|
||||
@@ -257,22 +257,12 @@ pub(crate) fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
|
||||
/// Hexadecimal digits (whitespace ignored, an odd last digit padded with 0); `None` on others.
|
||||
pub(crate) fn hex_decode(body: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(body.len() / 2);
|
||||
let mut high: Option<u8> = None;
|
||||
for &b in body {
|
||||
if is_space(b) {
|
||||
continue;
|
||||
}
|
||||
let v = char::from(b).to_digit(16)? as u8;
|
||||
match high.take() {
|
||||
Some(h) => out.push(h << 4 | v),
|
||||
None => high = Some(v),
|
||||
}
|
||||
// Callers pass an already-delimited body. Do not let the filter decoder's EOD
|
||||
// handling silently accept a stray terminator or discard bytes after it.
|
||||
if body.contains(&b'>') {
|
||||
return None;
|
||||
}
|
||||
if let Some(h) = high {
|
||||
out.push(h << 4);
|
||||
}
|
||||
Some(out)
|
||||
craft_stream_codecs::asciihex::decode(body, body.len().div_ceil(2)).ok()
|
||||
}
|
||||
|
||||
/// A number token (`12`, `-3.5`, `.5`, `1e-3`, `16#ff`), or `None`.
|
||||
@@ -310,4 +300,33 @@ mod tests {
|
||||
assert!(number("16#-ff").is_none());
|
||||
assert!(matches!(number("16#ff"), Some(Obj::Int(255))));
|
||||
}
|
||||
#[test]
|
||||
fn shared_hex_decode_keeps_body_boundaries_and_odd_nibbles() {
|
||||
assert_eq!(hex_decode(b" 4\t1\n4\r2\x0c4\0"), Some(vec![0x41, 0x42, 0x40]));
|
||||
assert_eq!(hex_decode(b""), Some(vec![]));
|
||||
for invalid in [b"41>42".as_slice(), b">", b"4g", b"4\x0b1", b"\xff"] {
|
||||
assert_eq!(hex_decode(invalid), None);
|
||||
}
|
||||
// Every byte pairs with each possible nibble, including all whitespace
|
||||
// and invalid-byte combinations; this is the former body-only contract.
|
||||
for first in 0..=255u8 {
|
||||
for second in 0..=255u8 {
|
||||
let input = [first, second];
|
||||
let mut digits = Vec::new();
|
||||
let mut valid = true;
|
||||
for b in input {
|
||||
if is_space(b) {
|
||||
continue;
|
||||
}
|
||||
match char::from(b).to_digit(16) {
|
||||
Some(d) => digits.push(d as u8),
|
||||
None => valid = false,
|
||||
}
|
||||
}
|
||||
let expected =
|
||||
if !valid { None } else { Some(digits.chunks(2).map(|pair| (pair[0] << 4) | pair.get(1).copied().unwrap_or(0)).collect()) };
|
||||
assert_eq!(hex_decode(&input), expected, "{input:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,6 +81,7 @@ pub(super) fn make_face(bytes: FontBytes, index: u32, spec: FaceStyle, path: Opt
|
||||
svg_glyphs,
|
||||
gsub: std::sync::OnceLock::new(),
|
||||
unencoded: std::sync::OnceLock::new(),
|
||||
char_list: std::sync::OnceLock::new(),
|
||||
named_chars: std::sync::OnceLock::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -206,6 +206,8 @@ pub struct FontFace {
|
||||
pub(super) gsub: std::sync::OnceLock<super::gsub::GsubIndex>,
|
||||
/// [`Self::unencoded_glyphs`], read once.
|
||||
pub(super) unencoded: std::sync::OnceLock<std::sync::Arc<[u32]>>,
|
||||
/// [`Self::mapped_chars`], read once.
|
||||
pub(super) char_list: std::sync::OnceLock<Arc<[(char, u32)]>>,
|
||||
/// [`Self::name_owner`]'s glyph names to characters, read once.
|
||||
pub(super) named_chars: std::sync::OnceLock<std::collections::HashMap<String, char>>,
|
||||
}
|
||||
@@ -368,11 +370,20 @@ impl FontFace {
|
||||
}
|
||||
/// Every mapped character and its glyph id, sorted by code point (the Glyphs panel).
|
||||
pub fn chars(&self) -> Vec<(char, u32)> {
|
||||
let Some(f) = self.skrifa() else { return vec![] };
|
||||
let mut v: Vec<(char, u32)> = f.charmap().mappings().filter_map(|(cp, g)| char::from_u32(cp).map(|c| (c, g.to_u32()))).collect();
|
||||
v.sort_unstable_by_key(|x| x.0);
|
||||
v.dedup_by_key(|x| x.0);
|
||||
v
|
||||
self.mapped_chars().to_vec()
|
||||
}
|
||||
/// [`Self::chars`], read from the font once for the face and shared by every caller. Empty when
|
||||
/// the font cannot be read or maps no character.
|
||||
pub fn mapped_chars(&self) -> Arc<[(char, u32)]> {
|
||||
self.char_list
|
||||
.get_or_init(|| {
|
||||
let Some(f) = self.skrifa() else { return Arc::from([]) };
|
||||
let mut v: Vec<(char, u32)> = f.charmap().mappings().filter_map(|(cp, g)| char::from_u32(cp).map(|c| (c, g.to_u32()))).collect();
|
||||
v.sort_unstable_by_key(|x| x.0);
|
||||
v.dedup_by_key(|x| x.0);
|
||||
v.into()
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
/// Advance width of glyph `gid` in font units.
|
||||
pub fn advance(&self, gid: u32) -> f64 {
|
||||
|
||||
@@ -1505,6 +1505,52 @@ fn remapped_source_sans(family: &str, postscript: &str, mapping: &[(char, char)]
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`large_cmap_font`].
|
||||
pub const LARGE_CMAP_FAMILY: &str = "Largecmap Sans";
|
||||
|
||||
/// The family of [`cmapless_font`].
|
||||
pub const CMAPLESS_FAMILY: &str = "Cmapless Sans";
|
||||
|
||||
/// The bundled Source Sans 3 Regular with a `cmap` of `count` characters from U+20000 up, about as
|
||||
/// many as a large CJK font maps when `count` is 50,000. Each character maps to the font's next
|
||||
/// glyph in turn after `.notdef`, so most glyphs have several characters.
|
||||
pub fn large_cmap_font(count: u32) -> Option<Vec<u8>> {
|
||||
use write_fonts::tables::cmap::Cmap;
|
||||
|
||||
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let font = skrifa::FontRef::new(BASE).ok()?;
|
||||
let glyphs = u32::from(font.maxp().ok()?.num_glyphs()).checked_sub(1).filter(|n| *n > 0)?;
|
||||
let mappings = (0..count).map(|i| Some((char::from_u32(0x2_0000_u32.checked_add(i)?)?, write_fonts::types::GlyphId::new(1 + i % glyphs))));
|
||||
let cmap = Cmap::from_mappings(mappings.collect::<Option<Vec<_>>>()?).ok()?;
|
||||
source_sans_with_cmap(LARGE_CMAP_FAMILY, "LargecmapSans-Regular", Some(&cmap))
|
||||
}
|
||||
|
||||
/// The bundled Source Sans 3 Regular without a `cmap` table: it maps no character.
|
||||
pub fn cmapless_font() -> Option<Vec<u8>> {
|
||||
source_sans_with_cmap(CMAPLESS_FAMILY, "CmaplessSans-Regular", None)
|
||||
}
|
||||
|
||||
/// The bundled Source Sans 3 Regular named `family`, with `cmap` in place of its own (none when
|
||||
/// `cmap` is `None`), and its other tables kept.
|
||||
fn source_sans_with_cmap(family: &str, postscript: &str, cmap: Option<&write_fonts::tables::cmap::Cmap>) -> Option<Vec<u8>> {
|
||||
const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let font = skrifa::FontRef::new(BASE).ok()?;
|
||||
let full = format!("{family} Regular");
|
||||
let name = name_table(&[(1, family), (2, "Regular"), (4, full.as_str()), (6, postscript)])?;
|
||||
let mut builder = FontBuilder::new();
|
||||
if let Some(cmap) = cmap {
|
||||
builder.add_table(cmap).ok()?;
|
||||
}
|
||||
builder.add_raw(Tag::new(b"name"), name);
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if tag != Tag::new(b"cmap") && !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
|
||||
}
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`tall_ideograph_font`].
|
||||
pub const TALL_IDEOGRAPH_FAMILY: &str = "Tall Ideograph Sans";
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ mod alternates;
|
||||
mod axes;
|
||||
mod bidi;
|
||||
mod bitmaps;
|
||||
mod char_list;
|
||||
mod colr;
|
||||
mod combos;
|
||||
mod composers;
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! A face's list of mapped characters (the Glyphs panel's grid): read from the font once for the
|
||||
//! face, and the same list, in the same order, as a fresh read of the font's `cmap`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use skrifa::MetadataProvider;
|
||||
|
||||
use crate::test_fonts::{CMAPLESS_FAMILY, LARGE_CMAP_FAMILY, VARIABLE_FAMILY, cmapless_font, large_cmap_font, variable_font};
|
||||
use crate::*;
|
||||
|
||||
/// The characters `face` maps, read from its `cmap` each time: every mapping with a valid code point,
|
||||
/// sorted by code point, one per character.
|
||||
fn read_chars(face: &FontFace) -> Vec<(char, u32)> {
|
||||
let Some(f) = face.skrifa() else { return vec![] };
|
||||
let mut v: Vec<(char, u32)> = f.charmap().mappings().filter_map(|(cp, g)| char::from_u32(cp).map(|c| (c, g.to_u32()))).collect();
|
||||
v.sort_unstable_by_key(|x| x.0);
|
||||
v.dedup_by_key(|x| x.0);
|
||||
v
|
||||
}
|
||||
|
||||
/// A database of the bundled fonts, the test variable font, a font with a large `cmap` and one with
|
||||
/// no `cmap`.
|
||||
fn db() -> FontDb {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert!(db.add_font(variable_font().expect("the variable test font builds")) > 1, "its named instances are faces");
|
||||
assert_eq!(db.add_font(large_cmap_font(50_000).expect("the large test font builds")), 1);
|
||||
assert_eq!(db.add_font(cmapless_font().expect("the cmapless test font builds")), 1);
|
||||
db
|
||||
}
|
||||
|
||||
/// Faces of every kind the panel browses: static faces, a variable font's named instance and an
|
||||
/// instance at other axis settings, a large `cmap`, and no `cmap`.
|
||||
fn faces(db: &FontDb) -> Vec<Arc<FontFace>> {
|
||||
let mut faces: Vec<Arc<FontFace>> = [
|
||||
(FALLBACK_FAMILY, "Regular"),
|
||||
(FALLBACK_FAMILY, "Bold"),
|
||||
("Inter", "Regular"),
|
||||
("JetBrains Mono", "Regular"),
|
||||
(VARIABLE_FAMILY, "Regular"),
|
||||
(VARIABLE_FAMILY, "Bold"),
|
||||
(LARGE_CMAP_FAMILY, "Regular"),
|
||||
(CMAPLESS_FAMILY, "Regular"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(family, style)| db.face(family, style).unwrap_or_else(|| panic!("{family} {style} is loaded")))
|
||||
.collect();
|
||||
let regular = db.face(VARIABLE_FAMILY, "Regular").expect("the variable face");
|
||||
let axes: BTreeMap<String, f64> = [("wght".to_string(), 620.0)].into_iter().collect();
|
||||
let instance = db.instance(®ular, &axes);
|
||||
assert_ne!(instance.id(), regular.id(), "a new instance");
|
||||
faces.push(instance);
|
||||
faces
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_character_list_is_the_fonts_cmap_read_once() {
|
||||
let db = db();
|
||||
let faces = faces(&db);
|
||||
for face in &faces {
|
||||
let list = face.mapped_chars();
|
||||
assert_eq!(&list[..], read_chars(face).as_slice(), "{face:?}");
|
||||
assert_eq!(face.chars(), read_chars(face), "{face:?}");
|
||||
assert!(Arc::ptr_eq(&list, &face.mapped_chars()), "{face:?}: read once");
|
||||
}
|
||||
let large = db.face(LARGE_CMAP_FAMILY, "Regular").expect("the large face");
|
||||
assert_eq!(large.mapped_chars().len(), 50_000);
|
||||
let none = db.face(CMAPLESS_FAMILY, "Regular").expect("the cmapless face");
|
||||
assert!(none.mapped_chars().is_empty(), "a font with no cmap maps no character");
|
||||
// Each face keeps its own list: an instance of a variable font shares its characters, not the
|
||||
// list read for another face.
|
||||
for (i, a) in faces.iter().enumerate() {
|
||||
for b in &faces[i + 1..] {
|
||||
assert!(a.mapped_chars().is_empty() || !Arc::ptr_eq(&a.mapped_chars(), &b.mapped_chars()), "{a:?} and {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Times one face's character list read from the font each time against the list read once, for the
|
||||
/// bundled Source Sans 3 Regular and a font mapping 50,000 characters. Run with
|
||||
/// `cargo test --release -p vectorcraft-text --lib character_list_timing -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
|
||||
fn character_list_timing() {
|
||||
const CALLS: usize = 100;
|
||||
let db = db();
|
||||
for (family, style) in [(FALLBACK_FAMILY, "Regular"), (LARGE_CMAP_FAMILY, "Regular")] {
|
||||
let face = db.face(family, style).expect("the face");
|
||||
let mut read = vec![];
|
||||
let mut kept = vec![];
|
||||
for _ in 0..7 {
|
||||
let start = std::time::Instant::now();
|
||||
let mut n = 0;
|
||||
for _ in 0..CALLS {
|
||||
n += std::hint::black_box(read_chars(&face)).len();
|
||||
}
|
||||
read.push(start.elapsed().as_secs_f64() * 1000.0 / CALLS as f64);
|
||||
let start = std::time::Instant::now();
|
||||
let mut m = 0;
|
||||
for _ in 0..CALLS {
|
||||
m += std::hint::black_box(face.mapped_chars()).len();
|
||||
}
|
||||
kept.push(start.elapsed().as_secs_f64() * 1000.0 / CALLS as f64);
|
||||
assert_eq!(n, m);
|
||||
}
|
||||
read.sort_by(f64::total_cmp);
|
||||
kept.sort_by(f64::total_cmp);
|
||||
println!(
|
||||
"{family} {style}, {} characters: read each time median {:.4} ms, read once median {:.6} ms per call; samples {read:.4?} and {kept:.6?}",
|
||||
face.mapped_chars().len(),
|
||||
read[3],
|
||||
kept[3]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ pub use lookup::{
|
||||
EDGE_NAME, FACE_NAME, Face, LIVE_PAINT_NAME, LIVE_PAINT_PREFIX, LP_JOIN_TOL, SOURCES_NAME, builder_members, connected_edges,
|
||||
connected_edges_through, drawn_outlines, edge_near, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at,
|
||||
live_paint_takes, lp_stroke_paint, node_outline, outline_snap, path_contains, shape_builder_shapes, shapes_for, sources, visible_edge_near,
|
||||
visible_face_at,
|
||||
visible_edges_along, visible_face_at,
|
||||
};
|
||||
pub use map::{
|
||||
BuilderMap, HATCH, HIGHLIGHT_RED, Hit, MergeGeometry, MergeInput, PreparedMerge, Rest, Touched, hatch, maps_built, merge_geometry, merge_inputs,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::cache::RegionCache;
|
||||
use super::lookup::{
|
||||
connected_edges, connected_edges_through, edges, face_at, faces, flood_faces, is_live_paint, leaf_shapes, live_paint_at, live_paint_at_where,
|
||||
lp_stroke_paint, node_outline, visible_edge_near, visible_face_at,
|
||||
lp_stroke_paint, node_outline, visible_edge_near, visible_edges_along, visible_face_at,
|
||||
};
|
||||
use super::map::{BuilderMap, HIGHLIGHT_RED, sorted_roots};
|
||||
use super::{
|
||||
@@ -173,9 +173,12 @@ enum LpPaint {
|
||||
/// With Paint Strokes alone on, a click paints the edge nearest the pointer and
|
||||
/// Shift-click fills the face. With both on, a click paints the edge nearest the pointer when one
|
||||
/// is within 4 pixels, else it fills the face, and Shift-click fills the face. With both off, a
|
||||
/// click paints nothing. With Highlight off, the face or edge under the pointer is not
|
||||
/// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints
|
||||
/// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper.
|
||||
/// click paints nothing. A drag from where a click paints an edge paints that edge and every edge
|
||||
/// of the same group that the drag crosses or touches with the current stroke, as one undo step
|
||||
/// (Escape cancels); a drag from where a click fills a face fills only faces. With Highlight off,
|
||||
/// the face or edge under the pointer is not highlighted. The cursor is a filled bucket where a
|
||||
/// click fills a face, a brush where it paints an edge and an empty bucket where it paints nothing;
|
||||
/// with Alt it is the Eyedropper.
|
||||
///
|
||||
/// A double-click on a face fills it and the faces reached from it across edges that draw no
|
||||
/// stroke (`scope: "connected"`); on an edge it paints the edges joined to it that have its stroke.
|
||||
@@ -195,16 +198,17 @@ enum LpPaint {
|
||||
/// Swatches panel, wrapping around; from a color that is no swatch, Right picks the first swatch
|
||||
/// and Left the last. The selected art keeps its paint. With `cursorSwatchPreview` (on), the
|
||||
/// active paint shows as a chip above the pointer between the swatches before and after it,
|
||||
/// except during a fill drag or with Alt held; a solid color that is no swatch shows alone, and a
|
||||
/// except during a fill or stroke drag or with Alt held; a solid color that is no swatch shows alone, and a
|
||||
/// paint that is not a solid color shows no chip.
|
||||
pub struct LivePaintBucketTool {
|
||||
pub(super) cache: RegionCache,
|
||||
pub(super) hover: LpHover,
|
||||
/// Where the pointer last moved, and the modifiers held there.
|
||||
at: Option<(Point, Mods)>,
|
||||
/// The fill command and polyline previewed from the press's snapshot.
|
||||
fill_drag: Option<(Value, Vec<Vec<Point>>)>,
|
||||
/// What a fill drag paints, as it was at its press.
|
||||
/// The command (`livePaint.fill` or `livePaint.strokeEdge`), its params and the polyline of a
|
||||
/// drag, previewed from the press's snapshot.
|
||||
fill_drag: Option<(&'static str, Value, Vec<Vec<Point>>)>,
|
||||
/// What a drag paints, as it was at its press.
|
||||
drag_from: LpDragFrom,
|
||||
/// The last [`LP_PRESSES`] presses, oldest first: the face or edge each one painted, with its
|
||||
/// paint before that press, or None for a press that painted no face or edge.
|
||||
@@ -234,15 +238,15 @@ struct LpPress {
|
||||
/// The other faces or edges the double-click that followed the press reached, each with its
|
||||
/// fill or drawn stroke paint before the double-click.
|
||||
also: Vec<(NodeId, Paint)>,
|
||||
/// The other faces the press's drag crossed, its release included, each with its fill before
|
||||
/// the press.
|
||||
/// The other faces or edges the press's drag crossed, its release included, each with its fill
|
||||
/// or drawn stroke paint before the press.
|
||||
dragged: Vec<(NodeId, Paint)>,
|
||||
/// For a press that makes the Live Paint group: what the group is made from, with the path
|
||||
/// chunks of the press's drag, its release included.
|
||||
dragged_made: Option<Arc<(LpMade, Vec<Vec<Point>>)>>,
|
||||
}
|
||||
|
||||
/// What a Live Paint Bucket fill drag paints, as it was at the press.
|
||||
/// What a Live Paint Bucket fill or stroke drag paints, as it was at the press.
|
||||
#[derive(Default)]
|
||||
enum LpDragFrom {
|
||||
#[default]
|
||||
@@ -251,6 +255,8 @@ enum LpDragFrom {
|
||||
Faces(Vec<Arc<Node>>),
|
||||
/// What the group is made from, for a drag that makes the group.
|
||||
Made(LpMade),
|
||||
/// The Live Paint group whose edges a stroke drag paints.
|
||||
Edges(Arc<Node>),
|
||||
}
|
||||
|
||||
/// The faces among `faces` (a Live Paint group's faces, back to front) that a drag along the path
|
||||
@@ -404,13 +410,15 @@ impl LivePaintBucketTool {
|
||||
usize::from(!cx.fill_active)
|
||||
}
|
||||
|
||||
fn begin_fill(&mut self, params: Value, p: Point) -> Vec<Action> {
|
||||
self.fill_drag = Some((params.clone(), vec![vec![p]]));
|
||||
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), params)]
|
||||
/// Start a drag pressed at `p` that previews `cmd` with `params` and the drag's path.
|
||||
fn begin_fill(&mut self, cmd: &'static str, params: Value, p: Point) -> Vec<Action> {
|
||||
self.fill_drag = Some((cmd, params.clone(), vec![vec![p]]));
|
||||
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview(cmd.into(), params)]
|
||||
}
|
||||
|
||||
fn drag_fill(&mut self, p: Point) -> Vec<Action> {
|
||||
let Some((params, chunks)) = &mut self.fill_drag else { return vec![] };
|
||||
let Some((cmd, params, chunks)) = &mut self.fill_drag else { return vec![] };
|
||||
let cmd = *cmd;
|
||||
let Some(points) = chunks.last_mut() else { return vec![] };
|
||||
let Some(&last) = points.last() else { return vec![] };
|
||||
if last == p {
|
||||
@@ -431,7 +439,7 @@ impl LivePaintBucketTool {
|
||||
if !continuation.is_empty() {
|
||||
params["continuation"] = Value::Array(continuation);
|
||||
}
|
||||
vec![Action::Preview("livePaint.fill".into(), params)]
|
||||
vec![Action::Preview(cmd.into(), params)]
|
||||
}
|
||||
|
||||
/// What a click paints, Shift held or not. Shift switches Paint Fills alone to Paint Strokes
|
||||
@@ -459,13 +467,13 @@ impl LivePaintBucketTool {
|
||||
self.note_press(Some(LpPress { part: Some(n.id), at, before, also: vec![], dragged: vec![], dragged_made: None }));
|
||||
}
|
||||
|
||||
/// End the fill drag, noting on the last press the other faces its drag crossed, with their
|
||||
/// fills before the press (for a press that makes the group, what the group is made from and
|
||||
/// the drag, for [`Self::before`] to look the faces up in the group made). → whether a fill
|
||||
/// drag was on.
|
||||
/// End the drag, noting on the last press the other faces or edges its drag crossed, with their
|
||||
/// fills or drawn stroke paints before the press (for a press that makes the group, what the
|
||||
/// group is made from and the drag, for [`Self::before`] to look the faces up in the group
|
||||
/// made). → whether a drag was on.
|
||||
fn end_fill(&mut self) -> bool {
|
||||
let from = std::mem::take(&mut self.drag_from);
|
||||
let Some((_, chunks)) = self.fill_drag.take() else { return false };
|
||||
let Some((_, _, chunks)) = self.fill_drag.take() else { return false };
|
||||
let Some(Some(last)) = self.presses.last_mut() else { return true };
|
||||
match from {
|
||||
LpDragFrom::None => {}
|
||||
@@ -474,6 +482,11 @@ impl LivePaintBucketTool {
|
||||
last.dragged = crossed_faces(&faces, &chunks).into_iter().filter(|(id, _)| part != Some(*id)).collect();
|
||||
}
|
||||
LpDragFrom::Made(made) => last.dragged_made = Some(Arc::new((made, chunks))),
|
||||
LpDragFrom::Edges(group) => {
|
||||
let part = last.part;
|
||||
last.dragged =
|
||||
visible_edges_along(&group, &chunks).into_iter().filter(|e| part != Some(e.id)).map(|e| (e.id, lp_stroke_paint(e))).collect();
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -549,22 +562,16 @@ impl LivePaintBucketTool {
|
||||
if clicks == 2
|
||||
&& let Some(group) = cx.doc.node(g)
|
||||
{
|
||||
// The other edge of this group either click painted joins as the stroke paint it
|
||||
// had before. A face either click filled is not an edge and does not join.
|
||||
// The other edges of this group either click painted, by its press or its drag, join
|
||||
// as the stroke paint they had before. A face either click filled is not an edge and
|
||||
// does not join. `livePaint.strokeEdge` takes at most 4096 of them.
|
||||
let group_edges: std::collections::HashSet<NodeId> = edges(group).iter().map(|x| x.id).collect();
|
||||
let mut seen = std::collections::HashSet::from([e.id]);
|
||||
let mut through: Vec<NodeId> = vec![];
|
||||
for id in self
|
||||
.presses
|
||||
.len()
|
||||
.checked_sub(2)
|
||||
.and_then(|i| self.presses.get(i..))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|q| q.before == like)
|
||||
.filter_map(|q| q.part)
|
||||
{
|
||||
if id != e.id && group_edges.contains(&id) && !through.contains(&id) {
|
||||
for id in self.presses.len().checked_sub(2).and_then(|i| self.presses.get(i..)).into_iter().flatten().flatten().flat_map(|q| {
|
||||
q.part.filter(|_| q.before == like).into_iter().chain(q.dragged.iter().filter(|(_, before)| *before == like).map(|(id, _)| *id))
|
||||
}) {
|
||||
if through.len() < 4096 && group_edges.contains(&id) && seen.insert(id) {
|
||||
through.push(id);
|
||||
}
|
||||
}
|
||||
@@ -718,7 +725,8 @@ impl Tool for LivePaintBucketTool {
|
||||
&& let Some((g, Some(e))) = lp_part_at(cx.doc, p, cx.tol(4.0), true, &|id| lp_visible(cx, id))
|
||||
{
|
||||
self.note_part(e, true, p);
|
||||
return vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }))];
|
||||
self.drag_from = cx.doc.node(g).map_or(LpDragFrom::None, |n| LpDragFrom::Edges(Arc::new(n.clone())));
|
||||
return self.begin_fill("livePaint.strokeEdge", json!({ "group": g.0, "point": point, "tolerance": cx.tol(4.0) }), p);
|
||||
}
|
||||
if !matches!(paint, LpPaint::Fills | LpPaint::Both) {
|
||||
self.note_press(None);
|
||||
@@ -730,7 +738,7 @@ impl Tool for LivePaintBucketTool {
|
||||
None => self.note_press(None),
|
||||
}
|
||||
self.drag_from = LpDragFrom::Faces(cx.doc.node(g).map(|n| faces(n).into_iter().cloned().collect()).unwrap_or_default());
|
||||
return self.begin_fill(json!({ "group": g.0, "point": point }), p);
|
||||
return self.begin_fill("livePaint.fill", json!({ "group": g.0, "point": point }), p);
|
||||
}
|
||||
if self.cache.at(cx, p).is_some() {
|
||||
let roots = sorted_roots(cx.doc, &cx.selection.objects);
|
||||
@@ -738,7 +746,7 @@ impl Tool for LivePaintBucketTool {
|
||||
let before = made_face_fill(&made, p);
|
||||
self.note_press(Some(LpPress { part: None, at: p, before, also: vec![], dragged: vec![], dragged_made: None }));
|
||||
self.drag_from = LpDragFrom::Made(made);
|
||||
return self.begin_fill(json!({ "ids": json_ids(&roots), "point": point }), p);
|
||||
return self.begin_fill("livePaint.fill", json!({ "ids": json_ids(&roots), "point": point }), p);
|
||||
}
|
||||
self.note_press(None);
|
||||
vec![]
|
||||
@@ -762,7 +770,7 @@ impl Tool for LivePaintBucketTool {
|
||||
self.presses.clear();
|
||||
}
|
||||
|
||||
/// Escape during a fill drag cancels it. Left and Right pick the color swatch before or after
|
||||
/// Escape during a fill or stroke drag cancels it. Left and Right pick the color swatch before or after
|
||||
/// the active paint, while no drag is on.
|
||||
fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {
|
||||
if key == ToolKey::Escape {
|
||||
@@ -819,7 +827,7 @@ impl Tool for LivePaintBucketTool {
|
||||
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
let mut out = lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32);
|
||||
// No chips during a fill drag, or while Alt makes the tool sample with the eyedropper.
|
||||
// No chips during a fill or stroke drag, or while Alt makes the tool sample with the eyedropper.
|
||||
if self.preview
|
||||
&& !self.busy()
|
||||
&& let Some((at, mods)) = self.at
|
||||
|
||||
@@ -90,6 +90,65 @@ pub fn visible_edge_near(group: &Node, p: Point, tol: f64) -> Option<&Arc<Node>>
|
||||
nearest_edge(edges(group).into_iter().filter(|e| e.visible), p, tol)
|
||||
}
|
||||
|
||||
/// The edges of `group` that are not hidden and that the polyline through the points of each chunk
|
||||
/// of `chunks` crosses or comes within [`LP_JOIN_TOL`] of, each once, in the group's order. Each
|
||||
/// stretch of the polyline tests only the edge segments whose bounds lie near it.
|
||||
pub fn visible_edges_along<'a>(group: &'a Node, chunks: &[Vec<Point>]) -> Vec<&'a Arc<Node>> {
|
||||
use kurbo::ParamCurveNearest as _;
|
||||
let shown: Vec<&Arc<Node>> = edges(group).into_iter().filter(|e| e.visible).collect();
|
||||
// Each edge segment, with the index in `shown` of its edge.
|
||||
let mut owner: Vec<usize> = vec![];
|
||||
let mut segs: Vec<(kurbo::CubicBez, bool)> = vec![];
|
||||
for (i, e) in shown.iter().enumerate() {
|
||||
for s in e.path_data().map(lp_segments).unwrap_or_default() {
|
||||
owner.push(i);
|
||||
segs.push((s, true));
|
||||
}
|
||||
}
|
||||
if segs.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let grid = LpEdgeGrid::new(&segs);
|
||||
let close = LP_JOIN_TOL * LP_JOIN_TOL;
|
||||
let mut hit = vec![false; shown.len()];
|
||||
for chunk in chunks {
|
||||
for pair in chunk.windows(2) {
|
||||
let &[a, b] = pair else { continue };
|
||||
let line = kurbo::Line::new(a, b);
|
||||
let on_line = |p: Point| line.nearest(p, 1e-9).distance_sq <= close;
|
||||
for k in grid.near_box(Rect::from_points(a, b).inflate(LP_JOIN_TOL, LP_JOIN_TOL)) {
|
||||
let (Some((c, _)), Some(&i)) = (segs.get(k), owner.get(k)) else { continue };
|
||||
let Some(h) = hit.get_mut(i) else { continue };
|
||||
if *h {
|
||||
continue;
|
||||
}
|
||||
let on_seg = |p: Point| c.nearest(p, 1e-9).distance_sq <= close;
|
||||
// An end of either one on the other covers a touch and a stretch that runs along
|
||||
// the edge, where no single crossing point exists. Where neither crosses the other,
|
||||
// their closest points are ends or a point of the edge where it runs parallel to
|
||||
// the drag. A crossing kurbo finds just before or after an end of the edge counts
|
||||
// only through the checks on that end.
|
||||
*h = on_seg(a)
|
||||
|| on_seg(b)
|
||||
|| on_line(c.p0)
|
||||
|| on_line(c.p3)
|
||||
|| (a != b
|
||||
&& (kurbo::PathSeg::Cubic(*c).intersect_line(line).iter().any(|x| (0.0..=1.0).contains(&x.segment_t))
|
||||
|| lp_parallel_at(c, b - a).into_iter().any(|t| on_line(kurbo::ParamCurve::eval(c, t)))));
|
||||
}
|
||||
}
|
||||
}
|
||||
shown.into_iter().zip(hit).filter_map(|(e, h)| h.then_some(e)).collect()
|
||||
}
|
||||
|
||||
/// The parameters strictly between 0 and 1 where cubic `c` runs parallel to direction `d`: the
|
||||
/// roots of the cross product of its derivative with `d`.
|
||||
fn lp_parallel_at(c: &kurbo::CubicBez, d: kurbo::Vec2) -> Vec<f64> {
|
||||
let [a, b, e] = [c.p1 - c.p0, c.p2 - c.p1, c.p3 - c.p2].map(|v| v.cross(d));
|
||||
// a(1-t)² + 2b·t(1-t) + e·t², expanded in powers of t.
|
||||
kurbo::common::solve_quadratic(a, 2.0 * (b - a), a - 2.0 * b + e).into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0).collect()
|
||||
}
|
||||
|
||||
/// The edge of `edges` nearest to `p` within `tol`.
|
||||
fn nearest_edge<'a>(edges: impl IntoIterator<Item = &'a Arc<Node>>, p: Point, tol: f64) -> Option<&'a Arc<Node>> {
|
||||
let mut best: Option<(f64, &Arc<Node>)> = None;
|
||||
|
||||
@@ -1120,8 +1120,170 @@ fn bucket_click_fills_face_and_shift_click_strokes_edge() {
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 25.0)), vec![Action::Commit]);
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift));
|
||||
let Action::Exec(id, _) = &acts[0] else { panic!() };
|
||||
let [Action::Begin(_), Action::Preview(id, _)] = acts.as_slice() else { panic!("{acts:?}") };
|
||||
assert_eq!(id, "livePaint.strokeEdge");
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 51.0, 25.0).with_mods(shift)), vec![Action::Commit]);
|
||||
}
|
||||
|
||||
/// A drag reaches the visible edges its path crosses or passes within 0.0001 pt of, including the
|
||||
/// middle of a curved edge it runs past without crossing; a hidden edge and an edge farther away are
|
||||
/// not reached.
|
||||
#[test]
|
||||
fn visible_edges_along_finds_crossed_and_near_edges() {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut arc = BezPath::new();
|
||||
arc.move_to((100.0, 0.0));
|
||||
// Farthest right at (130, 50), where it runs straight down.
|
||||
arc.curve_to((140.0, 0.0), (140.0, 100.0), (100.0, 100.0));
|
||||
let mut kids = vec![empty_sources(&mut d)];
|
||||
let mut ids = vec![];
|
||||
for (path, visible) in [
|
||||
(shapes::line(Point::new(0.0, 0.0), Point::new(0.0, 100.0)), true),
|
||||
(shapes::line(Point::new(50.0, 0.0), Point::new(50.0, 100.0)), false),
|
||||
(vectorcraft_geom::PathData::from_bezpath(&arc), true),
|
||||
(shapes::line(Point::new(0.0, 200.0), Point::new(100.0, 200.0)), true),
|
||||
] {
|
||||
let id = d.alloc_id();
|
||||
let mut edge = Node::path(id, path, Appearance::default());
|
||||
edge.name = Some(EDGE_NAME.into());
|
||||
edge.visible = visible;
|
||||
kids.push(Arc::new(edge));
|
||||
ids.push(id);
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, kids);
|
||||
g.name = Some(LIVE_PAINT_NAME.into());
|
||||
d.insert(Some(l), 0, g).unwrap();
|
||||
let group = d.node(gid).unwrap();
|
||||
let reached = |x: f64| {
|
||||
let chunks = vec![
|
||||
vec![Point::new(-10.0, 50.0), Point::new(60.0, 50.0), Point::new(60.0, -20.0)],
|
||||
vec![Point::new(60.0, -20.0), Point::new(x, -20.0), Point::new(x, 60.0)],
|
||||
];
|
||||
visible_edges_along(group, &chunks).iter().map(|e| e.id).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(reached(130.00005), vec![ids[0], ids[2]]);
|
||||
assert_eq!(reached(130.001), vec![ids[0]]);
|
||||
}
|
||||
|
||||
/// A drag that passes 0.0002 pt before the start of a long curved edge does not reach it, although
|
||||
/// the curve extended a tiny step past its start meets the drag.
|
||||
#[test]
|
||||
fn visible_edges_along_skips_an_edge_the_drag_meets_only_past_its_end() {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut curve = BezPath::new();
|
||||
curve.move_to((0.0, 0.0));
|
||||
curve.curve_to((100000.0, 0.0), (200000.0, 100.0), (300000.0, 100.0));
|
||||
let id = d.alloc_id();
|
||||
let mut edge = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&curve), Appearance::default());
|
||||
edge.name = Some(EDGE_NAME.into());
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, vec![empty_sources(&mut d), Arc::new(edge)]);
|
||||
g.name = Some(LIVE_PAINT_NAME.into());
|
||||
d.insert(Some(l), 0, g).unwrap();
|
||||
let group = d.node(gid).unwrap();
|
||||
let reached = |x: f64| visible_edges_along(group, &[vec![Point::new(x, -1.0), Point::new(x, 1.0)]]).iter().map(|e| e.id).collect::<Vec<_>>();
|
||||
assert_eq!(reached(-0.0002), Vec::<NodeId>::new());
|
||||
assert_eq!(reached(-0.00005), vec![id]);
|
||||
assert_eq!(reached(0.0002), vec![id]);
|
||||
}
|
||||
|
||||
/// A double-click on an edge after a press whose drag stroked another edge of the line joins
|
||||
/// through that edge as the stroke paint it had before the drag.
|
||||
#[test]
|
||||
fn bucket_edge_double_click_joins_through_an_edge_the_first_drag_stroked() {
|
||||
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 0.0, 0.0));
|
||||
let green = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(0.0, 1.0, 0.0));
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let l = d.layers[0].id;
|
||||
let mut kids = vec![empty_sources(&mut d)];
|
||||
let mut ids = vec![];
|
||||
for (x0, x1) in [(0.0, 30.0), (30.0, 70.0), (70.0, 100.0)] {
|
||||
let id = d.alloc_id();
|
||||
let mut a = Appearance::default();
|
||||
a.set_stroke(black.clone());
|
||||
let mut edge = Node::path(id, shapes::line(Point::new(x0, 100.0), Point::new(x1, 100.0)), a);
|
||||
edge.name = Some(EDGE_NAME.into());
|
||||
kids.push(Arc::new(edge));
|
||||
ids.push(id);
|
||||
}
|
||||
let gid = d.alloc_id();
|
||||
let mut g = Node::group(gid, kids);
|
||||
g.name = Some(LIVE_PAINT_NAME.into());
|
||||
d.insert(Some(l), 0, g).unwrap();
|
||||
let mut later = d.clone();
|
||||
for id in &ids[1..] {
|
||||
later.node_mut(*id).unwrap().appearance.set_stroke(green.clone());
|
||||
}
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let (cx, later) = (cx(&d, &s, &p), cx(&later, &s, &p));
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let mut t = LivePaintBucketTool::default();
|
||||
// The first press strokes the right edge and its drag crosses the middle one.
|
||||
for (k, x, y) in
|
||||
[(PointerKind::Down, 85.0, 100.0), (PointerKind::Drag, 85.0, 110.0), (PointerKind::Drag, 50.0, 110.0), (PointerKind::Up, 50.0, 90.0)]
|
||||
{
|
||||
t.pointer(&cx, &ev(k, x, y).with_mods(shift));
|
||||
}
|
||||
t.pointer(&later, &ev(PointerKind::Down, 85.0, 100.0).with_mods(shift));
|
||||
t.pointer(&later, &ev(PointerKind::Up, 85.0, 100.0).with_mods(shift));
|
||||
let like = serde_json::to_value(&black).unwrap();
|
||||
assert_eq!(
|
||||
t.pointer(&later, &ev(PointerKind::DoubleClick, 85.0, 100.0).with_mods(shift)),
|
||||
vec![Action::Exec(
|
||||
"livePaint.strokeEdge".into(),
|
||||
json!({ "group": gid.0, "point": [85.0, 100.0], "tolerance": 4.0, "scope": "connected", "through": [ids[1].0], "match": like })
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
/// A drag from an edge previews `livePaint.strokeEdge` with the drag's path as it goes and commits
|
||||
/// once on the release; Escape cancels it, and what the drag paints is fixed at the press.
|
||||
#[test]
|
||||
fn bucket_edge_drag_previews_points_and_commits_once() {
|
||||
let (d, gid, ..) = live_group_doc();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let shift = Mods { shift: true, ..Default::default() };
|
||||
let stroke = |points: Value| {
|
||||
let mut v = json!({ "group": gid.0, "point": [51.0, 25.0], "tolerance": 4.0 });
|
||||
if !points.is_null() {
|
||||
v["points"] = points;
|
||||
}
|
||||
Action::Preview("livePaint.strokeEdge".into(), v)
|
||||
};
|
||||
let mut t = LivePaintBucketTool::default();
|
||||
assert_eq!(
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift)),
|
||||
vec![Action::Begin("Live Paint Bucket".into()), stroke(Value::Null)]
|
||||
);
|
||||
assert!(t.busy());
|
||||
// Shift let go during the drag: the drag still paints edges.
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 25.0)), vec![stroke(json!([[51.0, 25.0], [75.0, 25.0]]))]);
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 120.0, 25.0)), vec![stroke(json!([[51.0, 25.0], [75.0, 25.0], [120.0, 25.0]])), Action::Commit]);
|
||||
assert!(!t.busy());
|
||||
// Escape before the release cancels the drag, and the release then commits nothing.
|
||||
assert_eq!(
|
||||
t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(shift)),
|
||||
vec![Action::Begin("Live Paint Bucket".into()), stroke(Value::Null)]
|
||||
);
|
||||
t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 25.0).with_mods(shift));
|
||||
assert!(t.claims_key(&cx, ToolKey::Escape));
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
|
||||
assert!(t.pointer(&cx, &ev(PointerKind::Up, 120.0, 25.0).with_mods(shift)).is_empty());
|
||||
// With both options on, a drag from a face fills faces, even across an edge.
|
||||
t.set_option("paintStrokes", &json!(true));
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0));
|
||||
let [Action::Begin(_), Action::Preview(id, _)] = acts.as_slice() else { panic!("{acts:?}") };
|
||||
assert_eq!(id, "livePaint.fill");
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Drag, 51.0, 25.0));
|
||||
let [Action::Preview(id, _)] = acts.as_slice() else { panic!("{acts:?}") };
|
||||
assert_eq!(id, "livePaint.fill");
|
||||
t.pointer(&cx, &ev(PointerKind::Up, 51.0, 25.0));
|
||||
}
|
||||
|
||||
/// A double-click runs a click's command with `scope: "connected"` and a triple-click with
|
||||
@@ -1484,7 +1646,12 @@ fn bucket_options_choose_what_a_click_paints() {
|
||||
let fill = |x: f64| {
|
||||
vec![Action::Begin("Live Paint Bucket".into()), Action::Preview("livePaint.fill".into(), json!({ "group": gid.0, "point": [x, 25.0] }))]
|
||||
};
|
||||
let stroke = |x: f64| vec![Action::Exec("livePaint.strokeEdge".into(), json!({ "group": gid.0, "point": [x, 25.0], "tolerance": 4.0 }))];
|
||||
let stroke = |x: f64| {
|
||||
vec![
|
||||
Action::Begin("Live Paint Bucket".into()),
|
||||
Action::Preview("livePaint.strokeEdge".into(), json!({ "group": gid.0, "point": [x, 25.0], "tolerance": 4.0 })),
|
||||
]
|
||||
};
|
||||
let click = |t: &mut LivePaintBucketTool, x: f64, m: Mods| {
|
||||
let acts = t.pointer(&cx, &ev(PointerKind::Down, x, 25.0).with_mods(m));
|
||||
t.pointer(&cx, &ev(PointerKind::Up, x, 25.0).with_mods(m));
|
||||
@@ -3095,8 +3262,13 @@ fn live_paint_edges_outside_the_faces_come_from_the_nearest_visible_group() {
|
||||
bucket.set_option("cursorSwatchPreview", &json!(false));
|
||||
bucket.pointer(&cx, &ev(PointerKind::Move, x, y).with_mods(shift));
|
||||
assert_eq!(edge_x(&bucket.overlays(&cx)), want.map(|w| w.2));
|
||||
let stroked = want.map(|(g, ..)| Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, y], "tolerance": 4.0 })));
|
||||
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, x, y).with_mods(shift)), stroked.into_iter().collect::<Vec<_>>());
|
||||
let stroked = want.map(|(g, ..)| {
|
||||
vec![
|
||||
Action::Begin("Live Paint Bucket".into()),
|
||||
Action::Preview("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, y], "tolerance": 4.0 })),
|
||||
]
|
||||
});
|
||||
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, x, y).with_mods(shift)), stroked.unwrap_or_default());
|
||||
};
|
||||
check(&d, Some((back, back_right, 100.0)));
|
||||
// A hidden group's edges are not highlighted or picked.
|
||||
@@ -3139,8 +3311,13 @@ fn live_paint_tools_skip_hidden_edges() {
|
||||
bucket.set_option("cursorSwatchPreview", &json!(false));
|
||||
bucket.pointer(&cx, &ev(PointerKind::Move, x, 50.0).with_mods(shift));
|
||||
assert_eq!(edge_x(&bucket.overlays(&cx)), want.map(|w| w.2), "x {x}");
|
||||
let stroked = want.map(|(g, ..)| Action::Exec("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, 50.0], "tolerance": 4.0 })));
|
||||
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, x, 50.0).with_mods(shift)), stroked.into_iter().collect::<Vec<_>>(), "x {x}");
|
||||
let stroked = want.map(|(g, ..)| {
|
||||
vec![
|
||||
Action::Begin("Live Paint Bucket".into()),
|
||||
Action::Preview("livePaint.strokeEdge".into(), json!({ "group": g.0, "point": [x, 50.0], "tolerance": 4.0 })),
|
||||
]
|
||||
});
|
||||
assert_eq!(bucket.pointer(&cx, &ev(PointerKind::Down, x, 50.0).with_mods(shift)), stroked.unwrap_or_default(), "x {x}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use crate::guides::{DrawSnap, Leave};
|
||||
use crate::shape::{box_params, drag_rect, turned_box};
|
||||
use crate::shape::{box_params, turned_box};
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
|
||||
/// How much ↑ or ↓ changes the arc's slope while it is dragged out.
|
||||
@@ -155,17 +155,13 @@ impl FamilyTool {
|
||||
}
|
||||
|
||||
/// How the dragged point keeps to the start: a spiral's radius goes anywhere, the arc's and
|
||||
/// the grids' corner keeps to a diagonal with Shift (a grid's square is taken along the
|
||||
/// Constrain Angle's axes instead when it turns them, [`Self::command_at`]).
|
||||
/// the grids' corner keeps to a diagonal with Shift (an arc's or a grid's square is taken along
|
||||
/// the Constrain Angle's axes instead when it turns them, [`Self::command_at`]).
|
||||
fn leave(&self, cx: &ToolContext, start: Point, m: Mods) -> Option<Leave> {
|
||||
let turned = self.is_grid() && vectorcraft_geom::constrain_axes(cx.constrain_angle).is_some();
|
||||
let turned = vectorcraft_geom::constrain_axes(cx.constrain_angle).is_some();
|
||||
(self.id != "spiral").then(|| Leave::diagonal(start, m.shift && !turned))
|
||||
}
|
||||
|
||||
fn is_grid(&self) -> bool {
|
||||
matches!(self.id, "rectangularGrid" | "polarGrid")
|
||||
}
|
||||
|
||||
/// The natural logarithm of the radius of the inner end of a spiral of outer radius `r` drawn
|
||||
/// with the tool's decay and segments (a logarithm, so that a low decay with many segments does
|
||||
/// not round to 0). The decay ratio is clamped to 0.05…0.9999 as `shapes::spiral` clamps it.
|
||||
@@ -245,7 +241,7 @@ impl FamilyTool {
|
||||
}
|
||||
|
||||
/// [`Self::command`] with General › Constrain Angle `base` (degrees, counter-clockwise): the
|
||||
/// grids are drawn along the x and y axes turned by it, as the rectangle is.
|
||||
/// arc and the grids are drawn along the x and y axes turned by it, as the rectangle is.
|
||||
pub fn command_at(&self, start: Point, p: Point, m: Mods, base: f64) -> (String, Value) {
|
||||
match self.id {
|
||||
"spiral" => {
|
||||
@@ -263,25 +259,30 @@ impl FamilyTool {
|
||||
}
|
||||
(format!("shape.{}", self.id), params)
|
||||
}
|
||||
// The arc: its box along the Constrain Angle's axes, with the reference point taken in
|
||||
// that box and turned out onto the page; the arc turns about it.
|
||||
_ => {
|
||||
let r = drag_rect(start, p, m).abs();
|
||||
let (r, axes) = turned_box(start, p, m, base);
|
||||
let r = r.abs();
|
||||
let (w, h) = (r.width().max(1e-9), r.height().max(1e-9));
|
||||
let rp = vectorcraft_geom::reference_point(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), self.reference.min(8));
|
||||
let anchor = Point::new(r.x0 + rp.x, r.y0 + rp.y);
|
||||
(
|
||||
"shape.arc".into(),
|
||||
json!({
|
||||
"x": anchor.x,
|
||||
"y": anchor.y,
|
||||
"lengthX": w,
|
||||
"lengthY": h,
|
||||
"reference": self.reference,
|
||||
"baseAlong": self.base_along,
|
||||
"slope": self.slope,
|
||||
"closed": self.closed,
|
||||
"fillArc": self.fill_arc,
|
||||
}),
|
||||
)
|
||||
let local = Point::new(r.x0 + rp.x, r.y0 + rp.y);
|
||||
let anchor = axes.map_or(local, |a| a * local);
|
||||
let mut params = json!({
|
||||
"x": anchor.x,
|
||||
"y": anchor.y,
|
||||
"lengthX": w,
|
||||
"lengthY": h,
|
||||
"reference": self.reference,
|
||||
"baseAlong": self.base_along,
|
||||
"slope": self.slope,
|
||||
"closed": self.closed,
|
||||
"fillArc": self.fill_arc,
|
||||
});
|
||||
if let Some(rotation) = axes.and_then(|_| vectorcraft_geom::constrain_rotation(base)) {
|
||||
params["rotation"] = json!(rotation);
|
||||
}
|
||||
("shape.arc".into(), params)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -433,8 +434,8 @@ impl Tool for FamilyTool {
|
||||
let mut o = self.snap.guides().to_vec();
|
||||
if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) {
|
||||
// The size as drawn (from the centre with Alt, square with Shift).
|
||||
// A grid's along the Constrain Angle's axes, as it is drawn.
|
||||
let r = if self.is_grid() { turned_box(s, self.last, self.mods, cx.constrain_angle).0 } else { drag_rect(s, self.last, self.mods) };
|
||||
// An arc's or a grid's along the Constrain Angle's axes, as it is drawn.
|
||||
let r = turned_box(s, self.last, self.mods, cx.constrain_angle).0;
|
||||
let (w, h) = if self.id == "spiral" { ((self.last - s).x.abs(), (self.last - s).y.abs()) } else { (r.width(), r.height()) };
|
||||
o.push(Overlay::Measure { p: self.last, text: cx.size_label(w, h) });
|
||||
}
|
||||
@@ -1080,6 +1081,58 @@ mod tests {
|
||||
assert_eq!(v["rotation"], json!(-30.0));
|
||||
}
|
||||
|
||||
/// General › Constrain Angle: an arc is drawn along the turned axes, its reference point taken
|
||||
/// in the turned box and the arc turned about it; Shift's equal lengths are taken along the
|
||||
/// turned axes, and F, C and ↑ keep the turn and the reference point; at 0° and whole turns
|
||||
/// the arc is as before.
|
||||
#[test]
|
||||
fn arcs_follow_the_constrain_angle() {
|
||||
let t = FamilyTool::new("arc");
|
||||
let (a, b) = (Point::new(100.0, 100.0), Point::new(160.0, 120.0));
|
||||
let flat = t.command(a, b, Mods::default());
|
||||
assert!(flat.1.get("rotation").is_none(), "{flat:?}");
|
||||
assert_eq!(t.command_at(a, b, Mods::default(), 0.0), flat);
|
||||
assert_eq!(t.command_at(a, b, Mods::default(), 360.0), flat);
|
||||
// At 90° the drag runs 20 along the turned x axis and 60 along the turned y axis; the
|
||||
// top-left reference point of that box is at (100, 120) on the page.
|
||||
let (c, v) = t.command_at(a, b, Mods::default(), 90.0);
|
||||
assert_eq!(c, "shape.arc");
|
||||
assert_eq!(
|
||||
v,
|
||||
json!({"x": 100.0, "y": 120.0, "lengthX": 20.0, "lengthY": 60.0, "reference": 0, "baseAlong": "x", "slope": 50.0, "closed": false, "fillArc": false, "rotation": -90.0})
|
||||
);
|
||||
let shift = Mods { shift: true, ..Mods::default() };
|
||||
let (_, v) = t.command_at(a, b, shift, 30.0);
|
||||
assert!((v["lengthX"].as_f64().unwrap() - v["lengthY"].as_f64().unwrap()).abs() < 1e-9, "equal along the turned axes: {v}");
|
||||
assert_eq!(v["rotation"], json!(-30.0));
|
||||
|
||||
// A Shift drag at 30°: the pointer is not held to the page's diagonal.
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let mut cx = cx(&d, &s, &p);
|
||||
cx.smart_guides = false;
|
||||
cx.constrain_angle = 30.0;
|
||||
let mut t = FamilyTool::new("arc");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0));
|
||||
let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 70.0, 30.0).with_mods(shift));
|
||||
let expected = t.command_at(Point::new(10.0, 10.0), Point::new(70.0, 30.0), shift, 30.0);
|
||||
assert_eq!(out, vec![Action::Begin("Arc".into()), Action::Preview(expected.0, expected.1.clone())]);
|
||||
let preview = |a: Vec<Action>| match &a[..] {
|
||||
[Action::Preview(c, v)] if c == "shape.arc" => v.clone(),
|
||||
_ => panic!("{a:?}"),
|
||||
};
|
||||
let v = preview(t.key(&cx, ToolKey::Letter('f'), Mods::default()));
|
||||
assert_eq!(v["baseAlong"], json!("y"));
|
||||
let v = preview(t.key(&cx, ToolKey::Letter('c'), Mods::default()));
|
||||
assert_eq!(v["closed"], json!(true));
|
||||
let v = preview(t.key(&cx, ToolKey::Up, Mods::default()));
|
||||
assert_eq!(v["slope"], json!(60.0));
|
||||
for k in ["x", "y", "lengthX", "lengthY", "rotation"] {
|
||||
assert_eq!(v[k], expected.1[k], "{k} stays");
|
||||
}
|
||||
}
|
||||
|
||||
/// The start and the dragged corner snap to Smart Guides (#506), Shift sliding the corner of
|
||||
/// a square grid along its diagonal into line.
|
||||
#[test]
|
||||
|
||||
@@ -126,7 +126,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
let size_at = r.right_center() - vec2(6.0, 0.0);
|
||||
p.text(size_at, egui::Align2::RIGHT_CENTER, &size, font.clone(), t.text_dim);
|
||||
p.with_clip_rect(r.with_max_x(size_at.x - 80.0)).text(mid + vec2(NUMBER_W, 0.0), egui::Align2::LEFT_CENTER, name, font, t.text);
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, on, format!("{} {name} {size}", i + 1)));
|
||||
widgets::list_item_info(&resp, on, || format!("{} {name} {size}", i + 1));
|
||||
if resp.double_clicked() {
|
||||
double = Some(i);
|
||||
} else if resp.clicked() {
|
||||
|
||||
@@ -82,6 +82,24 @@ fn select_by_artboards_lists_the_artboards_and_selects_on_ok() {
|
||||
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rows_report_their_choice_as_the_selected_state() {
|
||||
use egui::accesskit::Role;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.run("artboard.new", json!({"x": 150, "y": 0, "width": 200, "height": 50, "name": "Banner"})).unwrap();
|
||||
app.run("view.goToArtboard", json!({"index": 0})).unwrap();
|
||||
menus::invoke(&mut app, super::COMMAND, serde_json::Value::Null);
|
||||
let tree = crate::widgets::accessibility_tests::tree(|ui| crate::dialogs::show(&mut app, ui.ctx()));
|
||||
let mut rows: Vec<_> =
|
||||
tree.iter().filter(|n| n.role() == Role::ListItem).map(|n| (n.label().map(str::to_string), n.is_selected(), n.toggled())).collect();
|
||||
rows.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(
|
||||
rows,
|
||||
[(Some("1 Artboard 1 100 × 100 pt".to_string()), Some(true), None), (Some("2 Banner 200 × 50 pt".to_string()), Some(false), None)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_clicking_a_row_fits_its_artboard_and_keeps_the_choice() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
|
||||
@@ -495,12 +495,14 @@ impl VectorcraftApp {
|
||||
|
||||
/// The canvas panel's body: the document tabs, the canvas (a pane for each document while
|
||||
/// Window › Arrange › Tile is on) and the isolation bar over it. While the current document is
|
||||
/// in a floating window, the tab strip's document draws as a pane.
|
||||
/// in a floating window, the tab strip's document draws as a pane, which a Selection drag's
|
||||
/// artwork can be released in ([`canvas::note_drop`]).
|
||||
pub(crate) fn canvas_area(&mut self, ui: &mut egui::Ui) {
|
||||
let t = theme::Tokens::get(ui.ctx());
|
||||
// Tools may already occupy the left side of this panel.
|
||||
ui.painter().rect_filled(ui.available_rect_before_wrap(), 0.0, t.pasteboard);
|
||||
self.canvas.windows.strip = None;
|
||||
self.canvas.windows.drops.clear();
|
||||
if self.ui.screen_mode < 3 {
|
||||
chrome::doc_tabs(self, ui);
|
||||
}
|
||||
@@ -509,10 +511,15 @@ impl VectorcraftApp {
|
||||
if !canvas::tiled_area(self, ui) {
|
||||
if floats {
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
if let Some(w) = crate::doc_windows::tab_window(self)
|
||||
&& canvas::pane(self, ui, w, rect)
|
||||
{
|
||||
crate::doc_windows::show_window(self, w);
|
||||
if let Some(w) = crate::doc_windows::tab_window(self) {
|
||||
let pressed = canvas::pane(self, ui, w, rect);
|
||||
// A drag from a current window that is an OS window ends in that window.
|
||||
if !crate::doc_windows::native(self, ui.ctx()) {
|
||||
canvas::note_drop(self, ui, w, rect);
|
||||
}
|
||||
if pressed {
|
||||
crate::doc_windows::show_window(self, w);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
canvas::show(self, ui);
|
||||
|
||||
@@ -42,7 +42,7 @@ pub use cursor::{HOVER_STILL_SECS, STILL_SECS, ViewKey};
|
||||
use cursor::{cursor_icon, hover_cursor, hover_wait, still_wait};
|
||||
use drag::drag_id;
|
||||
pub use drag::{apply_requests, dispatch, mods};
|
||||
pub(crate) use drag::{end_document_drag, pose_on_page, release_art_in_window, release_over_panel};
|
||||
pub(crate) use drag::{art_out, end_art_move, end_document_drag, pose_on_page, release_art_in_window, release_over_panel};
|
||||
#[cfg(test)]
|
||||
use drag::{frame_moves, tool_drag_doc_id, tool_drag_moved, tool_frame_moves, tool_press_doc_id};
|
||||
pub use fill::Fill;
|
||||
@@ -65,7 +65,7 @@ pub use overlays::SharedPaths;
|
||||
use overlays::selected_anchor;
|
||||
use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay};
|
||||
pub use panes::Panes;
|
||||
pub(crate) use panes::{consolidate, pane, tile, tiled_area};
|
||||
pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area};
|
||||
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
|
||||
pub(crate) use raster::{color_image, color_image_owned, render_job};
|
||||
pub use selection_marks::SelectionMarks;
|
||||
|
||||
@@ -29,6 +29,11 @@ pub(crate) fn end_document_drag(ctx: &egui::Context) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether a Selection tool move has left the canvas ([`drag_art_out`]) and still waits there.
|
||||
pub(crate) fn art_out(ctx: &egui::Context) -> bool {
|
||||
matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Art))
|
||||
}
|
||||
|
||||
/// Temp-memory key for the active canvas drag state.
|
||||
pub(super) fn drag_id() -> egui::Id {
|
||||
egui::Id::unique("canvas-drag")
|
||||
@@ -320,6 +325,9 @@ pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response,
|
||||
/// panel that takes the art ([`widgets::PanelDrag::Art`]) takes it where it was, and no move is
|
||||
/// left open (#2826). The art stays where it last moved while the pointer is over the panel.
|
||||
pub(crate) fn release_over_panel(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// A floating window's pane, or the main window's while the current window floats, takes the
|
||||
// art first.
|
||||
super::release_on_noted(app, ctx);
|
||||
crate::document_drag::cleanup(app, ctx);
|
||||
let art = matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Art));
|
||||
// Over a floating panel's own OS window the pointer is gone from this window, and the release
|
||||
@@ -355,8 +363,9 @@ pub(crate) fn release_art_in_window(app: &mut VectorcraftApp, ctx: &egui::Contex
|
||||
}
|
||||
}
|
||||
|
||||
/// Roll back the art move dragged off the canvas; a panel takes the art instead.
|
||||
fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
/// Roll back the art move dragged off the canvas, and end the canvas's drag; a panel or another
|
||||
/// window's tiled pane takes the art instead.
|
||||
pub(crate) fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// With no document open there is nothing to roll back; the tool still gets its mouse-up.
|
||||
let _ = app.session.cancel_interaction();
|
||||
let view = app.view_info();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document
|
||||
//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its
|
||||
//! document from a render of its own, with its artboards, guides and selected objects, and a press
|
||||
//! in it makes its document the current one. Each view Window › New Window opened has a pane of
|
||||
//! its own ([`crate::doc_windows`]).
|
||||
//! in it makes its document the current one. A Selection drag released in it drops the dragged
|
||||
//! artwork into its document ([`crate::document_drag::drop_on_pane`]). Each view Window › New
|
||||
//! Window opened has a pane of its own ([`crate::doc_windows`]).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -243,12 +244,18 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect();
|
||||
let unfitted = refit_resized(app, &areas);
|
||||
let mut activate = None;
|
||||
let (mut cursor, mut dropped) = (None, None);
|
||||
// The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar)
|
||||
// stays over them.
|
||||
for (w, cell) in cells.iter().copied().filter(|(w, _)| Some(*w) != active) {
|
||||
for ((w, cell), (_, area)) in cells.iter().copied().zip(areas.iter().copied()).filter(|((w, _), _)| Some(*w) != active) {
|
||||
if pane(app, ui, w, cell) {
|
||||
activate = Some(w);
|
||||
}
|
||||
match artwork_over(app, ui, w, area) {
|
||||
Some(Over::Held(c)) => cursor = Some(c),
|
||||
Some(Over::Released(at, carried)) => dropped = Some((w, at, carried)),
|
||||
None => {}
|
||||
}
|
||||
ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
|
||||
}
|
||||
if let Some((_, cell)) = cells.iter().copied().find(|(w, _)| Some(*w) == active) {
|
||||
@@ -256,6 +263,10 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
super::show(app, &mut canvas);
|
||||
ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside);
|
||||
}
|
||||
// After the canvas, which sets the cursor of the drag it holds.
|
||||
if let Some(c) = cursor {
|
||||
ui.ctx().set_cursor_icon(c);
|
||||
}
|
||||
// Note the fits this frame made, for `refit_resized`.
|
||||
for ((w, area), was_unfitted) in areas.iter().zip(unfitted) {
|
||||
if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) {
|
||||
@@ -263,12 +274,86 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
|
||||
}
|
||||
}
|
||||
app.canvas.panes.last = cells;
|
||||
if let Some(w) = activate {
|
||||
if let Some((w, at, carried)) = dropped {
|
||||
crate::document_drag::drop_on_pane(app, ui.ctx(), w, at, carried);
|
||||
} else if let Some(w) = activate {
|
||||
crate::doc_windows::show_window(app, w);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A Selection drag's artwork over another window's tiled pane.
|
||||
enum Over {
|
||||
/// Held there: the cursor that shows whether a release moves or copies it.
|
||||
Held(egui::CursorIcon),
|
||||
/// Released there, at a document point in the pane's own view.
|
||||
Released(Point, crate::document_drag::Carried),
|
||||
}
|
||||
|
||||
/// A Selection drag's artwork over `area`, the part of window `w`'s pane inside its rulers and
|
||||
/// scroll bars, where no panel or floating window is over the pointer. A release there takes the
|
||||
/// artwork before the canvas sees the release ([`crate::document_drag::take_for_pane`]).
|
||||
fn artwork_over(app: &mut VectorcraftApp, ui: &Ui, w: Win, area: egui::Rect) -> Option<Over> {
|
||||
let (uid, _) = slot(app, w)?;
|
||||
let p = ui.input(crate::document_drag::released_at)?;
|
||||
if !area.contains(p) || ui.ctx().layer_id_at(p).is_some_and(|l| l != ui.layer_id()) {
|
||||
return None;
|
||||
}
|
||||
let cursor = crate::document_drag::pane_cursor(app, ui.ctx(), uid)?;
|
||||
if !ui.input(|i| i.pointer.primary_released()) {
|
||||
return Some(Over::Held(cursor));
|
||||
}
|
||||
let v = crate::doc_windows::view(app, w).copied()?;
|
||||
let at = Xf::at(area, &v, ui.ctx().zoom_factor()).to_doc(p);
|
||||
Some(Over::Released(at, crate::document_drag::take_for_pane(app, ui.ctx())?))
|
||||
}
|
||||
|
||||
/// Note window `w`'s pane, drawn in `cell` of `ui` outside Tile (a floating window inside the main
|
||||
/// window, or the main window while the current window floats), as a place a Selection drag's
|
||||
/// artwork can be released in ([`release_on_noted`]): the part inside its rulers and scroll bars.
|
||||
pub(crate) fn note_drop(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) {
|
||||
let Some(s) = slot(app, w) else { return };
|
||||
let area = view_rects(app, cell, ui.ctx().pixels_per_point()).1;
|
||||
app.canvas.windows.drops.push((s, area, ui.layer_id()));
|
||||
}
|
||||
|
||||
/// The noted pane ([`note_drop`]) at `p`, where no panel or other window is over it: its window
|
||||
/// and its art area.
|
||||
fn noted_at(app: &VectorcraftApp, ctx: &egui::Context, p: egui::Pos2) -> Option<(Win, egui::Rect)> {
|
||||
let top = ctx.layer_id_at(p);
|
||||
let (s, area, _) = app.canvas.windows.drops.iter().rev().find(|(_, area, layer)| area.contains(p) && top.is_none_or(|l| l == *layer))?;
|
||||
let w = crate::doc_windows::windows(app).into_iter().find(|w| slot(app, *w) == Some(*s))?;
|
||||
Some((w, *area))
|
||||
}
|
||||
|
||||
/// A Selection drag's artwork released over a pane the last frame noted ([`note_drop`]) drops into
|
||||
/// its document ([`crate::document_drag::drop_on_pane`]), at the document point where the button
|
||||
/// went up, in that pane's own view. Runs at the start of a frame, before any canvas sees the release.
|
||||
pub(crate) fn release_on_noted(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
if app.canvas.windows.drops.is_empty() || !ctx.input(|i| i.pointer.primary_released()) {
|
||||
return;
|
||||
}
|
||||
let Some(p) = ctx.input(crate::document_drag::released_at) else { return };
|
||||
let Some((w, area)) = noted_at(app, ctx, p) else { return };
|
||||
let Some(v) = crate::doc_windows::view(app, w).copied() else { return };
|
||||
let at = Xf::at(area, &v, ctx.zoom_factor()).to_doc(p);
|
||||
if let Some(carried) = crate::document_drag::take_for_pane(app, ctx) {
|
||||
crate::document_drag::drop_on_pane(app, ctx, w, at, carried);
|
||||
}
|
||||
}
|
||||
|
||||
/// While a Selection drag's artwork is held over a pane this frame noted ([`note_drop`]), the cursor
|
||||
/// shows whether a release there moves or copies it ([`crate::document_drag::pane_cursor`]).
|
||||
pub(crate) fn noted_cursor(app: &VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return };
|
||||
if let Some((w, _)) = noted_at(app, ctx, p)
|
||||
&& let Some((uid, _)) = slot(app, w)
|
||||
&& let Some(c) = crate::document_drag::pane_cursor(app, ctx, uid)
|
||||
{
|
||||
ctx.set_cursor_icon(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// Window `w`'s [`Slot`].
|
||||
fn slot(app: &VectorcraftApp, (i, n): Win) -> Option<Slot> {
|
||||
app.session.documents().get(i).map(|d| (d.uid, n))
|
||||
|
||||
@@ -165,6 +165,254 @@ fn a_press_in_another_pane_makes_its_document_current_without_drawing() {
|
||||
assert!(app.session.documents()[1..].iter().all(|d| d.doc.art_bounds().is_none()));
|
||||
}
|
||||
|
||||
/// One headless frame at `time` seconds as the app runs it: a Selection move released off the
|
||||
/// canvas ends first ([`crate::canvas::release_over_panel`]), then the tabs and the panes draw.
|
||||
fn timed_frame(app: &mut VectorcraftApp, ctx: &egui::Context, time: Option<f64>, events: Vec<egui::Event>) -> egui::FullOutput {
|
||||
let raw = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))),
|
||||
max_texture_side: Some(8192),
|
||||
time,
|
||||
events,
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
crate::canvas::release_over_panel(app, ui.ctx());
|
||||
app.canvas_area(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
out
|
||||
}
|
||||
|
||||
/// [`timed_frame`] without a time. → the cursor.
|
||||
fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::CursorIcon {
|
||||
timed_frame(app, ctx, None, events).platform_output.cursor_icon
|
||||
}
|
||||
|
||||
/// Two 400 × 300 pt documents tiled side by side: the first, current, holds a selected 100 pt
|
||||
/// square at 50, 50 and the second a 50 pt square at 300, 230. The Selection tool is chosen.
|
||||
fn tiled_pair() -> (VectorcraftApp, egui::Context) {
|
||||
let mut app = app_with(0);
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 300, "y": 230, "width": 50, "height": 50})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.select_tool("selection");
|
||||
app.ui.task_bar = false;
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
(app, ctx)
|
||||
}
|
||||
|
||||
/// Press on document point `at` on the canvas and move the pointer 20 × 10 points, still on the
|
||||
/// canvas: the Selection tool moves the art under it.
|
||||
fn grab(app: &mut VectorcraftApp, ctx: &egui::Context, at: Point) {
|
||||
let p = Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(at);
|
||||
app_frame(app, ctx, vec![egui::Event::PointerMoved(p), button(p, true)]);
|
||||
app_frame(app, ctx, vec![egui::Event::PointerMoved(p + vec2(20.0, 10.0))]);
|
||||
assert!(app.session.in_interaction(), "the Selection tool moves the art");
|
||||
}
|
||||
|
||||
/// Window `w`'s pane: the screen point that shows document point `at` in it, and the pane.
|
||||
fn in_pane(app: &VectorcraftApp, ctx: &egui::Context, w: Win, at: Point) -> (Pos2, egui::Rect) {
|
||||
let (_, cell) = app.canvas.panes.last.iter().copied().find(|(o, _)| *o == w).unwrap();
|
||||
let area = view_rects(app, cell, ctx.pixels_per_point()).1;
|
||||
(Xf::at(area, crate::doc_windows::view(app, w).unwrap(), 1.0).to_screen(at), cell)
|
||||
}
|
||||
|
||||
/// How many objects document `i`'s first layer holds.
|
||||
fn objects(app: &VectorcraftApp, i: usize) -> usize {
|
||||
app.session.documents()[i].doc.layers[0].children().map_or(0, Vec::len)
|
||||
}
|
||||
|
||||
/// The bounds of the one object selected in the current document.
|
||||
fn selected_bounds(app: &VectorcraftApp) -> Rect {
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.selection.objects.len(), 1, "one object is selected");
|
||||
st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_drag_released_in_another_documents_pane_copies_the_art_there() {
|
||||
let (mut app, ctx) = tiled_pair();
|
||||
// The target's view differs from the source's: the grab point still lands under the pointer.
|
||||
app.views[1].zoom *= 0.6;
|
||||
app.views[1].rotation = 30.0;
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
let source = app.session.documents()[0].doc.clone();
|
||||
let source_undo = app.session.documents()[0].history.undo.len();
|
||||
let target = app.session.documents()[1].doc.clone();
|
||||
let target_undo = app.session.documents()[1].history.undo.len();
|
||||
let clipboard = app.session.clipboard.clone();
|
||||
grab(&mut app, &ctx, Point::new(100.0, 100.0));
|
||||
let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(170.0, 120.0));
|
||||
// The release comes in the first frame the pointer is over the pane.
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop), button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(1), "the pane's document is the current one");
|
||||
let placed = selected_bounds(&app);
|
||||
assert!((placed.center().x - 170.0).abs() < 0.01 && (placed.center().y - 120.0).abs() < 0.01, "{placed:?}");
|
||||
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo + 1, "one step to undo");
|
||||
assert_eq!(app.session.documents()[0].doc, source, "the source keeps its art where it was");
|
||||
assert_eq!(app.session.documents()[0].history.undo.len(), source_undo);
|
||||
assert_eq!(app.session.clipboard, clipboard, "the drag leaves the clipboard alone");
|
||||
assert!(!app.session.tool_busy());
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.session.documents()[1].doc, target);
|
||||
app.run("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_held_over_another_pane_shows_a_copy_and_drags_back_the_other_way() {
|
||||
let (mut app, ctx) = tiled_pair();
|
||||
grab(&mut app, &ctx, Point::new(100.0, 100.0));
|
||||
let (over, _) = in_pane(&app, &ctx, (1, 1), Point::new(200.0, 150.0));
|
||||
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(over)]);
|
||||
assert_eq!(cursor, egui::CursorIcon::Copy, "over another document's pane the art is copied");
|
||||
assert_eq!(app.session.active_index(), Some(0), "holding the art over a pane does not switch documents");
|
||||
let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(120.0, 90.0));
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
|
||||
app_frame(&mut app, &ctx, vec![button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(1));
|
||||
assert_eq!(objects(&app, 1), 2, "the copy joins the target's square");
|
||||
// From the target, now the canvas, back into the first document's pane.
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
grab(&mut app, &ctx, Point::new(325.0, 255.0));
|
||||
let (back, _) = in_pane(&app, &ctx, (0, 1), Point::new(300.0, 200.0));
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(back), button(back, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(0));
|
||||
let placed = selected_bounds(&app);
|
||||
assert!((placed.center().x - 300.0).abs() < 0.01 && (placed.center().y - 200.0).abs() < 0.01, "{placed:?}");
|
||||
assert_eq!(objects(&app, 0), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_drag_into_another_view_of_its_document_moves_the_art() {
|
||||
let (mut app, ctx) = tiled_pair();
|
||||
app.run("window.newWindow", json!({})).unwrap();
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
let current = crate::doc_windows::current(&app).unwrap();
|
||||
let other = app.canvas.panes.last.iter().map(|(w, _)| *w).find(|w| w.0 == 0 && *w != current).unwrap();
|
||||
let undo = app.session.documents()[0].history.undo.len();
|
||||
let target = app.session.documents()[1].doc.clone();
|
||||
grab(&mut app, &ctx, Point::new(100.0, 100.0));
|
||||
let (drop, _) = in_pane(&app, &ctx, other, Point::new(250.0, 200.0));
|
||||
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
|
||||
assert_eq!(cursor, egui::CursorIcon::Move, "another view of the same document moves the art");
|
||||
app_frame(&mut app, &ctx, vec![button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(crate::doc_windows::current(&app), Some(other), "the pane's view is the current window");
|
||||
assert_eq!(objects(&app, 0), 1, "the square moved, not copied");
|
||||
let moved = selected_bounds(&app);
|
||||
assert!((moved.center().x - 250.0).abs() < 0.01 && (moved.center().y - 200.0).abs() < 0.01, "{moved:?}");
|
||||
assert_eq!(app.session.documents()[0].history.undo.len(), undo + 1);
|
||||
assert_eq!(app.session.documents()[1].doc, target, "the other document is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pane_drop_lands_where_the_button_went_up_and_copies_when_alt_was_held_then() {
|
||||
// A pointer move later in the frame of the release does not move the drop.
|
||||
let (mut app, ctx) = tiled_pair();
|
||||
grab(&mut app, &ctx, Point::new(100.0, 100.0));
|
||||
let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(170.0, 120.0));
|
||||
let (later, _) = in_pane(&app, &ctx, (1, 1), Point::new(80.0, 60.0));
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop), button(drop, false), egui::Event::PointerMoved(later)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(1));
|
||||
let placed = selected_bounds(&app);
|
||||
assert!((placed.center().x - 170.0).abs() < 0.01 && (placed.center().y - 120.0).abs() < 0.01, "{placed:?}");
|
||||
// Alt held at the release and let go later in that frame copies into another view of the source.
|
||||
let (mut app, ctx) = tiled_pair();
|
||||
app.run("window.newWindow", json!({})).unwrap();
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
let current = crate::doc_windows::current(&app).unwrap();
|
||||
let other = app.canvas.panes.last.iter().map(|(w, _)| *w).find(|w| w.0 == 0 && *w != current).unwrap();
|
||||
grab(&mut app, &ctx, Point::new(100.0, 100.0));
|
||||
let (drop, _) = in_pane(&app, &ctx, other, Point::new(250.0, 200.0));
|
||||
let alt = egui::Modifiers::ALT;
|
||||
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::ModifiersChanged(alt), egui::Event::PointerMoved(drop)]);
|
||||
assert_eq!(cursor, egui::CursorIcon::Copy, "Alt shows a copy");
|
||||
let up = egui::Event::PointerButton { pos: drop, button: egui::PointerButton::Primary, pressed: false, modifiers: alt };
|
||||
app_frame(&mut app, &ctx, vec![up, egui::Event::ModifiersChanged(egui::Modifiers::NONE)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(crate::doc_windows::current(&app), Some(other));
|
||||
assert_eq!(objects(&app, 0), 2, "the square was copied, not moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_carried_through_a_tab_drops_into_a_third_documents_pane() {
|
||||
let (mut app, ctx) = tiled_pair();
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.run("window.arrange.tile", json!({})).unwrap();
|
||||
let source = app.session.documents()[0].doc.clone();
|
||||
let third = app.session.documents()[2].doc.clone();
|
||||
let titles = |out: egui::FullOutput| -> Vec<egui::Rect> {
|
||||
let mut t: Vec<_> = out
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
Shape::Text(t) if t.galley.text().contains(" @ ") => Some(egui::Rect::from_min_size(t.pos, t.galley.size())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
t.sort_by(|a, b| a.left().total_cmp(&b.left()));
|
||||
t
|
||||
};
|
||||
timed_frame(&mut app, &ctx, Some(0.0), vec![]);
|
||||
let tabs = titles(timed_frame(&mut app, &ctx, Some(0.01), vec![]));
|
||||
assert_eq!(tabs.len(), 3);
|
||||
let p = Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(Point::new(100.0, 100.0));
|
||||
timed_frame(&mut app, &ctx, Some(0.05), vec![egui::Event::PointerMoved(p), button(p, true)]);
|
||||
timed_frame(&mut app, &ctx, Some(0.1), vec![egui::Event::PointerMoved(p + vec2(20.0, 10.0))]);
|
||||
timed_frame(&mut app, &ctx, Some(0.2), vec![egui::Event::PointerMoved(tabs[2].center())]);
|
||||
timed_frame(&mut app, &ctx, Some(0.25), vec![]);
|
||||
timed_frame(&mut app, &ctx, Some(0.8), vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(2), "holding the art over the third tab makes that document current");
|
||||
timed_frame(&mut app, &ctx, Some(0.85), vec![]);
|
||||
let (drop, _) = in_pane(&app, &ctx, (1, 1), Point::new(150.0, 100.0));
|
||||
timed_frame(&mut app, &ctx, Some(0.9), vec![egui::Event::PointerMoved(drop)]);
|
||||
timed_frame(&mut app, &ctx, Some(1.0), vec![button(drop, false)]);
|
||||
timed_frame(&mut app, &ctx, Some(1.1), vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(1), "the pane's document is the current one");
|
||||
assert_eq!(objects(&app, 1), 2, "the copy joins the second document's square");
|
||||
let placed = selected_bounds(&app);
|
||||
assert!((placed.center().x - 150.0).abs() < 0.01 && (placed.center().y - 100.0).abs() < 0.01, "{placed:?}");
|
||||
assert_eq!(app.session.documents()[0].doc, source);
|
||||
assert_eq!(app.session.documents()[2].doc, third, "the document the tab showed is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_released_off_a_panes_art_area_or_after_escape_changes_nothing() {
|
||||
for (case, escape) in [("scroll bar", false), ("art area after Escape", true)] {
|
||||
let (mut app, ctx) = tiled_pair();
|
||||
let docs: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect();
|
||||
grab(&mut app, &ctx, Point::new(100.0, 100.0));
|
||||
let (inside, cell) = in_pane(&app, &ctx, (1, 1), Point::new(200.0, 150.0));
|
||||
let at = if escape { inside } else { pos2(cell.right() - 2.0, cell.center().y) };
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
if escape {
|
||||
let key = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
|
||||
app_frame(&mut app, &ctx, vec![key]);
|
||||
}
|
||||
app_frame(&mut app, &ctx, vec![button(at, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(0), "{case}: the source stays current");
|
||||
let after: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect();
|
||||
assert!(after == docs, "{case}: neither document changes");
|
||||
assert!(!app.session.in_interaction(), "{case}: the move ended");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consolidate_all_windows_shows_one_document_again() {
|
||||
let mut app = app_with(2);
|
||||
|
||||
@@ -133,8 +133,8 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
// Search → command palette (its shortcut opens it too).
|
||||
if search {
|
||||
let tip = match menus::shortcut_of("help.commandPalette") {
|
||||
Some(sc) => format!("{} ({})", tl!("Search commands and tools"), menus::shown_shortcut(sc)),
|
||||
None => tl!("Search commands and tools").to_string(),
|
||||
Some(sc) => format!("{} ({})", tl!("Search commands, tools, panels and effects"), menus::shown_shortcut(sc)),
|
||||
None => tl!("Search commands, tools, panels and effects").to_string(),
|
||||
};
|
||||
if widgets::icon_button(ui, "search", &tip, app.ui.palette_open, icon).clicked() {
|
||||
app.ui.palette_open = !app.ui.palette_open;
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//! the main window, it is a window inside the app's window, as floating panels are
|
||||
//! ([`crate::panel_docking`]). The current document's window holds the canvas
|
||||
//! ([`crate::canvas::show`]); each other window draws its document as a Tile pane does
|
||||
//! ([`crate::canvas::pane`]), and a press in it makes its document the current one.
|
||||
//! ([`crate::canvas::pane`]), and a press in it makes its document the current one. In a window
|
||||
//! inside the app's window, a Selection drag released over that pane drops the dragged artwork into
|
||||
//! its document ([`crate::canvas::release_on_noted`]); an OS window's pane does not take it.
|
||||
//!
|
||||
//! A document tab dragged off the tab strip floats its document in a window under the pointer,
|
||||
//! and a document window dragged onto the tab strip by its title bar (an OS window by the tab at
|
||||
@@ -95,6 +97,10 @@ pub struct Windows {
|
||||
known: Vec<u64>,
|
||||
/// The documents' views beyond the one each shows ([`views`]).
|
||||
pub(crate) views: Views,
|
||||
/// The panes the last frame drew outside Tile that a Selection drag's artwork can be released
|
||||
/// in ([`crate::canvas::note_drop`]): each window's view ([`views::key`]), the part of its pane
|
||||
/// inside its rulers and scroll bars in the main window's points, and the layer it drew in.
|
||||
pub(crate) drops: Vec<((u64, u32), egui::Rect, egui::LayerId)>,
|
||||
}
|
||||
|
||||
impl Windows {
|
||||
@@ -325,7 +331,7 @@ pub(crate) fn dock_all(app: &mut VectorcraftApp) {
|
||||
/// floats panels by the same rule), and no control channel is attached. With a control channel the
|
||||
/// windows stay inside the main window, where `ui.click`, `ui.drag` and `ui.screenshot` reach them
|
||||
/// and `canvasRect` is in the main window's coordinates.
|
||||
fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
|
||||
pub(crate) fn native(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
|
||||
if ctx.embed_viewports() || app.control_rx.is_some() {
|
||||
return false;
|
||||
}
|
||||
@@ -469,6 +475,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
activate = Some(win);
|
||||
}
|
||||
}
|
||||
// After every canvas, which sets the cursor of the drag it holds.
|
||||
crate::canvas::noted_cursor(app, ctx);
|
||||
// The tab strip a dragged window would go back under shows where it lands.
|
||||
if let Some(strip) = app.canvas.windows.strip.filter(|_| over_strip) {
|
||||
let t = crate::theme::Tokens::get(ctx);
|
||||
@@ -499,9 +507,10 @@ pub(crate) fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
|
||||
/// Window `win`'s body in `ui`: the canvas for the current window, else (and while `blocked` by a
|
||||
/// modal) a pane. The view fits the body again when the body changed size since `fit` and the view
|
||||
/// has not moved. → whether a press in the pane asks for its window to become the current one, the
|
||||
/// body's rect and the fit after this frame.
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool), fit: Option<Fit>) -> (bool, egui::Rect, Option<Fit>) {
|
||||
/// has not moved. With `drops`, a pane drawn while no modal blocks it is noted as a place a Selection
|
||||
/// drag's artwork can be released in ([`crate::canvas::note_drop`]). → whether a press in the pane
|
||||
/// asks for its window to become the current one, the body's rect and the fit after this frame.
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool), fit: Option<Fit>, drops: bool) -> (bool, egui::Rect, Option<Fit>) {
|
||||
let t = crate::theme::Tokens::get(ui.ctx());
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
ui.painter().rect_filled(rect, 0.0, t.pasteboard);
|
||||
@@ -517,7 +526,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, (win, blocked): (Win, bool)
|
||||
crate::canvas::show(app, ui);
|
||||
false
|
||||
} else {
|
||||
crate::canvas::pane(app, ui, win, rect)
|
||||
let pressed = crate::canvas::pane(app, ui, win, rect);
|
||||
if drops && !blocked {
|
||||
crate::canvas::note_drop(app, ui, win, rect);
|
||||
}
|
||||
pressed
|
||||
};
|
||||
ui.advance_cursor_after_rect(rect);
|
||||
let fit = match view(app, win) {
|
||||
@@ -564,7 +577,8 @@ fn os_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win,
|
||||
}
|
||||
let tab = crate::chrome::window_tab(app, ui, win);
|
||||
let (over_strip, dock) = if blocked { (false, false) } else { drag_tab(app, ui, ((w.uid, w.view), origin), &tab, strip) };
|
||||
let (pressed, rect, fit) = body(app, ui, (win, blocked), w.fit);
|
||||
// The OS window's points are not the main window's: its pane takes no artwork.
|
||||
let (pressed, rect, fit) = body(app, ui, (win, blocked), w.fit, false);
|
||||
let activate = pressed || (!blocked && (tab.clicked() || tab.drag_started()));
|
||||
// Keys the window's widgets left over run the main window's shortcuts and tool keys, as a
|
||||
// floating panel's do.
|
||||
@@ -649,7 +663,7 @@ fn app_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: &DocWindow, (win
|
||||
.frame(frame)
|
||||
.open(&mut open)
|
||||
.show(ctx, |ui| {
|
||||
let (pressed, r, f) = body(app, ui, (win, blocked), fit);
|
||||
let (pressed, r, f) = body(app, ui, (win, blocked), fit, true);
|
||||
(activate, rect, fit) = (pressed, Some(r), f);
|
||||
});
|
||||
// A press on its title bar or edges, which brings the window to the front, also makes its
|
||||
|
||||
@@ -925,3 +925,303 @@ fn switching_views_targets_the_artboard_the_view_shows() {
|
||||
show_window(&mut app, (0, 2));
|
||||
assert_eq!(app.session.tool_options()["active"], json!(1));
|
||||
}
|
||||
|
||||
/// One headless frame as the app runs it: a Selection move released off the canvas ends first
|
||||
/// ([`crate::canvas::release_over_panel`]), then the tabs and the canvas or panes, then the floating
|
||||
/// document windows. → the cursor.
|
||||
fn app_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::CursorIcon {
|
||||
let raw = egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))),
|
||||
max_texture_side: Some(8192),
|
||||
events,
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
crate::canvas::release_over_panel(app, ui.ctx());
|
||||
app.canvas_area(ui);
|
||||
show(app, ui.ctx());
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
out.platform_output.cursor_icon
|
||||
}
|
||||
|
||||
/// Two 400 × 300 pt documents on `ctx`: the first, current under its tab, holds a 50 pt square at
|
||||
/// 300, 230, and the second, in a floating window, a 50 pt square at 50, 50. The Selection tool is
|
||||
/// chosen.
|
||||
fn floating_pair(ctx: &egui::Context) -> VectorcraftApp {
|
||||
let mut app = app_with(0);
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 300, "y": 230, "width": 50, "height": 50})).unwrap();
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 50, "height": 50})).unwrap();
|
||||
app.run("window.arrange.floatInWindow", json!({})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.select_tool("selection");
|
||||
app.ui.task_bar = false;
|
||||
app_frame(&mut app, ctx, vec![]);
|
||||
app_frame(&mut app, ctx, vec![]);
|
||||
app
|
||||
}
|
||||
|
||||
/// Press on document point `at` on the canvas, clear of document 1's window when it floats, and
|
||||
/// move the pointer 10 × 5 points: the Selection tool moves the art under it.
|
||||
fn grab(app: &mut VectorcraftApp, ctx: &egui::Context, at: vectorcraft_geom::Point) {
|
||||
let p = crate::canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(at);
|
||||
if app.session.documents().len() > 1 && app.session.active_index() != Some(1) && is_floating(app, 1) {
|
||||
assert!(!window_of(app, ctx, 1).contains(p), "the art is clear of the floating window");
|
||||
}
|
||||
app_frame(app, ctx, vec![egui::Event::PointerMoved(p), button(p, true)]);
|
||||
app_frame(app, ctx, vec![egui::Event::PointerMoved(p + vec2(10.0, 5.0))]);
|
||||
assert!(app.session.in_interaction(), "the Selection tool moves the art");
|
||||
}
|
||||
|
||||
/// The screen point that shows document point `at` in window `w`'s pane, which the last frame noted
|
||||
/// as a place to release artwork in.
|
||||
fn in_noted(app: &VectorcraftApp, w: Win, at: vectorcraft_geom::Point) -> Pos2 {
|
||||
let k = key(app, w).unwrap();
|
||||
let (_, area, _) = app.canvas.windows.drops.iter().find(|(s, _, _)| *s == k).unwrap();
|
||||
crate::canvas::Xf::at(*area, view(app, w).unwrap(), 1.0).to_screen(at)
|
||||
}
|
||||
|
||||
/// How many objects document `i`'s first layer holds.
|
||||
fn objects(app: &VectorcraftApp, i: usize) -> usize {
|
||||
app.session.documents()[i].doc.layers[0].children().map_or(0, Vec::len)
|
||||
}
|
||||
|
||||
/// The center of the one object selected in the current document.
|
||||
fn selected_center(app: &VectorcraftApp) -> vectorcraft_geom::Point {
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.selection.objects.len(), 1, "one object is selected");
|
||||
st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap().center()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_drag_released_in_another_documents_floating_window_copies_the_art_there() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = floating_pair(&ctx);
|
||||
// The target's view differs from the source's: the grab point still lands under the pointer.
|
||||
let v = view_mut(&mut app, (1, 1)).unwrap();
|
||||
v.zoom *= 0.6;
|
||||
v.rotation = 30.0;
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
let source = app.session.documents()[0].doc.clone();
|
||||
let source_undo = app.session.documents()[0].history.undo.len();
|
||||
let target = app.session.documents()[1].doc.clone();
|
||||
let target_undo = app.session.documents()[1].history.undo.len();
|
||||
let clipboard = app.session.clipboard.clone();
|
||||
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
|
||||
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(170.0, 120.0));
|
||||
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
|
||||
assert_eq!(cursor, egui::CursorIcon::Copy, "over another document's window the art is copied");
|
||||
assert_eq!(app.session.active_index(), Some(0), "holding the art over the window does not switch documents");
|
||||
app_frame(&mut app, &ctx, vec![button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(1), "the window's document is the current one");
|
||||
assert_eq!(objects(&app, 1), 2, "the copy joins the target's square");
|
||||
let placed = selected_center(&app);
|
||||
assert!((placed.x - 170.0).abs() < 0.01 && (placed.y - 120.0).abs() < 0.01, "{placed:?}");
|
||||
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo + 1, "one step to undo");
|
||||
assert_eq!(app.session.documents()[0].doc, source, "the source keeps its art where it was");
|
||||
assert_eq!(app.session.documents()[0].history.undo.len(), source_undo);
|
||||
assert_eq!(app.session.clipboard, clipboard, "the drag leaves the clipboard alone");
|
||||
assert!(!app.session.tool_busy());
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(app.session.documents()[1].doc, target);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_release_in_the_first_frame_over_a_floating_window_still_copies_the_art() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = floating_pair(&ctx);
|
||||
let source = app.session.documents()[0].doc.clone();
|
||||
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
|
||||
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0));
|
||||
// The canvas has not handed the move over yet: the pane takes it before the canvas sees the
|
||||
// release.
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop), button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(1));
|
||||
assert_eq!(objects(&app, 1), 2);
|
||||
let placed = selected_center(&app);
|
||||
assert!((placed.x - 200.0).abs() < 0.01 && (placed.y - 150.0).abs() < 0.01, "{placed:?}");
|
||||
assert_eq!(app.session.documents()[0].doc, source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_floating_window_drop_lands_where_the_button_went_up() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = floating_pair(&ctx);
|
||||
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
|
||||
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0));
|
||||
let later = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(120.0, 220.0));
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
|
||||
// A pointer move later in the frame of the release does not move the drop.
|
||||
app_frame(&mut app, &ctx, vec![button(drop, false), egui::Event::PointerMoved(later)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(1));
|
||||
assert_eq!(objects(&app, 1), 2);
|
||||
let placed = selected_center(&app);
|
||||
assert!((placed.x - 200.0).abs() < 0.01 && (placed.y - 150.0).abs() < 0.01, "{placed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_dragged_from_a_floating_window_drops_into_the_main_windows_document() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = floating_pair(&ctx);
|
||||
show_window(&mut app, (1, 1));
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert!(current_floats(&app), "the floating window holds the canvas");
|
||||
let target = app.session.documents()[1].doc.clone();
|
||||
grab(&mut app, &ctx, vectorcraft_geom::Point::new(75.0, 75.0));
|
||||
// The main window draws document 0 as a pane; this point is clear of the floating window.
|
||||
let at = vectorcraft_geom::Point::new(360.0, 40.0);
|
||||
let drop = in_noted(&app, (0, 1), at);
|
||||
assert!(!window_of(&app, &ctx, 1).contains(drop), "{drop:?}");
|
||||
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
|
||||
assert_eq!(cursor, egui::CursorIcon::Copy);
|
||||
app_frame(&mut app, &ctx, vec![button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(0), "the main window's document is the current one");
|
||||
assert_eq!(objects(&app, 0), 2);
|
||||
let placed = selected_center(&app);
|
||||
assert!((placed.x - at.x).abs() < 0.01 && (placed.y - at.y).abs() < 0.01, "{placed:?}");
|
||||
assert_eq!(app.session.documents()[1].doc, target, "the source in the floating window is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_drag_into_a_floating_view_of_its_document_moves_the_art() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app_with(0);
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 300, "y": 230, "width": 50, "height": 50})).unwrap();
|
||||
app.run("window.newWindow", json!({})).unwrap();
|
||||
app.run("window.arrange.floatInWindow", json!({})).unwrap();
|
||||
show_window(&mut app, (0, 1));
|
||||
app.select_tool("selection");
|
||||
app.ui.task_bar = false;
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert!(floats(&app, (0, 2)) && current(&app) == Some((0, 1)));
|
||||
let undo = app.session.documents()[0].history.undo.len();
|
||||
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
|
||||
let drop = in_noted(&app, (0, 2), vectorcraft_geom::Point::new(150.0, 100.0));
|
||||
let cursor = app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
|
||||
assert_eq!(cursor, egui::CursorIcon::Move, "another view of the same document moves the art");
|
||||
app_frame(&mut app, &ctx, vec![button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(current(&app), Some((0, 2)), "the floating view is the current window");
|
||||
assert_eq!(objects(&app, 0), 1, "the square moved, not copied");
|
||||
let moved = selected_center(&app);
|
||||
assert!((moved.x - 150.0).abs() < 0.01 && (moved.y - 100.0).abs() < 0.01, "{moved:?}");
|
||||
assert_eq!(app.session.documents()[0].history.undo.len(), undo + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_released_on_a_floating_windows_title_bar_or_after_escape_changes_nothing() {
|
||||
for (case, escape) in [("title bar", false), ("art area after Escape", true)] {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = floating_pair(&ctx);
|
||||
let docs: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect();
|
||||
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
|
||||
let (window, body) = (window_of(&app, &ctx, 1), body_of(&app, 1));
|
||||
let at = if escape {
|
||||
in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0))
|
||||
} else {
|
||||
pos2(window.left() + 60.0, (window.top() + body.top()) / 2.0)
|
||||
};
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
|
||||
if escape {
|
||||
let key = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
|
||||
app_frame(&mut app, &ctx, vec![key]);
|
||||
}
|
||||
app_frame(&mut app, &ctx, vec![button(at, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(0), "{case}: the source stays current");
|
||||
let after: Vec<_> = app.session.documents().iter().map(|d| (d.doc.clone(), d.history.undo.len())).collect();
|
||||
assert!(after == docs, "{case}: neither document changes");
|
||||
assert!(!app.session.in_interaction(), "{case}: the move ended");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_transfer_whose_source_changed_drops_nothing_in_a_floating_window() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = floating_pair(&ctx);
|
||||
app.run("file.new", json!({"width": 400, "height": 300, "name": "Third"})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.select_tool("selection");
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
let tab = tab_at(&frame(&mut app, &ctx, vec![]), "Third");
|
||||
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
|
||||
// Held over the third document's tab, the drag becomes a transfer to that document.
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(tab)]);
|
||||
for _ in 0..60 {
|
||||
if app.session.active_index() == Some(2) {
|
||||
break;
|
||||
}
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
}
|
||||
assert_eq!(app.session.active_index(), Some(2), "the tab hover switched documents");
|
||||
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0));
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
|
||||
// The source changes between frames, as a command from the control channel would change it.
|
||||
app.session.set_active(0);
|
||||
app.session.execute("shape.ellipse", &json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap();
|
||||
app.session.set_active(2);
|
||||
let target = app.session.documents()[1].doc.clone();
|
||||
let target_undo = app.session.documents()[1].history.undo.len();
|
||||
app_frame(&mut app, &ctx, vec![button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.documents()[1].doc, target, "the floating window's document does not take the changed art");
|
||||
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo);
|
||||
assert_eq!(app.session.active_index(), Some(2), "the window does not become current");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tab_transfer_whose_target_is_no_longer_current_drops_nothing_in_a_floating_window() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = floating_pair(&ctx);
|
||||
app.run("file.new", json!({"width": 400, "height": 300, "name": "Third"})).unwrap();
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
app.select_tool("selection");
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
let tab = tab_at(&frame(&mut app, &ctx, vec![]), "Third");
|
||||
grab(&mut app, &ctx, vectorcraft_geom::Point::new(325.0, 255.0));
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(tab)]);
|
||||
for _ in 0..60 {
|
||||
if app.session.active_index() == Some(2) {
|
||||
break;
|
||||
}
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
}
|
||||
assert_eq!(app.session.active_index(), Some(2), "the tab hover switched documents");
|
||||
let drop = in_noted(&app, (1, 1), vectorcraft_geom::Point::new(200.0, 150.0));
|
||||
app_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(drop)]);
|
||||
// Another document becomes current between frames, as a command from the control channel
|
||||
// would make it.
|
||||
app.session.set_active(0);
|
||||
let target = app.session.documents()[1].doc.clone();
|
||||
let target_undo = app.session.documents()[1].history.undo.len();
|
||||
app_frame(&mut app, &ctx, vec![button(drop, false)]);
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.documents()[1].doc, target, "the floating window's document does not take the art");
|
||||
assert_eq!(app.session.documents()[1].history.undo.len(), target_undo);
|
||||
assert_eq!(app.session.active_index(), Some(0), "the window does not become current");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_os_windows_pane_is_not_a_place_to_release_art_in_the_main_windows_points() {
|
||||
let _host = native_host();
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_embed_viewports(false);
|
||||
if !native(&app_with(0), &ctx) {
|
||||
// Wayland: the windows are inside the main window.
|
||||
return;
|
||||
}
|
||||
let mut app = floating_pair(&ctx);
|
||||
assert!(app.canvas.windows.drops.is_empty(), "the other document's OS window is not noted");
|
||||
show_window(&mut app, (1, 1));
|
||||
app_frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.canvas.windows.drops.is_empty(), "nor is the main window's pane while an OS window holds the canvas");
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! A selection dragged across document tabs remains editable and leaves its source intact.
|
||||
//! A selection dragged across document tabs, or into another document's tiled pane or floating
|
||||
//! window, remains editable and leaves its source intact.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -90,13 +91,15 @@ pub(crate) fn cleanup(app: &VectorcraftApp, ctx: &Context) {
|
||||
|| i.multi_touch().is_some()
|
||||
|| i.events.iter().any(|e| matches!(e, egui::Event::Touch { phase: egui::TouchPhase::Cancel, .. }))
|
||||
});
|
||||
let outside_release =
|
||||
ctx.input(|i| i.pointer.primary_released() && !app.canvas_rect.is_some_and(|r| i.pointer.interact_pos().is_some_and(|p| r.contains(p))));
|
||||
// The canvas and the other windows' tiled panes take a release ([`drop_on_pane`]).
|
||||
let target = |p: egui::Pos2| app.canvas_rect.is_some_and(|r| r.contains(p)) || app.canvas.panes.last.iter().any(|(_, r)| r.contains(p));
|
||||
let outside_release = ctx.input(|i| i.pointer.primary_released() && !released_at(i).is_some_and(target));
|
||||
if !valid || cancel || outside_release || app.ui.dialog.is_some() {
|
||||
egui::DragAndDrop::clear_payload(ctx);
|
||||
}
|
||||
}
|
||||
if !ctx.input(|i| i.pointer.primary_down()) {
|
||||
// The source and grab point last through the release, for the pane it is released over.
|
||||
if !ctx.input(|i| i.pointer.primary_down() || i.pointer.primary_released()) {
|
||||
ctx.data_mut(|d| {
|
||||
d.remove::<Origin>(origin_id());
|
||||
d.remove::<Hover>(hover_id());
|
||||
@@ -193,11 +196,17 @@ pub(crate) fn drop_on_canvas(app: &mut VectorcraftApp, resp: &Response, xf: &can
|
||||
if resp.contains_pointer() {
|
||||
resp.ctx.set_cursor_icon(if same && !copy { egui::CursorIcon::Move } else { egui::CursorIcon::Copy });
|
||||
}
|
||||
if let Some(art) = resp.dnd_release_payload::<Artwork>()
|
||||
&& let Some(at) = resp.ctx.input(|i| i.pointer.interact_pos()).map(|p| xf.to_doc(p))
|
||||
// The canvas takes a release where the button went up, as [`cleanup`] judges it, and not where
|
||||
// a later move in the same frame leaves the pointer.
|
||||
let ctx = &resp.ctx;
|
||||
let over = |p: egui::Pos2| resp.interact_rect.contains(p) && !ctx.layer_id_at(p).is_some_and(|l| l != resp.layer_id);
|
||||
if let Some(p) = ctx.input(|i| i.pointer.primary_released().then(|| released_at(i)).flatten()).filter(|p| over(*p))
|
||||
&& let Some(art) = egui::DragAndDrop::take_payload::<Artwork>(ctx)
|
||||
{
|
||||
let at = xf.to_doc(p);
|
||||
let result = if same {
|
||||
// Back in the source tab, resume the ordinary move (Alt copies).
|
||||
let copy = release_alt(&resp.ctx);
|
||||
app.run("object.move", json!({"ids": art.ids, "dx": at.x-art.origin.grab.x, "dy": at.y-art.origin.grab.y, "copy": copy}))
|
||||
} else {
|
||||
app.run(
|
||||
@@ -210,3 +219,108 @@ pub(crate) fn drop_on_canvas(app: &mut VectorcraftApp, resp: &Response, xf: &can
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The artwork a Selection drag carries out of its canvas, taken by another window's tiled pane
|
||||
/// ([`take_for_pane`]): its source and grab point, and the objects that travel.
|
||||
pub(crate) struct Carried {
|
||||
origin: Origin,
|
||||
ids: Vec<NodeId>,
|
||||
}
|
||||
|
||||
/// The artwork a Selection drag carries: the transfer a tab hover started, or a Selection move of
|
||||
/// the current document that left its canvas. The canvas hands that move over as a panel drag
|
||||
/// ([`widgets::PanelDrag::Art`]) the frame after the pointer leaves, and Escape drops that; until
|
||||
/// then the move under way is the drag. Either way the objects the move started with travel, not
|
||||
/// an Alt-drag's preview copies.
|
||||
fn carried(app: &VectorcraftApp, ctx: &Context) -> Option<Carried> {
|
||||
if ctx.input(|i| !i.focused || i.multi_touch().is_some() || i.key_pressed(egui::Key::Escape)) || app.ui.dialog.is_some() {
|
||||
return None;
|
||||
}
|
||||
if let Some(art) = egui::DragAndDrop::payload::<Artwork>(ctx) {
|
||||
// The same checks as [`cleanup`]: a floating window's pane takes the release before cleanup
|
||||
// runs, and an edited or closed source, or a target that is no longer the current
|
||||
// document, carries nothing.
|
||||
let source = app.session.documents().iter().any(|d| d.uid == art.origin.uid && d.same_content(&art.source));
|
||||
let target = app.session.active().is_some_and(|d| d.uid == art.target);
|
||||
return (source && target).then(|| Carried { origin: art.origin.clone(), ids: art.ids.clone() });
|
||||
}
|
||||
let origin = ctx.data(|d| d.get_temp::<Origin>(origin_id()))?;
|
||||
let st = app.session.active().filter(|d| d.uid == origin.uid)?;
|
||||
let ids = match egui::DragAndDrop::payload::<widgets::PanelDrag>(ctx).as_deref() {
|
||||
Some(widgets::PanelDrag::Art(ids)) => ids.clone(),
|
||||
Some(_) => return None,
|
||||
None if canvas::art_out(ctx) => return None,
|
||||
None => st.interaction.as_ref().filter(|i| i.label == "Move" || i.label == "Copy")?.selection.objects.clone(),
|
||||
};
|
||||
(!ids.is_empty()).then_some(Carried { origin, ids })
|
||||
}
|
||||
|
||||
/// Over the tiled pane of a window of document `uid`, while a Selection drag carries artwork: the
|
||||
/// cursor that shows a move for another view of the source document without Alt, and a copy
|
||||
/// otherwise. None when no artwork is carried.
|
||||
pub(crate) fn pane_cursor(app: &VectorcraftApp, ctx: &Context, uid: u64) -> Option<egui::CursorIcon> {
|
||||
let c = carried(app, ctx)?;
|
||||
let copy = ctx.input(|i| i.modifiers.alt);
|
||||
Some(if c.origin.uid == uid && !copy { egui::CursorIcon::Move } else { egui::CursorIcon::Copy })
|
||||
}
|
||||
|
||||
/// A release over another window's tiled pane takes the carried artwork: the drag ends, and a
|
||||
/// move still under way on the canvas goes back to where it started, before the canvas sees the
|
||||
/// release ([`canvas::end_art_move`]).
|
||||
pub(crate) fn take_for_pane(app: &mut VectorcraftApp, ctx: &Context) -> Option<Carried> {
|
||||
let c = carried(app, ctx)?;
|
||||
let moving = !egui::DragAndDrop::has_payload_of_type::<Artwork>(ctx) && app.session.in_interaction();
|
||||
egui::DragAndDrop::clear_payload(ctx);
|
||||
ctx.data_mut(|d| d.remove::<Origin>(origin_id()));
|
||||
if moving {
|
||||
canvas::end_art_move(app, ctx);
|
||||
}
|
||||
Some(c)
|
||||
}
|
||||
|
||||
/// The artwork `c` taken over window `w`'s tiled pane ([`take_for_pane`]), released at document
|
||||
/// point `at` in that pane's view: `w` becomes the current window, and the artwork lands with its
|
||||
/// grab point at `at`. Into another document it is copied (`edit.dropSelection`), and the source
|
||||
/// stays as it was; in another view of the source document it moves, and Alt copies it
|
||||
/// (`object.move`). When the command fails, the window that was current stays current and the
|
||||
/// status bar shows the error.
|
||||
pub(crate) fn drop_on_pane(app: &mut VectorcraftApp, ctx: &Context, w: crate::doc_windows::Win, at: Point, c: Carried) {
|
||||
let Carried { origin, ids } = c;
|
||||
let Some(uid) = app.session.documents().get(w.0).map(|d| d.uid) else { return };
|
||||
let before = crate::doc_windows::current(app);
|
||||
app.ui.home = None;
|
||||
crate::doc_windows::show_window(app, w);
|
||||
let result = if uid == origin.uid {
|
||||
let copy = release_alt(ctx);
|
||||
app.run("object.move", json!({"ids": ids, "dx": at.x - origin.grab.x, "dy": at.y - origin.grab.y, "copy": copy}))
|
||||
} else {
|
||||
app.run("edit.dropSelection", json!({"sourceDocument": origin.uid, "ids": ids, "grab": [origin.grab.x, origin.grab.y], "at": [at.x, at.y]}))
|
||||
};
|
||||
if let Err(e) = result {
|
||||
if let Some(b) = before {
|
||||
crate::doc_windows::show_window(app, b);
|
||||
}
|
||||
app.status(e);
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// The primary button's release in this frame: where it went up, and the modifiers held then.
|
||||
fn primary_release(i: &egui::InputState) -> Option<(egui::Pos2, egui::Modifiers)> {
|
||||
i.events.iter().find_map(|e| match e {
|
||||
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } => Some((*pos, *modifiers)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the primary button went up in this frame, else where the pointer is. A pointer move later
|
||||
/// in the frame of the release does not change where the artwork is released.
|
||||
pub(crate) fn released_at(i: &egui::InputState) -> Option<egui::Pos2> {
|
||||
primary_release(i).map(|(p, _)| p).or(i.pointer.interact_pos())
|
||||
}
|
||||
|
||||
/// Whether Alt was held when the primary button went up in this frame, else whether it is held now.
|
||||
/// Alt let go later in the frame of the release still copies.
|
||||
fn release_alt(ctx: &Context) -> bool {
|
||||
ctx.input(|i| primary_release(i).map_or(i.modifiers.alt, |(_, m)| m.alt))
|
||||
}
|
||||
|
||||
@@ -3188,8 +3188,12 @@ digits Malayalam Малаялам
|
||||
Scripts Скриптове
|
||||
Search Търсене
|
||||
Search All Търсене във всички
|
||||
Search commands and tools Търсене на команди и инструменти
|
||||
Search commands and tools… Търсене на команди и инструменти…
|
||||
Search commands, tools, panels and effects Търсене на команди, инструменти, панели и ефекти
|
||||
Search commands, tools, panels and effects… Търсене на команди, инструменти, панели и ефекти…
|
||||
No commands match Няма съвпадащи команди
|
||||
{pos} of {total}: {name} {pos} от {total}: {name}
|
||||
@plural {n} result|{n} results {n} резултат|{n} резултата
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} от {n} резултат. Продължете да пишете, за да ги стесните.|{shown} от {n} резултата. Продължете да пишете, за да ги стесните.
|
||||
Recent Commands Последни команди
|
||||
No recent commands Няма последни команди
|
||||
Search Commands… Търсене на команди…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1301,7 +1301,7 @@ lighting Light Svjetlo
|
||||
Name* @ 66.67% (RGB/Preview) Naziv* @ 66,67% (RGB/pregled)
|
||||
No Document Nema dokumenta
|
||||
Press Pritisnite
|
||||
Search commands and tools Pretraži naredbe i alate
|
||||
Search commands, tools, panels and effects Pretraži naredbe, alate, panele i efekte
|
||||
Style: Stil:
|
||||
Switch workspace Promijeni radni prostor
|
||||
Show all open documents Prikaži sve otvorene dokumente
|
||||
@@ -4388,7 +4388,11 @@ font-technology Variable Varijabilni
|
||||
Saved {path} Sačuvano: {path}
|
||||
Saving Čuvanje
|
||||
Saving {} Čuvanje {}
|
||||
Search commands and tools… Pretraži naredbe i alate…
|
||||
Search commands, tools, panels and effects… Pretraži naredbe, alate, panele i efekte…
|
||||
No commands match Nijedna naredba se ne podudara
|
||||
{pos} of {total}: {name} {pos} od {total}: {name}
|
||||
@plural {n} result|{n} results {n} rezultat|{n} rezultata|{n} rezultata
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.
|
||||
Recent Commands Nedavne naredbe
|
||||
No recent commands Nema nedavnih naredbi
|
||||
Dashed Line Isprekidana linija
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3983,42 +3983,42 @@ digits Malayalam Malaiàlam
|
||||
Saved Desat
|
||||
Saved recovery data for {title} S’han desat les dades de recuperació de {title}
|
||||
Saved Selection 1 Selecció desada 1
|
||||
Saved Selection 10 Selecció desada 2
|
||||
Saved Selection 11 Selecció desada 3
|
||||
Saved Selection 12 Selecció desada 4
|
||||
Saved Selection 13 Selecció desada 5
|
||||
Saved Selection 14 Selecció desada 6
|
||||
Saved Selection 15 Selecció desada 7
|
||||
Saved Selection 16 Selecció desada 8
|
||||
Saved Selection 17 Selecció desada 9
|
||||
Saved Selection 18 Selecció desada 10
|
||||
Saved Selection 19 Selecció desada 11
|
||||
Saved Selection 2 Selecció desada 12
|
||||
Saved Selection 20 Selecció desada 13
|
||||
Saved Selection 21 Selecció desada 14
|
||||
Saved Selection 22 Selecció desada 15
|
||||
Saved Selection 23 Selecció desada 16
|
||||
Saved Selection 24 Selecció desada 17
|
||||
Saved Selection 25 Selecció desada 18
|
||||
Saved Selection 3 Selecció desada 19
|
||||
Saved Selection 4 Selecció desada 20
|
||||
Saved Selection 5 Selecció desada 21
|
||||
Saved Selection 6 Selecció desada 22
|
||||
Saved Selection 7 Selecció desada 23
|
||||
Saved Selection 8 Selecció desada 24
|
||||
Saved Selection 9 Selecció desada 25
|
||||
Saved Selection 10 Selecció desada 10
|
||||
Saved Selection 11 Selecció desada 11
|
||||
Saved Selection 12 Selecció desada 12
|
||||
Saved Selection 13 Selecció desada 13
|
||||
Saved Selection 14 Selecció desada 14
|
||||
Saved Selection 15 Selecció desada 15
|
||||
Saved Selection 16 Selecció desada 16
|
||||
Saved Selection 17 Selecció desada 17
|
||||
Saved Selection 18 Selecció desada 18
|
||||
Saved Selection 19 Selecció desada 19
|
||||
Saved Selection 2 Selecció desada 2
|
||||
Saved Selection 20 Selecció desada 20
|
||||
Saved Selection 21 Selecció desada 21
|
||||
Saved Selection 22 Selecció desada 22
|
||||
Saved Selection 23 Selecció desada 23
|
||||
Saved Selection 24 Selecció desada 24
|
||||
Saved Selection 25 Selecció desada 25
|
||||
Saved Selection 3 Selecció desada 3
|
||||
Saved Selection 4 Selecció desada 4
|
||||
Saved Selection 5 Selecció desada 5
|
||||
Saved Selection 6 Selecció desada 6
|
||||
Saved Selection 7 Selecció desada 7
|
||||
Saved Selection 8 Selecció desada 8
|
||||
Saved Selection 9 Selecció desada 9
|
||||
Saved Selections Seleccions desades
|
||||
Saved to User Defined: {} Desat a Definit per l’usuari: {}
|
||||
Saved View 1 Vista desada 1
|
||||
Saved View 10 Vista desada 2
|
||||
Saved View 11 Vista desada 3
|
||||
Saved View 12 Vista desada 4
|
||||
Saved View 13 Vista desada 5
|
||||
Saved View 14 Vista desada 6
|
||||
Saved View 15 Vista desada 7
|
||||
Saved View 16 Vista desada 8
|
||||
Saved View 17 Vista desada 9
|
||||
Saved View 18 Vista desada 10
|
||||
Saved View 10 Vista desada 10
|
||||
Saved View 11 Vista desada 11
|
||||
Saved View 12 Vista desada 12
|
||||
Saved View 13 Vista desada 13
|
||||
Saved View 14 Vista desada 14
|
||||
Saved View 15 Vista desada 15
|
||||
Saved View 16 Vista desada 16
|
||||
Saved View 17 Vista desada 17
|
||||
Saved View 18 Vista desada 18
|
||||
Saved View 19 Vista desada 19
|
||||
Saved View 2 Vista desada 2
|
||||
Saved View 20 Vista desada 20
|
||||
@@ -4117,8 +4117,12 @@ digits Malayalam Malaiàlam
|
||||
Scrub Numeric Fields by Dragging Canvia els camps numèrics arrossegant
|
||||
Search Cerca
|
||||
Search All Cerca a tot
|
||||
Search commands and tools Cerca ordres i eines
|
||||
Search commands and tools… Cerca ordres i eines…
|
||||
Search commands, tools, panels and effects Cerca ordres, eines, panells i efectes
|
||||
Search commands, tools, panels and effects… Cerca ordres, eines, panells i efectes…
|
||||
No commands match Cap ordre coincideix
|
||||
{pos} of {total}: {name} {pos} de {total}: {name}
|
||||
@plural {n} result|{n} results {n} resultat|{n} resultats
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultat. Continueu escrivint per reduir-los.|{shown} de {n} resultats. Continueu escrivint per reduir-los.
|
||||
Recent Commands Ordres recents
|
||||
No recent commands No hi ha ordres recents
|
||||
Search Commands… Cerca ordres…
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1325,7 +1325,7 @@ lighting Light Světlo
|
||||
Name* @ 66.67% (RGB/Preview) Název* @ 66,67 % (RGB/náhled)
|
||||
No Document Žádný dokument
|
||||
Press Klávesou
|
||||
Search commands and tools Hledat příkazy a nástroje
|
||||
Search commands, tools, panels and effects Hledat příkazy, nástroje, panely a efekty
|
||||
Style: Styl:
|
||||
Switch workspace Přepnout pracovní prostor
|
||||
Show all open documents Zobrazit všechny otevřené dokumenty
|
||||
@@ -4493,7 +4493,11 @@ font-technology Variable Variabilní
|
||||
Saved {path} Uloženo: {path}
|
||||
Saving Ukládání
|
||||
Saving {} Ukládání {}
|
||||
Search commands and tools… Hledat příkazy a nástroje…
|
||||
Search commands, tools, panels and effects… Hledat příkazy, nástroje, panely a efekty…
|
||||
No commands match Žádný příkaz neodpovídá
|
||||
{pos} of {total}: {name} {pos} z {total}: {name}
|
||||
@plural {n} result|{n} results {n} výsledek|{n} výsledky|{n} výsledků
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} výsledku. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.
|
||||
Recent Commands Nedávné příkazy
|
||||
No recent commands Žádné nedávné příkazy
|
||||
Dashed Line Čárkovaná čára
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3902,7 +3902,7 @@ lighting Light Lys
|
||||
Name* @ 66.67% (RGB/Preview) Navn* @ 66.67% (RGB/forhåndsvisning)
|
||||
No Document Intet dokument
|
||||
Press Tryk på
|
||||
Search commands and tools Søg i kommandoer og værktøjer
|
||||
Search commands, tools, panels and effects Søg i kommandoer, værktøjer, paneler og effekter
|
||||
Style: Typografi:
|
||||
Switch workspace Skift arbejdsområde
|
||||
Show all open documents Vis alle åbne dokumenter
|
||||
@@ -6867,7 +6867,11 @@ font-technology Variable Variable
|
||||
Saved {path} Gemte {path}
|
||||
Saving Gemmer
|
||||
Saving {} Gemmer {}
|
||||
Search commands and tools… Søg i kommandoer og værktøjer…
|
||||
Search commands, tools, panels and effects… Søg i kommandoer, værktøjer, paneler og effekter…
|
||||
No commands match Ingen kommandoer passer
|
||||
{pos} of {total}: {name} {pos} af {total}: {name}
|
||||
@plural {n} result|{n} results {n} resultat|{n} resultater
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} af {n} resultat. Skriv videre for at indsnævre dem.|{shown} af {n} resultater. Skriv videre for at indsnævre dem.
|
||||
Recent Commands Seneste kommandoer
|
||||
No recent commands Ingen seneste kommandoer
|
||||
Dashed Line Stiplet linje
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3252,8 +3252,12 @@ digits Malayalam Malayalam
|
||||
Filter Layers Panel Rows Zeilen im Ebenenbedienfeld filtern
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` steht für geänderte Einstellungen: Speichern Sie die Vorgabe unter einem anderen Namen
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` muss ein Array mit diesen Namen sein: {_1}
|
||||
Search commands and tools Befehle und Werkzeuge suchen
|
||||
Search commands and tools… Befehle und Werkzeuge suchen…
|
||||
Search commands, tools, panels and effects Befehle, Werkzeuge, Bedienfelder und Effekte suchen
|
||||
Search commands, tools, panels and effects… Befehle, Werkzeuge, Bedienfelder und Effekte suchen…
|
||||
No commands match Keine passenden Befehle
|
||||
{pos} of {total}: {name} {pos} von {total}: {name}
|
||||
@plural {n} result|{n} results {n} Ergebnis|{n} Ergebnisse
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} von {n} Ergebnis. Tippen Sie weiter, um sie einzugrenzen.|{shown} von {n} Ergebnissen. Tippen Sie weiter, um sie einzugrenzen.
|
||||
Recent Commands Zuletzt verwendete Befehle
|
||||
No recent commands Keine zuletzt verwendeten Befehle
|
||||
Search Commands… Befehle suchen…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3954,8 +3954,12 @@ digits Malayalam Μαλαγιάλαμ
|
||||
Scribble… Μουτζούρωμα…
|
||||
Script / Brush Σενάριο / Πινέλο
|
||||
Search All Αναζήτηση όλων
|
||||
Search commands and tools Αναζήτηση εντολών και εργαλείων
|
||||
Search commands and tools… Αναζήτηση εντολών και εργαλείων…
|
||||
Search commands, tools, panels and effects Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ
|
||||
Search commands, tools, panels and effects… Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ…
|
||||
No commands match Καμία εντολή δεν ταιριάζει
|
||||
{pos} of {total}: {name} {pos} από {total}: {name}
|
||||
@plural {n} result|{n} results {n} αποτέλεσμα|{n} αποτελέσματα
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} από {n} αποτέλεσμα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.|{shown} από {n} αποτελέσματα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.
|
||||
Recent Commands Πρόσφατες εντολές
|
||||
No recent commands Δεν υπάρχουν πρόσφατες εντολές
|
||||
Search Commands… Αναζήτηση εντολών…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3290,8 +3290,12 @@ digits Malayalam Malayálam
|
||||
Filter Layers Panel Rows Filtrar filas del panel Capas
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` representa ajustes modificados: guarda el preajuste con otro nombre
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` debe ser una lista de estos nombres: {_1}
|
||||
Search commands and tools Buscar comandos y herramientas
|
||||
Search commands and tools… Buscar comandos y herramientas…
|
||||
Search commands, tools, panels and effects Buscar comandos, herramientas, paneles y efectos
|
||||
Search commands, tools, panels and effects… Buscar comandos, herramientas, paneles y efectos…
|
||||
No commands match Ningún comando coincide
|
||||
{pos} of {total}: {name} {pos} de {total}: {name}
|
||||
@plural {n} result|{n} results {n} resultado|{n} resultados
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Sigue escribiendo para acotarlos.|{shown} de {n} resultados. Sigue escribiendo para acotarlos.
|
||||
Recent Commands Comandos recientes
|
||||
No recent commands No hay comandos recientes
|
||||
Search Commands… Buscar comandos…
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -1303,7 +1303,7 @@ lighting Light Valo
|
||||
Name* @ 66.67% (RGB/Preview) Nimi* @ 66.67% (RGB/esikatselu)
|
||||
No Document Ei asiakirjaa
|
||||
Press Paina
|
||||
Search commands and tools Hae komentoja ja työkaluja
|
||||
Search commands, tools, panels and effects Hae komentoja, työkaluja, paneeleita ja tehosteita
|
||||
Style: Tyyli:
|
||||
Switch workspace Vaihda työtilaa
|
||||
Show all open documents Näytä kaikki avoimet asiakirjat
|
||||
@@ -4412,7 +4412,11 @@ font-technology Variable Muuttuvat
|
||||
Saved {path} Tallennettu {path}
|
||||
Saving Tallennetaan
|
||||
Saving {} Tallennetaan {}
|
||||
Search commands and tools… Hae komentoja ja työkaluja…
|
||||
Search commands, tools, panels and effects… Hae komentoja, työkaluja, paneeleita ja tehosteita…
|
||||
No commands match Mikään komento ei vastaa hakua
|
||||
{pos} of {total}: {name} {pos}/{total}: {name}
|
||||
@plural {n} result|{n} results {n} tulos|{n} tulosta
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.|{shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.
|
||||
Recent Commands Viimeisimmät komennot
|
||||
No recent commands Ei viimeisimpiä komentoja
|
||||
Dashed Line Katkoviiva
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3278,8 +3278,12 @@ digits Malayalam Malayalam
|
||||
Filter Layers Panel Rows Filtrer les lignes du panneau Calques
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` désigne des réglages modifiés : enregistrez le paramètre prédéfini sous un autre nom
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` doit être un tableau de noms parmi {_1}
|
||||
Search commands and tools Chercher commandes et outils
|
||||
Search commands and tools… Chercher commandes et outils…
|
||||
Search commands, tools, panels and effects Chercher commandes, outils, panneaux et effets
|
||||
Search commands, tools, panels and effects… Chercher commandes, outils, panneaux et effets…
|
||||
No commands match Aucune commande ne correspond
|
||||
{pos} of {total}: {name} {pos} sur {total} : {name}
|
||||
@plural {n} result|{n} results {n} résultat|{n} résultats
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} sur {n} résultat. Continuez à taper pour les affiner.|{shown} sur {n} résultats. Continuez à taper pour les affiner.
|
||||
Recent Commands Commandes récentes
|
||||
No recent commands Aucune commande récente
|
||||
Search Commands… Rechercher des commandes…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3393,8 +3393,12 @@
|
||||
Search Commands… આદેશો શોધો…
|
||||
Search Fonts Folder ફોન્ટ ફોલ્ડર શોધો
|
||||
Search Preferences પસંદગીઓ શોધો
|
||||
Search commands and tools આદેશો અને ટૂલ્સ શોધો
|
||||
Search commands and tools… આદેશો અને ટૂલ્સ શોધો…
|
||||
Search commands, tools, panels and effects આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો
|
||||
Search commands, tools, panels and effects… આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો…
|
||||
No commands match કોઈ આદેશ મેળ ખાતો નથી
|
||||
{pos} of {total}: {name} {total} માંથી {pos}: {name}
|
||||
@plural {n} result|{n} results {n} પરિણામ|{n} પરિણામો
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} માંથી {shown} પરિણામ. તેમને સંકુચિત કરવા લખતા રહો.|{n} માંથી {shown} પરિણામો. તેમને સંકુચિત કરવા લખતા રહો.
|
||||
Recent Commands તાજેતરના આદેશો
|
||||
No recent commands કોઈ તાજેતરના આદેશો નથી
|
||||
Search images છબીઓ શોધો
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 72 and column 5.
|
@@ -4467,8 +4467,12 @@ antiAlias Sharp शार्प
|
||||
Search खोजें
|
||||
Search All सभी खोजें
|
||||
Search artboards खोज आर्टबोर्ड
|
||||
Search commands and tools खोज आदेश और टूल
|
||||
Search commands and tools… आदेश और टूल खोजें…
|
||||
Search commands, tools, panels and effects आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें
|
||||
Search commands, tools, panels and effects… आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें…
|
||||
No commands match कोई आदेश मेल नहीं खाता
|
||||
{pos} of {total}: {name} {total} में से {pos}: {name}
|
||||
@plural {n} result|{n} results {n} परिणाम|{n} परिणाम
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।|{n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।
|
||||
Recent Commands हाल के आदेश
|
||||
No recent commands कोई हाल का आदेश नहीं
|
||||
Search Commands… कमांड खोजें…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3911,8 +3911,12 @@ mark-style Japanese Japán
|
||||
Filter Layers Panel Rows Rétegek panel sorainak szűrése
|
||||
@msg `Custom` stands for changed settings: save the preset under another name a `Custom` a módosított beállításokat jelöli: mentsd az előbeállítást más néven
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}`: ezen nevek tömbje kell: {_1}
|
||||
Search commands and tools Parancsok és eszközök keresése
|
||||
Search commands and tools… Parancsok és eszközök keresése…
|
||||
Search commands, tools, panels and effects Parancsok, eszközök, panelek és effektusok keresése
|
||||
Search commands, tools, panels and effects… Parancsok, eszközök, panelek és effektusok keresése…
|
||||
No commands match Nincs egyező parancs
|
||||
{pos} of {total}: {name} {pos}/{total}: {name}
|
||||
@plural {n} result|{n} results {n} találat
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} találatból {shown} látható. Gépeljen tovább a szűkítéshez.
|
||||
Recent Commands Legutóbbi parancsok
|
||||
No recent commands Nincsenek legutóbbi parancsok
|
||||
Search Commands… Parancsok keresése…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1228,7 +1228,7 @@ lighting Light Cahaya
|
||||
Name* @ 66.67% (RGB/Preview) Nama* @ 66.67% (RGB/Pratinjau)
|
||||
No Document Tidak ada dokumen
|
||||
Press Tekan
|
||||
Search commands and tools Cari perintah dan alat
|
||||
Search commands, tools, panels and effects Cari perintah, alat, panel, dan efek
|
||||
Style: Gaya:
|
||||
Switch workspace Ganti ruang kerja
|
||||
Show all open documents Tampilkan semua dokumen terbuka
|
||||
@@ -4144,7 +4144,11 @@ font-technology Variable Variabel
|
||||
Saved {path} Berhasil menyimpan {path}
|
||||
Saving Menyimpan
|
||||
Saving {} Menyimpan {}
|
||||
Search commands and tools… Cari perintah dan alat…
|
||||
Search commands, tools, panels and effects… Cari perintah, alat, panel, dan efek…
|
||||
No commands match Tidak ada perintah yang cocok
|
||||
{pos} of {total}: {name} {pos} dari {total}: {name}
|
||||
@plural {n} result|{n} results {n} hasil
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} dari {n} hasil. Terus ketik untuk mempersempitnya.
|
||||
Recent Commands Perintah terbaru
|
||||
No recent commands Tidak ada perintah terbaru
|
||||
Dashed Line Garis putus-putus
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2495 and column 5.
|
@@ -3333,8 +3333,12 @@ digits Malayalam Malayalam
|
||||
Filter Layers Panel Rows Filtra righe del pannello Livelli
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` indica impostazioni modificate: salva il preset con un altro nome
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` deve essere un array di questi nomi: {_1}
|
||||
Search commands and tools Cerca comandi e strumenti
|
||||
Search commands and tools… Cerca comandi e strumenti…
|
||||
Search commands, tools, panels and effects Cerca comandi, strumenti, pannelli ed effetti
|
||||
Search commands, tools, panels and effects… Cerca comandi, strumenti, pannelli ed effetti…
|
||||
No commands match Nessun comando corrisponde
|
||||
{pos} of {total}: {name} {pos} di {total}: {name}
|
||||
@plural {n} result|{n} results {n} risultato|{n} risultati
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} di {n} risultato. Continua a digitare per restringerli.|{shown} di {n} risultati. Continua a digitare per restringerli.
|
||||
Recent Commands Comandi recenti
|
||||
No recent commands Nessun comando recente
|
||||
Search Commands… Cerca comandi…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3211,8 +3211,12 @@ mark-style Japanese 日本式
|
||||
Filter Layers Panel Rows レイヤーパネルの行をフィルター
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` は変更した設定を表します: プリセットを別の名前で保存してください
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` には {_1} の中の名前の配列を指定してください
|
||||
Search commands and tools コマンドとツールを検索
|
||||
Search commands and tools… コマンドとツールを検索…
|
||||
Search commands, tools, panels and effects コマンド、ツール、パネル、効果を検索
|
||||
Search commands, tools, panels and effects… コマンド、ツール、パネル、効果を検索…
|
||||
No commands match 一致するコマンドはありません
|
||||
{pos} of {total}: {name} {total} 件中 {pos} 件目: {name}
|
||||
@plural {n} result|{n} results {n} 件
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} 件中 {shown} 件。続けて入力すると絞り込めます。
|
||||
Recent Commands 最近使ったコマンド
|
||||
No recent commands 最近使ったコマンドはありません
|
||||
Secondary セカンダリ
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3270,7 +3270,7 @@ lighting Light სინათლე
|
||||
Name* @ 66.67% (RGB/Preview) სახელი* @ 66.67% (RGB/წინასწარი ნახვა)
|
||||
No Document დოკუმენტი არ არის
|
||||
Press დააჭირეთ
|
||||
Search commands and tools ბრძანებებისა და ხელსაწყოების ძიება
|
||||
Search commands, tools, panels and effects ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება
|
||||
Style: სტილი:
|
||||
Switch workspace სამუშაო სივრცის გადართვა
|
||||
Show all open documents ყველა ღია დოკუმენტის ჩვენება
|
||||
@@ -6096,7 +6096,11 @@ font-technology Variable ცვლადი
|
||||
Saved {path} შენახულია: {path}
|
||||
Saving შენახვა
|
||||
Saving {} ინახება: {}
|
||||
Search commands and tools… ბრძანებებისა და ხელსაწყოების ძიება…
|
||||
Search commands, tools, panels and effects… ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება…
|
||||
No commands match შესაბამისი ბრძანება არ არის
|
||||
{pos} of {total}: {name} {pos} / {total}: {name}
|
||||
@plural {n} result|{n} results {n} შედეგი
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} შედეგიდან {shown}. გააგრძელეთ აკრეფა მათ შესამცირებლად.
|
||||
Recent Commands ბოლო ბრძანებები
|
||||
No recent commands ბოლო ბრძანებები არ არის
|
||||
Dashed Line ტირეებიანი ხაზი
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3200,8 +3200,12 @@ mark-style Japanese 일본식
|
||||
Filter Layers Panel Rows 레이어 패널 행 필터링
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom`은 변경된 설정을 나타냅니다. 프리셋을 다른 이름으로 저장하세요
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}`은(는) 다음 이름의 배열이어야 합니다: {_1}
|
||||
Search commands and tools 명령 및 도구 검색
|
||||
Search commands and tools… 명령 및 도구 검색…
|
||||
Search commands, tools, panels and effects 명령, 도구, 패널 및 효과 검색
|
||||
Search commands, tools, panels and effects… 명령, 도구, 패널 및 효과 검색…
|
||||
No commands match 일치하는 명령이 없습니다
|
||||
{pos} of {total}: {name} {total}개 중 {pos}번째: {name}
|
||||
@plural {n} result|{n} results 결과 {n}개
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 결과 {n}개 중 {shown}개. 계속 입력하여 범위를 좁히세요.
|
||||
Recent Commands 최근 명령
|
||||
No recent commands 최근 명령 없음
|
||||
Secondary 보조
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1796,7 +1796,7 @@ lighting Light Licht
|
||||
Name* @ 66.67% (RGB/Preview) Naam* @ 66.67% (RGB/Voorbeeld)
|
||||
No Document Geen document
|
||||
Press Druk op
|
||||
Search commands and tools Opdrachten en gereedschappen zoeken
|
||||
Search commands, tools, panels and effects Opdrachten, gereedschappen, panelen en effecten zoeken
|
||||
Style: Stijl:
|
||||
Switch workspace Werkruimte wisselen
|
||||
Show all open documents Alle geopende documenten tonen
|
||||
@@ -4761,7 +4761,11 @@ font-technology Variable Variabel
|
||||
Saved {path} {path} opgeslagen
|
||||
Saving Bezig met opslaan
|
||||
Saving {} {} wordt opgeslagen
|
||||
Search commands and tools… Opdrachten en gereedschappen zoeken…
|
||||
Search commands, tools, panels and effects… Opdrachten, gereedschappen, panelen en effecten zoeken…
|
||||
No commands match Geen opdrachten gevonden
|
||||
{pos} of {total}: {name} {pos} van {total}: {name}
|
||||
@plural {n} result|{n} results {n} resultaat|{n} resultaten
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} van {n} resultaat. Typ verder om ze te beperken.|{shown} van {n} resultaten. Typ verder om ze te beperken.
|
||||
Recent Commands Recente opdrachten
|
||||
No recent commands Geen recente opdrachten
|
||||
Dashed Line Streepjeslijn
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -1255,7 +1255,7 @@ lighting Light Światło
|
||||
Name* @ 66.67% (RGB/Preview) Nazwa* @ 66,67% (RGB/Podgląd)
|
||||
No Document Brak dokumentu
|
||||
Press Naciśnij
|
||||
Search commands and tools Szukaj poleceń i narzędzi
|
||||
Search commands, tools, panels and effects Szukaj poleceń, narzędzi, paneli i efektów
|
||||
Style: Styl:
|
||||
Switch workspace Przełącz obszar roboczy
|
||||
Show all open documents Pokaż wszystkie otwarte dokumenty
|
||||
@@ -4334,7 +4334,11 @@ font-technology Variable Zmienne
|
||||
Saved {path} Zapisano {path}
|
||||
Saving Zapisywanie
|
||||
Saving {} Zapisywanie {}
|
||||
Search commands and tools… Szukaj poleceń i narzędzi…
|
||||
Search commands, tools, panels and effects… Szukaj poleceń, narzędzi, paneli i efektów…
|
||||
No commands match Żadne polecenie nie pasuje
|
||||
{pos} of {total}: {name} {pos} z {total}: {name}
|
||||
@plural {n} result|{n} results {n} wynik|{n} wyniki|{n} wyników
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} wyniku. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić.
|
||||
Recent Commands Ostatnie polecenia
|
||||
No recent commands Brak ostatnich poleceń
|
||||
Dashed Line Linia przerywana
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2749,8 +2749,12 @@ digits Malayalam Malaiala
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` representa configurações alteradas: salve a predefinição com outro nome
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` deve ser uma matriz destes nomes: {_1}
|
||||
Search Commands… Pesquisar Comandos…
|
||||
Search commands and tools Pesquisar comandos e ferramentas
|
||||
Search commands and tools… Pesquisar comandos e ferramentas…
|
||||
Search commands, tools, panels and effects Pesquisar comandos, ferramentas, painéis e efeitos
|
||||
Search commands, tools, panels and effects… Pesquisar comandos, ferramentas, painéis e efeitos…
|
||||
No commands match Nenhum comando corresponde
|
||||
{pos} of {total}: {name} {pos} de {total}: {name}
|
||||
@plural {n} result|{n} results {n} resultado|{n} resultados
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Continue digitando para filtrá-los.|{shown} de {n} resultados. Continue digitando para filtrá-los.
|
||||
Recent Commands Comandos recentes
|
||||
No recent commands Nenhum comando recente
|
||||
Secondary Secundária
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3322,8 +3322,12 @@ digits Malayalam Малаялам
|
||||
Filter Layers Panel Rows Фильтровать строки панели «Слои»
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` обозначает изменённые параметры: сохраните набор под другим именем
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` должно быть массивом из этих имён: {_1}
|
||||
Search commands and tools Поиск команд и инструментов
|
||||
Search commands and tools… Поиск команд и инструментов…
|
||||
Search commands, tools, panels and effects Поиск команд, инструментов, панелей и эффектов
|
||||
Search commands, tools, panels and effects… Поиск команд, инструментов, панелей и эффектов…
|
||||
No commands match Нет подходящих команд
|
||||
{pos} of {total}: {name} {pos} из {total}: {name}
|
||||
@plural {n} result|{n} results {n} результат|{n} результата|{n} результатов
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} из {n} результата. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их.
|
||||
Recent Commands Недавние команды
|
||||
No recent commands Нет недавних команд
|
||||
Search Commands… Поиск команд…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3208,8 +3208,12 @@ digits Malayalam Malayalam
|
||||
Scripts Skript
|
||||
Search Sök
|
||||
Search All Sök i alla
|
||||
Search commands and tools Sök kommandon och verktyg
|
||||
Search commands and tools… Sök kommandon och verktyg…
|
||||
Search commands, tools, panels and effects Sök kommandon, verktyg, paneler och effekter
|
||||
Search commands, tools, panels and effects… Sök kommandon, verktyg, paneler och effekter…
|
||||
No commands match Inga kommandon matchar
|
||||
{pos} of {total}: {name} {pos} av {total}: {name}
|
||||
@plural {n} result|{n} results {n} resultat|{n} resultat
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} av {n} resultat. Fortsätt skriva för att begränsa dem.|{shown} av {n} resultat. Fortsätt skriva för att begränsa dem.
|
||||
Recent Commands Senaste kommandon
|
||||
No recent commands Inga senaste kommandon
|
||||
Search Commands… Sök kommandon…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -434,6 +434,30 @@ fn font_height_reference_labels_are_in_complete_catalogs() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Each catalog's Saved View N and Saved Selection N rows carry the number N, and no two of a
|
||||
/// catalog's saved views or saved selections show one name, whatever digits the language uses.
|
||||
#[test]
|
||||
fn numbered_saved_views_and_selections_keep_their_number() {
|
||||
let mut bad = vec![];
|
||||
for lang in LANGUAGES.iter().filter(|lang| !lang.source.is_empty()) {
|
||||
for kind in ["Saved View", "Saved Selection"] {
|
||||
let mut seen = std::collections::HashMap::new();
|
||||
for n in 1..=25 {
|
||||
let source = format!("{kind} {n}");
|
||||
let Some(row) = lang.catalog().plain(&source) else { continue };
|
||||
let numbers: Vec<&str> = row.split(|c: char| !c.is_ascii_digit()).filter(|s| !s.is_empty()).collect();
|
||||
if !numbers.is_empty() && numbers != [n.to_string().as_str()] {
|
||||
bad.push(format!("{}: {source} -> {row}", lang.code));
|
||||
}
|
||||
if let Some(earlier) = seen.insert(row, source.clone()) {
|
||||
bad.push(format!("{}: {earlier} and {source} both show {row}", lang.code));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(bad.is_empty(), "{}", bad.join("\n"));
|
||||
}
|
||||
|
||||
/// The Objects on Path Options section's Detach button, its undo step and the message for a
|
||||
/// Detach with no object chosen.
|
||||
#[test]
|
||||
|
||||
@@ -3080,8 +3080,12 @@ digits Malayalam Malayalam
|
||||
Redefine {name} “{name}” Stilini Yeniden Tanımla
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` değiştirilmiş ayarları ifade eder: ön ayarı başka bir adla kaydedin
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` şu adlardan oluşan bir dizi olmalıdır: {_1}
|
||||
Search commands and tools Komutları ve araçları arayın
|
||||
Search commands and tools… Komutları ve araçları arayın…
|
||||
Search commands, tools, panels and effects Komutları, araçları, panelleri ve efektleri arayın
|
||||
Search commands, tools, panels and effects… Komutları, araçları, panelleri ve efektleri arayın…
|
||||
No commands match Eşleşen komut yok
|
||||
{pos} of {total}: {name} {pos}/{total}: {name}
|
||||
@plural {n} result|{n} results {n} sonuç
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} sonuçtan {shown} tanesi. Daraltmak için yazmaya devam edin.
|
||||
Recent Commands Son komutlar
|
||||
No recent commands Son komut yok
|
||||
Search Commands… Arama Komutları…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3325,8 +3325,12 @@ digits Malayalam Малаялам
|
||||
Filter Layers Panel Rows Фільтрувати рядки панелі «Шари»
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` позначає змінені параметри: збережіть набір під іншим ім’ям
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` має бути масивом цих назв: {_1}
|
||||
Search commands and tools Пошук команд та інструментів
|
||||
Search commands and tools… Пошук команд та інструментів…
|
||||
Search commands, tools, panels and effects Пошук команд, інструментів, панелей та ефектів
|
||||
Search commands, tools, panels and effects… Пошук команд, інструментів, панелей та ефектів…
|
||||
No commands match Немає відповідних команд
|
||||
{pos} of {total}: {name} {pos} з {total}: {name}
|
||||
@plural {n} result|{n} results {n} результат|{n} результати|{n} результатів
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} з {n} результату. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх.
|
||||
Recent Commands Нещодавні команди
|
||||
No recent commands Немає нещодавніх команд
|
||||
Search Commands… Пошук команд…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3668,8 +3668,12 @@ mark-style Japanese Kiểu Nhật
|
||||
Filter Layers Panel Rows Lọc hàng bảng Lớp
|
||||
@msg `Custom` stands for changed settings: save the preset under another name `Custom` biểu thị các cài đặt đã thay đổi: hãy lưu thiết lập sẵn với tên khác
|
||||
@msg `{key}` must be an array of these names: {_1} `{key}` phải là một mảng gồm các tên sau: {_1}
|
||||
Search commands and tools Tìm kiếm lệnh và công cụ
|
||||
Search commands and tools… Tìm kiếm lệnh và công cụ…
|
||||
Search commands, tools, panels and effects Tìm kiếm lệnh, công cụ, bảng và hiệu ứng
|
||||
Search commands, tools, panels and effects… Tìm kiếm lệnh, công cụ, bảng và hiệu ứng…
|
||||
No commands match Không có lệnh nào khớp
|
||||
{pos} of {total}: {name} {pos} trên {total}: {name}
|
||||
@plural {n} result|{n} results {n} kết quả
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} trên {n} kết quả. Tiếp tục gõ để thu hẹp.
|
||||
Recent Commands Lệnh gần đây
|
||||
No recent commands Không có lệnh gần đây
|
||||
Search Commands… Tìm kiếm lệnh…
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 205 and column 5.
|
@@ -3152,8 +3152,12 @@ digits Malayalam 马拉雅拉姆数字
|
||||
Locked 已锁定
|
||||
Hidden 已隐藏
|
||||
Filter Layers Panel Rows 筛选图层面板行
|
||||
Search commands and tools 搜索命令和工具
|
||||
Search commands and tools… 搜索命令和工具…
|
||||
Search commands, tools, panels and effects 搜索命令、工具、面板和效果
|
||||
Search commands, tools, panels and effects… 搜索命令、工具、面板和效果…
|
||||
No commands match 没有匹配的命令
|
||||
{pos} of {total}: {name} 第 {pos} 个,共 {total} 个:{name}
|
||||
@plural {n} result|{n} results {n} 个结果
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 个结果,显示 {shown} 个。继续输入以缩小范围。
|
||||
Recent Commands 最近使用的命令
|
||||
No recent commands 没有最近使用的命令
|
||||
Search Commands… 搜索命令…
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4458,8 +4458,12 @@ digits Malayalam 馬來亞拉姆數字
|
||||
Locked 已鎖定
|
||||
Hidden 已隱藏
|
||||
Filter Layers Panel Rows 篩選圖層面板列
|
||||
Search commands and tools 搜尋指令與工具
|
||||
Search commands and tools… 搜尋指令與工具…
|
||||
Search commands, tools, panels and effects 搜尋指令、工具、面板與效果
|
||||
Search commands, tools, panels and effects… 搜尋指令、工具、面板與效果…
|
||||
No commands match 沒有符合的指令
|
||||
{pos} of {total}: {name} 第 {pos} 個,共 {total} 個:{name}
|
||||
@plural {n} result|{n} results {n} 個結果
|
||||
@plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 個結果,顯示 {shown} 個。繼續輸入以縮小範圍。
|
||||
Recent Commands 最近使用的指令
|
||||
No recent commands 沒有最近使用的指令
|
||||
Search Commands… 搜尋指令…
|
||||
|
||||
|
Can't render this file because it is too large.
|
+1813
-121
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,764 @@
|
||||
//! The command palette's search: a small index of the words in each result's label, menu path and
|
||||
//! id, the menu bar's home of each result, and the ranking of the results a query matches.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{Entry, WRAPPED};
|
||||
use crate::menus;
|
||||
|
||||
/// The most characters of a query the index reads (VectorCraft's own limit). The substring rule
|
||||
/// and the exact tiers read the whole query.
|
||||
const INDEX_CHARS: usize = 200;
|
||||
|
||||
/// The field of a result a word comes from, best first.
|
||||
const LABEL: u8 = 0;
|
||||
const PATH: u8 = 1;
|
||||
const ID: u8 = 2;
|
||||
|
||||
/// A word's grade in a result, best first: a whole word of the label, a word of the label it
|
||||
/// starts, a word of the menu path it is or starts, a word of the id it is or starts, or text
|
||||
/// inside a word of any field ([`super::matching`]'s substring rule).
|
||||
const LABEL_WORD: u8 = 1;
|
||||
const LABEL_PREFIX: u8 = 2;
|
||||
const PATH_WORD: u8 = 3;
|
||||
const ID_WORD: u8 = 4;
|
||||
const SUBSTRING: u8 = 5;
|
||||
const NONE: u8 = u8::MAX;
|
||||
|
||||
/// How a whole query matches a result, best first: it is the result's id, it is a label, a label
|
||||
/// starts with it, or it is the initials of a label.
|
||||
const EXACT_ID: u8 = 0;
|
||||
const EXACT_LABEL: u8 = 1;
|
||||
const PREFIX: u8 = 2;
|
||||
const INITIALS: u8 = 3;
|
||||
const NO_PHRASE: u8 = 4;
|
||||
|
||||
/// One result in the list of a term: the result's place in the catalog and the field the term is
|
||||
/// a word of.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Posting {
|
||||
entry: u16,
|
||||
field: u8,
|
||||
}
|
||||
|
||||
/// The words of every result, each distinct word stored once.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Index {
|
||||
/// Every distinct word, one after another.
|
||||
term_text: String,
|
||||
/// Each word's offset and length in `term_text`, sorted by the word's text.
|
||||
terms: Vec<(u32, u32)>,
|
||||
/// Each word's first posting and number of postings in `postings`, in the order of `terms`.
|
||||
spans: Vec<(u32, u32)>,
|
||||
postings: Vec<Posting>,
|
||||
/// The initials of each result's labels, one line per label.
|
||||
initials_text: String,
|
||||
/// Each result's offset and length in `initials_text`.
|
||||
initials: Vec<(u32, u16)>,
|
||||
}
|
||||
|
||||
/// Splits `text` into lowercase words at whitespace and at `.`, `-`, `/`, `(`, `)`, `…`, `›`, `,`
|
||||
/// and `:`.
|
||||
fn words(text: &str) -> impl Iterator<Item = &str> {
|
||||
text.split(|c: char| c.is_whitespace() || matches!(c, '.' | '-' | '/' | '(' | ')' | '…' | '›' | ',' | ':')).filter(|w| !w.is_empty())
|
||||
}
|
||||
|
||||
/// The first letter of each word of `label`, words split at whitespace and at `-`, `/`, `(` and
|
||||
/// `›`, lowercased.
|
||||
fn initials_of(label: &str) -> String {
|
||||
label
|
||||
.split(|c: char| c.is_whitespace() || matches!(c, '-' | '/' | '(' | '›'))
|
||||
.filter_map(|w| w.chars().find(|c| c.is_alphanumeric()))
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A name's last `›`-separated part (the label) and the parts before it (the menu path).
|
||||
fn split_name(name: &str) -> (&str, &str) {
|
||||
match name.rsplit_once(" › ") {
|
||||
Some((path, label)) => (label, path),
|
||||
None => (name, ""),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` without the id that follows it when the result shows its id.
|
||||
fn without_id<'a>(name: &'a str, id: &str) -> &'a str {
|
||||
name.strip_suffix(')').and_then(|n| n.strip_suffix(id)).and_then(|n| n.strip_suffix(" (")).unwrap_or(name)
|
||||
}
|
||||
|
||||
/// The lowercased names a result is found by: the plain English name, the English name and the
|
||||
/// shown name ([`super::build`]'s haystack lines).
|
||||
fn names(e: &Entry) -> impl Iterator<Item = &str> {
|
||||
e.haystack.lines().take(3)
|
||||
}
|
||||
|
||||
/// The lowercased ids a result is found by: its own, and the engine command's a UI command wraps.
|
||||
fn ids(e: &Entry) -> impl Iterator<Item = &str> {
|
||||
e.haystack.lines().skip(3)
|
||||
}
|
||||
|
||||
impl Index {
|
||||
/// The index of `entries`, whose menu homes and menu items read `homes` in the UI language. The
|
||||
/// words of a result's menu home and of its menu item's label count as menu path words. A
|
||||
/// catalog with more results than a posting can name gets an empty index, and queries match by
|
||||
/// the substring rule alone.
|
||||
pub(crate) fn build(entries: &[Entry], homes: &[Option<String>]) -> Index {
|
||||
if entries.len() > usize::from(u16::MAX) {
|
||||
return Index::default();
|
||||
}
|
||||
let mut found: Vec<(String, u16, u8)> = vec![];
|
||||
let mut initials_text = String::new();
|
||||
let mut initials = Vec::with_capacity(entries.len());
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
let Ok(entry) = u16::try_from(i) else { break };
|
||||
let id = ids(e).next().unwrap_or_default();
|
||||
let start = initials_text.len();
|
||||
let mut seen_initials: Vec<String> = vec![];
|
||||
for name in names(e) {
|
||||
let (label, path) = split_name(without_id(name, id));
|
||||
found.extend(words(label).map(|w| (w.to_string(), entry, LABEL)));
|
||||
found.extend(words(path).map(|w| (w.to_string(), entry, PATH)));
|
||||
let ini = initials_of(label);
|
||||
if ini.chars().count() >= 2 && !seen_initials.contains(&ini) {
|
||||
if !seen_initials.is_empty() {
|
||||
initials_text.push('\n');
|
||||
}
|
||||
initials_text.push_str(&ini);
|
||||
seen_initials.push(ini);
|
||||
}
|
||||
}
|
||||
for home in [e.home.as_deref(), Some(e.menu_item), homes.get(i).and_then(Option::as_deref)].into_iter().flatten() {
|
||||
found.extend(words(&home.to_lowercase()).map(|w| (w.to_string(), entry, PATH)));
|
||||
}
|
||||
for id in ids(e) {
|
||||
found.extend(words(id).map(|w| (w.to_string(), entry, ID)));
|
||||
}
|
||||
let len = u16::try_from(initials_text.len() - start).unwrap_or(0);
|
||||
initials.push((u32::try_from(start).unwrap_or(0), len));
|
||||
}
|
||||
found.sort_unstable();
|
||||
found.dedup();
|
||||
let mut index = Index { initials_text, initials, ..Index::default() };
|
||||
let mut last: Option<&str> = None;
|
||||
for (word, entry, field) in &found {
|
||||
if last != Some(word.as_str()) {
|
||||
let (Ok(offset), Ok(len), Ok(start)) =
|
||||
(u32::try_from(index.term_text.len()), u32::try_from(word.len()), u32::try_from(index.postings.len()))
|
||||
else {
|
||||
return Index::default();
|
||||
};
|
||||
index.term_text.push_str(word);
|
||||
index.terms.push((offset, len));
|
||||
index.spans.push((start, 0));
|
||||
last = Some(word.as_str());
|
||||
}
|
||||
index.postings.push(Posting { entry: *entry, field: *field });
|
||||
if let Some(span) = index.spans.last_mut() {
|
||||
span.1 += 1;
|
||||
}
|
||||
}
|
||||
index.term_text.shrink_to_fit();
|
||||
index.terms.shrink_to_fit();
|
||||
index.spans.shrink_to_fit();
|
||||
index.postings.shrink_to_fit();
|
||||
index.initials_text.shrink_to_fit();
|
||||
index.initials.shrink_to_fit();
|
||||
index
|
||||
}
|
||||
|
||||
/// The bytes the index holds.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
self.term_text.capacity()
|
||||
+ self.terms.capacity() * std::mem::size_of::<(u32, u32)>()
|
||||
+ self.spans.capacity() * std::mem::size_of::<(u32, u32)>()
|
||||
+ self.postings.capacity() * std::mem::size_of::<Posting>()
|
||||
+ self.initials_text.capacity()
|
||||
+ self.initials.capacity() * std::mem::size_of::<(u32, u16)>()
|
||||
}
|
||||
|
||||
/// The text of the word at `(offset, len)` in `term_text`.
|
||||
fn text(&self, &(offset, len): &(u32, u32)) -> &str {
|
||||
let offset = offset as usize;
|
||||
self.term_text.get(offset..offset + len as usize).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The best grade (1 to 4) `word` gets in each result, [`NONE`] where it is no word and starts
|
||||
/// no word of the result. The words it starts are found by a binary search of the sorted words.
|
||||
fn grades(&self, word: &str, n: usize) -> Vec<u8> {
|
||||
let mut out = vec![NONE; n];
|
||||
let start = self.terms.partition_point(|t| self.text(t) < word);
|
||||
for (t, at) in self.terms.iter().enumerate().skip(start) {
|
||||
let term = self.text(at);
|
||||
if !term.starts_with(word) {
|
||||
break;
|
||||
}
|
||||
let whole = term == word;
|
||||
let Some(&(begin, len)) = self.spans.get(t) else { continue };
|
||||
let (begin, len) = (begin as usize, len as usize);
|
||||
for p in self.postings.get(begin..begin + len).unwrap_or_default() {
|
||||
let grade = match p.field {
|
||||
LABEL if whole => LABEL_WORD,
|
||||
LABEL => LABEL_PREFIX,
|
||||
PATH => PATH_WORD,
|
||||
_ => ID_WORD,
|
||||
};
|
||||
if let Some(g) = out.get_mut(usize::from(p.entry)) {
|
||||
*g = (*g).min(grade);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Is `query` (no spaces) the initials of one of result `i`'s labels?
|
||||
fn initials_are(&self, i: usize, query: &str) -> bool {
|
||||
let Some(&(offset, len)) = self.initials.get(i) else { return false };
|
||||
let (offset, len) = (offset as usize, usize::from(len));
|
||||
self.initials_text.get(offset..offset + len).is_some_and(|text| text.lines().any(|l| l == query))
|
||||
}
|
||||
}
|
||||
|
||||
/// `query` trimmed, lowercased, with each run of whitespace made one space.
|
||||
pub(crate) fn normalize(query: &str) -> String {
|
||||
query.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()
|
||||
}
|
||||
|
||||
/// The order of a result's kind when everything else ties: a tool, a command of the menu bar, a
|
||||
/// panel, an effect, a filter plug-in, then a command with no item in the menu bar.
|
||||
pub(crate) fn kind(id: &str, home: Option<&str>) -> u8 {
|
||||
match id.split_once(':').map(|(k, _)| k) {
|
||||
Some("tool") => 0,
|
||||
Some("panel") => 2,
|
||||
Some("effect") => 3,
|
||||
Some("plugin") => 4,
|
||||
_ if home.is_some() => 1,
|
||||
_ => 5,
|
||||
}
|
||||
}
|
||||
|
||||
/// How the whole lowercased `query` matches result `e` ([`EXACT_ID`] to [`NO_PHRASE`]), where
|
||||
/// `initials` says whether the query is the initials of one of its labels. A query starts a name
|
||||
/// when it starts the name's label, or, for a query that holds `›`, the name with its menu path.
|
||||
fn phrase(e: &Entry, query: &str, initials: bool) -> u8 {
|
||||
if ids(e).any(|id| id == query) {
|
||||
return EXACT_ID;
|
||||
}
|
||||
let trimmed = query.trim_end_matches('…');
|
||||
let labels = || names(e).flat_map(|n| [n, split_name(n).0]);
|
||||
if labels().any(|l| l == query || l.trim_end_matches('…') == trimmed) {
|
||||
return EXACT_LABEL;
|
||||
}
|
||||
// A menu's title alone does not put the items of that menu in this tier.
|
||||
let with_path = query.contains('›');
|
||||
if names(e).any(|n| split_name(n).0.starts_with(query) || (with_path && n.starts_with(query))) {
|
||||
return PREFIX;
|
||||
}
|
||||
if initials {
|
||||
return INITIALS;
|
||||
}
|
||||
NO_PHRASE
|
||||
}
|
||||
|
||||
/// What results are ordered by, compared field by field: how the whole query matches, the worst
|
||||
/// grade a word gets, the sum of the grades, the kind of result and the label's length.
|
||||
type RankKey = (u8, u8, u32, u8, usize);
|
||||
|
||||
/// The results of `entries` that the lowercased `query` matches, best first, as places in
|
||||
/// `entries`. A result matches when every word of the query is text in one of its names or ids
|
||||
/// (the rule the palette always had, so nothing it found is lost), when every word of the query is
|
||||
/// or starts a word of its label, menu path or id, or when the query is the initials of a label
|
||||
/// ("ea" for Export As…). Results are ordered by how the whole query matches ([`phrase`]), then by
|
||||
/// the worst grade a word gets, the sum of the grades, the kind of result ([`kind`]), the label's
|
||||
/// length and the catalog order. An empty query lists every result in catalog order.
|
||||
pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec<u32> {
|
||||
let query = normalize(query);
|
||||
if query.is_empty() {
|
||||
return (0..entries.len()).filter_map(|i| u32::try_from(i).ok()).collect();
|
||||
}
|
||||
let spaced: Vec<&str> = query.split(' ').collect();
|
||||
let head: String = query.chars().take(INDEX_CHARS).collect();
|
||||
let tokens: Vec<&str> = words(&head).collect();
|
||||
let n = entries.len();
|
||||
let indexed: Vec<Vec<u8>> = tokens.iter().map(|t| index.grades(t, n)).collect();
|
||||
// The index reads only the start of a longer query, so such a query matches by the substring
|
||||
// rule, which reads all of it.
|
||||
let fits = query.chars().count() <= INDEX_CHARS;
|
||||
let packed: String = query.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
let packed = Some(packed).filter(|p| (2..=6).contains(&p.chars().count()) && p.chars().all(char::is_alphabetic));
|
||||
let mut ranked: Vec<(RankKey, u32)> = vec![];
|
||||
for (i, e) in entries.iter().enumerate() {
|
||||
let Ok(place) = u32::try_from(i) else { break };
|
||||
let substring = spaced.iter().all(|w| e.haystack.contains(w));
|
||||
let initials = packed.as_deref().is_some_and(|p| index.initials_are(i, p));
|
||||
// Each word's grade, the worst and their sum; with initials, every word counts as a word
|
||||
// the label starts, as the initials stand for every word of the label.
|
||||
let (mut all_indexed, mut worst, mut sum) = (fits && !tokens.is_empty(), 0u8, 0u32);
|
||||
for (grades, token) in indexed.iter().zip(&tokens) {
|
||||
let mut g = grades.get(i).copied().unwrap_or(NONE);
|
||||
if g == NONE {
|
||||
all_indexed = false;
|
||||
if e.haystack.contains(token) {
|
||||
g = SUBSTRING;
|
||||
}
|
||||
}
|
||||
let g = if initials { g.min(LABEL_PREFIX) } else { g.min(SUBSTRING) };
|
||||
worst = worst.max(g);
|
||||
sum += u32::from(g);
|
||||
}
|
||||
if !(substring || all_indexed || initials) {
|
||||
continue;
|
||||
}
|
||||
let tier = phrase(e, &query, initials);
|
||||
let length = split_name(&e.shown).0.chars().count();
|
||||
ranked.push(((tier, worst, sum, e.kind, length), place));
|
||||
}
|
||||
ranked.sort_by_key(|&(key, place)| (key, place));
|
||||
ranked.into_iter().map(|(_, place)| place).collect()
|
||||
}
|
||||
|
||||
/// The first place in the menu bar of each item a result runs, as an English `›`-separated path
|
||||
/// of the menus that hold it: by command id, `panel:<id>` for a Window menu panel (Learn too),
|
||||
/// `effect:<id>` for an Effect menu item and `plugin:<id>` for an Object › Plug-ins filter. With
|
||||
/// the native Mac menu bar (`native`), About, Preferences (under Settings), Language, Appearance
|
||||
/// and Quit are in the application menu, which comes first, as `native_menu::mac_layout` puts
|
||||
/// them. The in-window menu bar shows no application menu. Each home comes with the English label
|
||||
/// of its item (File › Exit for Quit VectorCraft), empty for the application menu's items.
|
||||
pub(crate) fn menu_homes(native: bool) -> HashMap<String, (String, &'static str)> {
|
||||
fn key(id: &str, p: &serde_json::Value) -> String {
|
||||
let field = |k: &str| p.get(k).and_then(serde_json::Value::as_str);
|
||||
match (id, field("panel"), field("effect"), field("id")) {
|
||||
("window.panel", Some(panel), ..) => format!("panel:{panel}"),
|
||||
("window.learn", ..) => format!("panel:{}", crate::panels::learn::ID),
|
||||
("effect.dialog" | "effect.apply", _, Some(effect), _) => format!("effect:{effect}"),
|
||||
("plugin.dialog", _, _, Some(filter)) => format!("plugin:{filter}"),
|
||||
_ => WRAPPED.iter().find(|(engine, _)| *engine == id).map_or(id, |(_, ui)| ui).to_string(),
|
||||
}
|
||||
}
|
||||
fn walk(items: &[menus::Item], path: &mut Vec<&'static str>, skip: &[&str], out: &mut HashMap<String, (String, &'static str)>) {
|
||||
for it in items {
|
||||
match it {
|
||||
menus::Item::Cmd(label, id, p) if !skip.contains(id) => {
|
||||
out.entry(key(id, p)).or_insert_with(|| (path.join(" › "), *label));
|
||||
}
|
||||
menus::Item::Sub(name, children) => {
|
||||
path.push(name);
|
||||
walk(children, path, skip, out);
|
||||
path.pop();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = HashMap::new();
|
||||
let app_menu: &[(&str, &str)] =
|
||||
&[("help.about", ""), ("edit.preferences", "Settings"), ("app.language", "Language"), ("window.brightness", "Appearance"), ("app.quit", "")];
|
||||
let skip: Vec<&str> = if native { app_menu.iter().map(|(id, _)| *id).collect() } else { vec![] };
|
||||
if native {
|
||||
for (id, sub) in app_menu {
|
||||
let path = if sub.is_empty() { crate::native_menu::APP_NAME.to_string() } else { format!("{} › {sub}", crate::native_menu::APP_NAME) };
|
||||
out.insert((*id).to_string(), (path, ""));
|
||||
}
|
||||
}
|
||||
// The tree's first menu is the application menu, which the in-window bar never shows and
|
||||
// the native bar builds itself.
|
||||
for (name, items) in menus::menu_tree().into_iter().skip(1) {
|
||||
walk(&items, &mut vec![name], &skip, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::{Catalog, catalog};
|
||||
use super::*;
|
||||
use crate::i18n::Lang;
|
||||
|
||||
/// The ids of the results `query` lists, best first.
|
||||
fn ranked(c: &Catalog, query: &str) -> Vec<String> {
|
||||
rank(&c.list, &c.index, query).iter().filter_map(|&i| c.list.get(i as usize)).map(|e| e.id.clone()).collect()
|
||||
}
|
||||
|
||||
/// A result named `name` (`›`-separated, its last part the label) with id `id`.
|
||||
fn entry(name: &str, id: &str) -> Entry {
|
||||
let home = None;
|
||||
Entry {
|
||||
id: id.to_string(),
|
||||
shortcut: String::new(),
|
||||
shown: name.to_string(),
|
||||
haystack: [name, name, name, id].map(str::to_lowercase).join("\n"),
|
||||
kind: kind(id, home.as_deref()),
|
||||
home,
|
||||
menu_item: "",
|
||||
}
|
||||
}
|
||||
|
||||
/// `entries` with their index.
|
||||
fn synthetic(entries: Vec<Entry>) -> Catalog {
|
||||
let index = Index::build(&entries, &[]);
|
||||
Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) }
|
||||
}
|
||||
|
||||
/// Where `id` is among the results of `query`.
|
||||
fn place(c: &Catalog, query: &str, id: &str) -> Option<usize> {
|
||||
ranked(c, query).iter().position(|r| r == id)
|
||||
}
|
||||
|
||||
/// For each pair of adjacent word grades, a result where the word gets the better grade ranks
|
||||
/// above one where it gets the worse, and both are listed. The second word of each query is a
|
||||
/// whole word of every label, so no whole-query tier applies.
|
||||
#[test]
|
||||
fn a_better_word_grade_ranks_first() {
|
||||
for (query, better, worse) in [
|
||||
// A whole word of the label, then a word of the label it starts.
|
||||
("cut zz", entry("Zz Cut", "a.one"), entry("Zz Cutter", "b.two")),
|
||||
// A word of the label it starts, then a word of the menu path.
|
||||
("fill zz", entry("Zz Filling", "a.one"), entry("Fill › Zz Other", "b.two")),
|
||||
// A word of the menu path, then a word of the id.
|
||||
("zap zz", entry("Zap › Zz One", "a.one"), entry("Zz Two", "zap.two")),
|
||||
// A word of the id, then text inside a word.
|
||||
("zip zz", entry("Zz Three", "zip.three"), entry("Zz Unzipped", "b.two")),
|
||||
] {
|
||||
let (b, w) = (better.id.clone(), worse.id.clone());
|
||||
// The worse one comes first in the catalog, so only the grade puts the better first.
|
||||
let c = synthetic(vec![worse, better]);
|
||||
assert_eq!(ranked(&c, query), [b, w], "{query}");
|
||||
}
|
||||
}
|
||||
|
||||
/// For each pair of adjacent whole-query tiers, a result in the better tier ranks above one in
|
||||
/// the worse.
|
||||
#[test]
|
||||
fn a_better_whole_query_tier_ranks_first() {
|
||||
for (query, better, worse) in [
|
||||
// The query is the result's id, then it is a label.
|
||||
("zz.one", entry("Alpha", "zz.one"), entry("zz.one", "b.two")),
|
||||
// The query is a label, then a label starts with it.
|
||||
("snap", entry("Snap", "a.one"), entry("Snapshot", "b.two")),
|
||||
// A label starts with the query, then the query is a label's initials.
|
||||
("ab", entry("Abacus", "a.one"), entry("Alpha Beta", "b.two")),
|
||||
// The query is a label's initials, then a whole word of a label that it does not start.
|
||||
("gb", entry("Green Blue", "a.one"), entry("Zz Gb", "b.two")),
|
||||
] {
|
||||
let (b, w) = (better.id.clone(), worse.id.clone());
|
||||
let c = synthetic(vec![worse, better]);
|
||||
assert_eq!(ranked(&c, query), [b, w], "{query}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of result and the label's length order results only when the grades tie: a tool
|
||||
/// with a short label stays below a command whose label holds the word whole. Ties keep the
|
||||
/// catalog order, the same on every ranking.
|
||||
#[test]
|
||||
fn kind_and_length_never_lift_a_worse_grade() {
|
||||
let c = synthetic(vec![entry("Zz Cutx", "tool:cutx"), entry("Zz Cut With a Much Longer Label", "a.one")]);
|
||||
assert_eq!(ranked(&c, "cut zz"), ["a.one", "tool:cutx"]);
|
||||
let c = synthetic(vec![entry("Zz Cut Long Label", "a.one"), entry("Zz Cut Long", "b.two"), entry("Zz Cut", "tool:cut")]);
|
||||
assert_eq!(ranked(&c, "cut zz"), ["tool:cut", "b.two", "a.one"], "the tool first, then the shorter label");
|
||||
let c = synthetic(vec![entry("Zz Same", "a.one"), entry("Zz Same", "b.two"), entry("Zz Same", "c.three")]);
|
||||
assert_eq!(ranked(&c, "same zz"), ["a.one", "b.two", "c.three"]);
|
||||
assert_eq!(ranked(&c, "same zz"), ranked(&c, "same zz"));
|
||||
}
|
||||
|
||||
/// A query that is a menu's title ranks a result whose label holds it as a word above the items
|
||||
/// of that menu, which match only by their menu path. A query that names the menu with `›`
|
||||
/// still starts the item's name.
|
||||
#[test]
|
||||
fn a_menu_title_does_not_lift_its_items() {
|
||||
let c = synthetic(vec![entry("Object › Paint", "a.one"), entry("Outline Object", "b.two")]);
|
||||
assert_eq!(ranked(&c, "object"), ["b.two", "a.one"]);
|
||||
assert_eq!(ranked(&c, "object › pa"), ["a.one"]);
|
||||
let en = catalog(Lang::EN, false);
|
||||
for q in ["object", "effect", "select", "view", "type", "edit"] {
|
||||
let first = rank(&en.list, &en.index, q).first().and_then(|&i| en.list.get(i as usize)).map(|e| e.shown.to_lowercase());
|
||||
let label = first.as_deref().map(|n| split_name(n).0.to_string()).unwrap_or_default();
|
||||
assert!(words(&label).any(|w| w.starts_with(q)), "{q}: {first:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The application menu of the native Mac menu bar holds the items [`menu_homes`] puts there,
|
||||
/// under the same submenus.
|
||||
#[test]
|
||||
fn native_homes_follow_the_native_application_menu() {
|
||||
use crate::native_menu::{self, MenuRole, Node};
|
||||
fn walk(nodes: &[Node], path: &mut Vec<String>, out: &mut HashMap<String, String>) {
|
||||
for n in nodes {
|
||||
match n {
|
||||
Node::Item(it) => {
|
||||
if let Some(id) = it.command {
|
||||
out.entry(id.to_string()).or_insert_with(|| path.join(" › "));
|
||||
}
|
||||
}
|
||||
Node::Submenu { label, children } => {
|
||||
path.push(label.clone());
|
||||
walk(children, path, out);
|
||||
path.pop();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let bar = native_menu::mac_layout(&app, &native_menu::from_tree(&app, &menus::menu_tree()), Lang::EN).bar;
|
||||
let app_menu = bar.menus.iter().find(|m| m.role == MenuRole::App).unwrap();
|
||||
let mut found = HashMap::new();
|
||||
walk(&app_menu.children, &mut vec![app_menu.title.clone()], &mut found);
|
||||
// The items the native bar runs itself (Hide, Hide Others, Minimize) are not palette results.
|
||||
found.retain(|id, _| ![native_menu::HIDE, native_menu::HIDE_OTHERS, native_menu::MINIMIZE].contains(&id.as_str()));
|
||||
let homes = menu_homes(true);
|
||||
let expected: HashMap<String, String> = homes
|
||||
.iter()
|
||||
.filter(|(_, (path, _))| path.split(" › ").next() == Some(native_menu::APP_NAME))
|
||||
.map(|(id, (path, _))| (id.clone(), path.clone()))
|
||||
.collect();
|
||||
assert!(!expected.is_empty());
|
||||
assert_eq!(found, expected);
|
||||
}
|
||||
|
||||
/// Queries from the list of things people type, on the English results: some list their command
|
||||
/// first, others within the first few results.
|
||||
#[test]
|
||||
fn common_queries_list_the_command_near_the_top() {
|
||||
let c = catalog(Lang::EN, false);
|
||||
let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default();
|
||||
let within = |q: &str, id: &str, n: usize| place(&c, q, id).is_some_and(|p| p < n);
|
||||
assert_eq!(first("ea"), "file.exportAs", "the initials of Export As…");
|
||||
assert_eq!(first("save"), "file.save");
|
||||
assert!(within("export", "file.exportAs", 3));
|
||||
assert_eq!(first("rect"), "tool:rectangle");
|
||||
let (tool, effect) = (place(&c, "rect", "tool:rectangle"), place(&c, "rect", "effect:convertToShape.rectangle"));
|
||||
assert!(effect.is_some() && tool < effect, "{tool:?} {effect:?}");
|
||||
assert!(within("type", "tool:type", 2));
|
||||
assert!(within("layers", "panel:layers", 3));
|
||||
assert_eq!(first("drop shadow"), "effect:stylize.dropShadow");
|
||||
assert_eq!(first("view.goto1"), "view.goto1", "the whole id, above Saved View 10");
|
||||
assert_eq!(first("bring front"), "object.arrange.bringToFront");
|
||||
assert!(within("ruler", "view.rulers", 4));
|
||||
assert!(place(&c, "ruler", "perspective.grid.rulers").is_some());
|
||||
assert_eq!(first("deselect"), "select.none");
|
||||
let mut blurs: Vec<String> = ranked(&c, "blur").into_iter().take(3).collect();
|
||||
blurs.sort();
|
||||
assert_eq!(blurs, ["effect:blur.gaussian", "effect:blur.radial", "effect:blur.smart"]);
|
||||
assert!(ranked(&c, "zzzz").is_empty());
|
||||
// English names are searched in every language.
|
||||
let zh = catalog(Lang::from_code("zh-hant").unwrap(), false);
|
||||
for q in ["save", "rect"] {
|
||||
assert_eq!(ranked(&zh, q).first(), ranked(&c, q).first(), "{q}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What the palette always matched: every word of the query is text in one of the result's
|
||||
/// names or ids.
|
||||
fn substring_rule<'a>(c: &'a Catalog, query: &str) -> Vec<&'a str> {
|
||||
let q = normalize(query);
|
||||
c.list.iter().filter(|e| q.split_whitespace().all(|w| e.haystack.contains(w))).map(|e| e.id.as_str()).collect()
|
||||
}
|
||||
|
||||
/// Each result's English name, shown name (in English, German and Chinese, Traditional) and id
|
||||
/// find it, first unless another result has that name; its id always lists it first.
|
||||
#[test]
|
||||
fn every_result_is_found_first_by_its_name_and_its_id() {
|
||||
for code in ["en", "de", "zh-hant"] {
|
||||
let c = catalog(Lang::from_code(code).unwrap(), false);
|
||||
let label = |n: &str| split_name(n).0.trim_end_matches('…').to_string();
|
||||
for e in &c.list {
|
||||
let english = e.haystack.lines().nth(1).unwrap_or_default();
|
||||
for query in [english, &e.shown] {
|
||||
let results = ranked(&c, query);
|
||||
assert!(results.contains(&e.id), "{code}: {query} finds {}", e.id);
|
||||
let q = normalize(query);
|
||||
let named = c.list.iter().filter(|o| names(o).any(|n| n == q || label(n) == label(&q))).count();
|
||||
if named <= 1 {
|
||||
assert_eq!(results.first(), Some(&e.id), "{code}: {query}");
|
||||
}
|
||||
}
|
||||
assert_eq!(ranked(&c, &e.id).first(), Some(&e.id), "{code}: {}", e.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The queries the palette's tests use and a list of things people type.
|
||||
const QUERIES: &[&str] = &[
|
||||
"select",
|
||||
"zoom",
|
||||
"zoom in",
|
||||
"show panel",
|
||||
"group",
|
||||
"layers",
|
||||
"color guide",
|
||||
"drop shadow",
|
||||
"use precise cursors",
|
||||
"continue in background",
|
||||
"export continue in background",
|
||||
"show rulers",
|
||||
"delete selection",
|
||||
"cancel key object",
|
||||
"fit headline",
|
||||
"batch",
|
||||
"flattener preview",
|
||||
"panel options",
|
||||
"close path",
|
||||
"knife",
|
||||
"play action",
|
||||
"reset panel",
|
||||
"other library",
|
||||
"ellipse",
|
||||
"blur",
|
||||
"save",
|
||||
"export",
|
||||
"rect",
|
||||
"type",
|
||||
"ea",
|
||||
"bring front",
|
||||
"ruler",
|
||||
"deselect",
|
||||
"view.goto1",
|
||||
"zzzz",
|
||||
"pen",
|
||||
"outlines",
|
||||
"join paths",
|
||||
"rounded corners",
|
||||
"scaling",
|
||||
"rotated",
|
||||
"eyedroper",
|
||||
"rectange",
|
||||
"elipse",
|
||||
"gruop",
|
||||
"remove bg",
|
||||
"outline text",
|
||||
"flip",
|
||||
"combine",
|
||||
"vectorize",
|
||||
"colour",
|
||||
"transparent background",
|
||||
"png",
|
||||
"object.group",
|
||||
"file.exportinbackground",
|
||||
"window",
|
||||
"s",
|
||||
"e",
|
||||
"…",
|
||||
"› ",
|
||||
];
|
||||
|
||||
/// For each query, every result the palette found before is still found, and when it found 50
|
||||
/// or fewer, each of them is among the first 50 results, so the list still shows it.
|
||||
#[test]
|
||||
fn every_result_found_before_is_still_found_and_shown() {
|
||||
assert_eq!(QUERIES.len(), 60);
|
||||
let c = catalog(Lang::EN, false);
|
||||
for q in QUERIES {
|
||||
let before = substring_rule(&c, q);
|
||||
let now = ranked(&c, q);
|
||||
for id in &before {
|
||||
let at = now.iter().position(|r| r == id);
|
||||
assert!(at.is_some(), "{q}: {id} is still found");
|
||||
if before.len() <= super::super::MAX_RESULTS {
|
||||
assert!(at < Some(super::super::MAX_RESULTS), "{q}: {id} is shown at {at:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A query longer than the index reads still has to match in full: two labels that share their
|
||||
/// first 200 characters are told apart by the rest.
|
||||
#[test]
|
||||
fn a_long_query_matches_in_full() {
|
||||
let shared = "a".repeat(200);
|
||||
let c = synthetic(vec![entry(&format!("{shared}b tail"), "a.one"), entry(&format!("{shared}c tail"), "b.two")]);
|
||||
let query = format!("{shared}b");
|
||||
assert_eq!(substring_rule(&c, &query), ["a.one"]);
|
||||
assert_eq!(ranked(&c, &query), ["a.one"]);
|
||||
}
|
||||
|
||||
/// Text in scripts without spaces, right-to-left text, combining characters, a very long pasted
|
||||
/// query, punctuation alone and names that differ only in the id they show.
|
||||
#[test]
|
||||
fn unusual_text_is_searched_safely() {
|
||||
let c = synthetic(vec![entry("物件 › 群組", "a.one"), entry("مرحبا عالم", "b.two"), entry("Cafe\u{301} Tool", "c.three")]);
|
||||
assert_eq!(ranked(&c, "群組"), ["a.one"]);
|
||||
assert_eq!(ranked(&c, "عالم"), ["b.two"]);
|
||||
assert_eq!(ranked(&c, "cafe\u{301}"), ["c.three"]);
|
||||
assert!(ranked(&c, &"x".repeat(5000)).is_empty());
|
||||
assert!(ranked(&c, &"群".repeat(5000)).is_empty());
|
||||
assert_eq!(ranked(&c, "›"), ["a.one"]);
|
||||
assert!(ranked(&c, "…,.-").is_empty());
|
||||
let en = catalog(Lang::EN, false);
|
||||
let both = ranked(&en, "fit headline");
|
||||
assert!(both.contains(&"type.fitHeadline".to_string()) && both.contains(&"text.fitHeadline".to_string()), "{both:?}");
|
||||
for id in ["type.fitHeadline", "text.fitHeadline"] {
|
||||
assert_eq!(ranked(&en, &format!("Type › Fit Headline ({id})")).first().map(String::as_str), Some(id));
|
||||
}
|
||||
let zh = Lang::from_code("zh-hant").unwrap();
|
||||
let zh_catalog = catalog(zh, false);
|
||||
let group = crate::i18n::tr(zh, "Group");
|
||||
assert!(place(&zh_catalog, group, "object.group").is_some_and(|p| p < 3), "{group}");
|
||||
}
|
||||
|
||||
/// Each result's home is the first item of the menu bar that runs it: an Effect menu item's
|
||||
/// submenu, the Window menu for a panel whose item shows and hides it, Learn's own item, and
|
||||
/// with the native Mac menu bar Preferences under the application menu's Settings.
|
||||
#[test]
|
||||
fn results_know_their_place_in_the_menu_bar() {
|
||||
let homes = menu_homes(false);
|
||||
let home = |id: &str| homes.get(id).map(|(path, _)| path.as_str());
|
||||
assert_eq!(home("effect:stylize.roundCorners"), Some("Effect › Stylize"));
|
||||
assert_eq!(home("panel:layers"), Some("Window"), "matched by the panel, although the item also asks to toggle it");
|
||||
assert_eq!(home("panel:learn"), Some("Window"));
|
||||
assert_eq!(home("panel:character"), Some("Window › Type"));
|
||||
assert_eq!(home("edit.preferences"), Some("Edit"));
|
||||
assert_eq!(home("help.about"), Some("Help"), "the in-window bar shows no application menu");
|
||||
assert_eq!(home("ui.layersPanelOptions"), None);
|
||||
assert_eq!(homes.get("app.quit"), Some(&("File".to_string(), "Exit")), "with its item's own label");
|
||||
let native = menu_homes(true);
|
||||
let native_home = |id: &str| native.get(id).map(|(path, _)| path.as_str());
|
||||
assert_eq!(native_home("edit.preferences"), Some("VectorCraft › Settings"));
|
||||
assert_eq!(native_home("help.about"), Some("VectorCraft"));
|
||||
assert_eq!(native_home("help.discord"), Some("Help"));
|
||||
let c = catalog(Lang::EN, false);
|
||||
let of = |id: &str| c.list.iter().find(|e| e.id == id).and_then(|e| e.home.clone());
|
||||
assert_eq!(of("effect:stylize.roundCorners").as_deref(), Some("Effect › Stylize"));
|
||||
assert_eq!(of("tool:pen"), None);
|
||||
// The home's words find the result: Preferences… under the native bar's Settings.
|
||||
let native_catalog = catalog(Lang::EN, true);
|
||||
assert!(place(&native_catalog, "settings pref", "edit.preferences").is_some());
|
||||
assert!(place(&c, "settings pref", "edit.preferences").is_none());
|
||||
// The menu item's own label finds the result too: File › Exit runs Quit VectorCraft.
|
||||
assert!(place(&c, "exit", "app.quit").is_some());
|
||||
}
|
||||
|
||||
/// The index of the real results takes at most 512 KiB, homes included.
|
||||
#[test]
|
||||
fn the_index_stays_small() {
|
||||
let c = catalog(Lang::EN, false);
|
||||
let homes: usize = c.list.iter().filter_map(|e| e.home.as_ref()).map(String::capacity).sum();
|
||||
let bytes = c.index.bytes() + homes;
|
||||
println!("{} results, index {} bytes, homes {homes} bytes", c.list.len(), c.index.bytes());
|
||||
assert!(bytes <= 512 * 1024, "{bytes}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "times the index and sample queries; run in a release build"]
|
||||
fn time_the_index_and_queries() {
|
||||
let started = std::time::Instant::now();
|
||||
let c = catalog(Lang::EN, false);
|
||||
let built = started.elapsed();
|
||||
let started = std::time::Instant::now();
|
||||
let index = Index::build(&c.list, &[]);
|
||||
println!("catalog {built:?}, index alone {:?}, {} results, {} bytes", started.elapsed(), c.list.len(), index.bytes());
|
||||
let long = "q".repeat(200);
|
||||
for q in ["e", "ea", "select", "bring front", "zzzz", long.as_str()] {
|
||||
let started = std::time::Instant::now();
|
||||
let runs = 100;
|
||||
for _ in 0..runs {
|
||||
std::hint::black_box(rank(&c.list, &c.index, q));
|
||||
}
|
||||
println!("{:>12}: {:?} per query", q.get(..12).unwrap_or(q), started.elapsed() / runs);
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
for _ in 0..100 {
|
||||
std::hint::black_box(substring_rule(&c, "bring front"));
|
||||
}
|
||||
println!("substring rule alone: {:?} per query", started.elapsed() / 100);
|
||||
}
|
||||
}
|
||||
@@ -299,6 +299,40 @@ fn insert(app: &mut VectorcraftApp, ctx: &egui::Context, ch: char) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid's cells for `face`: the characters listed, with their glyphs, then the glyphs listed by
|
||||
/// glyph id. `category` gives the glyphs of one of the face's categories; without it, the cells are
|
||||
/// the characters of `lo..=hi`, and in Entire Font (`subset` 0) also the glyphs no character maps.
|
||||
fn grid_glyphs(
|
||||
face: &vectorcraft_text::FontFace,
|
||||
category: Option<&vectorcraft_text::GlyphCategory>,
|
||||
subset: usize,
|
||||
(lo, hi): (u32, u32),
|
||||
) -> (Vec<(char, u32)>, std::sync::Arc<[u32]>) {
|
||||
let all = face.mapped_chars();
|
||||
match category {
|
||||
// A category lists its glyphs that a character maps by that character, and the others by
|
||||
// glyph id after them.
|
||||
Some(c) => {
|
||||
let wanted: HashSet<u32> = c.glyphs.iter().copied().collect();
|
||||
// A glyph several characters map is listed once, by the first of them; a glyph only a
|
||||
// space or control character maps is listed by glyph id, as no character it can insert.
|
||||
let mut mapped: HashSet<u32> = HashSet::new();
|
||||
let chars: Vec<(char, u32)> =
|
||||
all.iter().copied().filter(|(c, g)| !c.is_control() && !c.is_whitespace() && wanted.contains(g) && mapped.insert(*g)).collect();
|
||||
(chars, c.glyphs.iter().copied().filter(|g| !mapped.contains(g)).collect())
|
||||
}
|
||||
None => {
|
||||
// The list is sorted by code point, so the range's characters lie between two bounds.
|
||||
let start = all.partition_point(|(c, _)| (*c as u32) < lo);
|
||||
let end = all.partition_point(|(c, _)| (*c as u32) <= hi);
|
||||
let chars = all.get(start..end).unwrap_or_default().iter().copied().filter(|(c, _)| !c.is_control() && !c.is_whitespace()).collect();
|
||||
// Entire Font also lists the glyphs no character maps (positional forms, alternates,
|
||||
// ligatures) by glyph id, after the characters.
|
||||
(chars, if subset == 0 { face.unencoded_glyphs() } else { std::sync::Arc::from([]) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Browse and insert glyphs from the chosen font, with font controls below the glyph grid.
|
||||
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
@@ -335,25 +369,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.label(egui::RichText::new(tl!("No fonts are available.")).color(t.text_dim));
|
||||
return;
|
||||
};
|
||||
let (chars, unencoded): (Vec<(char, u32)>, Vec<u32>) = match category.and_then(|i| face.glyph_categories().get(i)) {
|
||||
// A category lists its glyphs that a character maps by that character, and the others by
|
||||
// glyph id after them.
|
||||
Some(c) => {
|
||||
let wanted: HashSet<u32> = c.glyphs.iter().copied().collect();
|
||||
// A glyph several characters map is listed once, by the first of them; a glyph only a
|
||||
// space or control character maps is listed by glyph id, as no character it can insert.
|
||||
let mut mapped: HashSet<u32> = HashSet::new();
|
||||
let chars: Vec<(char, u32)> =
|
||||
face.chars().into_iter().filter(|(c, g)| !c.is_control() && !c.is_whitespace() && wanted.contains(g) && mapped.insert(*g)).collect();
|
||||
(chars, c.glyphs.iter().copied().filter(|g| !mapped.contains(g)).collect())
|
||||
}
|
||||
None => {
|
||||
let chars = face.chars().into_iter().filter(|(c, _)| (lo..=hi).contains(&(*c as u32)) && !c.is_control() && !c.is_whitespace()).collect();
|
||||
// Entire Font also lists the glyphs no character maps (positional forms, alternates,
|
||||
// ligatures) by glyph id, after the characters.
|
||||
(chars, if subset == 0 { face.unencoded_glyphs().to_vec() } else { vec![] })
|
||||
}
|
||||
};
|
||||
let (chars, unencoded) = grid_glyphs(&face, category.and_then(|i| face.glyph_categories().get(i)), subset, (lo, hi));
|
||||
let total = chars.len() + unencoded.len();
|
||||
let cell = CELL_STEPS[cell_index(app)];
|
||||
let cols = ((w / cell).floor() as usize).max(1);
|
||||
@@ -2922,4 +2938,72 @@ mod tests {
|
||||
state.doc.walk(|n| texts += usize::from(matches!(n.kind, NodeKind::Text(_))));
|
||||
assert_eq!(texts, 0, "neither glyph created or changed text");
|
||||
}
|
||||
|
||||
/// The grid's cells built from the face's character list read once are the cells built from a
|
||||
/// fresh read of the font on every frame, for every Show choice, every category, a change of
|
||||
/// face back and forth, and a font with no `cmap`.
|
||||
#[test]
|
||||
fn the_grid_lists_the_same_cells_from_the_character_list_read_once() {
|
||||
use vectorcraft_text::test_fonts::{CATEGORIES_FAMILY, CMAPLESS_FAMILY, categories_font, cmapless_font};
|
||||
|
||||
/// The cells as the grid listed them on each frame from its own copy of the face's characters
|
||||
/// (`vectorcraft-text`'s tests check that list against a fresh read of the font).
|
||||
fn read_cells(
|
||||
face: &vectorcraft_text::FontFace,
|
||||
category: Option<usize>,
|
||||
subset: usize,
|
||||
(lo, hi): (u32, u32),
|
||||
) -> (Vec<(char, u32)>, Vec<u32>) {
|
||||
match category.and_then(|i| face.glyph_categories().get(i)) {
|
||||
Some(c) => {
|
||||
let wanted: HashSet<u32> = c.glyphs.iter().copied().collect();
|
||||
let mut mapped: HashSet<u32> = HashSet::new();
|
||||
let chars: Vec<(char, u32)> = face
|
||||
.chars()
|
||||
.into_iter()
|
||||
.filter(|(c, g)| !c.is_control() && !c.is_whitespace() && wanted.contains(g) && mapped.insert(*g))
|
||||
.collect();
|
||||
(chars, c.glyphs.iter().copied().filter(|g| !mapped.contains(g)).collect())
|
||||
}
|
||||
None => {
|
||||
let chars =
|
||||
face.chars().into_iter().filter(|(c, _)| (lo..=hi).contains(&(*c as u32)) && !c.is_control() && !c.is_whitespace()).collect();
|
||||
(chars, if subset == 0 { face.unencoded_glyphs().to_vec() } else { vec![] })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
assert_eq!(db.add_font(categories_font().expect("the categories test font builds")), 1);
|
||||
assert_eq!(db.add_font(cmapless_font().expect("the cmapless test font builds")), 1);
|
||||
let faces: Vec<_> = [
|
||||
(vectorcraft_text::FALLBACK_FAMILY, "Regular"),
|
||||
("Inter", "Regular"),
|
||||
(CATEGORIES_FAMILY, "Regular"),
|
||||
(vectorcraft_text::FALLBACK_FAMILY, "Regular"),
|
||||
(CMAPLESS_FAMILY, "Regular"),
|
||||
("JetBrains Mono", "Regular"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(family, style)| db.face(family, style).unwrap_or_else(|| panic!("{family} {style} is loaded")))
|
||||
.collect();
|
||||
let categories = db.face(CATEGORIES_FAMILY, "Regular").expect("the categories face");
|
||||
assert!(!categories.glyph_categories().is_empty(), "the test font has categories");
|
||||
let none = db.face(CMAPLESS_FAMILY, "Regular").expect("the cmapless face");
|
||||
assert!(none.mapped_chars().is_empty(), "no character is mapped");
|
||||
for face in &faces {
|
||||
for (subset, &(name, lo, hi)) in SUBSETS.iter().enumerate() {
|
||||
let (chars, unencoded) = grid_glyphs(face, None, subset, (lo, hi));
|
||||
assert_eq!((chars, unencoded.to_vec()), read_cells(face, None, subset, (lo, hi)), "{face:?} {name}");
|
||||
}
|
||||
for (i, c) in face.glyph_categories().iter().enumerate() {
|
||||
let (chars, unencoded) = grid_glyphs(face, Some(c), CATEGORY, (0, 0x10FFFF));
|
||||
assert_eq!((chars, unencoded.to_vec()), read_cells(face, Some(i), CATEGORY, (0, 0x10FFFF)), "{face:?} {:?}", c.kind);
|
||||
}
|
||||
}
|
||||
// Entire Font lists every glyph of a font with no `cmap` by glyph id.
|
||||
let (chars, unencoded) = grid_glyphs(&none, None, 0, (0, 0x10FFFF));
|
||||
assert!(chars.is_empty());
|
||||
assert!(!unencoded.is_empty(), "the glyphs are listed by glyph id");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ fn explore_tutorials_on_the_app_bar_shows_and_hides_the_learn_panel() {
|
||||
let ctx = context();
|
||||
assert!(!shown(&app));
|
||||
let nodes = frame(&mut app, &ctx, vec![], app_bar);
|
||||
let search = center_where(&nodes, |label| label.starts_with("Search commands and tools"));
|
||||
let search = center_where(&nodes, |label| label.starts_with("Search commands, tools, panels and effects"));
|
||||
let learn = center(&nodes, "Explore tutorials");
|
||||
let (search, learn) = (search.expect("the search icon shows"), learn.expect("the app bar has Explore tutorials"));
|
||||
assert!(learn.x < search.x && (learn.y - search.y).abs() < 1.0, "beside the search icon: {learn:?}, {search:?}");
|
||||
|
||||
@@ -114,7 +114,7 @@ fn variable_row(ui: &mut Ui, row: &VarRow, selected: bool) -> Response {
|
||||
let object_cell = Rect::from_min_max(pos2(name_right, rect.top()), rect.max);
|
||||
ui.painter().with_clip_rect(object_cell).text(object_cell.left_center() + pad, left, &row.object, font, t.text_dim);
|
||||
let full = if row.object.is_empty() { row.name.clone() } else { format!("{} · {}", row.name, row.object) };
|
||||
r.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &full));
|
||||
widgets::list_item_info(&r, selected, || full.clone());
|
||||
// A column clips a long name, so the whole of it shows on hover.
|
||||
r.on_hover_text(full)
|
||||
}
|
||||
@@ -707,6 +707,23 @@ mod tests {
|
||||
assert_eq!(app.ui.status, "");
|
||||
}
|
||||
|
||||
/// Each variable row is a list item, and only the highlighted one is selected.
|
||||
#[test]
|
||||
fn the_rows_report_the_highlight_as_the_selected_state() {
|
||||
use egui::accesskit::Role;
|
||||
let mut app = app_with_data();
|
||||
app.session.execute("variable.define", &json!({"name": "age", "kind": "visibility"})).unwrap();
|
||||
app.session.execute("variable.highlight", &json!({"variable": "Name"})).unwrap();
|
||||
let nodes = Driver::new().nodes(&mut app);
|
||||
let mut rows: Vec<_> = nodes
|
||||
.iter()
|
||||
.filter(|(_, n)| n.role() == Role::ListItem)
|
||||
.map(|(_, n)| (n.label().map(str::to_string), n.is_selected(), n.toggled()))
|
||||
.collect();
|
||||
rows.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
assert_eq!(rows, [(Some("Name · Alice".to_string()), Some(true), None), (Some("age".to_string()), Some(false), None)]);
|
||||
}
|
||||
|
||||
/// A click on a column header sorts the list by that column, and a second click on it
|
||||
/// reverses the order; the rows are drawn in the order `variable.list` reports.
|
||||
#[test]
|
||||
|
||||
@@ -305,14 +305,36 @@ fn open_dialog(app: &mut VectorcraftApp, files: Vec<Value>) {
|
||||
}
|
||||
|
||||
/// Is dialog file entry `file` a VectorCraft document on disk (what Link places as one locked
|
||||
/// object), or a PDF or `.ai` file on disk? A `.ai` saved without PDF compatibility is PostScript,
|
||||
/// which `file.place` embeds whether Link is on or not.
|
||||
/// object), or a PDF, `.ai`, EPS or PostScript file on disk? A DCS file (an EPS file naming its
|
||||
/// plates) is placed as a linked image instead. Where the platform reads part of a file, only the
|
||||
/// file's start is read; a file longer than that is taken to be at least as long as its binary EPS
|
||||
/// header says, and one whose header can't be told from it counts as a document.
|
||||
fn is_vectorcraft_file(app: &VectorcraftApp, file: &Value) -> bool {
|
||||
use vectorcraft_engine::cmd::place::{DCS_HEAD_BYTES, head_is_dcs};
|
||||
let Some(path) = file.get("path").and_then(Value::as_str) else { return false };
|
||||
let native = ["vectorcraft", vectorcraft_format::LEGACY_EXTENSION, "vctemplate"];
|
||||
// The file's start, and the file's length when that is all of it.
|
||||
let bytes = || match (&app.services.read_head, &app.services.read) {
|
||||
(Some(read_head), _) => read_head(path, DCS_HEAD_BYTES + 1).ok().map(|mut b| {
|
||||
let whole = b.len() <= DCS_HEAD_BYTES;
|
||||
b.truncate(DCS_HEAD_BYTES);
|
||||
let size = if whole { b.len() as u64 } else { u64::MAX };
|
||||
(b, size)
|
||||
}),
|
||||
(None, Some(read)) => read(path).ok().map(|b| {
|
||||
let size = b.len() as u64;
|
||||
(b, size)
|
||||
}),
|
||||
(None, None) => None,
|
||||
};
|
||||
let dcs = |(b, size): &(Vec<u8>, u64)| {
|
||||
let head = b.get(..DCS_HEAD_BYTES).unwrap_or(b);
|
||||
vectorcraft_pdf::is_postscript(head) && head_is_dcs(head, *size).unwrap_or(false)
|
||||
};
|
||||
match fileio::extension(path).as_str() {
|
||||
e if native.contains(&e) => true,
|
||||
"pdf" | "ai" | "ait" => app.services.read.as_ref().and_then(|r| r(path).ok()).is_none_or(|b| !vectorcraft_pdf::is_postscript(&b)),
|
||||
"pdf" | "ai" | "ait" => bytes().is_none_or(|b| !dcs(&b)),
|
||||
"eps" | "epsf" | "ps" => bytes().is_some_and(|b| vectorcraft_pdf::is_postscript(&b.0) && !dcs(&b)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -753,7 +753,7 @@ fn menu_bar_paths() -> &'static HashMap<&'static str, Vec<(String, Value)>> {
|
||||
/// The menu path of the item of the menu bar that runs command `id` as a key press runs it
|
||||
/// ([`a_menu_bar_item_runs`]): the first item that runs it with no params, or else the first item,
|
||||
/// whose params all its items give.
|
||||
fn menu_bar_path(id: &str) -> Option<&'static str> {
|
||||
pub(crate) fn menu_bar_path(id: &str) -> Option<&'static str> {
|
||||
let (_, params) = command_doc(id)?;
|
||||
let items = menu_bar_paths().get(id).filter(|_| a_menu_bar_item_runs(id, params))?;
|
||||
chosen_path(items)
|
||||
@@ -924,7 +924,7 @@ pub(crate) fn menu_target_now(app: &VectorcraftApp, id: &str) -> Option<Result<(
|
||||
/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed: the status
|
||||
/// line, with the engine's reason when it gives one. The app's own rules ([`menus::enabled`]) dim
|
||||
/// UI commands, and some commands the engine would run, without giving a reason.
|
||||
fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> {
|
||||
pub(crate) fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> {
|
||||
let Some(why) = vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()) else {
|
||||
return Err(format!("command `{id}` is not available right now"));
|
||||
};
|
||||
@@ -936,7 +936,7 @@ fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> {
|
||||
/// run without them (as the Variables panel's commands do), and it is a query, whose answer a key
|
||||
/// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a menu command whose params
|
||||
/// doc names a field a call must give (File › Document Setup › Units, `{units}`)?
|
||||
fn needs_a_value(key: &str) -> bool {
|
||||
pub(crate) fn needs_a_value(key: &str) -> bool {
|
||||
static KEYS: OnceLock<HashSet<&'static str>> = OnceLock::new();
|
||||
KEYS.get_or_init(|| {
|
||||
vectorcraft_engine::command_specs()
|
||||
@@ -3191,4 +3191,16 @@ mod tests {
|
||||
assert_eq!(r["shortcut"], "Cmd+Alt+Shift+F11");
|
||||
assert!(app.run("shortcuts.preset", json!({"name": null})).unwrap_err().starts_with("unknown preset"));
|
||||
}
|
||||
|
||||
/// A command that needs a value is listed in the editor once the user gives it a key, but the
|
||||
/// command search still leaves it out: a pick gives it no value.
|
||||
#[test]
|
||||
fn a_command_given_a_key_that_needs_a_value_is_no_pick() {
|
||||
let mut overrides = Overrides::default();
|
||||
crate::keymap::set_override(&mut overrides, "document.setUnits", "Cmd+Alt+Shift+F12");
|
||||
let entry = entries().iter().find(|e| e.key == "document.setUnits").cloned().expect("the editor has a row for it");
|
||||
assert!(!listed(&Overrides::default(), &entry) && listed(&overrides, &entry));
|
||||
assert!(needs_a_value("document.setUnits"));
|
||||
assert!(crate::palette::items().iter().all(|(_, id, _)| id != "document.setUnits"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,6 +291,51 @@ fn hovering_back_to_source_resumes_move_instead_of_copying() {
|
||||
assert!((bounds.x0 - 150.0).abs() < 0.001 && (bounds.y0 - 150.0).abs() < 0.001, "{bounds:?}");
|
||||
}
|
||||
|
||||
/// Verify that a drop back in the source tab lands where the button went up and copies when Alt was
|
||||
/// held then, though the pointer moves and Alt is let go later in the frame of the release.
|
||||
#[test]
|
||||
fn a_drop_back_in_the_source_uses_the_release_position_and_alt() {
|
||||
let (mut app, ctx, _, tabs) = drag_fixture();
|
||||
frame(&mut app, &ctx, 0.2, vec![Event::PointerMoved(tabs[1].center())]);
|
||||
frame(&mut app, &ctx, 0.25, vec![]);
|
||||
frame(&mut app, &ctx, 0.8, vec![]);
|
||||
frame(&mut app, &ctx, 0.9, vec![Event::PointerMoved(tabs[0].center())]);
|
||||
frame(&mut app, &ctx, 1.4, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(0));
|
||||
let xf = canvas::Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let drop = xf.to_screen(Point::new(175.0, 180.0));
|
||||
let later = xf.to_screen(Point::new(300.0, 250.0));
|
||||
let alt = egui::Modifiers::ALT;
|
||||
frame(&mut app, &ctx, 1.5, vec![Event::ModifiersChanged(alt), Event::PointerMoved(drop)]);
|
||||
let up = Event::PointerButton { pos: drop, button: PointerButton::Primary, pressed: false, modifiers: alt };
|
||||
frame(&mut app, &ctx, 1.6, vec![up, Event::PointerMoved(later), Event::ModifiersChanged(egui::Modifiers::NONE)]);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.doc.layers[0].children().map_or(0, Vec::len), 2, "Alt at the release copies the original");
|
||||
assert_eq!(st.selection.objects.len(), 1);
|
||||
let bounds = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap();
|
||||
assert!((bounds.x0 - 150.0).abs() < 0.001 && (bounds.y0 - 150.0).abs() < 0.001, "{bounds:?}");
|
||||
}
|
||||
|
||||
/// Verify that a release inside the other document's canvas drops the artwork there, though the
|
||||
/// pointer moves onto the tab strip later in the frame of the release.
|
||||
#[test]
|
||||
fn a_release_in_the_canvas_drops_though_the_pointer_then_leaves_it() {
|
||||
let (mut app, ctx, _, tabs) = drag_fixture();
|
||||
frame(&mut app, &ctx, 0.2, vec![Event::PointerMoved(tabs[1].center())]);
|
||||
frame(&mut app, &ctx, 0.25, vec![]);
|
||||
frame(&mut app, &ctx, 0.8, vec![]);
|
||||
assert_eq!(app.session.active_index(), Some(1));
|
||||
let before = app.session.active().unwrap().doc.layers[0].children().map_or(0, Vec::len);
|
||||
let drop = canvas::Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(Point::new(175.0, 180.0));
|
||||
assert!(!app.canvas_rect.unwrap().contains(tabs[0].center()));
|
||||
frame(&mut app, &ctx, 0.9, vec![Event::PointerMoved(drop)]);
|
||||
frame(&mut app, &ctx, 1.0, vec![button(drop, false), Event::PointerMoved(tabs[0].center())]);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.doc.layers[0].children().map_or(0, Vec::len), before + 1);
|
||||
let bounds = st.doc.node(st.selection.objects[0]).unwrap().geometric_bounds().unwrap();
|
||||
assert!((bounds.x0 - 150.0).abs() < 0.001 && (bounds.y0 - 150.0).abs() < 0.001, "{bounds:?}");
|
||||
}
|
||||
|
||||
/// Back in the source tab, the move resumes even when coming to the front measured the source's
|
||||
/// type again in its own composite fonts, which replaces the document without editing it.
|
||||
#[test]
|
||||
|
||||
@@ -756,21 +756,61 @@ fn the_place_dialog_links_a_pdf_page_and_embeds_it_with_link_off() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_place_dialog_does_not_offer_a_postscript_ai_as_a_locked_object() {
|
||||
fn the_place_dialog_offers_a_postscript_ai_and_an_eps_file_as_a_locked_object() {
|
||||
let mut app = app();
|
||||
let ps = b"%!PS-Adobe-3.0\n%%BoundingBox: 0 0 100 100\n%%EndComments\n1 0 0 setrgbcolor 10 10 50 50 rectfill\nshowpage\n%%EOF\n";
|
||||
let dir = Folder::new("ui-place-postscript");
|
||||
let path = dir.file("legacy.ai", ps);
|
||||
// file.place embeds a .ai saved without PDF compatibility, even with Link on.
|
||||
let r = app.session.execute("file.place", &json!({"path": path, "link": true})).unwrap();
|
||||
assert_eq!(r["linked"], json!(false), "{r}");
|
||||
let st = app.session.active().unwrap();
|
||||
assert!(!matches!(st.doc.node(st.selection.objects[0]).unwrap().kind, NodeKind::PlacedDocument(_)));
|
||||
// So Link's tooltip does not promise one locked object for it.
|
||||
for name in ["legacy.ai", "legacy.eps", "legacy.ps"] {
|
||||
let path = dir.file(name, ps);
|
||||
// With Link, file.place places a .ai saved without PDF compatibility, an EPS file and a
|
||||
// PostScript file as one locked placed document.
|
||||
let r = app.session.execute("file.place", &json!({"path": path, "link": true})).unwrap();
|
||||
assert_eq!(r["linked"], json!(true), "{name}: {r}");
|
||||
let st = app.session.active().unwrap();
|
||||
assert!(matches!(st.doc.node(st.selection.objects[0]).unwrap().kind, NodeKind::PlacedDocument(_)), "{name}");
|
||||
// So Link's tooltip promises one locked object for it.
|
||||
place_picked(&mut app, &path);
|
||||
let d = app.ui.dialog.as_ref().expect("the Place dialog");
|
||||
assert!(d.bool("__documents") && !d.bool("__others"), "{name}: {:?}", d.fields);
|
||||
assert!(crate::dialogs::place::link_tip(d).contains("locked object"), "{name}");
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
// Where the platform reads part of a file, only the file's start is read to tell.
|
||||
let asked = std::rc::Rc::new(std::cell::Cell::new(0));
|
||||
let seen = asked.clone();
|
||||
app.services.read_head = Some(Box::new(move |p: &str, max: usize| {
|
||||
seen.set(max);
|
||||
std::fs::read(p).map(|b| b[..b.len().min(max)].to_vec()).map_err(|e| e.to_string())
|
||||
}));
|
||||
place_picked(&mut app, &dir.file("headed.eps", ps));
|
||||
assert!(app.ui.dialog.as_ref().expect("the Place dialog").bool("__documents"));
|
||||
assert_eq!(asked.get(), vectorcraft_engine::cmd::place::DCS_HEAD_BYTES + 1);
|
||||
app.ui.dialog = None;
|
||||
// A DCS file is placed as a linked image, from its start alone too: past the start the
|
||||
// PostScript goes on longer than what is read.
|
||||
let mut dcs = b"%!PS-Adobe-2.0 EPSF-1.2\n%%BoundingBox: 0 0 20 10\n%%CyanPlate: pic.C\n%%EndComments\n".to_vec();
|
||||
dcs.resize(vectorcraft_engine::cmd::place::DCS_HEAD_BYTES + 100, b'\n');
|
||||
// The same PostScript behind a binary EPS header (no preview).
|
||||
let mut binary = vec![0xC5, 0xD0, 0xD3, 0xC6];
|
||||
binary.extend(30u32.to_le_bytes());
|
||||
binary.extend((dcs.len() as u32).to_le_bytes());
|
||||
binary.resize(30, 0);
|
||||
binary.extend(&dcs);
|
||||
let files = [("plates.eps", &dcs, true), ("plates.ai", &dcs, true), ("binary.eps", &binary, true), ("binary.eps", &binary, false)];
|
||||
for (name, bytes, head) in files {
|
||||
if !head {
|
||||
app.services.read_head = None;
|
||||
}
|
||||
place_picked(&mut app, &dir.file(name, bytes));
|
||||
let d = app.ui.dialog.as_ref().expect("the Place dialog");
|
||||
assert!(!d.bool("__documents") && d.bool("__others"), "{name}, head {head}: {:?}", d.fields);
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
// A file named .eps that isn't PostScript gets the tooltip for other files.
|
||||
let path = dir.file("notes.eps", b"not PostScript");
|
||||
place_picked(&mut app, &path);
|
||||
let d = app.ui.dialog.as_ref().expect("the Place dialog");
|
||||
assert!(!d.bool("__documents") && d.bool("__others"), "{:?}", d.fields);
|
||||
assert!(!crate::dialogs::place::link_tip(d).contains("locked object"));
|
||||
}
|
||||
|
||||
/// Tool key `key` as the Control bar's Apply (Enter) and Cancel (Escape) send it.
|
||||
|
||||
@@ -205,11 +205,13 @@ fn show_in_folder_needs_a_saved_document_and_a_file_manager() {
|
||||
assert_eq!(*shown.borrow(), ["/art/a.vectorcraft"]);
|
||||
}
|
||||
|
||||
/// The palette lists neither the old alias nor `file.documentColorMode`, which a pick can't run
|
||||
/// without a mode; the CMYK and RGB menu items run the one command.
|
||||
#[test]
|
||||
fn the_palette_lists_document_color_mode_once() {
|
||||
fn document_color_mode_is_one_command() {
|
||||
let items = palette::items();
|
||||
let ids: Vec<&str> = items.iter().map(|(_, id, _)| id.as_str()).filter(|id| id.to_ascii_lowercase().contains("documentcolormode")).collect();
|
||||
assert_eq!(ids, ["file.documentColorMode"]);
|
||||
assert!(ids.is_empty(), "{ids:?}");
|
||||
let mut app = app();
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
let entries = menus::menu_entries(&app);
|
||||
|
||||
@@ -327,7 +327,7 @@ mod tests {
|
||||
let has = |s: &str| texts.iter().any(|t| t == s);
|
||||
assert_eq!(has("Discord"), width > 1000.0, "{width}: {texts:?}");
|
||||
// Search is an icon only (as in PhotoCraft): its label lives in the tooltip.
|
||||
assert!(!has("Search commands and tools"), "{width}: {texts:?}");
|
||||
assert!(!has("Search commands, tools, panels and effects"), "{width}: {texts:?}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +105,13 @@ pub(crate) fn id_with(parent: egui::Id, salt: impl std::hash::Hash) -> egui::Id
|
||||
parent.with(HashOnly(salt))
|
||||
}
|
||||
|
||||
/// Gives `resp` the screen-reader role of a list item named `label`, with `selected` as its
|
||||
/// selected state. [`egui::WidgetInfo::selected`] would set the toggled state instead.
|
||||
pub(crate) fn list_item_info(resp: &Response, selected: bool, label: impl Fn() -> String) {
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, label()));
|
||||
resp.ctx.accesskit_node_builder(resp.id, |node| node.set_selected(selected));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod accessibility_tests {
|
||||
use egui::accesskit::{Node, Role, Toggled};
|
||||
@@ -219,6 +226,26 @@ pub(crate) mod accessibility_tests {
|
||||
on("Saved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_items_report_selection_and_section_headers_report_expansion() {
|
||||
let tree = tree(|ui| {
|
||||
for (name, on) in [("Artboard 1", true), ("Artboard 2", false)] {
|
||||
let resp = ui.allocate_response(vec2(120.0, 20.0), Sense::click());
|
||||
list_item_info(&resp, on, || name.to_string());
|
||||
}
|
||||
section_toggle(ui, "Open Section", true);
|
||||
section_toggle(ui, "Closed Section", false);
|
||||
});
|
||||
let state = |label| {
|
||||
let n = named(&tree, label);
|
||||
(n.role(), n.toggled(), n.is_selected(), n.is_expanded())
|
||||
};
|
||||
assert_eq!(state("Artboard 1"), (Role::ListItem, None, Some(true), None));
|
||||
assert_eq!(state("Artboard 2"), (Role::ListItem, None, Some(false), None));
|
||||
assert_eq!(state("Open Section"), (Role::DisclosureTriangle, None, None, Some(true)));
|
||||
assert_eq!(state("Closed Section"), (Role::DisclosureTriangle, None, None, Some(false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkboxes_and_radio_buttons_are_named_and_checked() {
|
||||
let tree = tree(|ui| {
|
||||
|
||||
@@ -36,7 +36,8 @@ pub fn section_toggle_name(ui: &mut Ui, text: &str, open: bool) -> Response {
|
||||
let chevron = Rect::from_center_size(pos2(rect.left() + 8.0, rect.center().y), vec2(12.0, 12.0));
|
||||
icons::paint(ui, if open { "chevron-down" } else { "chevron-right" }, chevron, if resp.hovered() { t.text_strong } else { t.icon });
|
||||
ui.painter().text(pos2(rect.left() + 18.0, rect.center().y), egui::Align2::LEFT_CENTER, text, theme::semibold(12.5), t.text);
|
||||
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::DisclosureTriangle, true, open, text));
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, text));
|
||||
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_expanded(open));
|
||||
resp.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
}
|
||||
|
||||
|
||||
+30
-1
@@ -497,7 +497,36 @@ to the source tab resumes a move (Alt copies). Escape or release outside the can
|
||||
Changing the source revision or unexpectedly changing/closing the destination cancels a stale
|
||||
transfer; focus loss, touch cancellation and multitouch cancel too. Moving tabs under a stationary
|
||||
pointer does not activate further tabs until the pointer moves. The close icon does not activate a tab during a drag. Overflow-menu hover activation and
|
||||
cross-window dragging remain outside this change.
|
||||
dragging into a floating document window that is an OS window of its own remain outside this change.
|
||||
|
||||
Under Window › Arrange › Tile, a Selection move released over another document's pane copies the
|
||||
artwork into that document through `edit.dropSelection`, with no tab hover first. The pane becomes
|
||||
the current window, the grab point lands under the pointer in that pane's own zoom and rotation, and
|
||||
the source move is rolled back, including when the pointer enters the pane and the button is released
|
||||
in the same frame. A release over another view of the source document (Window › New Window) moves the
|
||||
artwork there with `object.move`, and Alt copies it. While the artwork is held over a pane, the cursor
|
||||
shows a copy or a move. A release over a pane's rulers or scroll bars, or after Escape, changes
|
||||
neither document. A press in another pane with no artwork carried still only makes its document
|
||||
current. Page 14 of [the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf)
|
||||
describes documents arranged side by side, with items dragged from one document into another.
|
||||
Evidence: the `canvas::panes` tests drive real pointer frames from the current pane into another
|
||||
document's pane, back the other way, into another view, through a tab into a third document's pane,
|
||||
and off a pane's art area.
|
||||
|
||||
The same release works for documents in floating windows (Window › Arrange › Float in Window) where
|
||||
those windows are drawn inside the main window: on the web, on Wayland and with a control channel
|
||||
attached. A Selection move released over the art area of another document's floating window copies
|
||||
the artwork into that document, and one released over the pane the main window draws while the
|
||||
current document floats copies it into the main window's document. A floating window that shows
|
||||
another view of the source document takes a move, and Alt copies. The release is taken at the start
|
||||
of the frame, before any canvas sees it, so a release in the first frame over a window still drops the
|
||||
artwork. A release on a window's title bar, rulers or scroll bars, or after Escape, changes neither
|
||||
document. A floating window that is an OS window of its own, the default on Windows, macOS and X11,
|
||||
does not take the artwork: its pointer positions are in that window's points, not the main window's.
|
||||
Evidence: the `doc_windows` tests drive real pointer frames from the main window's canvas into a
|
||||
floating window (rotated and zoomed, and in the frame the pointer arrives), from a floating window
|
||||
into the main window's pane, into a floating view of the same document, and onto a title bar and
|
||||
after Escape, and check that no OS window's pane is noted.
|
||||
The cited regressions assert the internal clipboard; they do not exercise the native
|
||||
system-clipboard adapter. Tab activation resets the Selection tool through
|
||||
`Session::set_active`; gesture regressions verify it is idle after switching, dropping
|
||||
|
||||
+8
-4
@@ -488,8 +488,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
Until a choice is made (`default`), the panels follow General › Transform Pattern Tiles as before, and the menu
|
||||
checks Transform Both while it is on and Transform Object Only while it is off; a choice overrides it.
|
||||
Estimate unchanged.
|
||||
- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Arcs, spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged.
|
||||
- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Arcs, spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (<https://helpx.adobe.com/illustrator/using/drawing-simple-lines-shapes.html>). Estimate unchanged.
|
||||
- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged.
|
||||
- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (<https://helpx.adobe.com/illustrator/using/drawing-simple-lines-shapes.html>). Estimate unchanged.
|
||||
- **Done (2026-10-17):** Background Export shows its progress in a dialog with Cancel and Continue in Background (#2564), on the shared cancel token (#2546); a cancelled export writes no file. Save As, Export for Screens and Export Selection don't show it yet. Estimate unchanged. **2026-11-06:** opening a file that takes longer than 0.4 s shows a progress window too, with a moving bar, Cancel and Continue in Background (part of #5930); Save and Place still show only the status bar's spinner. Estimate unchanged.
|
||||
- **Done:** quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the controls with Threshold and Advanced (Paths, Corners, Noise), as the public documentation describes (<https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html>). Other context-specific Properties gaps remain.
|
||||
- **Done (2026-10-31, #394):** Units › East Asian Type is read, and Q and Ha are units. 1 Q and 1 Ha are each a
|
||||
@@ -875,8 +875,12 @@ sampling coexistence. Scores and estimates unchanged. See [development.md](devel
|
||||
Selection drags activate another visible document tab after 400 ms, then copy editable artwork
|
||||
on canvas release with the original grab point. Source and clipboard preservation, resource
|
||||
rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/Redo have regression
|
||||
coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain
|
||||
separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22).
|
||||
coverage (`tests_document_drag`, `tests_clipboard`). Under Window › Arrange › Tile, a release over
|
||||
another document's pane copies the artwork into that document as well, and a release over another
|
||||
view of the source document moves it (`canvas::panes` tests). A release over a floating document
|
||||
window drawn inside the main window, or over the main window's pane while the current document
|
||||
floats, does the same (`doc_windows` tests); a floating window that is an OS window of its own does
|
||||
not take the artwork yet. Overflow-menu drag remains separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22).
|
||||
|
||||
## Pathfinder › Trap (2026-10-23)
|
||||
|
||||
|
||||
+34
-11
@@ -761,6 +761,20 @@ dragged, headless `press_key` `c` chooses the tool bound to C (headless has no b
|
||||
from the typed letter, so with nothing being dragged `c` and `f` do not run their shortcuts there. Use `select_tool` or
|
||||
`invoke_menu` instead.
|
||||
|
||||
With General › Constrain Angle (`prefs.set {key: "constrainAngle"}`) other than 0° or a whole turn, the Arc tool's drag
|
||||
and its click dialog draw the arc along the turned x and y axes: the drag sends `shape.arc` with `lengthX` and `lengthY`
|
||||
measured along those axes, the reference point `x`, `y` at the drag's corner or the click, and a `rotation` of the
|
||||
Constrain Angle's negative. `shape.arc` takes `rotation` in degrees clockwise on the page, about `x1`, `y1` or about the
|
||||
reference point `x`, `y`; the arc's bounding box turns with it. Without `rotation`, or at 0° or a whole turn, the arc is
|
||||
upright, and a `rotation` that is not a number is an error that adds nothing.
|
||||
|
||||
`shape.arc` checks `reference`, `baseAlong` and `slope` in both of its forms. `reference` is a whole number from 0 to 8
|
||||
(`4.0` is 4) and is 0 when left out; `baseAlong` is `x` or `y` in either case and is `x` when left out; `slope` is
|
||||
from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100 with `x1`, `y1`, `x2`, `y2`. A
|
||||
`reference` or `baseAlong` given as anything else, null included, is an error naming the key (for example
|
||||
`` `baseAlong` must be one of x, y ``), as is a `slope` outside its range; the arc is not drawn and no undo step is
|
||||
added.
|
||||
|
||||
While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the
|
||||
spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows
|
||||
the pointer. With `mods.alt` alone, dragging outward adds whole winds of four segments and dragging inward removes
|
||||
@@ -2138,7 +2152,8 @@ and `rotation` in `shape.polygon`; `radius2`, `points` and `rotation` in `shape.
|
||||
`brightness`, `growth`, `fuzziness`, `rays`, `longest`, `rayFuzziness`, `rotation`, `rings`, `largest`, `x2`, `y2`, `direction`, `pathLength`, `seed` and
|
||||
`ringSeed` in `shape.flare` (`seed` must also be a whole number of at least 0, and `ringSeed` a whole number from
|
||||
0 to 2^53 - 1); `decay` and `segments` in `shape.spiral`; `rows` and `columns` in `shape.rectangularGrid`; `concentric`
|
||||
and `radial` in `shape.polarGrid`; `size` and the `width`, `height` and `fitMinPercent` of `area` in `text.create`;
|
||||
and `radial` in `shape.polarGrid` (the four grid counts must also be whole numbers of at least 0, so `2.5` rows gets
|
||||
`` `rows` must be a whole number of at least 0, not 2.5 ``); `size` and the `width`, `height` and `fitMinPercent` of `area` in `text.create`;
|
||||
`size` and `fitMinPercent` in `text.createInPath`; `start`, `end`, `size`, `tracking`,
|
||||
`baselineShift`, `hScale`, `vScale`, `rotation` and `strokeWidth` in `text.setRangeStyle`; `strokeWidth` in `text.setStyle`; `start` and `end` in
|
||||
`text.editRange` and `text.getRange`; `at` in `text.startList`; `start`, `hScale`, `vScale` and `rotation` in `text.touchType`; `start` in
|
||||
@@ -4113,8 +4128,12 @@ already walks Image Trace. Short agent entry points:
|
||||
With `paintStrokes` alone on, a click runs `livePaint.strokeEdge` on the edge within 4 screen pixels of the pointer,
|
||||
or nothing when none is in reach, and Shift-click runs `livePaint.fill`. With both on, a click runs
|
||||
`livePaint.strokeEdge` when an edge is within 4 screen pixels of the pointer and `livePaint.fill` otherwise, and
|
||||
Shift-click runs `livePaint.fill`. With both off, a click runs nothing. With `highlight` off, the face or edge under
|
||||
the pointer is not outlined.
|
||||
Shift-click runs `livePaint.fill`. With both off, a click runs nothing. A drag from a press that runs
|
||||
`livePaint.strokeEdge` previews it with the drag's path in `points` (and `continuation` past 4096 points), so the edge
|
||||
and every edge of the same group that the drag crosses or comes within 0.0001 pt of take the stroke, hidden edges and
|
||||
other groups' edges skipped; the release keeps it as one undo step and Escape before the release cancels it. A drag
|
||||
from a press that fills a face fills only faces. With `highlight` off, the face or edge under the pointer is not
|
||||
outlined.
|
||||
A double-click runs the command a click there runs with `scope: "connected"`, and a triple-click with
|
||||
`scope: "samePaint"`; Alt held runs nothing, and so does Cmd/Ctrl (`mods.cmd`), whose presses go to the selection
|
||||
tool Cmd lends. With Space held (`mods.space`, the view tools), a press, a
|
||||
@@ -4146,9 +4165,10 @@ already walks Image Trace. Short agent entry points:
|
||||
defaults to the face's fill or the stroke paint the edge draws with. `livePaint.strokeEdge {scope: "connected", through}`
|
||||
takes `through`, at most 4096 ids of the group's edges, each given once, that the join counts as drawing with `match`
|
||||
whatever they draw with now; a hidden edge among them is still skipped. The tool passes each other edge of the group
|
||||
that either of the double-click's two clicks painted and that drew with `match` before that click. `through` with
|
||||
that either of the double-click's two clicks painted, by its press or its drag, and that drew with `match` before
|
||||
that click. `through` with
|
||||
another scope, or one that is not an array of the group's edge ids or names an edge twice, is an error and changes
|
||||
nothing. `livePaint.fill` refuses a `scope` other than `"one"` with `points`. Both replies add `count`, the number of
|
||||
nothing. `livePaint.fill` and `livePaint.strokeEdge` refuse a `scope` other than `"one"` with `points`. Both replies add `count`, the number of
|
||||
faces or edges the click reaches, including those that already had the paint.
|
||||
With the Live Paint Bucket selected and no drag in progress, Left and Right without Shift, Alt or Cmd/Ctrl (which
|
||||
keep their shortcuts) run `paint.setFill {swatch, ids: []}` (or
|
||||
@@ -4156,7 +4176,7 @@ already walks Image Trace. Short agent entry points:
|
||||
Swatches panel, wrapping around at the ends; from a color that is no swatch, Right picks the first swatch and Left
|
||||
the last, and with no color swatch the tool does not take the keys. The selected art keeps its paint. With
|
||||
`cursorSwatchPreview` on, the active paint shows as a ringed chip above the pointer between the swatches before and
|
||||
after it, except during a fill drag or with Alt held; a solid color that is no swatch shows alone, and a paint that is not a solid color shows no chip. Left and
|
||||
after it, except during a fill or stroke drag or with Alt held; a solid color that is no swatch shows alone, and a paint that is not a solid color shows no chip. Left and
|
||||
Right step the swatches with `cursorSwatchPreview` off too.
|
||||
`livePaint.merge` keeps the bottom Live Paint group's id, name, lock, visibility, transparency, appearance, opacity
|
||||
mask and graphic style link. With a Live Paint group among the objects, `livePaint.make` adds the others to it as
|
||||
@@ -4166,7 +4186,8 @@ already walks Image Trace. Short agent entry points:
|
||||
objects; otherwise it returns an error and does not merge the objects.
|
||||
A Live Paint command that changes nothing records no undo step, keeps the redo steps, leaves a saved document saved
|
||||
and replies as usual: `livePaint.fill` (a click, or a Bucket drag) when every face it reaches already has one fill, shown,
|
||||
fully opaque, blending normally and with the paint (or no fill, for none), `livePaint.strokeEdge` when every edge it
|
||||
fully opaque, blending normally and with the paint (or no fill, for none), `livePaint.strokeEdge` (a click, or a
|
||||
Bucket drag from an edge) when every edge it
|
||||
reaches already has one such stroke with the paint and the width (at any width for none, or no stroke),
|
||||
`livePaint.gapOptions` (and the Gap Options
|
||||
dialog's OK) when every group already has the options and `closeGaps` finds no gap, and `livePaint.make` or
|
||||
@@ -7452,7 +7473,9 @@ artboard `page` (or, with `crop: "bounding"`, its art's bounds), linked to the f
|
||||
(see Linked images), and vectors in every output; with `link: false` (or from `dataBase64`) it is an editable copy
|
||||
of its art, as one clipped group. A PDF, `.ai` or `.ait` page read from `path` (with neither `password` nor
|
||||
`textAs: "outlines"`) is a placed document the same way, showing page `page` clipped to its `crop` box (or its
|
||||
art's bounds); with `link: false` it is placed as one clipped group. EPS and PostScript `.ai` files are embedded. `at` centres it, `rect` fits it, `replace`
|
||||
art's bounds); with `link: false` it is placed as one clipped group. An EPS file, a PostScript file or a PostScript `.ai` read from `path` is a placed document
|
||||
too, showing the art `link: false` places (clipped to its bounding box, or its art's bounds with `crop: "bounding"`);
|
||||
with `link: false` or from `dataBase64` it is one group. `at` centres it, `rect` fits it, `replace`
|
||||
swaps the selected object (keeping its place and transform), `template` puts it on a new template layer.
|
||||
A DCS file (Desktop Color Separation, version 1.0 or 2.0: an EPS file whose header names one EPS program per printing
|
||||
plate, <http://www.telegraphics.net/doc/DCS.txt>) is placed only from its `path` with link, as one linked image
|
||||
@@ -8073,13 +8096,13 @@ that includes a placed document fails and relinks nothing; placed documents are
|
||||
files are. Find in Folder… in the Linked File Not Found dialog and in the Links panel menu (`ui.findLinksInFolder`) runs
|
||||
both. The web build has no folder search.
|
||||
|
||||
Placed documents (a `.vectorcraft` file, or a PDF or `.ai` page, placed linked)
|
||||
Placed documents (a `.vectorcraft` file, a PDF or `.ai` page, or an EPS or PostScript file, placed linked)
|
||||
work the same way: the document keeps the file's bytes and a preview (JPEG or PNG, 1 px per point, at most 1024 px
|
||||
a side), and a save writes the preview (Include Linked Files: the file); output reads the file again, or uses the
|
||||
preview with a warning when it is gone or changed.
|
||||
`links.list` and `links.info` give them `document: true`, the file's `format` (`VectorCraft`, `PDF`,
|
||||
`PDF-compatible .ai`) and the artboard's or page's `pageWidth` and `pageHeight` (pt). A relinked PDF shows the same
|
||||
page and box of the new file. File › Package copies a placed PDF or `.ai` file as it is. For a `.ai` file read from
|
||||
`PDF-compatible .ai`, `EPS`, `PostScript`) and the artboard's or page's `pageWidth` and `pageHeight` (pt). A relinked
|
||||
PDF shows the same page and box of the new file. File › Package copies a placed PDF, `.ai` or EPS file as it is. For a `.ai` file read from
|
||||
its editing data, Package also copies the files its art places into the same folder. That file finds them by name,
|
||||
and Package warns when one is copied under another name: the copy then shows the file of that name, or its preview.
|
||||
Saving the file in the app updates the open documents that place it. `links.embed` (the Links panel's Break Link)
|
||||
|
||||
+6
-2
@@ -201,8 +201,12 @@ sampling coexistence. Scores and estimates unchanged. See [development.md](devel
|
||||
Selection drags activate another visible document tab after 400 ms, then copy editable artwork
|
||||
on canvas release with the original grab point. Source and clipboard preservation, resource
|
||||
rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/Redo have regression
|
||||
coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain
|
||||
separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22).
|
||||
coverage (`tests_document_drag`, `tests_clipboard`). Under Window › Arrange › Tile, a release over
|
||||
another document's pane copies the artwork into that document as well, and a release over another
|
||||
view of the source document moves it (`canvas::panes` tests). A release over a floating document
|
||||
window drawn inside the main window, or over the main window's pane while the current document
|
||||
floats, does the same (`doc_windows` tests); a floating window that is an OS window of its own does
|
||||
not take the artwork yet. Overflow-menu drag remains separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22).
|
||||
|
||||
## Revision history
|
||||
|
||||
|
||||
@@ -671,7 +671,10 @@ since 2026-10-01.
|
||||
- **PDF writes a warped image once:** with downsampling on, the pieces of an image bent by a Warp effect are resampled for the widest and the highest size any piece places the image at, so every piece paints one image XObject (a colorized image: one colorized image and its soft mask), instead of one image for each size a piece is placed at. Another placement of the same image is still resampled for its own size. Without downsampling, a colorized image and a CMYK image with a grayscale image mask on its grid are decoded and encoded once for all the sizes they are placed at (pdf `tests::compression::a_warped_image_is_written_once_for_all_its_pieces`, `tests::colorize::a_colorized_warped_image_is_written_once_for_all_its_pieces`, `export::images::tests::colorized_and_grid_masked_images_are_made_once_for_every_size_without_downsampling`). Scores and hours unchanged.
|
||||
- **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged.
|
||||
- **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted, with Scale Strokes & Effects or Transform Patterns on too, and on each copy. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. The Gradient tool still shows a fitted gradient's vector at its unturned fit. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged.
|
||||
- **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged.- **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests.
|
||||
- **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged.
|
||||
- **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (<https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests.
|
||||
- **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=226>) describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged.
|
||||
- **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged.
|
||||
- **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged.
|
||||
|
||||
- **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged.
|
||||
@@ -1326,6 +1329,11 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
The panel menu's Save Selection submenu has Save Selection…, Update Selection and Edit Selection…, enabled and run as in the Select menu, and lists the document's saved selections: choosing one selects its objects again (`select.recall`).
|
||||
Deleting rows from the Layers panel (the trash button, rows dragged onto it, the panel menu's Delete Selection, and Delete or Backspace on highlighted rows) asks "Delete this layer and its artwork?" when a layer or sublayer among them holds art, hidden, locked and nested art included, and "Delete the selected items and their artwork?" when several rows are deleted; OK deletes the rows it asked about in one undo step, and Cancel keeps them (`ui.layerDelete`). The help page's shortcut list names the Layers panel as the place where deleting asks for confirmation ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). An empty layer, a layer with only guides, and groups or objects alone are deleted without a question, and `layer.delete` itself does not ask (`panels::layers` tests `deleting_a_layer_that_holds_art_asks_first`, `delete_selection_asks_only_for_layers_with_art`).
|
||||
The Command Palette lists Window › Layers › Delete Selection once, as the Layers panel's `ui.layerDelete`, so a pick asks the same question; it does not list `layer.delete`, which scripts run without a question. New Brush…, Brush Options…, Symbol Options…, Import SVG Filter… and Convert to Text are also listed once each, as the UI command that opens the dialog or file chooser (`palette` tests `a_wrapped_engine_command_is_listed_once_as_its_ui_command`, `a_pick_of_delete_selection_asks_before_deleting_a_layer_with_art`).
|
||||
No two Command Palette results for different commands, tools or plug-ins show the same name, in English or in any language with a complete menu catalog. Results that would share a name show the panel, menu or command they belong to (Export › Continue in Background and Open › Continue in Background, View › Rulers › Show Rulers and View › Perspective Grid › Show Rulers, Layers › Panel Options… and Navigator › Panel Options…, Tools › Knife and Path › Knife); results that still share one show their id after it (Ellipse (shape.ellipse) and Ellipse (addon.shapes.ellipse)), as two filter plug-ins with one name do. A query still finds a result by its name without the added path. Batch…, Flattener Preview and the four Other Library… commands are listed once each as their UI command, and Place… and Print… once each (`palette` tests `different_results_show_different_names`, `results_that_share_a_name_show_where_they_belong`, `filter_plugins_with_one_name_show_their_ids`, `each_id_is_one_result`, `a_pick_of_a_renamed_result_runs_its_own_command`).
|
||||
The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. A query of "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`).
|
||||
The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`).
|
||||
A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`).
|
||||
The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`).
|
||||
`object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do.
|
||||
Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`).
|
||||
Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list.
|
||||
@@ -1419,6 +1427,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). Zig Zag spaces its ridges evenly along each segment, so lines and curves get a regular wave in Corner and Smooth (#1558). Warp › Arc (the effect and Envelope › Make with Warp) bends in the object's real proportions: a circular arc with concentric edges and no fold-over at 100%, so Arc on art that isn't square draws differently from before (#1581, fixes #1578). `effect.apply` and `effect.setParams` give an error for a misspelt or wrongly typed effect parameter instead of running the effect with its default (#1623, #1592). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). On the canvas, in Expand Appearance and in exports, Effect → Pathfinder uses the glyph outlines of type in the group, and results painted like the type keep its opacity and blend mode.
|
||||
- Cmd/Ctrl+4 (`pathfinder.repeat`) repeats the last successful Pathfinder panel operation, direct `object.pathfinder.*` command or `command.batch` step (including Actions playback) on the current selection; the panel menu names it. `action.batch`, Trap, compound-shape edits and live effects do not set history. Public references: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html).
|
||||
- Pathfinder Options ([Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the panel menu's Pathfinder Options… sets Precision (0.001–10 pt: results refit to within it, thinner pieces dropped), Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork (`object.pathfinder.options`, kept in the preferences) for every Shape Mode and Pathfinder operation; the defaults keep the earlier output (`pathops` `precision_drops_pieces_thinner_than_it`, engine `tests_pathops` Pathfinder Options tests, `panels::pathfinder` dialog test).
|
||||
- Pathfinder on clip groups (#8093): a clip group's members take part in the Shape Modes and Pathfinder buttons (`object.pathfinder.*`) only where its clipping path shows them, so Divide cuts the visible art along the mask and the hidden art goes; nested clip groups cut by each mask, a member the mask hides gives no piece, a cutting line's hidden part cuts nothing, a selected object the masks hide altogether counts as an empty shape where that changes the result (Intersect, Minus Front, Minus Back, Crop), and the clipping path adds no piece of its own (the public documentation doesn't say what Pathfinder does with masked art; our choice, asked on the issue). A cutting line is clipped by sampling, so a part of the mask much narrower than the mask itself can be missed. Make Compound Shape, Trap and the Pathfinder effects still take the members whole. Tests: `crates/engine/src/tests/pathfinder_clip.rs`.
|
||||
- Pathfinder › Trap ([trapping](https://helpx.adobe.com/illustrator/using/trapping.html), [Pathfinder panel](https://helpx.adobe.com/illustrator/using/pathfinder-panel-overview.html)): the Pathfinder panel menu's Trap… (`object.pathfinder.trap`) and Effect › Pathfinder › Trap… (`pathfinder.trap`, live on groups) add, where two objects' visible areas of different solid colours meet, a strip of the darker one's area along the edge, filled with the lighter colour at the Tint Reduction percentage and set to overprint (Reverse Traps: the darker colour spreads instead, but not a rich black); Thickness 0.01–5000 pt across vertical edges, Height/Width scales it across horizontal ones, Traps with Process Color paints a swatch colour's trap with its CMYK equivalent; the effect also has Precision and Remove Redundant Points. The panel's Trap is one undo step and groups the traps above the topmost selected object, selected; with no adjoining edges of different colours it says so and changes nothing. Tests: `crates/pathops/src/trap.rs`, `crates/effects/src/trap.rs`, `group::tests::trap_effect_adds_an_overprinting_strip_above_the_members`, `crates/engine/src/tests/trap.rs`, `panels::pathfinder::tests::trap_opens_its_options_and_ok_traps_the_selection`.
|
||||
- Compound shapes ([Create compound shapes with Pathfinder](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-shapes-with-pathfinder.html), [Pathfinder panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/pathfinder-panel-overview.html)): the Pathfinder panel menu's Make Compound Shape (every member in Add) and Alt-clicking a Shape Mode (every member in that mode) make the two or more selected paths, compound paths, groups, compound shapes or type a live compound shape (`object.compoundShape.make`): a group whose members each keep a shape mode and stay editable, drawn, printed and exported (SVG, PDF and the rest through the baked document) as the area the modes make from the backmost member up, open paths closed, painted with its own appearance, taken from the topmost member not subtracting. With members selected (Direct Selection, Layers panel, isolation mode) a Shape Mode button sets theirs (`object.compoundShape.setMode`) and is lit for the mode they share; paint given to a member goes to the compound shape. Release Compound Shape gives the members back as they were (`object.compoundShape.release`); Expand Compound Shape and the panel's Expand button turn it into the path or compound path of its area (`object.compoundShape.expand`). Shape Modes and Pathfinders take a compound shape as its area. Saved files keep it (`compound_shape`, `shape_mode`; an unknown mode reads as Add). Blends, envelopes and objects with a warp or another geometry effect are members as they draw (a blend's steps, an envelope's distorted art, the warped outline), and the area follows an edit of the blend, envelope or warp; Release gives them back as they were. Tests: `crates/engine/src/tests/compound_shape.rs`, `group::tests::compound_shapes_draw_the_area_their_shape_modes_make`, `group::tests::nested_compound_shapes_take_part_as_their_area`, `panels::pathfinder::tests::compound_shape_items_follow_the_selection`, the `CompoundShape` op of the property-test strategies. Not yet: the question marks on mixed member modes, hit-testing by the area (a click hits the members).
|
||||
- Effect › Path › Outline Object has no options. Type that carries it is drawn, exported (PDF and SVG as paths, with no font) and expanded as its glyph outlines while it stays editable, and the effects after it reshape those outlines. Paths and images draw as before. With Use Preview Bounds on, type is measured by its glyph outlines. Public reference: [Summary of effects](https://web.archive.org/web/20210901011839/https://helpx.adobe.com/illustrator/using/summary-effects.html) (archived copy).
|
||||
@@ -1985,7 +1994,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md).
|
||||
- Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it.
|
||||
- Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`).
|
||||
- Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. EPS and PostScript `.ai` files are still embedded (`crates/engine/src/tests/placed_document.rs`).
|
||||
- Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. An EPS file, a PostScript file or a PostScript `.ai` placed from a file with Link is a placed document the same way, showing the art placing it without Link gives (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); Links lists it as `EPS` or `PostScript`, and a save, Package, Break Link and Object › Expand treat it as they treat a placed PDF page. Placing one keeps the file linked rather than embedding it, as [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/eps-and-dcs-file-import-in-illustrator.html) describes; a DCS file stays a linked image (`crates/engine/src/tests/placed_document.rs`, `crates/engine/src/tests/package.rs`).
|
||||
- The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`).
|
||||
- File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`).
|
||||
- The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`).
|
||||
@@ -2289,8 +2298,12 @@ sampling coexistence. Scores and estimates unchanged. See [development.md](devel
|
||||
Selection drags activate another visible document tab after 400 ms, then copy editable artwork
|
||||
on canvas release with the original grab point. Source and clipboard preservation, resource
|
||||
rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/Redo have regression
|
||||
coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain
|
||||
separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22).
|
||||
coverage (`tests_document_drag`, `tests_clipboard`). Under Window › Arrange › Tile, a release over
|
||||
another document's pane copies the artwork into that document as well, and a release over another
|
||||
view of the source document moves it (`canvas::panes` tests). A release over a floating document
|
||||
window drawn inside the main window, or over the main window's pane while the current document
|
||||
floats, does the same (`doc_windows` tests); a floating window that is an OS window of its own does
|
||||
not take the artwork yet. Overflow-menu drag remains separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22).
|
||||
|
||||
## Gradient dither (2026-10-22)
|
||||
|
||||
@@ -2647,6 +2660,21 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s
|
||||
`live_paint_bucket_drag_rejects_invalid_points_atomically` covers invalid command input.
|
||||
Behaviour source: [Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html).
|
||||
Scores and estimates unchanged.
|
||||
- **Live Paint Bucket stroke drag:** starting on an edge (Shift with Paint Fills alone, or a
|
||||
plain press with Paint Strokes on), a drag paints with the current stroke that edge and every
|
||||
visible edge of the same group it crosses or touches, including edges between pointer events;
|
||||
edges of other groups and hidden edges keep their strokes. The gesture is one Undo step, Escape
|
||||
cancels it, and a drag over edges that already have the stroke records no undo step. A drag
|
||||
that starts on a face still fills only faces. `livePaint.strokeEdge` takes the drag's `points`
|
||||
and `continuation` as `livePaint.fill` does. Regression evidence:
|
||||
`live_paint_bucket_drag_strokes_crossed_edges_as_one_undo`,
|
||||
`live_paint_bucket_stroke_drag_no_op_keeps_history`,
|
||||
`live_paint_stroke_drag_rejects_invalid_points_atomically` and the tool's
|
||||
`bucket_edge_drag_previews_points_and_commits_once`,
|
||||
`visible_edges_along_finds_crossed_and_near_edges` and
|
||||
`bucket_edge_double_click_joins_through_an_edge_the_first_drag_stroked`. The help page describes dragging across
|
||||
edges to stroke several at once: [Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html);
|
||||
how a drag finds the edges it crosses is VectorCraft's own rule. Scores and estimates unchanged.
|
||||
- **Live Paint Bucket cursors:** over a face a click fills (of a Live Paint group, or a region of
|
||||
the selected paths) the cursor is a filled paint bucket, over an edge it paints it is a brush,
|
||||
and where a click paints nothing it is an empty bucket. It follows Paint Fills, Paint Strokes
|
||||
|
||||
+8
-4
@@ -385,7 +385,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
|
||||
| Interaction | Status | Evidence |
|
||||
|---|---|---|
|
||||
| Ordinary Save refused by filesystem permissions/read-only storage offers Save As | focused UI regressions passed; native acceptance pending | #6146; `io::tests_read_only_save`; same name/format suggested; unchanged format keeps options, changed format opens its Save options; Documents folder, UID-bound continuation; cancellation and automation isolation |
|
||||
| Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; overflow and cross-window drag remain separate |
|
||||
| Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; a release over another document's tiled pane copies it there too (`canvas::panes` tests), and so does a release over a floating window drawn inside the main window (`doc_windows` tests); overflow-menu drag and floating OS windows remain separate |
|
||||
| A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` |
|
||||
| A middle-click on a document tab or its × closes it as the × does; closing a modified document's last view asks to save first (VectorCraft addition, as in PhotoCraft) | done | #6506; `chrome::tests::a_middle_click_on_a_tab_closes_it_as_the_close_box_does`; not scored |
|
||||
| Panels hidden by Tab or Shift+Tab show for a while when the pointer rests on the left or right edge of the window, over the canvas, and hide again when it moves away; Tab shows them for good | done | Part of #5661; `window.panels.peek` ([Workspace basics](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html), "Hide or show all panels"); VectorCraft's own choices: the 6 pt band and the 0.3 s delays, only the docked panels on that side show (floating panels, Tools and the Control bar stay hidden), and nothing shows in Presentation Mode; `panel_docking::tests::resting_on_the_right_edge_shows_the_hidden_panels_over_the_canvas_until_the_pointer_leaves` and the tests after it |
|
||||
@@ -470,7 +470,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
|
||||
| DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) |
|
||||
| macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet |
|
||||
| Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) |
|
||||
| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); arcs, spirals, flares and Pen paths are not turned |
|
||||
| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rotate-objects-by-specific-angles.html>); spirals, flares and Pen paths are not turned |
|
||||
| Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 |
|
||||
| Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines |
|
||||
| Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` |
|
||||
@@ -543,8 +543,12 @@ sampling coexistence. Scores and estimates unchanged. See [development.md](devel
|
||||
Selection drags activate another visible document tab after 400 ms, then copy editable artwork
|
||||
on canvas release with the original grab point. Source and clipboard preservation, resource
|
||||
rendering, swatch conflicts, cancellation, rotated/zoomed views and target Undo/Redo have regression
|
||||
coverage (`tests_document_drag`, `tests_clipboard`). Overflow-menu and cross-window drag remain
|
||||
separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22).
|
||||
coverage (`tests_document_drag`, `tests_clipboard`). Under Window › Arrange › Tile, a release over
|
||||
another document's pane copies the artwork into that document as well, and a release over another
|
||||
view of the source document moves it (`canvas::panes` tests). A release over a floating document
|
||||
window drawn inside the main window, or over the main window's pane while the current document
|
||||
floats, does the same (`doc_windows` tests); a floating window that is an OS window of its own does
|
||||
not take the artwork yet. Overflow-menu drag remains separate. Scores and hours unchanged. [Behavior and command details](development.md#drag-artwork-between-document-tabs-2026-10-22).
|
||||
|
||||
## Live Paint Bucket
|
||||
|
||||
|
||||
Reference in New Issue
Block a user