Merge main into fix/open-dwg-files

This commit is contained in:
dotCooCoo
2026-12-03 19:49:53 -08:00
35 changed files with 1075 additions and 94 deletions
+174 -1
View File
@@ -21,11 +21,12 @@ use std::sync::Arc;
use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::shapes::CornerKind;
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile};
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
use crate::node::{Node, NodeId, NodeKind};
use crate::node::{LiveShape, Node, NodeId, NodeKind};
use crate::text::TextObject;
// =====================================================================================
@@ -1032,6 +1033,9 @@ enum Shape {
/// Paths and compound paths; `members`: the subpath count of each member when both keys are
/// compound paths.
Path { pair: PathPair, rules: (FillRule, FillRule), members: Option<(Vec<usize>, Vec<usize>)> },
/// Two live rectangles: each step is a live rectangle whose size, transform and corner radii
/// lie between the keys', so their rounded corners stay circular arcs.
LiveRect(Box<(LiveRectParts, LiveRectParts)>),
/// Text, symbols and images: their transforms interpolate.
Placed,
/// Anything else: a copy of the nearer key moved and scaled into the interpolated box.
@@ -1046,6 +1050,43 @@ pub struct Lerp {
shape: Shape,
}
/// A live rectangle's size, transform, corner kinds and corner radii in document units.
#[derive(Clone, Debug)]
struct LiveRectParts {
w: f64,
h: f64,
radii: [f64; 4],
kinds: [CornerKind; 4],
xf: Affine,
}
/// The parts of `s` when it is a live rectangle, with its radii as the lengths it draws.
fn live_rect(s: &LiveShape) -> Option<LiveRectParts> {
let LiveShape::Rectangle { w, h, radii, kinds, radii_relative, xf } = s else { return None };
let base = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, *w, *h));
let resolved = crate::corners::resolve_stored_radii(&base, radii, *radii_relative);
let corners = vectorcraft_geom::corners::path_corners(&base);
let mut drawn = [0.0; 4];
for (c, r) in corners.iter().zip(vectorcraft_geom::corners::fitted_radii(&corners, &resolved)) {
if let Some(d) = drawn.get_mut(c.index) {
*d = r;
}
}
Some(LiveRectParts { w: *w, h: *h, radii: drawn, kinds: *kinds, xf: *xf })
}
/// The parts of `a` and `b` when steps between them can be live rectangles: both are live
/// rectangles with the same corner kinds, turned and reflected alike, and with no scale or shear
/// left in their transforms, so each step only moves and resizes and its corners stay circular.
fn live_rect_pair(a: &LiveShape, b: &LiveShape) -> Option<(LiveRectParts, LiveRectParts)> {
let (x, y) = (live_rect(a)?, live_rect(b)?);
let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs());
// A rotation or a reflection: unit columns at right angles.
let rigid =
|c: [f64; 6]| (c[0].hypot(c[1]) - 1.0).abs() < 1e-9 && (c[2].hypot(c[3]) - 1.0).abs() < 1e-9 && (c[0] * c[2] + c[1] * c[3]).abs() < 1e-9;
(x.kinds == y.kinds && rigid(p) && rigid(q) && p[..4].iter().zip(&q[..4]).all(|(a, b)| (a - b).abs() < 1e-9)).then_some((x, y))
}
/// `n` shrunk to a point at `c`: the counterpart of an object only one of two groups has.
fn collapsed(n: &Node, c: Point) -> Node {
let mut x = n.clone();
@@ -1083,6 +1124,12 @@ impl Lerp {
| (NodeKind::SymbolInstance { .. }, NodeKind::SymbolInstance { .. })
| (NodeKind::Image(_), NodeKind::Image(_))
| (NodeKind::PlacedDocument(_), NodeKind::PlacedDocument(_)) => Shape::Placed,
// A clicked start point asks for anchors to be paired; the path route does that.
(NodeKind::Path { live: Some(la), .. }, NodeKind::Path { live: Some(lb), .. })
if let Some(parts) = live_rect_pair(la, lb).filter(|_| starts == (None, None)) =>
{
Shape::LiveRect(Box::new(parts))
}
_ => match (node_path(a), node_path(b)) {
(Some((pa, ra, ma)), Some((pb, rb, mb))) => {
Shape::Path { pair: PathPair::new(&pa, &pb, starts), rules: (ra, rb), members: ma.zip(mb) }
@@ -1145,6 +1192,28 @@ impl Lerp {
}
}
}
Shape::LiveRect(parts) => {
let (x, y) = &**parts;
let (p, q) = (x.xf.as_coeffs(), y.xf.as_coeffs());
let live = LiveShape::Rectangle {
w: lerp_f64(x.w, y.w, t),
h: lerp_f64(x.h, y.h, t),
radii: std::array::from_fn(|i| lerp_f64(x.radii[i], y.radii[i], t)),
kinds: x.kinds,
radii_relative: false,
xf: Affine::new([p[0], p[1], p[2], p[3], lerp_f64(p[4], q[4], t), lerp_f64(p[5], q[5], t)]),
};
let rule = match &base.kind {
NodeKind::Path { rule, .. } => *rule,
_ => FillRule::default(),
};
let mut n = Node::path(NodeId(0), live.to_path(), Appearance::default());
if let NodeKind::Path { rule: r, live: l, .. } = &mut n.kind {
*r = rule;
*l = Some(Box::new(live));
}
n
}
Shape::Placed => {
let mut n = base.clone();
match (&mut n.kind, &a.kind, &b.kind) {
@@ -2321,6 +2390,110 @@ mod tests {
assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0));
}
/// A live rectangle `w` by `h` at `(x, 0)` with every corner radius `r`.
fn rounded(x: f64, w: f64, h: f64, r: f64) -> Node {
let live =
LiveShape::Rectangle { w, h, radii: [r; 4], kinds: [CornerKind::Round; 4], radii_relative: false, xf: Affine::translate((x, 0.0)) };
let mut n = Node::path(NodeId(1), live.to_path(), Appearance::default());
if let NodeKind::Path { live: l, .. } = &mut n.kind {
*l = Some(Box::new(live));
}
n
}
/// The step's live radii, after checking that every curve of its outline is a circular arc of
/// that radius about the matching corner center.
fn round_step_radii(step: &Node) -> [f64; 4] {
let Some(LiveShape::Rectangle { radii, .. }) = step.live_shape() else { panic!("a live rectangle step: {step:?}") };
let r = radii[0];
let b = step.path_data().and_then(|p| p.bounds()).unwrap_or_default();
let centers = [(b.x0 + r, b.y0 + r), (b.x1 - r, b.y0 + r), (b.x1 - r, b.y1 - r), (b.x0 + r, b.y1 - r)].map(|(x, y)| Point::new(x, y));
let path = step.path_data().map(|p| p.to_bezpath()).unwrap_or_default();
let curves = path.segments().filter(|s| matches!(s, vectorcraft_geom::kurbo::PathSeg::Cubic(_))).count();
assert_eq!(curves, if r > 1e-9 { 4 } else { 0 }, "one arc per corner: {path:?}");
for seg in path.segments() {
if let vectorcraft_geom::kurbo::PathSeg::Cubic(c) = seg {
for u in [0.0, 0.25, 0.5, 0.75, 1.0] {
let p = c.eval(u);
let d = centers.iter().map(|q| (p - *q).hypot()).fold(f64::INFINITY, f64::min);
assert!((d - r).abs() < 0.01 * r.max(1.0), "{p:?} is {d} from its corner center, not {r}");
}
}
}
*radii
}
/// Steps between live rectangles are live rectangles whose corner radii lie between the keys'.
#[test]
fn steps_between_rounded_rectangles_keep_round_corners() {
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
for r in round_step_radii(&blend.at(0.5)) {
assert!((r - 20.0).abs() < 1e-9, "{r}");
}
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 0.0), &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
for t in [0.25, 0.5, 0.75] {
for r in round_step_radii(&blend.at(t)) {
assert!((r - 30.0 * t).abs() < 1e-9, "{t}: {r}");
}
}
// A radius too large for its rectangle counts as the radius it draws.
let blend = Lerp::new(&rounded(0.0, 20.0, 20.0, 100.0), &rounded(300.0, 200.0, 200.0, 10.0), (None, None));
for r in round_step_radii(&blend.at(0.5)) {
assert!((r - 10.0).abs() < 1e-9, "{r}");
}
// Keys turned differently keep the anchor-by-anchor route.
let mut turned = rounded(300.0, 200.0, 60.0, 30.0);
turned.transform(Affine::rotate(0.5), false);
assert!(matches!(Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &turned, (None, None)).shape, Shape::Path { .. }));
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
let mut b = rounded(300.0, 100.0, 100.0, 30.0);
a.transform(Affine::rotate(30.0_f64.to_radians()), false);
b.transform(Affine::rotate(390.0_f64.to_radians()), false);
let blend = Lerp::new(&a, &b, (None, None));
assert!(matches!(&blend.shape, Shape::LiveRect(_)));
let step = blend.at(0.5);
let Some(LiveShape::Rectangle { xf, .. }) = step.live_shape() else { panic!("a live rectangle step") };
let Some(LiveShape::Rectangle { xf: first, .. }) = a.live_shape() else { panic!("a live rectangle key") };
assert_eq!(xf.as_coeffs()[..4], first.as_coeffs()[..4]);
for starts in [(Some(0), None), (None, Some(0))] {
assert!(matches!(Lerp::new(&a, &b, starts).shape, Shape::Path { .. }));
}
b.transform(Affine::scale_non_uniform(-1.0, 1.0), false);
assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. }));
for scale in [1.0, 1e-200] {
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
let mut b = rounded(300.0, 100.0, 100.0, 30.0);
a.transform(Affine::scale_non_uniform(scale, scale * 1e-12), false);
b.transform(Affine::scale_non_uniform(scale, -scale * 1e-12), false);
assert!(matches!(Lerp::new(&a, &b, (None, None)).shape, Shape::Path { .. }));
}
// Keys whose corner kinds differ keep the anchor-by-anchor route.
let mut kinds = [CornerKind::Round; 4];
kinds[2] = CornerKind::InvertedRound;
let live = LiveShape::Rectangle { w: 200.0, h: 60.0, radii: [30.0; 4], kinds, radii_relative: false, xf: Affine::translate((300.0, 0.0)) };
let mut inverted = Node::path(NodeId(1), live.to_path(), Appearance::default());
if let NodeKind::Path { live: l, .. } = &mut inverted.kind {
*l = Some(Box::new(live));
}
let blend = Lerp::new(&rounded(0.0, 100.0, 100.0, 10.0), &inverted, (None, None));
assert!(matches!(blend.shape, Shape::Path { .. }));
// The last step is the inverted key's outline.
assert_eq!(blend.at(1.0).path_data().and_then(|p| p.bounds()), inverted.path_data().and_then(|p| p.bounds()));
// Each step keeps the fill rule of the key it is nearer.
let mut a = rounded(0.0, 100.0, 100.0, 10.0);
if let NodeKind::Path { rule, .. } = &mut a.kind {
*rule = FillRule::EvenOdd;
}
let blend = Lerp::new(&a, &rounded(300.0, 200.0, 60.0, 30.0), (None, None));
assert!(matches!(&blend.shape, Shape::LiveRect(_)));
let rule = |n: &Node| match &n.kind {
NodeKind::Path { rule, .. } => *rule,
_ => panic!("a path step: {n:?}"),
};
assert_eq!(rule(&blend.at(0.25)), FillRule::EvenOdd);
assert_eq!(rule(&blend.at(0.75)), FillRule::NonZero);
}
/// A step between two distorted images has its corners between the keys' corners.
#[test]
fn steps_between_distorted_images_have_corners_between_theirs() {
+1 -1
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Blend"],
Some("Cmd+Alt+B"),
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way. A start anchor makes rectangles blend anchor by anchor.), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
has_doc,
blend_make
),
+32
View File
@@ -171,6 +171,38 @@ fn pathfinder_refuses_a_selection_without_paths_and_invalid_coordinates() {
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
}
/// Divide refuses a cutting line with more segments than its planar map takes, instead of
/// dividing the square without the line, and leaves the document and the undo history as they were.
#[test]
fn divide_refuses_cutting_lines_past_the_segment_cap() {
let mut s = session();
let base = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let cutter = NodeId(s.execute("path.create", &json!({"anchors": [{"x": -10, "y": 50}, {"x": 110, "y": 50}]})).unwrap()["id"].as_u64().unwrap());
// A zigzag across the square with one segment more than the cap, the square's four sides aside.
let segments = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS - 3;
s.edit("zigzag", |d, sel| {
let mut bp = vectorcraft_geom::BezPath::new();
bp.move_to((-10.0, 40.0));
for i in 1..=segments {
let x = -10.0 + 120.0 * i as f64 / segments as f64;
bp.line_to((x, if i % 2 == 0 { 40.0 } else { 60.0 }));
}
// Unfilled, so the zigzag stays open and cuts.
let n = d.node_mut(cutter).unwrap();
n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
n.kind = NodeKind::Path { path: PathData::from_bezpath(&bp), rule: FillRule::NonZero, live: None, clipping: false, guide: false };
sel.set([cutter, base]);
Ok(())
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let undo_len = s.doc().unwrap().history.undo.len();
let e = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
assert!(e.contains("select fewer paths"), "{e}");
assert!(s.doc().unwrap().doc == before);
assert_eq!(s.doc().unwrap().history.undo.len(), undo_len);
}
#[test]
fn exclude_makes_compound() {
let mut s = session();
+1 -1
View File
@@ -22,4 +22,4 @@ mod pixels;
pub(crate) use filters::Stream;
#[cfg(test)]
pub(crate) use ops::{measured, with_data_limit};
pub(crate) use ops::{max_data, measured, with_data_limit};
+1 -1
View File
@@ -22,7 +22,7 @@ pub(super) const fn max_data() -> usize {
/// The most bytes one filter or image reads: [`DATA_LIMIT`] of this thread.
#[cfg(test)]
pub(super) fn max_data() -> usize {
pub(crate) fn max_data() -> usize {
DATA_LIMIT.get()
}
+34 -1
View File
@@ -17,6 +17,39 @@ use super::obj::{Dict, DictRef, Key, Obj, Op, PsError, Res, Shared, ps_err};
/// Most operations one file may run, whatever its length.
const MAX_OPS: u64 = 50_000_000;
#[cfg(test)]
thread_local! {
/// The most operations one file may run on this thread, whatever its length ([`MAX_OPS`] unless
/// a test lowered it).
static OPS_LIMIT: std::cell::Cell<u64> = const { std::cell::Cell::new(MAX_OPS) };
}
/// The most operations one file may run, whatever its length: [`MAX_OPS`].
#[cfg(not(test))]
const fn max_ops() -> u64 {
MAX_OPS
}
/// The most operations one file may run, whatever its length: [`OPS_LIMIT`] of this thread.
#[cfg(test)]
pub(crate) fn max_ops() -> u64 {
OPS_LIMIT.get()
}
/// Runs `f` with [`max_ops`] set to `limit` on this thread, and restores it afterwards.
#[cfg(test)]
pub(crate) fn with_ops_limit<R>(limit: u64, f: impl FnOnce() -> R) -> R {
struct Restore(u64);
impl Drop for Restore {
fn drop(&mut self) {
OPS_LIMIT.set(self.0);
}
}
let _restore = Restore(OPS_LIMIT.replace(limit));
f()
}
/// More operations a file may run for each byte of its program: a large file that draws a lot
/// runs proportionally more, and stays bounded by its length.
const OPS_PER_BYTE: u64 = 64;
@@ -228,7 +261,7 @@ impl<'a> Interp<'a> {
resources,
depth: 0,
ops: 0,
max_ops: MAX_OPS.saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)),
max_ops: max_ops().saturating_add((src.len() as u64).saturating_mul(OPS_PER_BYTE)),
allocated: 0,
seed: 1,
saves: vec![],
+9 -4
View File
@@ -7,9 +7,9 @@ use vectorcraft_color::{Color, GradientKind, Paint};
use vectorcraft_doc::{AppearanceItem, ColorMode, Document, LineCap, LineJoin, Node, NodeKind};
use vectorcraft_geom::{Point, Rect};
use crate::import::data::measured;
use crate::import::data::{max_data, measured, with_data_limit};
use crate::import::graphics::{GState, Out, tilings_compared};
use crate::import::interp::Interp;
use crate::import::interp::{Interp, max_ops, with_ops_limit};
use crate::import::obj::Obj;
use crate::import::{Dsc, import};
use crate::{EpsOptions, Level, Preview, Raster};
@@ -1282,11 +1282,16 @@ fn read_counting_tilings(body: &str) -> (crate::Imported, u64) {
}
/// [`read_within`], with how many patterns the tiling pattern lookups compared while reading, and
/// how many decoded bytes the measuring of images' data left out decoded.
/// how many decoded bytes the measuring of images' data left out decoded. The reading thread
/// reads with this thread's data and operation limits ([`with_data_limit`], [`with_ops_limit`]).
fn read_counting(body: &str, secs: u64) -> (crate::Imported, u64, u64) {
let (tx, rx) = std::sync::mpsc::channel();
let ps = eps(body);
std::thread::spawn(move || tx.send((import(&ps), tilings_compared(), measured())).ok());
let (data, ops) = (max_data(), max_ops());
std::thread::spawn(move || {
let read = with_ops_limit(ops, || with_data_limit(data, || import(&ps)));
tx.send((read, tilings_compared(), measured())).ok()
});
let (read, compared, measured) =
rx.recv_timeout(std::time::Duration::from_secs(secs)).unwrap_or_else(|_| panic!("reading {body} did not finish"));
(read.unwrap(), compared, measured)
+13 -7
View File
@@ -742,18 +742,24 @@ fn the_data_of_an_image_too_large_to_hold_is_skipped() {
}
/// Measuring the data of an image too large to hold decompresses it, and that is charged to the
/// operation budget: a program kept in a reusable stream, whose image over 300 MB of compressed
/// zeros is left out and measured again each time a loop runs the stream from its start, runs out
/// of the budget after it measured the data in full more than once and at most five times.
/// operation budget: a program kept in a reusable stream, whose image over compressed zeros is
/// left out and measured again each time a loop runs the stream from its start, runs out of the
/// budget after it measured the data in full more than once and at most five times. The reader
/// holds 1 MiB here, the zeros decompress to 4 MiB, and the budget a file has whatever its length
/// pays for measuring them twice.
#[test]
fn measuring_data_too_large_to_hold_in_a_loop_runs_out_of_the_budget() {
const LIMIT: usize = 1 << 20;
const DECODED: usize = 4 * LIMIT;
let mut program =
b"10000 10000 8 [1 0 0 1 0 0] currentfile << /Predictor 15 /Colors 3 /Columns 10000 >> /FlateDecode filter false 3 colorimage\n".to_vec();
program.extend(crate::ps::deflate(&vec![0u8; 300 << 20]));
program.extend(crate::ps::deflate(&vec![0u8; DECODED]));
let hex: String = program.iter().map(|b| format!("{b:02x}")).collect();
let measured =
super::tests::runs_out_of_budget_measuring(&format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop"));
assert!(((300 << 20) + 1..=5 * (300 << 20)).contains(&measured), "{measured} bytes measured");
let body = format!("/P <{hex}> /ReusableStreamDecode filter def {{ P 0 setfileposition P cvx exec }} loop");
let measured = super::interp::with_ops_limit(DECODED as u64 / 8, || {
crate::import::data::with_data_limit(LIMIT, || super::tests::runs_out_of_budget_measuring(&body))
});
assert!((DECODED as u64 + 1..=5 * DECODED as u64).contains(&measured), "{measured} bytes measured");
}
/// When an image too large to read is left out, the data of its mask (`InterleaveType` 3) is
+26 -1
View File
@@ -100,8 +100,11 @@ pub struct FontDb {
colours: Mutex<GlyphColours>,
/// The installed fonts: the system font scan's faces, found by any of their names
/// ([`FontDb::catalog`]). Lookups by family name wait for its first scan, so what they find
/// never depends on what ran before them.
/// never depends on what ran before them. The bundled faces join it on the first call of
/// [`FontDb::catalog`], so its faces are read through that call.
catalog: Arc<Catalog>,
/// The bundled faces were added to [`Self::catalog`].
bundled_cataloged: std::sync::Once,
/// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces,
/// so no family name, font menu, fallback or PostScript name lookup finds them.
pub(super) file_faces: RwLock<FileFaces>,
@@ -387,6 +390,28 @@ mod race_tests {
}
}
#[cfg(all(test, feature = "bundled-fonts"))]
mod bundled_catalog_tests {
use super::*;
fn bundled_in_catalog(catalog: &Catalog) -> usize {
catalog.faces().iter().filter(|f| f.source == craft::font_catalog::Source::Bundled).count()
}
#[test]
fn the_bundled_fonts_join_the_catalog_when_it_is_first_read() {
let db = FontDb::with_font_dirs(Vec::new());
assert!(!db.read_faces().is_empty(), "the database draws with its bundled faces from the start");
assert_eq!(bundled_in_catalog(&db.catalog), 0, "making the database copies no bundled font into the catalog");
// A lookup that only the catalog answers finds a bundled face.
assert_eq!(db.by_postscript_name("SourceSans3-Bold"), Some(("Source Sans 3".to_string(), "Bold".to_string())));
let added = bundled_in_catalog(&db.catalog);
assert!(added > 0, "the first read of the catalog adds the bundled fonts");
assert!(db.catalog().families().iter().any(|f| f == "Inter"), "font pickers list a bundled family");
assert_eq!(bundled_in_catalog(db.catalog()), added, "later reads add them no second time");
}
}
#[cfg(test)]
mod image_cache_tests {
use super::*;
+1 -1
View File
@@ -31,7 +31,7 @@ impl FontDb {
/// is dated by the file the link leads to. Fonts loaded from bytes and the bundled fonts are
/// never listed. Empty on wasm, which has no installed fonts.
pub fn recently_added(&self, now: SystemTime) -> RecentlyAdded {
let faces = self.catalog.faces();
let faces = self.catalog().faces();
// Each file's creation time once for all its faces (a collection or a variable font's
// named instances share one).
let mut created: HashMap<&Path, Option<SystemTime>> = HashMap::new();
+32 -18
View File
@@ -20,6 +20,14 @@ static NEXT_ID: AtomicU64 = AtomicU64::new(0);
/// [`FontDb::global`].
static GLOBAL: std::sync::OnceLock<FontDb> = std::sync::OnceLock::new();
/// The fonts a database starts with: the bundled fonts first, then explicitly supplied craft-fonts
/// faces: Japanese (Mincho first), Arabic, Thai, then remaining faces in manifest order. Existing
/// script fallback priorities stay ahead of the additional families users can now pick by name.
fn bundled_fonts() -> impl Iterator<Item = &'static [u8]> {
let craft = crate::craft_fonts::document_fonts().into_iter().map(|f| f.bytes);
BUNDLED.iter().copied().chain(craft)
}
impl FontDb {
/// A database holding the bundled fonts, whose system font scan reads `font_dirs` (folders,
/// read with their subfolders, and font files) and nothing else.
@@ -44,15 +52,7 @@ impl FontDb {
#[cfg(not(target_arch = "wasm32"))]
catalog.set_confined_dirs(confined_font_dirs());
let mut faces = Vec::new();
// Bundled fonts first, then explicitly supplied craft-fonts faces: Japanese (Mincho
// first), Arabic, Thai, then remaining faces in manifest order. Existing script fallback
// priorities stay ahead of the additional families users can now pick by name.
let craft = crate::craft_fonts::document_fonts().into_iter().map(|f| f.bytes);
for data in BUNDLED.iter().copied().chain(craft) {
// Font pickers list the catalog's families: the fonts the app carries are in it as bundled faces.
if let Err(e) = catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) {
log::warn!("a bundled font is not in the font catalog: {e}");
}
for data in bundled_fonts() {
for (i, spec) in enumerate_faces(data) {
if let Some(f) = make_face(FontBytes::Static(data), i, spec, None) {
faces.push(Arc::new(f));
@@ -65,6 +65,7 @@ impl FontDb {
images: Mutex::new(GlyphCache::default()),
colours: Mutex::new(GlyphCache::default()),
catalog: Arc::new(catalog),
bundled_cataloged: std::sync::Once::new(),
file_faces: RwLock::new(super::FileFaces::default()),
canonical_cache: Mutex::new(CanonicalNames::new()),
#[cfg(not(target_arch = "wasm32"))]
@@ -119,7 +120,20 @@ impl FontDb {
/// The installed fonts this database finds by name, shared with the framework's font menus and
/// pickers. Its lookups wait for its first scan ([`FontDb::scan_in_background`]).
///
/// The first call adds the bundled fonts to it as [`Source::Bundled`] faces, so font pickers
/// list them. A run that never looks a font up in the catalog, such as exporting a file without
/// type, does not hold the catalog's copies of their bytes.
// The catalog keeps its own copy of the bytes it is given. Adding the bundled fonts on first use
// can go once the catalog takes static bytes without copying them (craft-libs#4888).
pub fn catalog(&self) -> &Arc<Catalog> {
self.bundled_cataloged.call_once(|| {
for data in bundled_fonts() {
if let Err(e) = self.catalog.add_bytes(data.to_vec(), Source::Bundled, &Limits::default()) {
log::warn!("a bundled font is not in the font catalog: {e}");
}
}
});
&self.catalog
}
@@ -164,7 +178,7 @@ impl FontDb {
/// [`FontDb::families`], shared: cheap to call every frame.
pub fn family_list(&self) -> Arc<[String]> {
// The catalog's list is the same `Arc` until it rescans (here or in its watch).
let installed = self.catalog.families();
let installed = self.catalog().families();
let mut cache = self.family_cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some((from, list)) = cache.as_ref()
&& Arc::ptr_eq(from, &installed)
@@ -238,7 +252,7 @@ impl FontDb {
}
// An installed family's, from its names in other languages, as a loaded face's is chosen
// (every face of a family has the same names: one is enough).
let native = self.catalog.resolve(&family, "").and_then(|(f, _)| {
let native = self.catalog().resolve(&family, "").and_then(|(f, _)| {
let names: Vec<(Option<String>, String)> = f.localized_families.into_iter().map(|n| (n.language, n.name)).collect();
pick_native_label(&f.family, &names)
});
@@ -256,7 +270,7 @@ impl FontDb {
v.push((f.italic, f.weight, f.style.clone()));
}
}
for f in self.catalog.styles(family) {
for f in self.catalog().styles(family) {
if !v.iter().any(|(_, _, s)| s.eq_ignore_ascii_case(&f.style)) {
v.push((f.italic, f.weight, f.style));
}
@@ -282,7 +296,7 @@ impl FontDb {
for f in self.read_faces().iter().filter(|f| f.family.eq_ignore_ascii_case(family)) {
consider(&mut best, f.weight, f.italic, &f.style);
}
for f in self.catalog.styles(family) {
for f in self.catalog().styles(family) {
consider(&mut best, f.weight, f.italic, &f.style);
}
best.map(|(_, style)| style)
@@ -347,7 +361,7 @@ impl FontDb {
/// folders, any other waits for that scan to finish, as every catalog lookup does.
#[cfg(any(test, feature = "test-fonts"))]
pub(crate) fn ensure_catalog(&self) {
let _ = self.catalog.families();
let _ = self.catalog().families();
}
/// Catalog the installed fonts on a background thread, so the first lookup by family name
@@ -370,14 +384,14 @@ impl FontDb {
let _change = self.catalog.is_ready().then(crate::test_fonts::font_change);
// The first scan, or a rescan once it is done (never both at once). The count is of the installed faces: the
// catalog's less the bundled faces no installed file also has.
let cataloged = self.catalog.rescan();
let bundled_only = self.catalog.faces().iter().filter(|f| f.source == Source::Bundled && self.catalog.versions(f).len() == 1).count();
let catalog = self.catalog();
let cataloged = catalog.rescan();
let bundled_only = catalog.faces().iter().filter(|f| f.source == Source::Bundled && catalog.versions(f).len() == 1).count();
let n = cataloged.saturating_sub(bundled_only);
// Files may have been installed since: other versions are looked for again, in the catalog
// the rescan published. A version lookup made during the scan read the previous one.
self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear();
let installed: std::collections::HashSet<PathBuf> =
self.catalog.faces().iter().flat_map(|f| self.catalog.versions(f)).filter_map(|f| f.path).collect();
let installed: std::collections::HashSet<PathBuf> = catalog.faces().iter().flat_map(|f| catalog.versions(f)).filter_map(|f| f.path).collect();
// Faces loaded from a file this scan did not catalog, as a face or a version of one (the font was removed, or its folder
// is no longer read) are dropped with their outlines. A family with no face left and no
// cataloged file leaves the lists, and type set in it resolves to the fallback font. A face
+3 -4
View File
@@ -30,13 +30,12 @@ impl FontDb {
// The catalog first: the first scan takes the faces' lock, which a guard held here would block.
// The bundled faces have no file to read. The catalog lists a bundled face ahead of an
// installed file of the same face, so each face's file is its first installed version.
let cataloged: Vec<(String, String, PathBuf)> = self
.catalog
let catalog = self.catalog();
let cataloged: Vec<(String, String, PathBuf)> = catalog
.faces()
.iter()
.filter_map(|f| {
let path =
self.catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?;
let path = catalog.versions(f).into_iter().filter(|v| v.source != craft::font_catalog::Source::Bundled).find_map(|v| v.path)?;
Some((f.family.clone(), f.style.clone(), path))
})
.collect();
+13 -11
View File
@@ -73,7 +73,7 @@ impl FontDb {
}
#[cfg(not(target_arch = "wasm32"))]
{
let faces = self.catalog.styles(family);
let faces = self.catalog().styles(family);
let off = |f: &craft::font_catalog::FaceInfo| (f.italic, (f.weight - 400.0).abs());
let nearest = faces.iter().min_by(|a, b| {
let ((ai, aw), (bi, bw)) = (off(a), off(b));
@@ -89,7 +89,7 @@ impl FontDb {
/// Is `family` an installed family's own name (any ASCII case)?
fn is_installed(&self, family: &str) -> bool {
self.catalog.family(family).is_some_and(|f| f.eq_ignore_ascii_case(family))
self.catalog().family(family).is_some_and(|f| f.eq_ignore_ascii_case(family))
}
/// The family's own name and the style for a name given in a document: any of a family's
@@ -124,7 +124,7 @@ impl FontDb {
self.read_faces().iter().flat_map(|f| Alias::of(&f.family, &f.style, &f.keys)).filter(|(k, _)| *k == key).map(|(_, a)| a).collect();
// The installed face the name gives: by a family name in its family, by a legacy family
// name with its legacy style, by a full or PostScript name whatever the style.
let installed = self.catalog.resolve(family, style);
let installed = self.catalog().resolve(family, style);
let ns = norm(style);
// A family and style split from a PostScript name by an importer that didn't have the font
// (`Honoka-Mincho` → Honoka, Mincho): once it is installed, the face of that PostScript
@@ -147,7 +147,7 @@ impl FontDb {
if let Some(a) = found.iter().find(|a| a.style.is_none()) {
return (a.family.clone(), style.to_string());
}
if let Some(installed_family) = self.catalog.family(family) {
if let Some(installed_family) = self.catalog().family(family) {
return (installed_family, style.to_string());
}
if let Some(a) = found.iter().find(|a| a.paired.as_ref().is_some_and(|p| *p == ns) || a.paired.is_none()) {
@@ -278,7 +278,7 @@ impl FontDb {
let key = norm(name);
let mut families: Vec<String> = vec![first.family.clone()];
let named = |f: &&FaceInfo| f.postscript_name.as_deref().is_some_and(|p| norm(p) == key);
for f in self.catalog.faces().iter().filter(named) {
for f in self.catalog().faces().iter().filter(named) {
if families.len() < MAX_POSTSCRIPT_FACES && !families.iter().any(|known| known.eq_ignore_ascii_case(&f.family)) {
families.push(f.family.clone());
}
@@ -303,13 +303,14 @@ impl FontDb {
/// The cataloged face of PostScript name `name`: an installed face before a bundled face of another family with the
/// same name, as the installed faces alone answered before the bundled ones were cataloged.
fn cataloged_postscript(&self, name: &str) -> Option<FaceInfo> {
let face = self.catalog.by_postscript_name(name)?;
let catalog = self.catalog();
let face = catalog.by_postscript_name(name)?;
if face.source != Source::Bundled {
return Some(face);
}
let key = norm(name);
let named = |f: &&FaceInfo| f.source != Source::Bundled && f.postscript_name.as_deref().is_some_and(|p| norm(p) == key);
Some(self.catalog.faces().iter().find(named).cloned().unwrap_or(face))
Some(catalog.faces().iter().find(named).cloned().unwrap_or(face))
}
/// Load the files of the installed `family`, every cataloged version of its faces included,
@@ -317,8 +318,9 @@ impl FontDb {
/// thread meanwhile.
#[cfg(not(target_arch = "wasm32"))]
fn load_cataloged(&self, family: &str) -> bool {
let faces = self.catalog.styles(family);
let mut paths: Vec<PathBuf> = faces.iter().flat_map(|f| self.catalog.versions(f)).filter_map(|f| f.path).collect();
let catalog = self.catalog();
let faces = catalog.styles(family);
let mut paths: Vec<PathBuf> = faces.iter().flat_map(|f| catalog.versions(f)).filter_map(|f| f.path).collect();
paths.sort();
paths.dedup();
let files = paths.into_iter().flat_map(|p| font_files(&p).into_iter().map(move |data| (data, Some(p.clone()))));
@@ -403,7 +405,7 @@ impl FontDb {
#[cfg(not(target_arch = "wasm32"))]
fn is_cataloged(&self, family: &str, style: &str) -> bool {
let ns = norm(style);
self.catalog.styles(family).iter().any(|f| norm(&f.style) == ns)
self.catalog().styles(family).iter().any(|f| norm(&f.style) == ns)
}
/// The loaded face with [`FontFace::id`] `id` (the face a laid-out glyph came from), an
@@ -680,7 +682,7 @@ impl FontDb {
}
sys.file_searches += 1;
}
let mut paths: Vec<PathBuf> = self.catalog.faces().iter().filter_map(|f| f.path.clone()).collect();
let mut paths: Vec<PathBuf> = self.catalog().faces().iter().filter_map(|f| f.path.clone()).collect();
paths.sort();
paths.dedup();
for p in paths {
+1
View File
@@ -149,6 +149,7 @@ impl VectorcraftApp {
spelling: Default::default(),
text_nodes: Default::default(),
momentary: None,
momentary_keys: vec![],
hand: None,
zoom_tool: None,
selection_box: None,
+3
View File
@@ -81,6 +81,9 @@ pub struct CanvasCache {
/// The Hand, Zoom and Rotate View tools the Space key and its chords lend the canvas, between
/// passes; the tool adapter takes it out for its call and puts it back.
pub momentary: Option<craft::ui::canvas::Momentary>,
/// The keys down when the held momentary command started; empty while none is held or when none started it.
/// Temporary, with `tool_adapter::end_missed_momentary` (craft-libs#5056).
pub momentary_keys: Vec<craft::keymap::Key>,
pub hand: Option<craft::ui::canvas::HandTool>,
/// The selected Zoom tool keeps its press and drag rectangle between canvas passes.
pub zoom_tool: Option<craft::ui::canvas::ZoomTool>,
+24 -1
View File
@@ -12,7 +12,8 @@ use craft::ui::menu::PanelRow;
use craft::ui::popover::Popover;
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::commands::{CommandRef, CommandState, CommandStates};
use craft::ui::runtime::env::{Label, WordRows, WordsOverride, with_env};
use craft::ui::runtime::env::{Env, Label, WordRows, WordsOverride, with_env};
use craft::ui::style::{UiTokens, rgba_color};
use vectorcraft_doc::NodeKind;
use vectorcraft_doc::text::TextKind;
use vectorcraft_geom::{Point, Rect};
@@ -488,12 +489,14 @@ fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) ->
let has_shape = offer.shape.is_some();
let mut run: Option<(&'static str, serde_json::Value)> = None;
let mut show_swatches = false;
let mut layer = None;
let shown = TaskBar::new(tl!("Contextual Task Bar"), &offer.anchor, Bind::bound(&mut local))
.grip(TaskBarGrip::Bar)
.member_gap(Gap::Item)
.hang_gap(TaskBarHang::ClearOfHandles)
.more_rows(more_rows(&offer))
.show(ui, space.view.rect, |ui, _| {
layer = Some((ui.layer_id(), ui.opacity()));
for (label, icon, cmd, params) in &offer.actions {
if *cmd == TASK_BAR_FIDELITY {
// The Smooth tool's Fidelity, labeled, sets the tool's option once a typed or stepped value is
@@ -567,6 +570,9 @@ fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) ->
}
});
let (rect, hide) = (shown.output.rect, shown.output.hide);
if let Some((layer, opacity)) = layer {
accent_outline(ui, layer, opacity, rect);
}
if local != before {
app.ui.task_bar_place.set(key, local);
}
@@ -599,6 +605,23 @@ fn shown_task_bar(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) ->
Some(rect)
}
/// Outlines the Contextual Task Bar at `rect` on its `layer` in the accent border color, on the corners of the floating
/// surface the bar paints and at its rect rounded to pixels, at the `opacity` the bar's members paint at while the bar
/// fades in or out.
///
/// Temporary: craft-libs#4892 adds `TaskBar::edge(BarEdge::Accent)`, which draws this outline in place of the
/// surface's own border. Delete this function and set that edge on the bar once the craft-libs pin includes it.
fn accent_outline(ui: &Ui, layer: egui::LayerId, opacity: f32, rect: egui::Rect) {
let env = Env::of(ui);
let tokens = env.tokens.tokens();
let stroke = egui::Stroke::new(tokens.stroke.thin, rgba_color(tokens.color.accent.border));
let corners = UiTokens::corner(tokens.shape.radius.window);
let mut painter = ui.ctx().layer_painter(layer);
painter.set_opacity(opacity);
let rect = egui::emath::GuiRounding::round_to_pixels(rect, painter.pixels_per_point());
painter.rect_stroke(rect, corners, stroke, egui::StrokeKind::Inside);
}
/// The controls the Contextual Task Bar shows after its actions: the Fill and Stroke chips,
/// Recolor Artwork, and Lock or a basic shape's Shape Properties.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+41 -3
View File
@@ -7,8 +7,8 @@ use craft::behavior::{CancelReason, CanvasView, Cursor, DropOperation, PointerKi
use craft::keymap::{Chord, Key};
use craft::ui::canvas::ToolPath;
use craft::ui::canvas::{
Autoscroll, CanvasTool, Momentary, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey, ToolPass,
ToolPointer,
Autoscroll, CanvasTool, Momentary, MomentaryCommands, MomentaryShift, ToolAction, ToolClaims, ToolContext, ToolHost, ToolHostResponse, ToolKey,
ToolPass, ToolPointer,
};
use serde_json::json;
use vectorcraft_engine::ViewInfo;
@@ -615,6 +615,37 @@ impl CanvasTool for SessionTool<'_> {
}
}
/// Ends the held momentary command (Space's Hand, Cmd+Space's Zoom...) once none of the keys that were down when it
/// started is down, and returns the command still held. The shortcut board drops a queued release when the canvas
/// does not run on the frame the key goes up (a dialog or another tab in front). A hold that started with no key down
/// (automation) lasts until its release.
///
/// Temporary: craft-libs#5056 ends the hold inside the tool host. Remove this function, [`note_momentary_keys`],
/// their calls and `CanvasCache::momentary_keys` once the craft-libs pin includes that change.
fn end_missed_momentary(ctx: &egui::Context, momentary: &mut Momentary, keys: &mut Vec<Key>) -> Option<MomentaryCommands> {
let held = momentary.held()?;
if keys.is_empty() {
return Some(held);
}
let down = craft::ui::runtime::keys::held(ctx);
if keys.iter().any(|key| down.contains(key)) {
return Some(held);
}
momentary.fired(held, craft::ui::runtime::commands::FirePhase::Release);
keys.clear();
None
}
/// Notes the keys down when a momentary command starts (or changes), for [`end_missed_momentary`]; `before` is the
/// command held before the tool host's pass.
fn note_momentary_keys(ctx: &egui::Context, before: Option<MomentaryCommands>, momentary: &Momentary, keys: &mut Vec<Key>) {
match momentary.held() {
None => keys.clear(),
Some(held) if before != Some(held) => *keys = craft::ui::runtime::keys::held(ctx),
Some(_) => {}
}
}
/// Runs the tool host on `tool` with the app's momentary set, which the app keeps across passes. A finger, once a pen
/// has been seen, only navigates (palm rejection).
fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn CanvasTool) -> ToolHostResponse {
@@ -622,7 +653,9 @@ fn host_run(app: &mut VectorcraftApp, ui: &Ui, pass: &ToolPass, tool: &mut dyn C
let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView));
momentary.set_options(options);
momentary.hand_selected(app.session.tool_id() == "hand");
let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut app.canvas.momentary_keys);
let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool);
note_momentary_keys(ui.ctx(), before, &momentary, &mut app.canvas.momentary_keys);
app.canvas.momentary = Some(momentary);
response
}
@@ -755,9 +788,14 @@ fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> Too
let mut momentary = app.canvas.momentary.take().unwrap_or_else(|| Momentary::new(options).shift(MomentaryShift::RotateView));
momentary.set_options(options);
momentary.hand_selected(app.session.tool_id() == "hand");
let mut keys = std::mem::take(&mut app.canvas.momentary_keys);
drop(app);
let before = end_missed_momentary(ui.ctx(), &mut momentary, &mut keys);
let response = ToolHost::new().momentary(&mut momentary).navigates(crate::touch::finger_navigates_only()).run(ui, pass, tool);
tool.app().canvas.momentary = Some(momentary);
note_momentary_keys(ui.ctx(), before, &momentary, &mut keys);
let mut app = tool.app();
app.canvas.momentary = Some(momentary);
app.canvas.momentary_keys = keys;
response
}
@@ -48,6 +48,69 @@ fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>
out.textures_delta.clear();
}
/// A frame where the canvas does not run, as with a dialog or another tab in front.
fn frame_without_canvas(ctx: &egui::Context, events: Vec<egui::Event>) {
let raw =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), events, ..Default::default() };
let mut out = ctx.run_ui(raw, |_| {});
out.textures_delta.clear();
}
fn space_key(pressed: bool) -> egui::Event {
egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }
}
/// Space let go while the canvas is away for long enough that the shortcut board drops its queued release (two
/// frames) ends the momentary Hand at the canvas's next pass, and Space still held across such frames keeps it. The
/// Rectangle tool runs through the session's tool, and the Zoom tool through the framework's.
#[test]
fn space_let_go_while_the_canvas_is_away_ends_the_momentary_hand() {
for tool in ["rectangle", "zoom"] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
app.select_tool(tool);
let ctx = crate::testing::ui_context();
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![space_key(true)]);
frame(&mut app, &ctx, vec![]);
assert!(view_tool_held(&app), "{tool}: Space down holds the Hand");
frame_without_canvas(&ctx, vec![]);
frame_without_canvas(&ctx, vec![]);
frame(&mut app, &ctx, vec![]);
assert!(view_tool_held(&app), "{tool}: Space still down keeps the Hand across frames without the canvas");
frame_without_canvas(&ctx, vec![space_key(false)]);
frame_without_canvas(&ctx, vec![]);
frame(&mut app, &ctx, vec![]);
assert!(!view_tool_held(&app), "{tool}: Space let go while the canvas was away ends the Hand");
}
}
/// A momentary Hand whose key is down at another physical position than the one its shortcut names (another keyboard
/// layout) stays held across passes while that key is down, and ends once it goes up while the canvas is away.
#[test]
fn a_momentary_hand_from_another_layout_position_lasts_while_its_key_is_down() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
app.select_tool("rectangle");
let ctx = crate::testing::ui_context();
let key = |pressed| egui::Event::Key {
key: egui::Key::Space,
physical_key: Some(egui::Key::Backtick),
pressed,
repeat: false,
modifiers: egui::Modifiers::NONE,
};
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![key(true)]);
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![]);
assert!(view_tool_held(&app), "the key still down keeps the Hand");
frame_without_canvas(&ctx, vec![key(false)]);
frame_without_canvas(&ctx, vec![]);
frame(&mut app, &ctx, vec![]);
assert!(!view_tool_held(&app), "the key let go while the canvas was away ends the Hand");
}
/// With the Live Paint Bucket and the pointer still, an Alt-only pass changes the cursor and back.
#[test]
fn bucket_modifier_only_hover_updates_the_visible_cursor() {
+4 -1
View File
@@ -252,7 +252,10 @@ fn artboard_items(app: &VectorcraftApp) -> Vec<Node> {
.collect();
let unlock: Vec<Node> =
[entry("Unlock Selected", sel.clone(), false), entry("Unlock All", (0..n).collect(), false)].into_iter().flatten().collect();
for (label, items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] {
for (label, mut items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] {
// The selected and unselected targets are disjoint. If All matches a narrower row, it
// is adjacent to it after empty rows are removed. Keep the narrower row for that command key.
items.dedup_by(|a, b| matches!((a, b), (Node::Item(a), Node::Item(b)) if a.command == b.command));
if !items.is_empty() {
v.push(sub(label, items));
}
+41 -4
View File
@@ -21,6 +21,7 @@ use std::sync::Arc;
use craft::behavior::{Axis, DockSide, IconId};
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits, Tracked};
use craft::ui::dialog::DialogId;
use craft::ui::docking::{
ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels,
PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions,
@@ -73,6 +74,9 @@ pub(crate) struct Runtime {
/// A panel just floated out of a tool rail, whose window takes over the held press on the next
/// pass, with the pointer at this point inside it ([`continue_move`]).
hand_over: Option<(String, egui::Vec2)>,
/// The dialogs a panel in the open flyout opened, by id and opening serial: while one is open, Auto-Collapse Iconic
/// Panels leaves the flyout open ([`show`]).
flyout_dialogs: Vec<(DialogId, u64)>,
}
/// `ui.docking`: the layout in use, the hidden panels, the open flyout, the focused panel, the
@@ -1317,15 +1321,24 @@ fn window_viewport(app: &VectorcraftApp, panel: &str) -> Option<egui::ViewportId
}
/// Whether the OS window of a floating panel lies at `pos`, a point of the main window: a palette
/// window stays in front of the main window.
/// window stays in front of the main window. A hidden or minimized palette window does not count.
pub(crate) fn os_window_at(app: &VectorcraftApp, ctx: &egui::Context, pos: egui::Pos2) -> bool {
if app.dock_rt.windows.is_empty() {
return false;
}
// Workaround for craft-libs#4739: `WindowHost::viewports_at` still lists palette windows that are minimized, or
// hidden while a dialog or popup shows. Remove these checks when the craft-libs pin includes craft-libs#4739.
if app.any_dialog_open() {
return false;
}
let origin = ctx.input(|i| i.raw.viewports.get(&i.raw.viewport_id).and_then(|v| v.inner_rect).map(|r| r.min.to_vec2()));
let Some(origin) = origin else { return false };
let under = craft::ui::runtime::windows::WindowHost::of(ctx).viewports_at(pos + origin);
under.iter().any(|viewport| app.dock_rt.windows.iter().any(|(_, shown)| shown == viewport))
let host = craft::ui::runtime::windows::WindowHost::of(ctx);
let under = host.viewports_at(pos + origin);
// Workaround for craft-libs#4739 (see above).
let restored =
|viewport: &egui::ViewportId| host.facts(*viewport).is_some_and(|facts| facts.state != craft::host::target::WindowState::Minimized);
under.iter().filter(|viewport| restored(viewport)).any(|viewport| app.dock_rt.windows.iter().any(|(_, shown)| shown == viewport))
}
/// Brings the OS window of the floating window holding `panel` forward, as it was last drawn.
@@ -1335,6 +1348,16 @@ fn raise(app: &VectorcraftApp, ctx: &egui::Context, panel: &str) {
}
}
/// The open dialogs of the main window, by id and opening serial: a dialog closed and opened again has a new serial.
fn open_dialogs(app: &VectorcraftApp) -> Vec<(DialogId, u64)> {
app.dialogs().map_or_else(Vec::new, |dialogs| {
dialogs.with(|host| {
let host = &*host;
host.stack().ids().filter_map(|id| Some((id, host.open_serial(id)?))).collect()
})
})
}
/// The floating window holding `panel` takes over the held primary press on the next pass, with the
/// pointer at `grab` inside it: a panel floated out of a tool rail mid-drag follows the pointer and
/// docks where the release lands.
@@ -1360,7 +1383,15 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo
let presenting = app.ui.screen_mode >= 3;
// Shift+Tab, from its key, a menu or automation, closes a panel popped out of the icon column.
let mut flyout = flyout_before.clone().filter(|_| !keeps_tools);
let auto_collapse = app.session.prefs.auto_collapse_icon_panels;
let dialogs_before = open_dialogs(app);
if flyout_before.is_some() {
app.dock_rt.flyout_dialogs.retain(|dialog| dialogs_before.contains(dialog));
} else {
app.dock_rt.flyout_dialogs.clear();
}
// A dialog a panel of the flyout opened (the Gradient panel's stop popover) is a layer of the window's dialog host,
// outside the flyout's: while one is open, a press in it or the focus moving into it leaves the flyout open.
let auto_collapse = app.session.prefs.auto_collapse_icon_panels && app.dock_rt.flyout_dialogs.is_empty();
// The specs and rails leave the app for the pass, which lends the app to the panel bodies.
let specs = std::mem::take(&mut app.dock_rt.specs);
let rails = std::mem::take(&mut app.dock_rt.rails);
@@ -1406,6 +1437,12 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo
if app.ui.open_panel == flyout_before {
app.ui.open_panel = flyout;
}
if app.ui.open_panel.is_some() {
let opened: Vec<_> = open_dialogs(app).into_iter().filter(|dialog| !dialogs_before.contains(dialog)).collect();
app.dock_rt.flyout_dialogs.extend(opened);
} else {
app.dock_rt.flyout_dialogs.clear();
}
if output.error.is_some() {
Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[]));
app.status(tl!("Invalid panel layout; restored the default dock").to_string());
@@ -28,6 +28,8 @@ struct Window {
/// Whether the window shows on the desktop: the builder's visibility when it opened, then each
/// `Visible` command.
visible: bool,
/// Whether the OS reports the window minimized.
minimized: bool,
frames: usize,
/// The texts its last frame drew, with their rects in the window.
texts: Vec<(String, Rect)>,
@@ -59,6 +61,7 @@ impl Host {
std::iter::once((ViewportId::ROOT, info(ViewportId::ROOT, SCREEN.translate(ORIGIN.to_vec2()))))
.chain(self.windows.iter().map(|(id, w)| {
let mut info = info(*id, w.rect);
info.minimized = Some(w.minimized);
if w.close_requested {
info.events.push(egui::ViewportEvent::Close);
}
@@ -96,6 +99,7 @@ impl Host {
dropped: Vec::new(),
close_requested: false,
visible: builder.visible != Some(false),
minimized: false,
frames: 0,
texts: Vec::new(),
nodes: Vec::new(),
@@ -633,3 +637,47 @@ fn a_window_menu_panel_stays_shown_while_art_is_selected_and_moved() {
);
}
}
/// A floating panel's window over the canvas, with the main window holding the keyboard: the window and the point at
/// its middle, in the main window's points.
fn palette_over_canvas(h: &mut Harness) -> (ViewportId, Pos2) {
let viewport = h.float("graphicStyles");
h.host.borrow_mut().focus = ViewportId::ROOT;
h.frames(2);
let middle = h.host.borrow().windows[&viewport].rect.center() - ORIGIN.to_vec2();
let view = h.app.canvas_view().expect("the canvas was drawn");
assert!(view.rect.contains(middle), "the window lies over the canvas");
assert!(os_window_at(&h.app, &h.ctx, middle), "the shown window covers the canvas under it");
(viewport, middle)
}
/// A minimized palette window leaves the canvas under the place it had uncovered, and covers it again once restored.
#[test]
fn a_minimized_palette_window_does_not_cover_the_canvas() {
let mut h = Harness::new();
let (viewport, middle) = palette_over_canvas(&mut h);
h.host.borrow_mut().windows.get_mut(&viewport).unwrap().minimized = true;
h.frames(2);
assert!(!os_window_at(&h.app, &h.ctx, middle), "a minimized window covers nothing");
h.host.borrow_mut().windows.get_mut(&viewport).unwrap().minimized = false;
h.frames(2);
assert!(os_window_at(&h.app, &h.ctx, middle), "the restored window covers the canvas again");
}
/// While a dialog shows, the palette windows are hidden and leave the canvas uncovered.
#[test]
fn a_hidden_palette_window_does_not_cover_the_canvas() {
let mut h = Harness::new();
let (_, middle) = palette_over_canvas(&mut h);
crate::menus::invoke(&mut h.app, "view.rotate", json!({}));
h.frames(2);
assert!(h.app.any_dialog_open(), "the Rotate View dialog shows");
assert!(!os_window_at(&h.app, &h.ctx, middle), "a palette hidden behind a dialog covers nothing");
let ctx = h.app.ui_ctx.clone().expect("a frame ran");
let id = h.app.dialogs().expect("a window").with(|host| host.open_dialogs().last().map(|d| d.id)).expect("a dialog is open");
assert!(h.app.dialogs().expect("a window").with(|host| host.cancel_by_id(&ctx, id)), "the dialog took the answer");
crate::dialogs::host::pump(&mut h.app, &ctx);
h.frames(2);
assert!(!h.app.any_dialog_open(), "the dialog closed");
assert!(os_window_at(&h.app, &h.ctx, middle), "the palette covers the canvas again once the dialog closes");
}
+37
View File
@@ -1349,3 +1349,40 @@ fn a_tab_menus_stock_items_start_at_the_panel_items_check_column() {
let within = find(&shown, "Float").1;
assert!(within < stock.1 - 0.5, "\"Float\" starts {within} into its row with no rows before it, as far as {} after them", stock.1);
}
/// With Auto-Collapse Iconic Panels on, the popover the Gradient panel's stop chip opens from the panel's flyout leaves
/// the flyout open while it shows; once it closes, a click away from the flyout still closes it.
#[test]
fn a_popover_opened_from_an_auto_collapsing_flyout_leaves_the_flyout_open() {
let mut h = Harness::new();
h.app.session.prefs.auto_collapse_icon_panels = true;
h.app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 120, "height": 100})).unwrap();
let stops = json!([{"offset": 0, "color": "#2468ac"}, {"offset": 1, "color": "#e09020"}]);
h.app.run("paint.setFill", json!({"keepModel": true, "gradient": {"kind": "linear", "stops": stops}})).unwrap();
h.app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap();
h.app.select_tool("directSelection");
h.app.run("gradient.selectStop", json!({"index": 0})).unwrap();
h.app.run("window.panel", json!({"panel": "gradient"})).unwrap();
h.frames(3);
let flyout = h.app.ui.open_panel.clone();
assert!(flyout.is_some(), "the Gradient panel opens in its icon column's flyout");
let popover = craft::ui::dialog::dialog_id(crate::dialogs::gradient_stop::KIND);
let popover_open = |h: &Harness| h.app.dialogs().unwrap().with(|host| host.stack().contains(popover));
let chip = h
.nodes
.iter()
.filter(|(_, node)| node.label() == Some("Edit the stop"))
.find_map(|(_, node)| node.bounds())
.map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))
.expect("the flyout's stop chip");
h.click(chip.center());
h.frames(3);
assert!(popover_open(&h), "the chip opens the stop popover");
assert_eq!(h.app.ui.open_panel, flyout, "the flyout stays open while its panel's popover shows");
h.press(egui::Key::Escape, Default::default());
h.frames(2);
assert!(!popover_open(&h), "Escape closes the popover");
assert_eq!(h.app.ui.open_panel, flyout, "closing the popover leaves the flyout open");
h.click(h.canvas().center());
assert_eq!(h.app.ui.open_panel, None, "a click away from the flyout still closes it");
}
+2 -2
View File
@@ -1244,8 +1244,8 @@ fn the_artboard_tools_lock_entries_have_something_to_change() {
Some(sub) => menu_labels(children_of(sub)),
None => vec![],
};
assert_eq!(subs("Lock Artboards"), ["Lock All Except Selected", "Lock All"], "the selected artboard is locked already");
assert_eq!(subs("Unlock Artboards"), ["Unlock Selected", "Unlock All"]);
assert_eq!(subs("Lock Artboards"), ["Lock All Except Selected"], "only the unselected artboard can be locked");
assert_eq!(subs("Unlock Artboards"), ["Unlock Selected"], "only the selected artboard can be unlocked");
}
/// A right-click on an artboard that isn't selected selects it alone; on a selected one the selection
+22
View File
@@ -102,6 +102,13 @@ pub struct GradientUi {
/// `paint.editGradient` sorts the stops, so the gradient shown mid-gesture is the last preview
/// re-sorted: the editor's tags name stops of this one.
pub(crate) begun: Option<Vec<GradientStop>>,
/// The press of a double click that asked for a stop's color is still held. Until craft-libs#5131 reaches the
/// pin, the slider also drags the stop when the pointer drifts during that press, and the moved stop closes the
/// popover the double click opened: the panel drops that press's slider edits.
pub(crate) color_press: bool,
/// The slider's gesture that the press above began, dropped until its `Commit` or `Cancel`, which can arrive in a
/// pass after the button is up.
pub(crate) color_drag: bool,
}
/// Select stop `i` (the session's selected stop, shared with the Gradient tool's annotator, the
@@ -829,6 +836,21 @@ fn stops_editor(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_gra
.shared_selection(Bind::bound(&mut shared))
.drop_target::<PanelDrag>()
.show(ui);
let panel = &mut app.ui.gradient_panel;
let color_press = panel.color_press || out.color_requested.is_some();
let held = craft::ui::runtime::pointer::press_state(ui.ctx()).buttons.contains(craft::behavior::Buttons::PRIMARY);
let dropping = panel.color_drag || (color_press && out.edit.events.began());
let ended = matches!(out.edit.events.last(), Some(EditEvent::Commit { .. } | EditEvent::Cancel { .. } | EditEvent::Set { .. }));
panel.color_press = color_press && held;
panel.color_drag = dropping && !ended;
if color_press || dropping {
// The drift of the press that asked for the color moves no stop (craft-libs#5131).
if is_grad && let Some(request) = &out.color_requested {
let at = request.rect.map_or(out.edit.response.rect.left_bottom(), |r| r.left_bottom());
open_popover(app, request.index, at);
}
return;
}
let events = &out.edit.events;
if !is_grad {
// The slider shows the default gradient: an edit of it applies a gradient first.
+23 -6
View File
@@ -14,15 +14,15 @@ use serde_json::{Value, json};
use vectorcraft_engine::script::console::{Console, ConsoleLine, Ending, Entry};
// PLAN: assumed paths of the framework items below, re-exported by craft-ui (behavior, theme and keymap types)
use craft::behavior::{DisplayOrder, IconId, ItemSource};
use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection};
use craft::keymap::CommandRef;
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, LeastWidth, Props as _, ScrollAnchor, Show, ShowCollection, ShowContainer, Sizing, clicked};
use craft::ui::contract::{Bind, CollectionEvent, LeastWidth, Props as _, ScrollAnchor, Show, ShowCollection, ShowContainer, Sizing, clicked};
use craft::ui::layout::RowAlign;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow, RowInk};
use craft::ui::menu::PanelRow;
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::notices::Notice;
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::commands::{CommandState, CommandStates};
@@ -209,11 +209,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
selection.anchor = selection.anchor.take().filter(held);
let buttons = buttons(count > 0, !selection.items.is_empty());
let mut picked = None;
let mut menu_command = None;
Stack::new().fill().footer(|ui, _| picked = footer(ui, buttons).or(picked)).show(ui, |ui, _| {
if let Some(n) = notice(c) {
Notice::new(Tone::Info, n).show(ui);
}
List::<u64>::new(tl!("Script Console"))
let out = List::<u64>::new(tl!("Script Console"))
.id(ui.scope_id().with("console-lines"))
.row_menu()
.sizing(Sizing::Fill)
.scroll_anchor(ScrollAnchor::End)
.selection(Bind::bound(&mut *selection))
@@ -227,9 +230,23 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
Entry::Output(_) | Entry::Log(_) => row,
}
});
if let Some(line) = out.menu.map(|request| request.key).filter(held) {
// The row's More button can open the menu without a selection gesture.
if out.events.iter().any(|event| matches!(event, CollectionEvent::ContextMenu(_))) && !selection.items.contains(&line) {
*selection = Selection::single(line);
}
Menu::context(tl!("Script Console"), &out.response).show(ui, |ui, _| {
if MenuItem::new(tl!("Copy Line")).show(ui).ran {
menu_command = Some((COMMANDS[2], json!({"first": line, "last": line})));
}
if MenuItem::new(tl!("Copy Selected")).enabled(!selection.items.is_empty()).show(ui).ran {
menu_command = Some((COMMANDS[1], json!({})));
}
});
}
});
if let Some(id) = picked {
run_ui(app, id, json!({}));
if let Some((id, params)) = menu_command.or_else(|| picked.map(|id| (id, json!({})))) {
run_ui(app, id, params);
}
}
+192 -17
View File
@@ -4,6 +4,9 @@
//! objects' events, and a click on one picks it to edit. Remove Selected Entry
//! (`svgInteractivity.removeEvent`) and the panel menu's Clear Events (`svgInteractivity.clearEvents`)
//! remove them; Link JavaScript Files… opens the JavaScript Files dialog (`ui.javascriptFilesDialog`).
//! A right-click on an event row (or Shift+F10 on the focused row) picks that event and opens its
//! menu: Remove Event, Clear Events and Link JavaScript Files…, the same commands as the footer and
//! the panel menu.
//! Everything reads `svgInteractivity.info`.
use std::hash::{DefaultHasher, Hash, Hasher};
@@ -17,7 +20,7 @@ use craft::ui::display::{Shade, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Stack;
use craft::ui::list::{List, ListRow};
use craft::ui::menu::PanelRow;
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::pickers::Select;
use craft::ui::primitives::SubmitKey;
use craft::ui::runtime::commands::{CommandState, CommandStates};
@@ -35,6 +38,13 @@ pub const ID: &str = "svgInteractivity";
/// The engine command of the panel menu's one row.
const CLEAR_EVENTS: &str = "svgInteractivity.clearEvents";
/// What the footer or a row's menu picked, run once the list is drawn.
#[derive(Clone, Copy)]
enum RowAction {
Clear,
LinkFiles,
}
/// The SVG Interactivity panel's own state, kept while the app runs.
#[derive(Clone, Debug, Default)]
pub(crate) struct SvgInteractivityPanel {
@@ -51,8 +61,8 @@ pub(crate) struct Info {
script_target: Option<egui::IdSalt>,
}
/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selection size and ends.
pub(crate) type SelKey = ((u64, u64), u64, usize, Option<NodeId>, Option<NodeId>);
/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selected objects.
pub(crate) type SelKey = ((u64, u64), u64, Vec<NodeId>);
/// A side label's text without its colon: the label draws the colon itself
/// (`CommonWords::caption`), so the catalog's "Event:" keeps its translation here.
@@ -61,16 +71,11 @@ pub(crate) fn caption(label: &'static str) -> &'static str {
crate::i18n::t(label).trim_end_matches(':')
}
fn sel_key(app: &VectorcraftApp) -> Option<SelKey> {
let st = app.session.active()?;
let sel = &st.selection.objects;
Some(((st.uid, st.reverts), st.revision, sel.len(), sel.first().copied(), sel.last().copied()))
}
/// The memoized [`Info`] when it was read for the current document and selection.
fn cached(app: &VectorcraftApp) -> Option<&Info> {
let key = sel_key(app)?;
app.canvas.svg_info.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v)
let st = app.session.active()?;
let (((uid, reverts), revision, selection), info) = app.canvas.svg_info.as_ref()?;
(*uid == st.uid && *reverts == st.reverts && *revision == st.revision && selection == &st.selection.objects).then_some(info)
}
/// `svgInteractivity.info`, read again only when the document or the selection changes.
@@ -78,7 +83,8 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Info {
if let Some(v) = cached(app) {
return v.clone();
}
let Some(key) = sel_key(app) else { return Info::default() };
let Some(st) = app.session.active() else { return Info::default() };
let key = ((st.uid, st.reverts), st.revision, st.selection.objects.clone());
let r = app.session.execute("svgInteractivity.info", &json!({})).unwrap_or_default();
let events = r["events"]
.as_array()
@@ -134,7 +140,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let rows_stamp = stamp.finish();
let mut remove = None;
let mut footer_pick = None;
let has_doc = app.session.active().is_some();
let mut row_action = None;
let document = app.session.active().map(|st| st.uid);
let has_doc = document.is_some();
let can_clear = clearable(&info);
let listed = events.iter().any(|(e, _)| e == event);
Stack::new()
.fill()
@@ -155,9 +164,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
let selection = if listed { Selection::single(event.to_string()) } else { Default::default() };
let mut list = List::<String>::new(tl!("Events"))
// Keep each row menu with the drawing and artwork it was opened for.
.id(ui.scope_id().with(("svg-events", document, info.script_target)))
.select(SelectMode::Single)
.arrows_select(true)
.deletable(true)
.row_menu()
.rows_stamp(rows_stamp)
.selection(Bind::given(selection))
.sizing(Sizing::Fill);
@@ -180,12 +192,29 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
CollectionEvent::Activate(key) => pick = Some(key),
// The menu acts on the row it opened on, so that row becomes the picked event.
CollectionEvent::ContextMenu(request) => pick = Some(request.key),
CollectionEvent::Delete(_) => {
remove = pick.as_deref().or(listed.then_some(event)).map(str::to_owned);
}
_ => {}
}
}
// `list.menu` is `None` once its row leaves the list.
if let Some(request) = list.menu {
let key = request.key.clone();
Menu::context(request.key, &list.response).show(ui, |ui, _| {
if MenuItem::new(tl!("Remove Event")).show(ui).ran {
remove = Some(key.clone());
}
if MenuItem::new(tl!("Clear Events")).enabled(can_clear).show(ui).ran {
row_action = Some(RowAction::Clear);
}
if MenuItem::new(tl!("Link JavaScript Files…")).enabled(has_doc).show(ui).ran {
row_action = Some(RowAction::LinkFiles);
}
});
}
});
if let Some(e) = pick {
let state = &mut app.ui.svg_interactivity_panel;
@@ -200,10 +229,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
match footer_pick {
Some(0) => remove = Some(event.to_string()),
Some(1) => {
Some(1) => row_action = Some(RowAction::LinkFiles),
_ => {}
}
match row_action {
Some(RowAction::Clear) => {
app.run(CLEAR_EVENTS, json!({})).ok();
}
Some(RowAction::LinkFiles) => {
crate::menus::invoke(app, "ui.javascriptFilesDialog", json!({}));
}
_ => {}
None => {}
}
if let Some(event) = remove
&& app.run("svgInteractivity.removeEvent", json!({ "event": event })).is_ok_and(|out| out["changed"].as_u64().unwrap_or(0) > 0)
@@ -221,11 +257,16 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
/// Clear Events is on while the objects have events. The panel reads the events each frame it shows; a
/// panel that is not shown leaves the row off.
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
// (Where the objects' events differ, some of them have events.)
let any = cached(app).is_some_and(|info| info.has && info.events.as_ref().is_none_or(|l| !l.is_empty()));
let any = cached(app).is_some_and(clearable);
states.set(CommandRef::new(CLEAR_EVENTS), CommandState::new().enabled(any));
}
/// Clear Events has something to clear: the objects have events. (Where their events differ, some
/// of them have events.)
fn clearable(info: &Info) -> bool {
info.has && info.events.as_ref().is_none_or(|l| !l.is_empty())
}
/// The panel's own `ui.svgInteractivity.*` commands: it has none, because its menu row is the engine
/// command `svgInteractivity.clearEvents`.
pub(crate) fn run(_app: &mut VectorcraftApp, _id: &str, _params: &Value) -> Option<Result<Value, String>> {
@@ -481,4 +522,138 @@ mod tests {
assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some(script.as_str()));
assert!(panel.in_view(&last), "the picker scrolls the selected event into view");
}
/// A rectangle with two events, `onclick: 1;` and `onmouseover: 2;`, in the panel.
fn two_events() -> Panel {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "1;"}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onmouseover", "script": "2;"}));
Panel::new(app, show)
}
fn undo_len(panel: &Panel) -> usize {
panel.app().session.active().unwrap().history.undo.len()
}
#[test]
fn row_menu_picks_its_row_and_removes_that_event_in_one_undo_step() {
let mut panel = two_events();
panel.click("onclick: 1;");
assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("1;"));
panel.secondary_click("onmouseover: 2;");
assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;"), "the right-clicked row is picked");
let undo = undo_len(&panel);
panel.click_menu_item(tl!("Remove Event"));
panel.frame();
assert!(!panel.shows("onmouseover: 2;"), "the right-clicked event is removed");
assert!(panel.shows("onclick: 1;"), "the event picked before the right-click stays");
assert_eq!(undo_len(&panel), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
panel.frame();
assert!(panel.shows("onmouseover: 2;"), "one undo brings it back");
}
#[test]
fn row_menu_offers_the_panel_menu_and_footer_commands() {
let mut panel = two_events();
panel.secondary_click("onclick: 1;");
let mut states = CommandStates::default();
menu_states(&panel.app(), &mut states);
let panel_menu_clear = states.remove(&CommandRef::new(CLEAR_EVENTS)).is_some_and(|s| s.is_enabled());
assert_eq!(panel.menu_item_enabled(tl!("Clear Events")), panel_menu_clear, "Clear Events follows the panel menu");
assert!(panel.menu_item_enabled(tl!("Link JavaScript Files…")), "a document is open");
let undo = undo_len(&panel);
panel.click_menu_item(tl!("Clear Events"));
panel.frame();
assert!(!panel.shows("onclick: 1;") && !panel.shows("onmouseover: 2;"));
assert_eq!(undo_len(&panel), undo + 1);
}
#[test]
fn keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus() {
let mut panel = two_events();
panel.click("onclick: 1;");
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::F10, egui::Modifiers::SHIFT);
panel.frame();
assert!(panel.menu_item_enabled(tl!("Remove Event")));
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
panel.frame();
assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM));
assert!(panel.focused("onmouseover: 2;"), "Escape gives focus back to the row");
// Enter runs the menu's first row, Remove Event, announced in that frame like the footer's.
panel.key(egui::Key::F10, egui::Modifiers::SHIFT);
panel.frame();
let enter =
|pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
panel.frame_with(vec![enter(true)]);
let removed = crate::i18n::fmt(tl!("Removed SVG event {event}"), &[("event", "onmouseover")]);
let announced = panel.announces(&removed);
panel.frame_with(vec![enter(false)]);
panel.frame();
assert!(announced, "the removal is announced like the footer's");
assert!(!panel.shows("onmouseover: 2;"));
assert!(panel.shows("onclick: 1;"));
}
#[test]
fn row_menu_closes_when_artwork_selection_changes_in_the_same_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let ids = [0, 20, 40, 60].map(|x| run(&mut app, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].clone());
run(&mut app, "svgInteractivity.setEvent", json!({"ids": ids, "event": "onclick", "script": "1;"}));
let first = json!({"ids": [ids[0], ids[1], ids[3]]});
let second = json!({"ids": [ids[0], ids[2], ids[3]]});
run(&mut app, "select.set", first.clone());
let mut panel = Panel::new(app, show);
let item = tl!("Remove Event");
let role = craft::ui::contract::Role::MENU_ITEM;
panel.secondary_click("onclick: 1;");
assert!(panel.menu_item_enabled(item));
// Only the middle object changes, and both selections display the exact same row.
run(&mut panel.app(), "select.set", second);
panel.frame();
assert!(panel.shows("onclick: 1;"));
assert!(!panel.shows_role(item, role));
run(&mut panel.app(), "select.set", first);
panel.frame();
assert!(!panel.shows_role(item, role), "the old menu stays closed on return");
panel.secondary_click("onclick: 1;");
assert!(panel.menu_item_enabled(item), "the row can open a fresh menu");
}
#[test]
fn row_menu_closes_when_its_row_disappears_or_the_document_changes() {
let mut panel = two_events();
panel.secondary_click("onmouseover: 2;");
assert!(panel.menu_item_enabled(tl!("Remove Event")));
run(&mut panel.app(), "svgInteractivity.removeEvent", json!({"event": "onmouseover"}));
panel.frame();
assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM));
// A second document whose object has the same event: switching to it shows a row of the same
// name, which the menu must not carry over to.
{
let mut app = panel.app();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "1;"}));
app.run("window.nextDocument", json!({})).unwrap();
}
panel.frame();
panel.secondary_click("onclick: 1;");
assert!(panel.menu_item_enabled(tl!("Remove Event")));
panel.app().run("window.nextDocument", json!({})).unwrap();
panel.frame();
assert!(panel.shows("onclick: 1;"), "the other document lists the same event");
assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM));
}
}
@@ -77,6 +77,70 @@ fn the_console_footer_buttons_run_their_commands_at_minimum_width() {
assert!(!panel.enabled("Copy All"));
}
#[test]
fn the_row_menu_copies_its_line_or_the_selected_range_while_output_arrives() {
let mut app = app();
run(&mut app, "$.writeln('one'); $.writeln('two'); $.writeln('three')");
let mut panel = Panel::new(app, show);
panel.click("#1 c.js: one");
panel.click_with("#1 c.js: three", egui::Modifiers::SHIFT);
panel.secondary_click("#1 c.js: two");
run(&mut panel.app(), "$.writeln('later')");
panel.frame();
panel.click_menu_item("Copy Line");
assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: two"));
panel.secondary_click("#1 c.js: two");
panel.click_menu_item("Copy Selected");
assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: one\n#1 c.js: two\n#1 c.js: three"));
panel.secondary_click("#2 c.js: later");
panel.click_menu_item("Copy Selected");
assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#2 c.js: later"));
panel.secondary_click("#1 c.js: two");
panel.app().run("script.console.clear", json!({})).unwrap();
run(&mut panel.app(), "$.writeln('replacement')");
panel.frame();
assert!(!panel.shows("Copy Line"), "a replacement at the same row cannot inherit the menu");
}
#[test]
fn copy_line_follows_its_number_when_older_output_is_dropped() {
let mut app = app();
run(&mut app, "$.writeln('first'); $.writeln('target'); $.writeln('next')");
let mut panel = Panel::new(app, show);
panel.secondary_click("#1 c.js: target");
// Fill the console and evict its first line while the menu is open.
let free = vectorcraft_engine::script::console::MAX_CONSOLE_LINES - panel.app().session.script_console().lines().len();
// Each run also writes a start, an end and a report.
run(&mut panel.app(), &format!("for (var i = 0; i < {}; i++) $.writeln(i)", free - 2));
assert_eq!(panel.app().session.script_console().first_number(), 1);
panel.frame();
panel.click_menu_item("Copy Line");
assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: target"));
}
#[test]
fn the_focused_console_row_opens_its_menu_from_the_keyboard() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let mut app = app();
run(&mut app, "$.writeln('one')");
let mut panel = Panel::new(app, show);
panel.click("#1 c.js: one");
let list_focus = panel.ctx().memory(|memory| memory.focused()).expect("the console list has focus");
panel.key(Key::F10, Modifiers::SHIFT);
assert!(panel.menu_item_enabled("Copy Line"));
assert!(panel.menu_item_enabled("Copy Selected"));
panel.key(Key::Escape, Modifiers::NONE);
assert!(!panel.shows_role("Copy Line", Role::MENU_ITEM));
assert_eq!(panel.ctx().memory(|memory| memory.focused()), Some(list_focus));
}
#[test]
fn clear_works_during_a_run_and_the_run_goes_on_writing() {
let mut app = app();
+27
View File
@@ -614,12 +614,17 @@ fn every_context_label_is_a_menu_string() {
app.ui.context_spelling = None;
// The Lock Artboards and Unlock Artboards submenus of the Artboard tool.
app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 80})).unwrap();
app.run("artboard.new", json!({"x": 520, "y": 0, "width": 100, "height": 80})).unwrap();
app.run("artboard.setProps", json!({"index": 0, "locked": true})).unwrap();
app.select_tool("artboard");
shown.extend(labels(&app));
// Lock Selected with the artboard that isn't locked active.
crate::panels::artboards::select(&mut app, 1);
shown.extend(labels(&app));
// Unlock All has its own target when another locked artboard is outside the selection.
app.run("artboard.setProps", json!({"index": 2, "locked": true})).unwrap();
crate::panels::artboards::select(&mut app, 0);
shown.extend(labels(&app));
let missing: Vec<_> = shown.iter().filter(|l| !strings.contains(l.as_str())).collect();
assert!(missing.is_empty(), "context menu labels missing from menu_strings: {missing:?}");
for label in menus::CONTEXT_LABELS {
@@ -681,6 +686,28 @@ impl CanvasMenu {
}
}
#[test]
fn single_artboard_lock_submenus_open_and_apply_the_available_action() {
let mut app = app();
app.select_tool("artboard");
let mut canvas = CanvasMenu::new(app);
for (submenu, action, equivalent, locked) in
[("Lock Artboards", "Lock Selected", "Lock All", true), ("Unlock Artboards", "Unlock Selected", "Unlock All", false)]
{
canvas.right_click(100.0, 100.0);
let row = canvas.fixture.by_label(submenu).expect("the canvas offers the artboard submenu");
canvas.frame(vec![Event::PointerMoved(row.center())]);
canvas.fixture.advance(1.0);
canvas.frame(vec![]);
let row = canvas.fixture.by_label(action).expect("the submenu shows the action for the selected artboard");
assert!(canvas.fixture.by_label(equivalent).is_none(), "the same action has only one row");
canvas.fixture.click(&row);
canvas.frame(vec![]);
assert_eq!(canvas.app.borrow().session.active().unwrap().doc.artboards[0].locked, locked);
}
}
#[test]
fn create_outlines_from_the_canvas_menu_converts_selected_text_in_one_undo_step() {
let mut app = app();
+40
View File
@@ -2205,3 +2205,43 @@ fn every_action_the_bar_offers_can_be_turned_off() {
assert!(more, "{case}: the bar still shows its More Options");
}
}
/// The bar is outlined in the accent border color on the floating surface's corners, on the same rect where the surface
/// paints its own border.
#[test]
fn the_bar_is_outlined_in_the_accent_on_its_surface() {
use craft::theme::Tokens;
use craft::ui::runtime::env::Env;
use craft::ui::style::{UiTokens, rgba_color};
let mut tokens = None;
crate::testing::ui_context().run_ui(Default::default(), |ui| tokens = Some(Tokens::clone(Env::of(ui).tokens.tokens()))).textures_delta.clear();
let tokens = tokens.expect("the frame ran");
let accent = rgba_color(tokens.color.accent.border);
let corners = UiTokens::corner(tokens.shape.radius.window);
let mut app = app();
app.run("tool.select", json!({"tool": "selection"})).unwrap();
let ids = two_shapes(&mut app);
select(&mut app, &ids);
let (bar, outlines) = on_canvas(&mut app, |rig| {
let bar = rig.target(BAR).expect("the bar shows").rect;
let around = |r: Rect| r.expand(1.0).contains_rect(bar) && bar.expand(1.0).contains_rect(r);
let outlines: Vec<_> = rig
.fx
.frame_shapes()
.into_iter()
.filter_map(|shape| match shape {
egui::Shape::Rect(drawn) if drawn.stroke.width > 0.0 && around(drawn.rect) => {
Some((drawn.rect, drawn.stroke.color, drawn.corner_radius))
}
_ => None,
})
.collect();
(bar, outlines)
});
assert!(corners.nw > 0, "the floating surface has rounded corners: {corners:?}");
let edged = outlines.iter().find(|o| o.1 == accent).unwrap_or_else(|| panic!("the bar at {bar:?} has an accent outline: {outlines:?}"));
assert_eq!(edged.2, corners, "the accent outline takes the floating surface's corners");
let surface = outlines.iter().find(|o| o.1 != accent).unwrap_or_else(|| panic!("the surface paints its own border: {outlines:?}"));
assert_eq!(edged.0, surface.0, "the accent outline lies on the surface's own border");
}
@@ -267,6 +267,44 @@ impl Scene {
}
}
/// The pointer drifting a few points while the second press of a double click on a stop's marker is held leaves the
/// stop where it was, so the popover the double click opened stays open (#10560).
#[test]
fn gradient_stop_popover_stays_open_when_the_double_click_drifts() {
let _globals = GlobalState::new();
let mut scene = Scene::new(vec2(960.0, 720.0), false);
scene.idle(8);
let marker = scene.nodes.iter().filter(|n| n.label() == Some("Color stop 1 of 2")).find_map(Scene::node_rect).expect("the stop's marker");
let before = scene.snapshot();
let at = marker.center();
let button = |pos: Pos2, pressed: bool| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
scene.frame(vec![Event::PointerMoved(at)]);
for pressed in [true, false, true] {
scene.frame(vec![button(at, pressed)]);
}
assert!(scene.editor_open(), "the second press opens the popover");
let mut to = at;
for step in 1..=6 {
to = at + vec2(step as f32, 0.0);
scene.frame(vec![Event::PointerMoved(to)]);
}
scene.frame(vec![button(to, false)]);
scene.idle(3);
assert!(scene.editor_open(), "the popover stays open after the drift and the release");
assert_eq!(scene.snapshot(), before, "the drift moves no stop and records no undo step");
// A drag of its own, after the double click's time, moves the stop again.
scene.escape();
scene.idle(30);
scene.frame(vec![Event::PointerMoved(at)]);
scene.frame(vec![button(at, true)]);
for step in 1..=4 {
scene.frame(vec![Event::PointerMoved(at + vec2(15.0 * step as f32, 0.0))]);
}
scene.frame(vec![button(at + vec2(60.0, 0.0), false)]);
scene.idle(3);
assert!(scene.gradient().gradient.stops[0].offset > 0.0, "the next drag moves the stop");
}
#[test]
fn gradient_stop_mode_baseline_shift_and_menu_are_display_only() {
let _globals = GlobalState::new();
+4 -1
View File
File diff suppressed because one or more lines are too long
+12 -3
View File
@@ -4881,7 +4881,9 @@ carriage returns and the two together break lines, and other control characters
Pictures. The console keeps at most 2,048 lines and 1 MiB of text and drops the oldest lines past that. A line longer
than 4,096 bytes, and a script's name longer than 256 bytes, is cut with `…`. When the console has dropped or cut any lines, a note at the top counts them. The panel lays out only the
rows in view. Click a line to select it and Shift-click to extend the selection. Clear, Copy Selected and Copy All are
at the bottom of the panel and in its menu. Output goes on while the panel is closed.
at the bottom of the panel and in its menu. Right-click a selected line to keep the range. Choose Copy Line
to copy just that line, or Copy Selected to copy from the first selected line through the last. Right-clicking
an unselected line selects it. Output goes on while the panel is closed.
- `script.console {}` returns `{lines: [{run, name, kind, text}], droppedLines, truncatedLines}`. `run` is the
run's number in the session, and `kind` is `start`, `output`, `log`, `error`, `end` or `report`. An end line's text
@@ -11961,7 +11963,8 @@ every artboard, and Lock All Except Selected acts on the artboards that are not
that is not selected first selects it alone. An entry that cannot run is left out: Cut with a locked artboard or every
artboard selected, Delete Artboards with no artboard to delete, Select All Artboards with every artboard selected, Fit
to Artwork Bounds with no art on a selected unlocked artboard, Switch Orientation with no selected artboard to change,
and a lock entry with no artboard to change. The menu measures the art for Delete Empty Artboards and
and a lock entry with no artboard to change. When two lock or unlock entries would change the same artboards, the
menu shows the more specific action. The menu measures the art for Delete Empty Artboards and
Fit to Artwork Bounds once, at the right-click. Paste centers copied artboards on the right-click's point
(`edit.paste {artboardsAt: [x, y]}`) and centers copied objects there too (`center`). Chosen from a menu or the command
palette with the tool in use, `artboard.new` makes the new artboard active, `artboard.duplicate` selects the copies,
@@ -17080,7 +17083,13 @@ key holds a gradient or a pattern, the count is the largest distance between the
bounding-box edges divided by their mean width (left and right edges) or height (top and bottom), rounded, less one,
from 1 to 1000. Keys with no width or no height are measured by their other side, keys with neither in points, and
keys without bounds make 1 step. `starts` gives, per object, the anchor of its first subpath the blend starts
from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). With the
from (as the Blend tool's clicks on anchor points do; an open path's last anchor runs it the other way). Steps
between two live rectangles with the same corner kinds and the same rotation and reflection, and with no scale
or shear left in their transforms, are live rectangles whose width, height and drawn corner radii lie between
the keys', so their rounded corners stay circular arcs. The drawn radius is a key's radius fitted to its sides (a
20 by 10 key that stores a radius of 50 blends with a radius of 5). On a straight spine the steps' positions also
lie between the keys'; on an edited or replaced spine each step sits on the spine. Other path and live-shape pairs use anchor matching. A start anchor given in
`starts` for either key also sends live rectangles through anchor matching; an all-null `starts` does not. With the
Blend tool, `press_key` Escape drops the object clicked first and stops the next click adding to the blend
just made; the document and the selection stay as they are. A blend
among the objects takes the others in as more key objects, keeping its options, name, transparency and whether it
+2 -1
View File
@@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
- Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`.
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; once a script calls `setActiveArtboardIndex` on a document, untargeted paste and Fit to Artwork Bounds use that artboard instead of the Artboard tool's selection at the start of the run; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. A line's menu copies that line or the selected range. `crates/engine/src/tests/script_console.rs`.
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
- Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
@@ -2136,6 +2136,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
A double-click with the Live Paint Selection tool on a face selects it and the faces of its group that no stroked edge parts from it ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)), and on an edge selects it and the edges joined to it end to end that have its stroke paint ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)); Shift-double-click adds them to the selection or removes them from it. A triple-click on a face selects every face of its group with that face's fill, and on an edge every edge of its group that has its stroke paint ([the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)); hidden faces and edges are left out, and Shift-triple-click adds them to the selection or removes them from it.
When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`.
Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected.
Steps between two live rectangles with the same corner kinds, turned and reflected alike, are live rectangles whose sizes and drawn corner radii lie between the keys', so their rounded corners stay circular arcs (#10707). The drawn radii are the radii after each key's radius is fitted to its sides: a 20 by 10 key that stores a radius of 50 draws and blends with a radius of 5. On a straight spine the steps' positions also lie between the keys'; on an edited or replaced spine each step sits on the spine. A start point clicked on either key, a scale or shear left in a key's transform, and every other pair of paths keep anchor-by-anchor matching. Evidence: `blend::tests::steps_between_rounded_rectangles_keep_round_corners` in `crates/doc/src/blend.rs`.
The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`.
Blend Options on several selected blends (the Blend Options dialog, the Blend panel's Type, Ramp and Shift, and `object.blend.options`) sets only the values given or set in the dialog, and each blend keeps its own spacing, orientation, type, ramp and shift for the rest instead of taking the first blend's; a spacing mode given without a count keeps the count of a blend already in that mode. `object.blend.options {id}` edits that blend alone; a hidden or locked blend, an object that is not a blend, a value out of range and an unknown orientation are errors that change nothing, and a call that changes nothing records no undo step. A drag of the panel's Ramp or Shift slider previews on the canvas and records one undo step on release, and Type, Ramp and Reverse Spine are dimmed while a selected blend, or the blend of a key selected with Direct Selection, has no spine. Builds on #8022 by ruchirguitar. Evidence: `tests::blendopts::{options_on_several_blends_set_only_the_values_given, options_with_an_id_edit_that_blend_alone, options_that_change_nothing_or_are_refused_record_no_undo_step}`, `dialogs::blend_options::tests::on_several_blends_ok_sets_only_the_fields_changed` and `panels::tests_blend::{a_ramp_or_shift_drag_is_one_undo_step, ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options, ramp_is_dimmed_while_a_selected_blend_has_no_spine, ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_with_no_spine}`.
The Blend panel, the Object › Blend, Envelope Distort and Gradient Mesh menu items and their commands find each selected object's nearest blend, envelope or mesh by reading the object's place in the tree once, instead of looking up every ancestor by id, and the checks of whether one is selected stop at the first one found. The results, their order and the errors are the same. With Select All of 102,200 objects (100,000 rectangles, 2,000 blends and 200 envelopes in 10 layers), a release build took a median of 16.5 ms of thread CPU time for the Blend check before and 0.5 ms after, and 18.4 ms before and 8.2 ms after to list the selected blends. Evidence: `cmd::live::selected_tests` and `tests::lookups::nearest_finder_*`.
+3 -1
View File
File diff suppressed because one or more lines are too long
+44 -3
View File
@@ -5931,6 +5931,8 @@ fn screaming_or_camel(name: &str) -> bool {
fn inert(op: &str, local: &dyn Fn(&str) -> Option<bool>) -> Option<bool> {
let b = op.as_bytes();
let mut reads_local = false;
// Where the path that ends at the current name starts: `Vec` in `Vec::<u8>::new`.
let mut path_start = 0;
let mut i = 0;
while i < b.len() {
if !is_ident(b[i]) || b[i].is_ascii_digit() || (i > 0 && is_ident(b[i - 1])) {
@@ -5944,9 +5946,14 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option<bool>) -> Option<bool> {
}
let end = i + b[i..].iter().take_while(|&&c| is_ident(c)).count();
let name = &op[i..end];
let after = &op[end..];
// Turbofish arguments name types only, and the `(` after them makes a call of `name`.
let rest = skip_turbofish(b, end);
let after = &op[rest..];
let method = op[..i].ends_with('.') && !op[..i].ends_with("..");
let path_tail = op[..i].ends_with("::");
if !path_tail {
path_start = i;
}
if method {
if after.starts_with('(') && !FIXTURE_READS.contains(&name) {
return None;
@@ -5959,7 +5966,10 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option<bool>) -> Option<bool> {
}
} else if after.starts_with('(') {
let builder = ["Some", "Ok", "Err"].contains(&name)
|| (path_tail && ["Box::new", "String::from", "Vec::new"].iter().any(|p| op[..end].ends_with(p)))
|| (path_tail && {
let path = without_turbofish(&op[path_start..end]);
["Box::new", "String::from", "Vec::new"].iter().any(|p| path.ends_with(p))
})
|| (!path_tail && screaming_or_camel(name));
if !builder {
return None;
@@ -5974,11 +5984,28 @@ fn inert(op: &str, local: &dyn Fn(&str) -> Option<bool>) -> Option<bool> {
_ => return None,
}
}
i = end;
i = rest;
}
Some(reads_local)
}
/// `s` with every `::<…>` turbofish removed: `Vec::<u8>::new` becomes `Vec::new`.
fn without_turbofish(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
let next = if b[i..].starts_with(b"::<") { skip_turbofish(b, i) } else { i };
if next > i {
i = next;
} else {
out.push(b[i]);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// The initializer of the last immutable `let <name> = …;` in `body[..before]`: `None` when there is
/// none, `Some(None)` when the reaching binding is `mut`, a pattern or has no initializer. The
/// initializer comes with the offset of its `let`, where the names it reads are resolved.
@@ -8981,6 +9008,20 @@ mod tests {
assert_eq!(only("fixture-only", mut_pattern), [], "`mut n` in an `if let` binds `n`");
}
#[test]
fn echoes_read_through_turbofish_arguments() {
let empty = "#[test]\nfn t() {\n assert_eq!(Vec::<Amount>::new(), EXPECTED);\n}\n";
assert_eq!(only("constant-echo", empty), [(2, "constant-echo")], "a builder with a turbofish");
let later = "#[test]\nfn t() {\n assert_eq!(vec![Box::new(1), std::vec::Vec::<u8>::new()], EXPECTED);\n}\n";
assert_eq!(only("constant-echo", later), [(2, "constant-echo")], "a builder path after other elements");
let ok = "#[test]\nfn t() {\n assert_eq!(Ok::<_, String>(1), Ok(1));\n}\n";
assert_eq!(only("constant-echo", ok), [(2, "constant-echo")], "a variant with a turbofish");
let call = "#[test]\nfn t() {\n assert_eq!(parse::<u8>(\"1\"), 1);\n}\n";
assert_eq!(only("constant-echo", call), [], "a generic function called with a turbofish");
let method = "#[test]\nfn t() {\n let s = \"1\";\n assert_eq!(s.parse::<u8>(), Ok(1));\n}\n";
assert_eq!(only("fixture-only", method), [], "a method called with a turbofish");
}
#[test]
fn never_run_accepts_trailing_commas_in_cfg_predicates() {
for pred in ["not(unix,)", "not( unix , )", "all(not(unix,),)", "any(not(unix,),)"] {