diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b61d2429d0..e7ae30d3ca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,14 +89,15 @@ jobs: # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). # When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run - # failed jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg - # starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves - # 40 minutes for that. + # failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a + # free runner: the script fails when the leg has not started within 120 minutes, and then waits + # up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the + # script reports a leg that starts late with its own error before the job times out. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' runs-on: ubuntu-24.04 - timeout-minutes: 200 + timeout-minutes: 290 permissions: actions: write steps: diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index 200bbf3095..198e7dcc85 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -629,6 +629,15 @@ struct StartFile { record: StartRecord, } +impl Drop for StartFile { + /// Frees the lock when the start releases the file. A child process that any thread starts holds + /// a copy of the file's handle until it runs its program, and the lock is only freed by closing + /// every copy or by unlocking. + fn drop(&mut self) { + let _ = self.file.unlock(); + } +} + impl StartFile { /// Open `dir`'s [`START_FILE`], with the record the last start left in it (`None` when there is /// none or it can't be read). `Ok(None)` when another copy of the app holds it. diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index fe4a4ddcc5..792518993d 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -613,9 +613,7 @@ fn a_normal_exit_or_another_failure_does_not_restart() { assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into())); } -/// A log folder of its own for each test, and the guard that keeps other tests from starting a -/// program while it runs: the test releases the start file's lock and takes it again, and a child -/// starting meanwhile would keep it held (`crate::no_spawns`). +/// A log folder of its own for each test. struct TestDir(tempfile::TempDir); impl std::ops::Deref for TestDir { @@ -632,10 +630,23 @@ impl AsRef for TestDir { } } -fn start_dir(tag: &str) -> (TestDir, std::sync::RwLockReadGuard<'static, ()>) { - let spawns = crate::no_spawns(); - let dir = tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap(); - (TestDir(dir), spawns) +fn start_dir(tag: &str) -> TestDir { + TestDir(tempfile::Builder::new().prefix(&format!("vectorcraft-gpu-start-{tag}-")).tempdir().unwrap()) +} + +/// A start that ends frees the start file even while another handle to it is open, as a child +/// process that is starting holds one: the next start reads the file instead of taking it for +/// another copy of the app that is starting. +#[test] +fn an_ended_start_frees_the_start_file_while_a_copy_of_its_handle_is_open() { + let dir = start_dir("copy"); + let starting = Startup::default(); + starting.track(&dir, None, false); + let copy = starting.start.lock().unwrap().as_ref().map(|start| start.file.try_clone().unwrap()); + assert!(copy.is_some(), "the start holds the file"); + starting.ended(); + assert!(StartFile::open(&dir).unwrap().is_some(), "an ended start frees the start file"); + drop(copy); } /// What a start in `dir` leaves out; it then ends without crashing. @@ -661,7 +672,7 @@ fn issue_2243() -> Vec { /// it, without a status-bar note. #[test] fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() { - let (dir, _spawns) = start_dir("crash"); + let dir = start_dir("crash"); let c = issue_2243(); let first = Startup::default(); assert_eq!(first.track(&dir, None, false), LeftOut::default()); @@ -691,7 +702,7 @@ fn a_start_that_never_showed_a_frame_leaves_its_adapter_out_of_the_next() { /// an error, a restart on another adapter), leaves nothing out of the next. #[test] fn a_start_that_showed_its_first_frame_or_ended_is_cleared() { - let (dir, _spawns) = start_dir("shown"); + let dir = start_dir("shown"); let c = issue_2243(); for end in [Startup::presented as fn(&Startup), Startup::ended] { let first = Startup::default(); @@ -714,7 +725,7 @@ fn a_start_that_showed_its_first_frame_or_ended_is_cleared() { /// macOS, where wgpu has none. #[test] fn a_crash_while_listing_lists_opengl_alone() { - let (dir, _spawns) = start_dir("listing"); + let dir = start_dir("listing"); let first = Startup::default(); first.track(&dir, None, false); drop(first); @@ -740,7 +751,7 @@ fn a_crash_while_listing_lists_opengl_alone() { /// start shows its first frame on the adapter that crashed, the adapter counts again. #[test] fn wgpu_backend_or_adapter_name_ignores_the_crashes() { - let (dir, _spawns) = start_dir("explicit"); + let dir = start_dir("explicit"); let c = issue_2243(); let first = Startup::default(); first.track(&dir, None, false); @@ -760,7 +771,7 @@ fn wgpu_backend_or_adapter_name_ignores_the_crashes() { /// are ignored: the start goes on with nothing left out. #[test] fn a_damaged_or_unreadable_start_file_is_ignored() { - let (dir, _spawns) = start_dir("damaged"); + let dir = start_dir("damaged"); std::fs::create_dir_all(&dir).unwrap(); let damaged: [&[u8]; 9] = [ b"", diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 8907fe4bd1..872753f9d7 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -1034,19 +1034,5 @@ fn main() -> std::process::ExitCode { } } -/// Tests only: while a test starts another program, the child briefly holds a copy of every file -/// this process has open, until it runs that program. A file lock held through such a copy outlives -/// its own handle, so a GPU start test that released the start file and opened it again found it -/// still locked, as if another copy of the app were running, and failed. A test that starts a -/// program holds its write side; a test that depends on the start file's lock holds [`no_spawns`]. -#[cfg(all(test, feature = "wgpu"))] -static CHILD_SPAWN: std::sync::RwLock<()> = std::sync::RwLock::new(()); - -/// Held by a test that releases a locked file and opens it again (see [`CHILD_SPAWN`]). -#[cfg(all(test, feature = "wgpu"))] -fn no_spawns() -> std::sync::RwLockReadGuard<'static, ()> { - CHILD_SPAWN.read().unwrap_or_else(std::sync::PoisonError::into_inner) -} - #[cfg(all(test, feature = "wgpu"))] mod tests; diff --git a/apps/vectorcraft/src/nightly_session.rs b/apps/vectorcraft/src/nightly_session.rs index 5e24527592..b7416541ef 100644 --- a/apps/vectorcraft/src/nightly_session.rs +++ b/apps/vectorcraft/src/nightly_session.rs @@ -16,12 +16,38 @@ static SESSION: Mutex> = Mutex::new(None); static NOTICE_SHOWN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub struct Session { - _lease: File, + _lease: Lease, path: PathBuf, own_record: Vec, previous_unclean: bool, } +/// The profile's [`LEASE`], open and locked. +struct Lease(File); + +impl Lease { + /// Lock `root`'s [`LEASE`]: `None` when another window of the same profile holds it. + fn take(root: &Path) -> io::Result> { + let lease_path = root.join(LEASE); + regular_or_missing(&lease_path)?; + let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; + match lease.try_lock() { + Ok(()) => Ok(Some(Self(lease))), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), + Err(std::fs::TryLockError::Error(error)) => Err(error), + } + } +} + +impl Drop for Lease { + /// Frees the lease when the session ends, or when a session could not be started after the lock + /// was taken. A child process that any thread starts holds a copy of the lease's handle until it + /// runs its program, and the lock is only freed by closing every copy or by unlocking. + fn drop(&mut self) { + let _ = self.0.unlock(); + } +} + fn regular_or_missing(path: &Path) -> io::Result { match std::fs::symlink_metadata(path) { Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true), @@ -73,14 +99,13 @@ impl Session { if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) { return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large")); } - let lease_path = root.join(LEASE); - regular_or_missing(&lease_path)?; - let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?; - match lease.try_lock() { - Ok(()) => {} - Err(std::fs::TryLockError::WouldBlock) => return Ok(None), - Err(std::fs::TryLockError::Error(error)) => return Err(error), - } + let Some(lease) = Lease::take(root)? else { return Ok(None) }; + Self::record(lease, root, version, commit).map(Some) + } + + /// Write this launch's record while `lease` is held. On an error `lease` is dropped, which + /// unlocks it. + fn record(lease: Lease, root: &Path, version: &str, commit: Option<&str>) -> io::Result { let path = root.join(RECORD); let previous_unclean = regular_or_missing(&path)?; let own_record = serde_json::to_vec(&serde_json::json!({ @@ -90,7 +115,7 @@ impl Session { "commit": commit.filter(|value| !value.is_empty()), }))?; atomic_write_no_follow(&path, &own_record)?; - Ok(Some(Self { _lease: lease, path, own_record, previous_unclean })) + Ok(Self { _lease: lease, path, own_record, previous_unclean }) } pub fn previous_unclean(&self) -> bool { @@ -258,6 +283,54 @@ mod tests { assert!(!fixture.0.join(RECORD).exists(), "a controlled return clears its record"); } + #[test] + fn an_ended_session_frees_the_lease_while_a_copy_of_its_handle_is_open() { + let fixture = Fixture::new(); + let first = Session::begin(Some(&fixture.0), "first", None).unwrap().unwrap(); + // A child process that is starting holds such a copy. + let first_copy = first._lease.0.try_clone().unwrap(); + first.complete().unwrap(); + let second = Session::begin(Some(&fixture.0), "second", None).unwrap(); + assert!(second.is_some(), "a completed session frees the lease"); + let second_copy = second.as_ref().map(|session| session._lease.0.try_clone().unwrap()); + drop(second); + assert!(Session::begin(Some(&fixture.0), "third", None).unwrap().is_some(), "a dropped session frees the lease"); + drop((first_copy, second_copy)); + } + + /// `root`'s lease, locked as [`Session::begin`] locks it, and a copy of its handle such as a + /// child process that is starting holds. + fn locked_with_a_copy(root: &Path) -> (Lease, File) { + let lease = Lease::take(root).unwrap().unwrap(); + let copy = lease.0.try_clone().unwrap(); + (lease, copy) + } + + #[test] + fn a_session_that_cannot_check_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() { + let fixture = Fixture::new(); + std::fs::create_dir(fixture.0.join(RECORD)).unwrap(); + let (lease, copy) = locked_with_a_copy(&fixture.0); + assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "a folder is not a record"); + std::fs::remove_dir(fixture.0.join(RECORD)).unwrap(); + assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to check its record frees the lease"); + drop(copy); + } + + #[test] + fn a_session_that_cannot_write_its_record_frees_the_lease_while_a_copy_of_its_handle_is_open() { + let fixture = Fixture::new(); + // A folder at the temporary file's name makes the write fail after the record was checked. + let temporary = fixture.0.join(format!(".{RECORD}.{}.tmp", std::process::id())); + std::fs::create_dir(&temporary).unwrap(); + let (lease, copy) = locked_with_a_copy(&fixture.0); + assert!(Session::record(lease, &fixture.0, "nightly", None).is_err(), "the record cannot be written"); + assert!(!fixture.0.join(RECORD).exists()); + std::fs::remove_dir(&temporary).unwrap(); + assert!(Session::begin(Some(&fixture.0), "next", None).unwrap().is_some(), "a session that failed to write its record frees the lease"); + drop(copy); + } + #[test] fn cleanup_never_removes_an_unknown_changed_record() { let fixture = Fixture::new(); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 8f1b50dd58..b2d79faaed 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -145,6 +145,8 @@ mod tests { #[test] fn the_font_scans_read_the_fonts_folder_next_to_the_settings() { + // No test installs a launch's root in this process, so the settings folder stays the same here. + assert_eq!(profile::data_root(), None, "a test installed a launch's root beside the others"); install_fonts(); let fonts = prefs_dir().map(|dir| dir.join("Fonts")); assert!(fonts.is_some(), "a home folder to keep the settings in"); diff --git a/apps/vectorcraft/src/profile.rs b/apps/vectorcraft/src/profile.rs index 9b3a671c70..ad14e07a86 100644 --- a/apps/vectorcraft/src/profile.rs +++ b/apps/vectorcraft/src/profile.rs @@ -457,10 +457,35 @@ mod tests { } } - /// Installs the process-wide root: the one test that may, since a `OnceLock` is set once per - /// process (nextest gives every test its own). + /// Runs the test `name` of this module again in a child process of the test binary → whether + /// this is that child. For a test that installs the process-wide root, which every test running + /// beside it would then read as the settings folder. + fn in_own_process(name: &str) -> bool { + const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS"; + if std::env::var_os(CHILD).is_some() { + return true; + } + // The test's path without the crate's name: the desktop app and `vectorcraft-cli` both build this file. + let module = module_path!().split_once("::").map_or(module_path!(), |(_, path)| path); + let path = format!("{module}::{name}"); + let output = + std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", &path, "--nocapture"]).env(CHILD, "1").output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "{path} failed in its own process:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + false + } + + /// Installs the process-wide root, which a `OnceLock` holds once per process, so the test runs in + /// a process of its own. #[test] fn the_installed_root_is_used_once_and_must_be_absolute() { + if !in_own_process("the_installed_root_is_used_once_and_must_be_absolute") { + return; + } let dir = temp("installed-root"); assert!(install_data_root(PathBuf::from("relative/root")).is_err(), "a relative root is refused"); install_data_root(dir.to_path_buf()).unwrap(); diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6cd009ca54..121f12aaeb 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -81,6 +81,11 @@ pub struct HitOptions { /// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`]) /// hit the art on a layer whose Preview is off as painted, not in outline. pub ignore_layer_preview: bool, + /// The selection tools: where a click hits nothing else, a closed path or compound path with + /// no fill is hit inside its closed subpaths, the topmost first, as a filled one is. Off with + /// [`Self::path_only`] and in outline. Clipping paths and guides are still hit on their + /// outline only. [`hit_test`] and [`objects_at`] try every other object first. + pub unfilled_interiors: bool, } impl Default for HitOptions { @@ -94,6 +99,7 @@ impl Default for HitOptions { clip_outlines: false, area_type_interior: false, ignore_layer_preview: false, + unfilled_interiors: false, scope: None, } } @@ -417,11 +423,35 @@ impl Drop for DrawnOff { } } +thread_local! { + /// Whether a clipping path is being tested ([`InMask`]). + static IN_MASK: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While a guard lives, a clipping path is tested: it is not hit inside by its interior alone +/// ([`takes_interior`]). +struct InMask { + was: bool, +} + +impl InMask { + fn set() -> Self { + Self { was: IN_MASK.replace(true) } + } +} + +impl Drop for InMask { + fn drop(&mut self) { + IN_MASK.set(self.was); + } +} + /// `f()`, with `mask` under a [`DrawnOff`] guard: the clipping path of a clip group or of a /// clipping layer is clicked and touched by its own geometry, whatever its geometry effects do to -/// the region it clips to. +/// the region it clips to. It is also under an [`InMask`] guard. fn plain(mask: bool, f: impl FnOnce() -> T) -> T { let _off = mask.then(DrawnOff::set); + let _mask = mask.then(InMask::set); f() } @@ -636,17 +666,23 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option bool, editable_only: bool) -> Option { + let painted = hit_test_walk(doc, p, HitOptions { unfilled_interiors: false, ..opt }, skip, editable_only); + if painted.is_some() || !opt.unfilled_interiors || opt.path_only || opt.outline { + return painted; + } + hit_test_walk(doc, p, opt, skip, editable_only) +} + +/// One walk of [`hit_test_skipping`], with `opt` as given. +fn hit_test_walk(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option { let _walk = ArtWalk::open(); let finish = |mut h: Hit| { h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents)); @@ -1524,7 +1571,10 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: & return false; } } - hit_order(n, children, p).any(|i| children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept))) + hit_order(n, children, p).any(|i| { + let _mask = (i == 0 && n.clips()).then(InMask::set); + children.get(i).is_some_and(|c| !shaper_hides(n, i, None) && art_hit(c, p, opt, symbols, accept)) + }) } _ => hit_leaf(n, p, opt, symbols).is_some_and(|kind| accept(n.id, kind)), } @@ -1622,6 +1672,8 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio match &n.kind { NodeKind::Path { path, rule, .. } => { let has_fill = n.appearance.has_visible_fill(); + let interior = !has_fill && path.subpaths.iter().any(|sp| sp.closed) && takes_interior(n, opt); + let inside = || (interior && fill_contains(&closed_subpaths_at([path], p), *rule, p)).then_some(HitKind::Fill); if opt.outline && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) { @@ -1656,7 +1708,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio return Some(HitKind::Stroke); } if !near_decoration { - return None; + return inside(); } } let bp = path.to_bezpath(); @@ -1666,7 +1718,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) { return Some(HitKind::Fill); } - None + inside() } NodeKind::Compound { children, rule } => { // Painted strokes follow the whole compound path (alignment, dashes, width profiles): @@ -1684,7 +1736,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { return Some(HitKind::Outline); } - (!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) + if n.appearance.has_visible_fill() { + return (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill); + } + let closed = || closed_subpaths_at(children.iter().filter_map(|m| m.path_data()), p); + (takes_interior(n, opt) && fill_contains(&closed(), *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { @@ -1756,6 +1812,30 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } } +/// Is path or compound path `n`, which has no visible fill, hit inside its closed subpaths +/// ([`HitOptions::unfilled_interiors`])? Not a clipping path ([`InMask`]) or a guide. +fn takes_interior(n: &Node, opt: HitOptions) -> bool { + opt.unfilled_interiors + && !opt.outline + && !opt.path_only + && !IN_MASK.get() + && !matches!(n.kind, NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. }) +} + +/// The closed subpaths of `paths` whose control points' box holds `p`, as one path. A path outside +/// that box winds zero times round `p`, so this path's fill holds `p` as all the closed subpaths' +/// fill does. Open subpaths are left out: they bound no area. +fn closed_subpaths_at<'a>(paths: impl IntoIterator, p: Point) -> BezPath { + let holds = |b: Rect| b.x0 <= p.x && p.x <= b.x1 && b.y0 <= p.y && p.y <= b.y1; + let mut bp = BezPath::new(); + for pd in paths.into_iter().filter(|pd| pd.control_bounds().is_some_and(holds)) { + for sp in pd.subpaths.iter().filter(|sp| sp.closed) { + sp.to_bezpath_into(&mut bp); + } + } + bp +} + /// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a /// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a /// stroke along its shape, a fill inside it except with Selection by Path Only. @@ -2032,13 +2112,23 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a /// symbol instance or no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { - let _walk = ArtWalk::open(); + let walk = ArtWalk::open(); let outline = opt.outline || below_preview_off(doc, inst, opt.scope); let art = InstanceArt::drawn(doc, inst, outline)?; let symbols = doc.kept_symbol_boxes(); - let mut path = vec![]; - let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true }; - find.find(&art.art, &mut path, None, outline).map(|_| path) + let pick = |opt: HitOptions| { + let mut path = vec![]; + let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true }; + find.find(&art.art, &mut path, None, outline).map(|_| path) + }; + // As [`hit_test`] does: inside an unfilled closed path only where nothing else is hit. + pick(HitOptions { unfilled_interiors: false, ..opt }).or_else(|| { + if !opt.unfilled_interiors || opt.path_only || outline { + return None; + } + walk.restart(); + pick(opt) + }) } /// The walk of a symbol instance's placed art that [`symbol_part_at`] and [`instance_art_hit`] make. diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 071138d0de..7ac945e4ee 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -38,6 +38,168 @@ fn unfilled_interior_misses() { assert!(hit_test(&d, Point::new(50.5, 25.0), HitOptions::default()).is_some()); } +/// The selection tools' options with unfilled closed paths hit inside. +const INTERIORS: HitOptions = HitOptions { unfilled_interiors: true, ..SELECTING }; + +/// A path of `points` with a black stroke and no fill, inserted at the top of the first layer. +fn stroked(d: &mut Document, points: &[(f64, f64)], closed: bool) -> NodeId { + let l = d.layers[0].id; + let id = d.alloc_id(); + let pts: Vec = points.iter().map(|&(x, y)| Point::new(x, y)).collect(); + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed)); + d.insert(Some(l), 99, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap(); + id +} + +const FRAME: [(f64, f64); 4] = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + +#[test] +fn an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline() { + let mut d = Document::new(200.0, 200.0); + let frame = stroked(&mut d, &FRAME, true); + let at = |opt: HitOptions| hit_test(&d, Point::new(50.0, 50.0), opt).map(|h| h.leaf); + assert_eq!(at(INTERIORS), Some(frame)); + assert_eq!(at(SELECTING), None, "without the option, the interior misses"); + assert_eq!(at(HitOptions { path_only: true, ..INTERIORS }), None, "Object Selection by Path Only"); + assert_eq!(at(HitOptions { outline: true, ..INTERIORS }), None, "Outline view"); + assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![frame]); + assert!(objects_at(&d, Point::new(150.0, 50.0), INTERIORS, None).is_empty(), "outside it"); +} + +#[test] +fn an_open_path_is_not_hit_inside() { + let mut d = Document::new(200.0, 200.0); + stroked(&mut d, &FRAME, false); + assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None); +} + +/// What a click paints over comes first: an object drawn inside an unfilled frame above it is hit +/// where it paints, and the frame elsewhere inside; Select Behind lists the frame after it. +#[test] +fn art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let dot = d.alloc_id(); + d.insert(Some(l), 0, Node::path(dot, shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art())).unwrap(); + let frame = stroked(&mut d, &FRAME, true); + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf); + assert_eq!(at(&d, 50.0), Some(dot)); + assert_eq!(at(&d, 20.0), Some(frame)); + assert_eq!(objects_at(&d, Point::new(50.0, 50.0), INTERIORS, None), vec![dot, frame]); + // The topmost of two unfilled frames is hit inside both. + let inner = stroked(&mut d, &[(10.0, 10.0), (90.0, 10.0), (90.0, 90.0), (10.0, 90.0)], true); + assert_eq!(at(&d, 20.0), Some(inner)); + assert_eq!(at(&d, 5.0), Some(frame)); +} + +#[test] +fn an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes() { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look())); + let (id, outer, hole) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let members = vec![ring(outer, Rect::new(0.0, 0.0, 100.0, 100.0)), ring(hole, Rect::new(30.0, 30.0, 70.0, 70.0))]; + let mut compound = Node::new(id, NodeKind::Compound { children: members, rule: FillRule::EvenOdd }); + compound.appearance = look().into(); + d.insert(Some(l), 0, compound).unwrap(); + let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf); + assert_eq!(at(15.0), Some(id)); + assert_eq!(at(50.0), None, "in the hole"); +} + +#[test] +fn guides_and_clipping_paths_are_not_hit_inside() { + let mut d = Document::new(200.0, 200.0); + let guide = stroked(&mut d, &FRAME, true); + if let Some(NodeKind::Path { guide: g, .. }) = d.node_mut(guide).map(|n| &mut n.kind) { + *g = true; + } + assert_eq!(hit_test(&d, Point::new(50.0, 50.0), INTERIORS), None, "a guide"); + // A clip group whose art covers only part of its unfilled clipping path. + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut mask = Node::path(clip, shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::None, Paint::None, 0.0)); + if let NodeKind::Path { clipping, .. } = &mut mask.kind { + *clipping = true; + } + let picture = Node::path(art, shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 100.0)), Appearance::default_art()); + d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(mask), Arc::new(picture)], clip: true })).unwrap(); + let at = |x: f64| hit_test(&d, Point::new(x, 50.0), INTERIORS).map(|h| h.leaf); + assert_eq!(at(25.0), Some(art)); + assert_eq!(at(75.0), None, "inside the mask where no art paints"); + assert!(objects_at(&d, Point::new(75.0, 50.0), INTERIORS, None).is_empty()); +} + +/// A repeat's copies of an unfilled frame are hit inside, and the copies of a clip group's unfilled +/// compound clipping path are not. +#[test] +fn a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks() { + let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let kind = crate::pattern::RepeatKind::Grid { + h_spacing: 20.0, + v_spacing: 20.0, + rows: 1, + cols: 2, + grid_type: crate::pattern::TileType::Grid, + flip_rows: false, + flip_cols: false, + }; + let repeat = |d: &mut Document, source: Node| { + let r = d.alloc_id(); + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::new(r, NodeKind::Repeat(crate::pattern::RepeatSpec { kind: kind.clone(), source: vec![Arc::new(source)] }))) + .unwrap(); + r + }; + // Copies at 0..40 and 60..100. + let mut d = Document::new(300.0, 200.0); + let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), look()); + let r = repeat(&mut d, frame); + assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r)); + assert_eq!(hit_test(&d, Point::new(50.0, 20.0), INTERIORS), None, "between the copies"); + let mut d = Document::new(300.0, 200.0); + let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look())); + let members = vec![ring(d.alloc_id(), Rect::new(0.0, 0.0, 40.0, 40.0)), ring(d.alloc_id(), Rect::new(5.0, 5.0, 35.0, 35.0))]; + let mut mask = Node::new(d.alloc_id(), NodeKind::Compound { children: members, rule: FillRule::NonZero }); + mask.appearance = look().into(); + let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 40.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]); + clip.set_clips(true); + let r = repeat(&mut d, clip); + assert_eq!(hit_test(&d, Point::new(65.0, 20.0), INTERIORS).map(|h| h.leaf), Some(r), "on the clipped art"); + assert_eq!(hit_test(&d, Point::new(80.0, 20.0), INTERIORS), None, "inside the mask where no art paints"); +} + +/// Direct Selection in a dynamic symbol's art picks parts as a click on the document does: what +/// paints first, then an unfilled frame inside; an unfilled compound clipping path by its outline. +#[test] +fn symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let look = || Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0)), Appearance::default_art()); + let frame = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look()); + let ring = |id, r: Rect| Arc::new(Node::path(id, shapes::rectangle(r), look())); + let (mask_id, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let members = vec![ring(a, Rect::new(150.0, 0.0, 250.0, 100.0)), ring(b, Rect::new(160.0, 10.0, 240.0, 90.0))]; + let mut mask = Node::new(mask_id, NodeKind::Compound { children: members, rule: FillRule::NonZero }); + mask.appearance = look().into(); + let picture = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 0.0, 180.0, 100.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(picture)]); + clip.set_clips(true); + let root = Node::group(d.alloc_id(), vec![Arc::new(dot), Arc::new(frame), Arc::new(clip)]); + d.symbols.push(crate::Symbol { dynamic: true, name: "Framed".into(), art: Arc::new(root) }); + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Framed".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + let n = d.node(inst).unwrap(); + let at = |x: f64| symbol_part_at(&d, n, Point::new(x, 50.0), INTERIORS); + assert_eq!(at(50.0), Some(vec![0]), "the dot under the frame"); + assert_eq!(at(20.0), Some(vec![1]), "inside the frame"); + assert_eq!(at(220.0), None, "inside the clipping path where no art paints"); +} + #[test] fn long_plain_stroke_hits_its_middle_and_curved_end() { let mut d = Document::new(200.0, 200.0); @@ -1464,6 +1626,7 @@ const SELECTING: HitOptions = HitOptions { clip_outlines: true, area_type_interior: false, ignore_layer_preview: false, + unfilled_interiors: false, scope: None, }; diff --git a/crates/doc/src/placed_document.rs b/crates/doc/src/placed_document.rs index d72048dc0a..ef627c6840 100644 --- a/crates/doc/src/placed_document.rs +++ b/crates/doc/src/placed_document.rs @@ -380,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>; static LOADER: OnceLock = OnceLock::new(); +std::thread_local! { + /// Open checks use previews rather than loading placed documents for drawing. + static PREVIEWS_ONLY: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Restores whether only previews are used when an open check ends, including on unwind. +struct PreviewsOnly(bool); + +impl Drop for PreviewsOnly { + fn drop(&mut self) { + PREVIEWS_ONLY.with(|p| p.set(self.0)); + } +} + +/// Run an open check using placed documents' previews instead of loading their art on this +/// thread. Nested checks keep the scope active until the outer check ends. This prevents an +/// open check and drawing from recursively loading each other's nested files. +pub fn with_previews(check: impl FnOnce() -> T) -> T { + let _scope = PreviewsOnly(PREVIEWS_ONLY.with(|p| p.replace(true))); + check() +} + /// Register how files are read (the first registration stays). pub fn set_loader(l: Loader) { // Already set: the same loader, registered by another session. @@ -454,8 +476,12 @@ impl Cache { } /// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a -/// placed document from. `None` when it can't be read (or no loader is registered). +/// placed document from. `None` when it can't be read, no loader is registered, or an open check +/// uses [`with_previews`]. pub fn read(p: &PlacedDocument, bytes: &Arc>) -> Option> { + if PREVIEWS_ONLY.with(std::cell::Cell::get) { + return None; + } if let Some(e) = cache().get(&p.key, false, Some(bytes)) { return Some(e); } @@ -738,6 +764,22 @@ mod tests { Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0))) } + /// Nested open checks skip both new and cached art, and restore ordinary reads afterward. + #[test] + fn open_checks_leave_placed_documents_for_drawing_afterward() { + set_loader(stub_loader); + let p = placed("open-check-1"); + let bytes = Arc::new(b"leaf".to_vec()); + with_previews(|| assert!(read(&p, &bytes).is_none())); + assert!(read(&p, &bytes).is_some()); + with_previews(|| { + assert!(read(&p, &bytes).is_none()); + with_previews(|| assert!(read(&p, &bytes).is_none())); + assert!(read(&p, &bytes).is_none()); + }); + assert!(read(&p, &bytes).is_some()); + } + /// A color-masked image in a placed document's art keeps its masked pixels under the prefixed /// names its resources get. #[test] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index eb751c26d2..4d576cf153 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -122,7 +122,8 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF, and the work its import takes. vectorcraft-pdf = { workspace = true, features = ["read-count"] } -# The work `.ai` blends take to be checked and made live. +# The work `.ai` blends take to be checked and made live, and how many included EPS open checks +# an open performs. vectorcraft-eps = { workspace = true, features = ["work-count"] } # How many times the symbol list is read to find symbols by name, and how many objects are # measured against locked artboards. diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index 820572287f..ef9cd71850 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -333,11 +333,18 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec = const { std::cell::Cell::new(0) }; +} + /// The box around the control points of `s`, which holds all of `s`. fn control_box(s: CubicBez) -> Rect { Rect::from_points(s.p0, s.p1).union_pt(s.p2).union_pt(s.p3) @@ -529,13 +536,24 @@ fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize { /// Samples along the part of `c` from `t0` to `t1`, in order: (t, whether the point there is within /// `radius` of the stretches `of` of the drag `pts`). A piece no stretch comes near gives one sample /// out of reach; the others are halved until their control polygon is no longer than half the -/// reach, or until `budget` pieces have been measured, and then give one sample: in reach at the -/// piece's middle or at its place nearest the drag when either is in reach, otherwise out of reach -/// at its middle. Each piece measures only the stretches near +/// reach, or until fewer than the two halves are left in this segment's `budget` or in `shared`, +/// the pieces the whole drag may still measure past the first piece of each segment, and then give +/// one sample: in reach at the piece's middle or at its place nearest the drag when either is in +/// reach, otherwise out of reach at its middle. Both halves of a piece are taken from `budget` and +/// from `shared` before either is measured, so a search measures no more than one piece besides +/// what it takes from them. Each piece measures only the stretches near /// the piece it was cut from, so a long drag along a long curve costs about one pass over the drag /// per halving, plus the stretches near each piece. -fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usize]), radius: f64, budget: &mut usize, out: &mut Vec<(f64, bool)>) { - *budget = budget.saturating_sub(1); +fn reach_samples( + c: CubicBez, + (t0, t1): (f64, f64), + (pts, of): (&[Point], &[usize]), + radius: f64, + (budget, shared): (&mut usize, &mut usize), + out: &mut Vec<(f64, bool)>, +) { + #[cfg(test)] + PIECES_MEASURED.set(PIECES_MEASURED.get() + 1); let s = c.subsegment(t0..t1); let mid = 0.5 * (t0 + t1); let near = stretches_near(pts, of, control_box(s), radius); @@ -544,7 +562,7 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz return; } let len = s.p0.distance(s.p1) + s.p1.distance(s.p2) + s.p2.distance(s.p3); - if len <= (radius / 2.0).max(1e-3) || *budget == 0 || mid <= t0 || mid >= t1 { + if len <= (radius / 2.0).max(1e-3) || *budget < 2 || *shared < 2 || mid <= t0 || mid >= t1 { // The piece's middle, or the place on it nearest the drag when the middle is out of reach. let sample = if dist_to_stretches(pts, &near, c.eval(mid)) <= radius { (mid, true) @@ -555,8 +573,10 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz out.push(sample); return; } - reach_samples(c, (t0, mid), (pts, &near), radius, budget, out); - reach_samples(c, (mid, t1), (pts, &near), radius, budget, out); + *budget -= 2; + *shared -= 2; + reach_samples(c, (t0, mid), (pts, &near), radius, (&mut *budget, &mut *shared), out); + reach_samples(c, (mid, t1), (pts, &near), radius, (budget, shared), out); } /// `sp` cut where the reach of the drag crosses its curved segments, and whether each @@ -565,8 +585,11 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz /// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a /// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between /// stay as they are. A segment is searched no more than half the reach apart where it comes within -/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment. -fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec) { +/// the reach of the drag ([`reach_samples`]): each curved segment is measured whole, and then up +/// to `share` more pieces of it are measured while the drag's `shared` pieces last, so the segments +/// in reach share the search equally whatever order they come in, and a segment searched after +/// the pieces run out is still found where its middle or its place nearest the drag is in reach. +fn mark_reached(sp: &SubPath, reach: &DragReach, (share, shared): (usize, &mut usize)) -> (SubPath, Vec) { let (pts, radius) = (reach.pts, reach.radius); let n = sp.anchors.len(); let marked: Vec = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect(); @@ -578,7 +601,7 @@ fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec< let c = sp.segment(i); let (mut samples, mut budget) = (vec![], share); let near = reach.near_rect(control_box(c.subsegment(0.0..1.0))); - reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples); + reach_samples(c, (0.0, 1.0), (pts, &near), radius, (&mut budget, &mut *shared), &mut samples); // Stretches of samples alike, in order: (in reach, first, last). let mut runs: Vec<(bool, usize, usize)> = vec![]; for (k, s) in samples.iter().enumerate() { @@ -623,15 +646,16 @@ fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec< /// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach. /// A closed path whose first anchor is in reach starts at the point of the refitted path nearest -/// that anchor's place (VectorCraft's own rule). -fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option { +/// that anchor's place (VectorCraft's own rule). `search` is each curved segment's share of the +/// drag's search and the pieces the drag has left ([`mark_reached`]). +fn smooth_subpath(sp: &SubPath, reach: &DragReach, search: (usize, &mut usize), tol: f64, sigma: f64) -> Option { if sp.anchors.len() < 2 { return None; } let radius = reach.radius; let near = &|q: Point| reach.in_reach(q, 0.0); // A drag along a segment smooths it even when its anchors are out of reach. - let (sp, marked) = mark_reached(sp, reach, share); + let (sp, marked) = mark_reached(sp, reach, search); let sp = &sp; if !marked.iter().any(|m| *m) { return None; @@ -948,15 +972,17 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { paths.push((id, path_of(&st.doc, id)?.0)); } let reach = DragReach::new(&pts, radius); - // Each curved segment in reach gets the same share of the search, whatever order they come in. + // Each curved segment in reach gets the same share of the search, whatever order they come in, + // and all of them together measure no more than `MAX_REACH_PIECES` pieces past their first. let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum(); let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1); + let mut shared = MAX_REACH_PIECES; for (id, pd) in paths { let mut changed = false; let subs: Vec = pd .subpaths .iter() - .map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) { + .map(|sp| match smooth_subpath(sp, &reach, (share, &mut shared), tol, sigma) { Some(n) if n != *sp && n.anchors.len() >= 2 => { changed = true; n @@ -1304,19 +1330,106 @@ mod tests { assert_eq!(start_nearest(ring(), Point::new(f64::NAN, 0.0), &ring()), ring()); } + /// How many pieces `f` makes [`reach_samples`] measure on this thread. + fn pieces_measured(f: impl FnOnce()) -> usize { + let before = PIECES_MEASURED.get(); + f(); + PIECES_MEASURED.get() - before + } + /// Searching a curve 1,000,000 pt long under a drag of 1,000 points along it measures no more - /// pieces than the budget it is given, and a search with none left gives one sample. + /// than one piece besides the drag's `MAX_REACH_PIECES`, counting the pieces it halves as well + /// as those it samples, and a search with none of the drag's pieces left measures the curve + /// once and gives one sample, whatever share of its own it has. #[test] fn searching_a_segment_under_a_drag_stays_within_its_budget() { let c = CubicBez::new(Point::new(0.0, 0.0), Point::new(300000.0, 0.0), Point::new(700000.0, 0.0), Point::new(1000000.0, 0.0)); let pts: Vec = (0..1000).map(|i| Point::new(f64::from(i) * 1000.0, 0.0)).collect(); let all = drag_stretches(&pts); - let mut budget = MAX_REACH_PIECES; + let (mut budget, mut shared) = (MAX_REACH_PIECES, MAX_REACH_PIECES); let (mut first, mut second) = (vec![], vec![]); - reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut first); - reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, &mut budget, &mut second); - assert!(first.len() <= MAX_REACH_PIECES, "{} samples", first.len()); - assert_eq!((budget, second.len()), (0, 1), "the budget is spent, so the next search gives one sample"); + let measured = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut budget, &mut shared), &mut first)); + assert!(measured <= MAX_REACH_PIECES + 1, "{measured} pieces measured"); + assert!(first.len() <= measured && first.len() > 1, "{} samples", first.len()); + assert!(shared < 2, "{shared} pieces left"); + let mut fresh = MAX_REACH_PIECES; + let again = pieces_measured(|| reach_samples(c, (0.0, 1.0), (&pts, &all), 12.0, (&mut fresh, &mut shared), &mut second)); + assert_eq!((again, second.len()), (1, 1), "the drag's pieces are spent, so the next search gives one sample"); + } + + /// One curved segment `w` pt wide from `(x, y)`, bowed `h` pt up. + fn bow((x, y): (f64, f64), w: f64, h: f64) -> CubicBez { + CubicBez::new(Point::new(x, y), Point::new(x + w / 3.0, y + h), Point::new(x + 2.0 * w / 3.0, y + h), Point::new(x + w, y)) + } + + /// An open subpath of the curved segments `segs`, each starting where the one before ends. + fn chain(segs: &[CubicBez]) -> SubPath { + let mut anchors: Vec = vec![]; + for s in segs { + match anchors.last_mut() { + Some(last) => *last = Anchor::with_handles(s.p0, last.h_in, s.p1), + None => anchors.push(Anchor::with_handles(s.p0, s.p0, s.p1)), + } + anchors.push(Anchor::with_handles(s.p3, s.p2, s.p3)); + } + SubPath::new(anchors, false) + } + + /// A drag along two subpaths of 21,845 curved segments 100 pt long each, which share the search + /// three pieces to a segment, and past a third of 1,000 curved segments far from the drag: every + /// segment is measured whole and the whole drag measures no more than `MAX_REACH_PIECES` pieces + /// past those, though each segment in reach would halve its pieces while its share lasts. Each + /// segment in reach, the last one included, is halved once with its share of three, so the + /// segments searched first leave the later ones their share. + #[test] + fn a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each() { + let row = |(x, y): (f64, f64), n: u32| chain(&(0..n).map(|i| bow((x + f64::from(i) * 100.0, y), 100.0, 8.0)).collect::>()); + let subs = [row((0.0, 0.0), 21_845), row((3_000_000.0, 0.0), 21_845), row((0.0, 1e6), 1000)]; + let pts = [Point::new(-10.0, 0.0), Point::new(6_000_000.0, 0.0)]; + let segments: usize = subs.iter().map(SubPath::segment_count).sum(); + assert_eq!(segments, 2 * 21_845 + 1000); + let reach = DragReach::new(&pts, 12.0); + let in_reach = segments_in_reach(&PathData::new(subs.to_vec()), &reach); + assert_eq!(in_reach, 2 * 21_845, "the far segments are not counted"); + let share = (MAX_REACH_PIECES / in_reach).max(1); + assert_eq!(share, 3); + let mut shared = MAX_REACH_PIECES; + let mut marks = vec![]; + let measured = pieces_measured(|| { + for sp in &subs { + marks.push(mark_reached(sp, &reach, (share, &mut shared)).1); + } + }); + assert!(measured >= segments && measured <= segments + MAX_REACH_PIECES, "{measured} pieces measured for {segments} segments"); + assert_eq!((measured, shared), (segments + 2 * in_reach, MAX_REACH_PIECES - 2 * in_reach), "every segment in reach is halved once"); + assert!(marks[0].iter().all(|m| *m), "the first path's anchors are all on the drag"); + } + + /// More than `MAX_REACH_PIECES` short curved segments in reach are each measured once, and a + /// segment searched after the drag's pieces are spent is still found in reach where only a + /// narrow stretch of it, away from its middle, comes near the drag. + #[test] + fn every_curved_segment_is_searched_after_the_drags_pieces_run_out() { + let n = 140_000; + let tiny = chain(&(0..n).map(|i| bow((f64::from(i) * 4.0, 0.0), 4.0, 1.0)).collect::>()); + let pts = [Point::new(0.0, 0.0), Point::new(f64::from(n) * 4.0, 0.0)]; + let reach = DragReach::new(&pts, 12.0); + let share = (MAX_REACH_PIECES / segments_in_reach(&PathData::single(tiny.clone()), &reach).max(1)).max(1); + let mut shared = MAX_REACH_PIECES; + let measured = pieces_measured(|| { + mark_reached(&tiny, &reach, (share, &mut shared)); + }); + assert_eq!(measured, 140_000, "each segment is measured whole once"); + // An arch 1,000 pt wide and 300 pt high, with the drag on it a quarter of the way along. + let arch = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 400.0), Point::new(1000.0, 400.0), Point::new(1000.0, 0.0)); + let sp = chain(&[arch]); + let hit = [arch.eval(0.25)]; + assert!(dist_to_polyline(&hit, arch.eval(0.5)) > 12.0, "the arch's middle is out of reach"); + let mut spent = 0; + let (out, marked) = mark_reached(&sp, &DragReach::new(&hit, 12.0), (MAX_REACH_PIECES, &mut spent)); + assert_eq!(out.anchors.len(), 3, "{out:?}"); + assert_eq!(marked, vec![false, true, false]); + assert!(out.anchors[1].p.distance(hit[0]) <= 12.0, "{out:?}"); } /// A small piece of curve is measured only against the few stretches of a drag of 100,000 @@ -1384,14 +1497,14 @@ mod tests { assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures"); let share = (MAX_REACH_PIECES / in_reach).max(1); let mut got = None; - let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share))); + let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, (share, &mut { MAX_REACH_PIECES })))); assert!(marks < 100_000, "{marks} measures"); - let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0); + let smoothed = smooth_subpath(&sp, &reach, (share, &mut { MAX_REACH_PIECES }), 2.5, 4.0); assert!(smoothed.is_some()); let all = linear(&pts, 12.0); assert_eq!(segments_in_reach(&pd, &all), in_reach); - assert_eq!(Some(mark_reached(&sp, &all, share)), got); - assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed); + assert_eq!(Some(mark_reached(&sp, &all, (share, &mut { MAX_REACH_PIECES }))), got); + assert_eq!(smooth_subpath(&sp, &all, (share, &mut { MAX_REACH_PIECES }), 2.5, 4.0), smoothed); } /// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer @@ -1444,10 +1557,20 @@ mod tests { let in_reach = segments_in_reach(&pd, &all); assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first()); let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1); - assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first()); + assert_eq!( + mark_reached(sp, &grid, (share, &mut { MAX_REACH_PIECES })), + mark_reached(sp, &all, (share, &mut { MAX_REACH_PIECES })), + "path {k}, reach {radius}, drag {:?}", + pts.first() + ); let sigma = radius * SMOOTH_SPREAD; - let want = smooth_subpath(sp, &all, share, 2.5, sigma); - assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first()); + let want = smooth_subpath(sp, &all, (share, &mut { MAX_REACH_PIECES }), 2.5, sigma); + assert_eq!( + smooth_subpath(sp, &grid, (share, &mut { MAX_REACH_PIECES }), 2.5, sigma), + want, + "path {k}, reach {radius}, drag {:?}", + pts.first() + ); } } } diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index e959f126c0..83d9fab4d3 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -106,7 +106,7 @@ type PlacedPages = Vec<(u32, bool, vectorcraft_doc::PageBox)>; #[cfg(test)] thread_local! { - /// Tests: how many placed PDF or `.ai` pages [`page_fonts`] read on this thread. + /// Tests: how many placed PDF, `.ai` or EPS pages [`page_fonts`] read on this thread. pub(crate) static PAGES_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Tests: how many linked `.vectorcraft` files had their preview and PDF read on this thread, /// to keep them in the rewritten copy. @@ -196,16 +196,41 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { } } -/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`); -/// none for other files. +/// The fonts of the type on `pages` of the PDF, `.ai` or EPS file `name` (`bytes`, found at +/// `path`), and on the placed documents that art holds (an EPS file whose bytes a legacy `.ai` or +/// EPS file includes), [`MAX_NESTED_PAGES`] deep; none for other files. fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet { + nested_page_fonts(name, bytes, path, pages, 0) +} + +/// The most placed documents [`page_fonts`] reads inside one another. +const MAX_NESTED_PAGES: usize = 8; + +/// [`page_fonts`], `depth` placed documents in. +fn nested_page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages, depth: usize) -> BTreeSet { let mut fonts = BTreeSet::new(); - if super::place::document::is_pdf(name, bytes) { + if super::place::document::is_pdf(name, bytes) || super::place::document::is_postscript(bytes) { for &(page, bounding, page_box) in pages { #[cfg(test)] PAGES_READ.with(|c| c.set(c.get() + 1)); - if let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) { - fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes)); + let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) else { continue }; + fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes)); + if depth + 1 >= MAX_NESTED_PAGES { + continue; + } + let mut inner = Vec::new(); + let patterns = a.doc.patterns.iter().flat_map(|p| p.art.iter().map(|n| &**n)); + for n in a.doc.layers.iter().map(|l| &**l).chain(a.doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(&a.nodes) { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| { + if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind { + inner.push(p.clone()); + } + }); + } + for p in inner { + // Only the bytes the art keeps: its own file isn't looked for. + let Some(blob) = a.doc.images.get(&p.key).filter(|b| !b.is_proxy()) else { continue }; + fonts.extend(nested_page_fonts(p.link.name(), &blob.bytes, &p.link.path, &vec![(p.page(), p.bounding, p.page_box)], depth + 1)); } } } @@ -319,7 +344,7 @@ impl<'a> Collector<'a> { // Different linked documents can reuse the same stale absolute path yet // resolve it to distinct local assets. Keep a mapping per document. let mut local = BTreeMap::::new(); - // The fonts of the type on the PDF and `.ai` pages placed linked. + // The fonts of the type on the PDF, `.ai` and EPS pages placed linked. let mut placed_fonts = BTreeSet::new(); let mut placed = BTreeMap::::new(); let linked_files = |doc: &Document| match lookup { diff --git a/crates/engine/src/cmd/place/document.rs b/crates/engine/src/cmd/place/document.rs index a14b89fd25..f24242ed70 100644 --- a/crates/engine/src/cmd/place/document.rs +++ b/crates/engine/src/cmd/place/document.rs @@ -1,6 +1,7 @@ //! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file //! from a file, with `link`): one locked object showing an artboard of the document, a page of the -//! PDF or the EPS file's art, a [`PlacedDocument`]. +//! PDF or the EPS file's art, a [`PlacedDocument`]. An EPS file whose bytes a `.ai` file's editing +//! data includes opens as one too, read from those bytes. //! //! The object keeps the file's bytes (in the document's images, like image data) and the link; the //! art it shows is read from them the way placing the file without Link reads it @@ -223,6 +224,27 @@ impl Drop for Reading { } } +std::thread_local! { + /// How many placed documents [`read_document`] is reading inside one another on this thread. + static DRAWING: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A placed document being read for drawing ([`DRAWING`]): the count goes down when this goes. +struct Drawing; + +impl Drawing { + /// `None` when [`MAX_NESTED_READS`] are being read. + fn enter() -> Option { + DRAWING.with(|d| (d.get() < MAX_NESTED_READS).then(|| d.set(d.get() + 1))).map(|()| Drawing) + } +} + +impl Drop for Drawing { + fn drop(&mut self) { + DRAWING.with(|d| d.set(d.get().saturating_sub(1))); + } +} + /// `nodes` as one group, clipped to `clip` (its own ids: what drawing reads). fn group(nodes: Vec, clip: Option) -> Node { let mut children: Vec> = nodes.into_iter().map(Arc::new).collect(); @@ -234,11 +256,22 @@ fn group(nodes: Vec, clip: Option) -> Node { /// `p`'s file (`bytes`) read as the art it shows: how the document model reads placed documents /// ([`vectorcraft_doc::placed_document::set_loader`]). +/// `None` past [`MAX_NESTED_READS`] placed documents read inside one another: opening a file can +/// draw the placed documents in it, whose files can place others. pub(crate) fn read_document(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> { + let _drawing = Drawing::enter()?; + #[cfg(test)] + DOCUMENT_READS.with(|n| n.set(n.get() + 1)); let a = document_art(p.link.name(), bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, "draw").ok()?; Some((a.doc, group(a.nodes, a.clip), a.frame)) } +#[cfg(test)] +std::thread_local! { + /// Placed documents read for drawing on this thread, for tests that count work. + pub(crate) static DOCUMENT_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// `p`'s file read again, while it is the file it was read from (how the document model gets it /// when only the preview is stored, [`vectorcraft_doc::placed_document::set_file_reader`]). pub(crate) fn read_file_again(p: &PlacedDocument) -> Option> { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4a58edba23..7554440ab6 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -30,7 +30,8 @@ //! false then. Assigning to such a name throws the same error. //! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the //! active document's selection. A top-level `var selection = ...` does the same and does -//! not make a variable of the script. Assigning `documents` keeps its value. +//! not make a variable of the script. An assignment to `documents` is ignored outside strict +//! mode and throws a `TypeError` in strict mode code or with `#strict on`. //! - After `documents[0]`, documents are listed from the one active most recently to the one //! active longest ago. A change a script makes to a document in the back does not move it. //! - `pageItems` lists every object, with the objects inside groups and compound paths after the diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 344b5e436e..f0eeefd810 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -1115,6 +1115,82 @@ fn package_reads_no_placed_pdf_page_without_copy_fonts() { } } +/// With Copy Fonts on, Package reads the type of a placed EPS file whose bytes a `.ai` file's +/// editing data included, as it reads a placed PDF page's. +#[test] +fn package_reads_a_placed_eps_files_type_for_copy_fonts() { + use cmd::package::PAGES_READ; + use vectorcraft_testkit::ai; + let dir = Folder::new("package-placed-eps-fonts"); + let eps = + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Helvetica findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n"; + let src = dir.file("art/shape.eps"); + write(&src, eps.as_bytes()); + let src = src.replace('\\', "/"); + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n({src})`\n%%BeginDocument: {src}\n{eps}\n%%EndDocument\n~\n%AI5_EndPlace\n" + ); + let doc_path = dir.file("poster.ai"); + let page = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET"; + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)).as_bytes(), page)); + let mut s = session(); + open(&mut s, &doc_path); + let mut placed = 0; + s.doc().unwrap().doc.visit_placed(|_, _| placed += 1); + assert_eq!(placed, 1); + save(&mut s, &dir.file("poster.vectorcraft")); + let before = PAGES_READ.with(std::cell::Cell::get); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out"), "copyLinks": false, "copyFonts": true})); + assert_eq!(PAGES_READ.with(std::cell::Cell::get) - before, 1, "{r}"); + let listed = |r: &Value| r["fonts"].as_u64().unwrap_or(0) + r["skippedFonts"].as_array().map_or(0, |a| a.len() as u64); + assert_eq!(listed(&r), 1, "the type's font: {r}"); + + // Type only in an EPS file that the placed one, a legacy-format file, includes in turn. + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let typed = + "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Courier findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n"; + let inner = format!("[1 0 0 1 0 0] 0 0 60 60 (inner.eps) `\n%%BeginDocument: inner.eps\n{typed}%%EndDocument\n~\n"); + let outer = format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n\ + %%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\ + {inner}LB\n%AI5_EndLayer--\nshowpage\n%%EOF\n" + ); + write(&dir.file("art/shape.eps"), outer.as_bytes()); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page)); + open(&mut s, &doc_path); + save(&mut s, &dir.file("poster.vectorcraft")); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out2"), "copyLinks": false, "copyFonts": true})); + assert_eq!(listed(&r), 1, "the inner file's font: {r}"); + + // The included file is only in a pattern definition, outside the page's nodes. + let pattern = format!("%AI3_BeginPattern: (Type)\n(Type) 0 0 60 60\n0 A\n0 Xw\n{inner}E\n%AI3_EndPattern\n"); + let outer = outer.replace(&inner, "").replace("%AI5_BeginLayer", &format!("{pattern}%AI5_BeginLayer")); + let a = cmd::place::document::document_art("shape.eps", outer.as_bytes(), Some(&src), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap(); + let pattern = a.doc.pattern("Type").expect("the pattern definition is read"); + let mut placements = 0; + for n in &pattern.art { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| { + assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)), "the type is only in the included file"); + if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind { + placements += 1; + let blob = &a.doc.images[&p.key]; + assert!(!blob.is_proxy()); + assert_eq!(blob.bytes.as_slice(), typed.as_bytes()); + } + }); + } + assert_eq!(placements, 1, "the pattern holds the included file"); + for n in &a.nodes { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::PlacedDocument(_)))); + } + write(&dir.file("art/shape.eps"), outer.as_bytes()); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page)); + open(&mut s, &doc_path); + save(&mut s, &dir.file("poster.vectorcraft")); + let r = run(&mut s, "file.package", json!({"folder": dir.file("out3"), "copyLinks": false, "copyFonts": true})); + assert_eq!(listed(&r), 1, "the pattern's included file's font: {r}"); +} + /// `dir/art/badge.ai`, saved without its PDF part, its art placing each of `pics` (600 × 300 px, /// with a 2×1 preview) → its path. fn ai_placing(dir: &Folder, pics: &[&str]) -> String { diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 3458c5ae37..00f976ab3f 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -934,6 +934,127 @@ fn an_ai_file_that_places_itself_opens() { assert_eq!(found, [at], "{r}"); } +/// A placed EPS file whose bytes a `.ai` file's editing data includes (between `%%BeginDocument:` +/// and `%%EndDocument`) opens as a placed document of those bytes: it draws its art with its file +/// missing, and its file found unchanged is neither missing nor modified. A native save keeps the +/// bytes, so the copy reopens and draws without the file. +#[test] +fn a_placed_eps_file_included_in_an_ai_files_editing_data_draws_without_its_file() { + use vectorcraft_testkit::ai; + let dir = Folder::new("placed-eps-in-ai"); + // The file draws red and the page blue, so each check shows which one drew. + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor\n0 0 60 60 rectfill\n%%EOF\n"; + let (red, blue) = ([255, 0, 0], [0, 0, 255]); + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n(/no/such/folder/src/shape.eps)`\n\ + %%BeginDocument: /no/such/folder/src/shape.eps\n{eps}\n%%EndDocument\n%AI17_Begin_Content_if_version_gt:24 12\n\ + %AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n" + ); + let doc_path = dir.file("poster.ai"); + let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)); + write(&doc_path, &ai::ai(data.as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + let shown = |s: &Session| { + let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true); + let [r, g, b, _] = img.pixel(50, 50); + [r, g, b] + }; + let one = |s: &Session| { + let d = &s.doc().unwrap().doc; + let mut found = vec![]; + d.visit_placed(|n, p| found.push((n.id, p.clone()))); + let [(id, p)] = &found[..] else { panic!("one placed document: {found:?}") }; + (*id, p.clone(), d.images[&p.key].clone()) + }; + let mut s = session(); + + let r = open(&mut s, &doc_path); + assert_eq!(r["missingLinks"][0]["name"].as_str(), Some("shape.eps"), "{r}"); + let (id, p, blob) = one(&s); + assert_eq!((blob.bytes.as_slice(), blob.mime.as_str()), (eps.as_bytes(), "application/postscript")); + assert_eq!(p.link.relative.as_deref(), Some("src/shape.eps")); + let at = bounds(&s, id); + assert!((at.x0 - 20.0).abs() < 0.01 && (at.y0 - 20.0).abs() < 0.01 && (at.width() - 60.0).abs() < 0.01, "{at:?}"); + assert!(near(shown(&s), red), "its art draws: {:?}", shown(&s)); + + write(&dir.file("src/shape.eps"), eps.as_bytes()); + let r = open(&mut s, &doc_path); + assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}"); + assert!(near(shown(&s), red)); + + let copy = dir.file("copy.vectorcraft"); + save(&mut s, ©); + std::fs::remove_file(dir.file("src/shape.eps")).unwrap(); + open(&mut s, ©); + let (_, _, blob) = one(&s); + assert_eq!(blob.bytes.as_slice(), eps.as_bytes(), "the bytes are saved"); + assert!(near(shown(&s), red), "and draw: {:?}", shown(&s)); + + // A file named as PostScript of another kind, or with a name that doesn't say, draws the same. + for name in ["shape.ps", "shape", "shape.dat"] { + let named = place.replace("shape.eps", name); + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &named)).as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + open(&mut s, &doc_path); + let (_, p, blob) = one(&s); + assert_eq!((p.link.name(), blob.mime.as_str()), (name, "application/postscript")); + assert!(near(shown(&s), red), "{name} draws: {:?}", shown(&s)); + } + + // Bytes that can't be read leave the placed file unread: the file is read from its PDF part, + // and the object comes in as what the page draws there. + let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, broken))).as_bytes(), "0 0 1 rg 20 20 60 60 re f")); + let r = open(&mut s, &doc_path); + assert!(near(shown(&s), blue), "the page's art: {:?} {r}", shown(&s)); +} + +/// A synthetic EPS file that includes another placed EPS file, `depth` levels deep. +fn nested_included_eps(depth: usize) -> String { + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let mut eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor\n10 20 40 30 rectfill\n%%EOF\n".to_string(); + for _ in 0..depth { + eps = format!( + "%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\ + %%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\ + [1 0 0 1 0 0] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\nLB\n%AI5_EndLayer--\nshowpage\n%%EOF\n" + ); + } + eps +} + +/// Open checks and drawing must not recursively multiply each other's work. +#[test] +fn placed_eps_files_included_open_work_is_bounded() { + let dir = Folder::new("placed-eps-open-work"); + let path = dir.file("deep.eps"); + write(&path, nested_included_eps(12).as_bytes()); + let mut s = session(); + let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get); + let checks = vectorcraft_eps::included_eps_reads(); + open(&mut s, &path); + let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get) - drawings; + let checks = vectorcraft_eps::included_eps_reads() - checks; + eprintln!("included EPS work: {drawings} drawing reads, {checks} open checks"); + // At most 8 drawing loads, each with at most 8 parses for checks, plus the outer import's 8. + // Repeated structural reads share completed checks within each chain. + assert!(drawings <= 8, "{drawings} drawing reads, {checks} open checks"); + assert!(checks <= 8 * 8 + 8, "{drawings} drawing reads, {checks} open checks"); + assert!(drawings > 0 && checks > 0, "both read paths were exercised"); +} + +/// A legacy-format file (version 7 specification §16) placing an EPS file whose bytes it includes, +/// which is such a file in turn, 300 deep: it opens, reading a bounded number of them. +#[test] +fn placed_eps_files_included_300_deep_open() { + let dir = Folder::new("placed-eps-300-deep"); + let path = dir.file("deep.eps"); + write(&path, nested_included_eps(300).as_bytes()); + let mut s = session(); + open(&mut s, &path); + let mut placed = 0; + s.doc().unwrap().doc.visit_placed(|_, _| placed += 1); + assert_eq!(placed, 1); +} + #[test] fn a_pdf_compatible_ai_file_places_linked_like_a_pdf() { let dir = Folder::new("placed-ai-linked"); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 7add15fbc5..295ed12f90 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -2076,7 +2076,8 @@ fn objects_of_the_object_model_print_their_class_and_name() { } /// `activeDocument`, `documents` and `selection` without `app.` read the application's members, and -/// assigning one assigns the member: `selection` selects, `documents` keeps its value. +/// assigning one assigns the member: `selection` selects, and `documents` keeps its value outside +/// strict mode and throws a `TypeError` in strict mode code or with `#strict on`. #[test] fn the_application_members_can_be_named_without_app() { let (mut s, a, b) = doc(); @@ -2103,6 +2104,8 @@ fn the_application_members_can_be_named_without_app() { assert!(failure(&mut s, "activeDocument = 5;").contains("not a Document")); let e = failure(&mut s, "'use strict'; documents = 5;"); assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}"); + let e = failure(&mut s, "#strict on\ndocuments = 5;"); + assert!(e.contains("TypeError") && e.contains("cannot assign to property 'documents': it has only a getter"), "{e}"); // With no document open, reading `activeDocument` throws as `app.activeDocument` does. let mut s = Session::new(); assert!(failure(&mut s, "activeDocument;").contains("No active document")); diff --git a/crates/engine/src/tests/strokereach.rs b/crates/engine/src/tests/strokereach.rs index 1154073a3b..a04388af89 100644 --- a/crates/engine/src/tests/strokereach.rs +++ b/crates/engine/src/tests/strokereach.rs @@ -52,6 +52,9 @@ fn a_click_outside_an_outside_stroke_selects_it() { s.execute("paint.setFill", &json!({"none": true})).unwrap(); s.execute("stroke.set", &json!({"weight": 20, "align": "outside"})).unwrap(); s.execute("select.none", &json!({})).unwrap(); + // Object Selection by Path Only: the inside of the unfilled square takes no click of its own, + // so only the stroke is tested. + s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); // 0.8 × the weight outside the path: past where a centred stroke (plus the tolerance) reaches. assert_eq!(click(&mut s, 84.0, 200.0), [r]); s.execute("select.none", &json!({})).unwrap(); @@ -59,6 +62,9 @@ fn a_click_outside_an_outside_stroke_selects_it() { s.execute("stroke.set", &json!({"ids": [r.0], "align": "center"})).unwrap(); s.execute("select.none", &json!({})).unwrap(); assert!(click(&mut s, 84.0, 200.0).is_empty(), "a centred stroke doesn't reach"); + // With it off, a click inside the unfilled square selects it (#9175). + s.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + assert_eq!(click(&mut s, 116.0, 200.0), [r]); } #[test] diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 906f26771a..636c19fb36 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -4950,6 +4950,37 @@ proptest! { survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + /// A `.ai` whose placed EPS files have their bytes included between `%%BeginDocument:` and + /// `%%EndDocument` (one on `%_` lines, one with a nested document and counted data in it), + /// damaged, opened and drawn: their bytes are read as an EPS file when drawn. + #[test] + fn ai_placed_eps_files_with_included_bytes_never_panic( + cut in 0usize..4_000, + edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', '`', '~', 'E', 'D'])), 0..12), + ) { + use vectorcraft_testkit::ai; + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 40\n%%EndComments\n0 0 1 setrgbcolor\n0 0 60 40 rectfill\n%%EOF\n"; + let nested = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n%%BeginDocument: c.eps\nnewpath\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n"; + let place = |path: &str, matrix: &str, doc: &str| { + format!( + "%AI5_BeginPlace\n%%FileType: 0\n{matrix} 0 0 60 40 4 4 0\n({path})`\n%%BeginDocument: {path}\n{doc}\n%%EndDocument\n\ + %AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n" + ) + }; + let hidden: String = place("/tmp/b.eps", "[1 0 0 1 20 20]", eps).lines().map(|l| format!("%_{l}\n")).collect(); + let body = format!("{}{hidden}{}", place("/tmp/a.eps", "[1 0 0 1 20 20]", eps), place("/tmp/c.eps", "[1 0 0 1 0 0]", nested)); + let fixture = ai::editing_data(200.0, 100.0, &ai::layer("L", &body)); + // A session reads placed documents' files when they are drawn. + let _ = vectorcraft_engine::Session::new(); + let whole = vectorcraft_engine::cmd::fileio::load("x.ai", &ai::ai(fixture.as_bytes(), "0 0 1 rg 20 20 60 40 re f")); + let mut placed = 0; + whole.iter().for_each(|l| l.doc.visit_placed(|_, _| placed += 1)); + prop_assert!(placed == 3 && fixture.len() < 4_000, "{placed} placed documents, {} bytes: {:?}", fixture.len(), whole.map(|l| l.warnings)); + let text = mutate_text(&fixture, cut, &edits); + let file = ai::ai(text.as_bytes(), "0 0 1 rg 20 20 60 40 re f"); + survive("hostile .ai placed EPS files with included bytes", || vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc))?; + } + /// A `.ai` whose type (point type turned, vertical type, area type, threaded area type and type /// on a path, their stubs with the frames' paths, and the text document they name, as the `.ai` /// writer writes them) is damaged: read from its editing data alone and beside a page. @@ -6390,6 +6421,12 @@ fn arb_ai_token() -> impl Strategy { "\n%%BeginData: 14 Binary Bytes\n", "\n%%BeginBinary: 99999999999\n", "\n%%BeginData: 3 Hex Lines\n", + // A placed EPS file's bytes included in the data: one drawn, one with a box it can't + // take, one on `%_` lines. + "\n%%BeginDocument: a.eps\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n0 0 1 setrgbcolor 0 0 9 9 rectfill\n%%EndDocument\n", + "\n%%BeginDocument: a.eps\n%!PS\n%%BoundingBox: 0 0 1e308 -5\n%%EndDocument\n", + "\n%_%%BeginDocument: a.eps\n%_%!PS\n%_0 0 9 9 rectfill\n%_%%EndDocument\n", + "[1 0 0 1 0 0] 0 0 1e308 1e308 4 4 0 (a.eps) `", "\n%AI5_EndPlace\n", "Xm", "50 -50 -100 -100 5000 -2000 Xm", diff --git a/crates/eps/Cargo.toml b/crates/eps/Cargo.toml index 52413b8c28..6539bf6686 100644 --- a/crates/eps/Cargo.toml +++ b/crates/eps/Cargo.toml @@ -9,7 +9,8 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P workspace = true [features] -# `vectorcraft_eps::blend_work` for other crates' tests (dev-dependencies only). +# `vectorcraft_eps::blend_work` and `vectorcraft_eps::included_eps_reads` for other crates' tests +# (dev-dependencies only). work-count = [] [dependencies] diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 4458f29d2b..38fba94616 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -280,6 +280,12 @@ pub fn page(bytes: &[u8]) -> Result { Ok(Rect::new(0.0, 0.0, urx - llx, ury - lly)) } +/// An EPS or PostScript file's bounding box (`%%HiResBoundingBox` when it has one) in its own +/// space, as `[llx, lly, urx, ury]`, read from its comments; `None` without one. +pub(crate) fn bounding_box(bytes: &[u8]) -> Option<[f64; 4]> { + Dsc::read(program(bytes).ok()?).bbox +} + /// [`import`], an Illustrator EPS through the editing copy of its art only when `editing_data` /// (else what its page prints, as any EPS). pub fn import_with(bytes: &[u8], editing_data: bool) -> Result { diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 149728decf..525eb71f22 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -62,12 +62,12 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color, - read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, + BLEND_BUDGET, LINKED_PREVIEWS, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, + parsed_type_color, read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ - BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, - palette, read_beside, read_in, symbols, variables, + BindingRef, Brushes, PaletteSwatches, PlacedEps, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, + graphic_styles, palette, read_beside, read_in, symbols, variables, }; #[cfg(test)] pub(crate) use style::ART_STYLE_PARSES; diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index d9a14a0239..6ff37bec92 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -59,6 +59,9 @@ pub(crate) fn drawn_note(typed: bool) -> &'static str { pub(super) const MAX_PENDING: usize = 64; /// The most envelopes and warped text objects one import draws to check; more keep their drawn art. pub(crate) const MAX_CHECKED: usize = 256; +/// The most comparisons with pages those checks make in one import, one for each page an object +/// is on ([`drawn_alike`]); an object that needs more keeps its drawn art. +pub(crate) const MAX_PAGE_COMPARISONS: usize = 4 * MAX_CHECKED; /// The most strokes with dashes aligned to corners one import draws to check against their drawn /// looks (apart from [`MAX_CHECKED`]); more keep their drawn looks. pub(crate) const MAX_DASH_CHECKS: usize = 256; @@ -664,13 +667,31 @@ fn differing(live: &Document, drawn: &Document, region: Rect, scale: f64) -> Opt } /// The differences from their drawn art that the live envelopes and warped type of one import may -/// add up to, as shares of the page drawn as the page check draws it: half of what that check allows -/// ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), so they never make the file open from its PDF part -/// instead. +/// add up to on each page the art may be compared with, as shares of that page drawn as the page +/// check draws it: half of what that check allows ([`MAX_DIFFERENCE`], [`MAX_SOLID_DIFFERENCE`]), +/// so they never make the file open from its PDF part instead. Each page has its own share. #[derive(Debug, Default)] pub(crate) struct Spent { - pub(super) any: f64, - pub(super) solid: f64, + /// Each page with the shares of it spent so far: of pixels that differ at all, and of those + /// whose neighbors all differ too. + pub(super) pages: Vec<(Rect, f64, f64)>, + /// How many comparisons with pages have been made ([`MAX_PAGE_COMPARISONS`]). + pub(super) compared: usize, +} + +impl Spent { + /// The shares of `page` spent so far. + pub(super) fn on(&self, page: Rect) -> (f64, f64) { + self.pages.iter().find(|(p, ..)| *p == page).map_or((0.0, 0.0), |&(_, any, solid)| (any, solid)) + } + + /// Set the shares of `page` spent so far. + fn set(&mut self, page: Rect, any: f64, solid: f64) { + match self.pages.iter_mut().find(|(p, ..)| *p == page) { + Some(spent) => *spent = (page, any, solid), + None => self.pages.push((page, any, solid)), + } + } } /// A text object read with a Warp. @@ -738,7 +759,8 @@ pub struct WarpedType { pub(super) envelopes: Vec, pub(super) checks: usize, pub(super) spent: Spent, - pub(super) page: Option, + /// The pages the art may be compared with, each with its own share of the budget ([`Spent`]). + pub(super) pages: Vec, /// [`super::Structure::type_clips`]: type in an envelope's contents clips its clipping group too. pub(super) type_clips: HashMap, /// The envelopes of type that may open live in layers built without a page, by their place @@ -884,7 +906,7 @@ impl WarpedType { let (id, layer) = (doc.alloc_id(), doc.alloc_id()); let mut plain = art.clone(); (plain.visible, plain.opacity) = (true, 1.0); - let page = self.page.filter(|_| shown.contains(&drawn)); + let pages: Vec = if shown.contains(&drawn) { self.pages.clone() } else { vec![] }; let mut alike = None; // In Edit Contents, a grid that draws the type elsewhere than its drawn art is tried again // moved onto that art ([`moved_onto`]), after every other way. @@ -917,7 +939,7 @@ impl WarpedType { let shared = Shared { patterns: &doc.patterns, images: &doc.images }; let mut live_one = envelope.clone(); (live_one.visible, live_one.opacity) = (true, 1.0); - if drawn_alike(&live_one, &plain, layer, &shared, page, &mut self.spent) { + if drawn_alike(&live_one, &plain, layer, &shared, &pages, &mut self.spent) { alike = Some(envelope); break; } @@ -942,7 +964,8 @@ impl WarpedType { /// budget has no check left for) with that look: `made` gives the text object a slot became. A /// frame in `threaded` stays type, since the frames of a thread share one story. A replaced /// object's box goes back into the comparisons with the page (out of `restyled`), and only what - /// `doc` shows counts against the page's share of the budget. Returns how many were replaced. + /// `doc` shows counts against the share of the budget of each page it is on. Returns how many + /// were replaced. pub(crate) fn settle( self, doc: &mut Document, @@ -950,7 +973,7 @@ impl WarpedType { threaded: &BTreeSet, restyled: &mut Vec, ) -> usize { - let Self { looks, mut checks, mut spent, page, .. } = self; + let Self { looks, mut checks, mut spent, pages, .. } = self; let mut shown_ids = BTreeSet::new(); doc.layers.iter().for_each(|l| collect_shown(l, &mut shown_ids)); let mut replaced = 0; @@ -965,7 +988,8 @@ impl WarpedType { let (mut shown, mut plain) = (text.clone(), look.clone()); (shown.visible, shown.opacity) = (true, 1.0); (plain.visible, plain.opacity) = (true, 1.0); - alike = warped_alike(&shown, &plain, layer, &shared, page.filter(|_| shown_ids.contains(&id)), &mut spent); + let on: &[Rect] = if shown_ids.contains(&id) { &pages } else { &[] }; + alike = warped_alike(&shown, &plain, layer, &shared, on, &mut spent); } if alike { continue; @@ -1032,23 +1056,24 @@ pub(super) fn warps(appearance: &Appearance) -> bool { } /// Do `live` and `drawn` draw alike? Either neither has any paint ([`paints`]), or few of the -/// pixels either inks differ and fewer still where a whole patch differs, and, on `page` (when the -/// file has one), they differ little enough that with the differences in `spent` the page check -/// still takes the layers' art (it is added to `spent` when they do). Both are drawn on `layer`, a -/// layer id no other node has. -pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { - alike_within(live, drawn, live.visual_bounds(), layer, shared, page, spent) +/// pixels either inks differ and fewer still where a whole patch differs, and, on each of `pages` +/// they are on (the pages the art may be compared with), they differ little enough that with the +/// differences `spent` holds for that page the page check still takes the layers' art (they are +/// added to `spent` when they do on every one). Both are drawn on `layer`, a layer id no other node +/// has. +pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { + alike_within(live, drawn, live.visual_bounds(), layer, shared, pages, spent) } /// [`drawn_alike`] for type under a Warp, compared over all that its effects draw, which can reach /// past its own box. -pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { +pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { let reach = vectorcraft_render::effect_bounds(&alone(live, layer, shared).symbol_boxes(), live); - alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, page, spent) + alike_within(live, drawn, vectorcraft_geom::union_opt(live.visual_bounds(), reach), layer, shared, pages, spent) } /// [`drawn_alike`], with `live` measured as `reach`. -fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { +fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, pages: &[Rect], spent: &mut Spent) -> bool { // Neither has any paint (type with no fill and no stroke, its drawn art the outlines unpainted): // both draw nothing, so they draw alike and add nothing to what the page check sees. Their // shapes aren't compared. Art that paints, however faintly, is compared as before. @@ -1069,21 +1094,31 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, s if share(solid) > MAX_SOLID || share(any) > MAX_ANY { return false; } - let Some(page) = page.filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) else { return true }; - // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along the - // page's longer side). - let on_page = region.intersect(page); - let scale = compare_scale(page); - if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 { - return true; + let mut added = vec![]; + for &page in pages.iter().filter(|p| p.is_finite() && p.width() > 0.0 && p.height() > 0.0) { + // Only what is on the page counts, drawn as the page check draws it (about 400 pixels along + // the page's longer side). + let on_page = region.intersect(page); + let scale = compare_scale(page); + if on_page.width() * scale < 1.0 || on_page.height() * scale < 1.0 { + continue; + } + if spent.compared >= MAX_PAGE_COMPARISONS { + return false; + } + spent.compared += 1; + let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false }; + let pixels = (page.width() * scale * page.height() * scale).max(1.0); + let (was_any, was_solid) = spent.on(page); + let (any, solid) = (was_any + any as f64 / pixels, was_solid + solid as f64 / pixels); + if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 { + return false; + } + added.push((page, any, solid)); } - let Some((any, solid, _)) = differing(&x, &y, on_page, scale) else { return false }; - let pixels = (page.width() * scale * page.height() * scale).max(1.0); - let (any, solid) = (spent.any + any as f64 / pixels, spent.solid + solid as f64 / pixels); - if any > MAX_DIFFERENCE / 2.0 || solid > MAX_SOLID_DIFFERENCE / 2.0 { - return false; + for (page, any, solid) in added { + spent.set(page, any, solid); } - *spent = Spent { any, solid }; true } @@ -1161,7 +1196,7 @@ mod tests { #[test] fn art_with_no_paint_draws_alike_and_faint_art_is_still_compared() { let shared = Shared { patterns: &[], images: &BTreeMap::new() }; - let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, None, &mut Spent::default()); + let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, &[], &mut Spent::default()); let (none, other_none) = (square_node(1, None), square_node(2, None)); assert!(alike(&none, &other_none)); let (faint, other_faint) = (square_node(1, Some(0.02)), square_node(2, Some(0.02))); @@ -1169,6 +1204,22 @@ mod tests { assert!(!alike(&none, &square_node(2, Some(1.0)))); } + /// Each page an object is on takes one of the import's comparisons with pages. With none left, + /// art on a page keeps its drawn art, and art on no page needs none. + #[test] + fn comparisons_with_pages_stop_at_their_limit() { + let shared = Shared { patterns: &[], images: &BTreeMap::new() }; + let (live, drawn) = (square_node(1, Some(1.0)), square_node(2, Some(1.0))); + let (page, other) = (Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(0.0, 0.0, 60.0, 60.0)); + let mut spent = Spent { compared: MAX_PAGE_COMPARISONS - 2, ..Default::default() }; + assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[page, other], &mut spent)); + assert_eq!(spent.compared, MAX_PAGE_COMPARISONS); + assert!(!drawn_alike(&live, &drawn, NodeId(999), &shared, &[page], &mut spent)); + let off = Rect::new(500.0, 500.0, 600.0, 600.0); + assert!(drawn_alike(&live, &drawn, NodeId(999), &shared, &[off], &mut spent)); + assert_eq!(spent.compared, MAX_PAGE_COMPARISONS); + } + /// "AVA" at 40 points, at (10, 60). fn type_node(id: u64, style: CharStyle) -> Node { Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "AVA", CharStyle { size: 40.0, ..style })))) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 66cdb82adc..dc757b1462 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -57,8 +57,13 @@ //! The version 7 form (§16) has no `%AI5_BeginPlace`: `[matrix] llx lly urx ury (path)` and //! `` ` ``, then `%%IncludeFile:` or the file between `%%BeginDocument:` and `%%EndDocument`, //! then `~`; its box is the file's `%%BoundingBox`. Newer files have three more numbers before -//! the path. Operands of any other shape, a second `` ` `` before `~` or an included document -//! that doesn't end leave the placed file unread. +//! the path. A placed EPS file whose bytes are included between `%%BeginDocument:` and +//! `%%EndDocument` (DSC 3.0 p. 68) is a placed document that keeps those bytes and draws them, +//! its file found or not; its box is the +//! file's bounding box, which the matrix takes from the file's own space (y up) into art space, +//! as in the version 7 form. +//! Operands of any other shape, a second `` ` `` before `~` or an included document that +//! doesn't end leave the placed file unread. //! - Art with an appearance the format can't write as plain art (several fills or strokes, //! effects, brushes) comes first as that look, drawn (a group, or an image where an effect //! rasterizes it), then the object itself on `%_` @@ -148,22 +153,27 @@ mod raster; mod types; pub(crate) use art::join_and; -use art::preview_png; +use art::{included_document, preview_png}; pub use document::{ BindingRef, Brushes, PaletteSwatches, Symbols, VariableRead, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, symbols, variables, }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; +#[cfg(test)] +pub(crate) use on_path::on_path_measured; +#[cfg(test)] +pub(crate) use ops::array_slots; pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; +pub(crate) use types::LINKED_PREVIEWS; pub(crate) use types::MAX_NODES; -pub use types::PlacedPage; -use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; +use types::{BrushArtColors, FLIP, Frame, GState, Kind, MAX_PLACED_DOCUMENT, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead}; #[cfg(test)] pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED}; +pub use types::{PlacedEps, PlacedPage}; pub(super) use types::{blend_mode, blend_name}; #[path = "legacy_text.rs"] @@ -212,6 +222,8 @@ pub struct Structure { pub placed_elsewhere: Vec<(NodeId, Affine)>, /// The placed files that are pages of PDF or `.ai` files. pub placed_pages: Vec, + /// Included EPS files whose previews wait for variable binding before conversion. + pub placed_eps: Vec, /// The live envelopes read from the editing data, by id, with the drawn art each took the place /// of: the importer puts that art back when the layers with the envelopes don't draw as the page. pub envelopes_drawn: Vec<(NodeId, Node)>, @@ -472,6 +484,10 @@ struct BrushesKept { bending: HashMap, } +/// What the pages the art may be compared with are worked out from: the move into the document, +/// the number of artboards, the first artboard and the art's bounding box. +type PageSources = (Option, usize, Option, Option); + struct Reader<'a> { lex: Lexer<'a>, stack: Vec, @@ -604,6 +620,8 @@ struct Reader<'a> { envelope_checks: usize, /// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]). envelope_spent: super::envelope::Spent, + /// [`Self::pages_in_doc`] as last worked out, with what it was worked out from. + page_cache: Option<(PageSources, Arc<[Rect]>)>, /// How many more strokes with dashes aligned to corners this import may draw to check /// ([`super::MAX_DASH_CHECKS`]). dash_checks: usize, @@ -667,6 +685,8 @@ struct Reader<'a> { placed_elsewhere: Vec<(NodeId, Affine)>, /// See [`Structure::placed_pages`]. placed_pages: Vec, + /// See [`Structure::placed_eps`]. + placed_eps: Vec, unread_elsewhere: Vec<(NodeId, Rect)>, /// CMYK samples converted, by value. cmyk_cache: HashMap<[u8; 4], [u8; 3]>, @@ -877,6 +897,7 @@ impl<'a> Reader<'a> { envelopes: Vec::new(), envelope_checks: super::envelope::MAX_CHECKED, envelope_spent: super::envelope::Spent::default(), + page_cache: None, dash_checks: super::MAX_DASH_CHECKS, defs_only: false, warped_type: Vec::new(), @@ -901,6 +922,7 @@ impl<'a> Reader<'a> { placeholders: vec![], placed_elsewhere: vec![], placed_pages: vec![], + placed_eps: vec![], placed_tails: vec![], unread_elsewhere: vec![], mesh: None, @@ -939,6 +961,15 @@ impl<'a> Reader<'a> { } } + /// The line end just before `doc`, an included document the lexer has just read: the one that + /// ends its `%%BeginDocument:` line. `None` when `doc` isn't in the data read so far. + fn line_end_before(&self, doc: &[u8]) -> Option<&'static [u8]> { + let read = self.lex.slice(0, self.lex.offset()); + let at = doc.as_ptr().addr().checked_sub(read.as_ptr().addr())?; + let before = read.get(..at)?; + [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| before.ends_with(e)) + } + fn run(&mut self) -> Result<(), String> { while let Some(t) = self.lex.next_token() { if self.done { @@ -961,11 +992,14 @@ impl<'a> Reader<'a> { p.preview = preview_png(d); } } - // A placed file's document, included whole: its art isn't read here. When no - // `%%EndDocument` ends it, the placed file isn't read. + // A placed file's document, included whole: its art isn't read here, its bytes are + // kept for the placed file. When no `%%EndDocument` ends it, the placed file isn't + // read. Tok::Document(d) => { + let sep = d.and_then(|d| self.line_end_before(d)); if let Some(p) = self.place.as_mut() { p.broken |= d.is_none(); + p.document = d.filter(|d| d.len() <= MAX_PLACED_DOCUMENT).map(|d| included_document(d, hidden, sep)); } } } diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 030c70aa51..95606c9ebb 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -2,17 +2,88 @@ use super::containers::close; use super::document::TEXT_SLOT; use super::raster::{self, Limits, Shape}; use super::types::{ - FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS, - MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail, + EPS_MIME, FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, + MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedEps, PlacedPage, PlacedTail, }; use super::{ Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node, NodeId, NodeKind, Obj, OpacityMask, PageBox, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps, }; -use vectorcraft_doc::links::missing_placeholder; +use vectorcraft_doc::PlacedDocument; +use vectorcraft_doc::links::{hash_bytes, missing_placeholder}; use vectorcraft_doc::placed_document::key_for; +use vectorcraft_pdf::is_postscript; + +/// Open-check results by content and nesting depth: the remaining depth changes their warnings. +type EpsChecks = Vec<((String, usize), Option>)>; + +/// The most open-check results kept during one outer check; no file bytes are retained. +const MAX_EPS_CHECKS: usize = 64; + +std::thread_local! { + /// How many included EPS files [`readable_eps`] is reading inside one another on this thread. + static READING_EPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Checks completed during this thread's outer check, including files that do not read. + static EPS_CHECKS: std::cell::RefCell = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// An included EPS file being read by [`readable_eps`] ([`READING_EPS`]): the count goes down when +/// this goes. +struct ReadingEps; + +impl ReadingEps { + /// `None` when 8 are being read. + fn enter() -> Option { + READING_EPS.with(|d| (d.get() < 8).then(|| d.set(d.get() + 1))).map(|()| Self) + } +} + +impl Drop for ReadingEps { + fn drop(&mut self) { + READING_EPS.with(|d| d.set(d.get().saturating_sub(1))); + if READING_EPS.with(std::cell::Cell::get) == 0 { + EPS_CHECKS.with_borrow_mut(Vec::clear); + } + } +} + +/// The warnings of reading `bytes` as an EPS file, the way a placed document's art is read from +/// them (art left out after an operator that isn't read, for one); `None` when they don't read. +/// Past 8 included files read inside one another they count as readable without warnings; drawing +/// reads a bounded number of them in turn. The check uses previews for placed documents, so +/// drawing does not start another chain of checks inside this one. Repeated structural reads +/// share completed checks at the same depth until the outer check ends. +fn readable_eps(bytes: &[u8]) -> Option> { + let key = (hash_bytes(bytes), READING_EPS.with(std::cell::Cell::get)); + if let Some(warnings) = EPS_CHECKS.with_borrow(|c| c.iter().find(|(k, _)| *k == key).map(|(_, warnings)| warnings.clone())) { + return warnings; + } + let Some(_reading) = ReadingEps::enter() else { return Some(vec![]) }; + #[cfg(any(test, feature = "work-count"))] + crate::INCLUDED_EPS_READS.with(|n| n.set(n.get() + 1)); + let warnings = vectorcraft_doc::placed_document::with_previews(|| { + crate::import_names(bytes, true, false, crate::NameEncoding::default()).ok().map(|r| r.warnings) + }); + EPS_CHECKS.with_borrow_mut(|c| { + if c.len() >= MAX_EPS_CHECKS { + c.remove(0); + } + c.push((key, warnings.clone())); + }); + warnings +} impl<'a> Reader<'a> { + /// Do the bytes `eps` of an included EPS file read ([`readable_eps`])? When they do, what reading + /// them warns of is a warning of this file's too. + fn read_included(&mut self, eps: &[u8]) -> bool { + let Some(warnings) = readable_eps(eps) else { return false }; + for w in warnings { + self.warn(&format!("a placed EPS file: {w}")); + } + true + } + /// A text object (`/AI11Text`): an empty group standing for it, named after its story. pub(super) fn text_slot(&mut self, o: &Obj) -> Result<(), String> { if self.pattern.is_some() { @@ -838,8 +909,9 @@ impl<'a> Reader<'a> { } /// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that - /// shows the preview the data keeps of it, as a linked image whose file is missing does. One - /// without a preview, a path or a matrix isn't read. + /// shows the preview the data keeps of it, as a linked image whose file is missing does. An EPS + /// file whose bytes the data includes becomes a placed document of them ([`Self::placed_eps`]). + /// One without a preview or those bytes, a path or a matrix isn't read. pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> { // Where a symbol's art puts a placed file's pixels isn't known. if self.symbol.is_some() { @@ -847,11 +919,43 @@ impl<'a> Reader<'a> { self.left_out_of_symbol(); return Ok(()); } + let mut deferred = None; let (m, b, path, png, w, h, folder) = match self.place.take() { Some(Place { broken: true, .. }) => { self.unreadable("placed files", hidden); return Ok(()); } + Some(Place { matrix: Some(m), bounds: Some(b), path, document: Some(eps), preview, folder, .. }) + // A file without a bounding box of its own has its art read on a page of another + // size, which the placed box can't be matched to. + // One named `.ai` or `.ait` is read with the artboard its header gives rather than + // its bounding box, so it isn't read either. Bytes that don't read as an EPS file + // leave it as a placed file without them: its preview, or an unread one. + if !path.is_empty() + && !ai_named(&path) + && is_postscript(&eps) + // A native document's artboard, rather than its bounding box, frames what the loader reads. + && !native_eps(&eps) + && crate::dcs::read(&eps).is_none() + && sane(b) + && b.width() > 0.0 + && b.height() > 0.0 + && eps_box(&eps).is_some() + && self.read_included(&eps) => + { + let Some((placed, blob)) = self.placed_eps(m, path.clone(), eps, folder.clone(), hidden) else { return Ok(()) }; + if let Some((png, w, h)) = preview { + // No image variable binds pattern or brush art, which a reader of its own + // reads: there the placed document goes in at once. + if self.pattern.is_some() { + return self.add_placed_eps(placed, blob, hidden); + } + deferred = Some((placed, blob)); + (m, b, path, png, w, h, folder) + } else { + return self.add_placed_eps(placed, blob, hidden); + } + } Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)), folder, .. }) if !path.is_empty() => { (m, b, path, png, w, h, folder) } @@ -902,6 +1006,10 @@ impl<'a> Reader<'a> { .filter(|a| a.as_coeffs().iter().all(|v| v.is_finite())); let xf = self.space() * m * over_file; if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + // An included EPS file is still read when its preview can't be placed. + if let Some((placed, blob)) = deferred { + return self.add_placed_eps(placed, blob, hidden); + } self.unreadable("placed files", hidden); return Ok(()); } @@ -911,7 +1019,11 @@ impl<'a> Reader<'a> { let key = linked_key(&blob, &path); let fresh = !self.doc.images.contains_key(&key); self.doc.images.entry(key.clone()).or_insert(blob); - self.warn(LINKED_PREVIEWS); + // An included EPS file shows its preview only when an image variable binds it, which the + // importer notes then. + if deferred.is_none() { + self.warn(LINKED_PREVIEWS); + } let id = NodeId(self.doc.peek_next_id()); if let Some(shift) = elsewhere && self.placed_elsewhere.len() < MAX_PLACED_ELSEWHERE @@ -928,7 +1040,11 @@ impl<'a> Reader<'a> { self.placed_tails.push(PlacedTail { id, key: key.clone(), size: (b.width(), b.height()), fresh, depth }); let mut link = LinkInfo::new(path); link.relative = folder.and_then(|f| relative_path(&f, link.name())); - self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden) + self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)?; + if let Some((placed, blob)) = deferred { + self.placed_eps.push(PlacedEps { id, placed, blob }); + } + Ok(()) } /// The dictionary `o` after the placed file just read: with a page or a box in it, that file is @@ -962,6 +1078,54 @@ impl<'a> Reader<'a> { self.placed_pages.push(PlacedPage { id: tail.id, page, bounding, page_box, size: tail.size }); } + /// The placed EPS file at `path` whose bytes `eps` the data includes, its box (in its own space, + /// y up: the bounding box its comments give, [`eps_box`], which its art is read in) taken into + /// art space by `m`: a placed document showing that box, which keeps the bytes and draws them + /// whether or not its file is found. Its link has the size and hash of those bytes, so a file + /// found unchanged isn't reported as modified. The placed document has no preview, so a save + /// keeps the bytes. Not read without that box. + fn placed_eps(&mut self, m: Affine, path: String, eps: Vec, folder: Option, hidden: bool) -> Option<(PlacedDocument, ImageBlob)> { + let Some(b) = eps_box(&eps) else { + self.unreadable("placed files", hidden); + return None; + }; + // The placed document's box runs down from the file's top left corner. + let xf = self.space() * m * Affine::new([1.0, 0.0, 0.0, -1.0, b.x0, b.y1]); + if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 { + self.unreadable("placed files", hidden); + return None; + } + let hash = hash_bytes(&eps); + let key = key_for(&hash, 1, false, PageBox::Crop); + let mut link = LinkInfo::new(path); + link.relative = folder.and_then(|f| relative_path(&f, link.name())); + (link.page, link.size, link.hash) = (Some(1), u64::try_from(eps.len()).ok(), Some(hash)); + let blob = ImageBlob { mime: EPS_MIME.into(), bytes: Arc::new(eps), proxy: None, file_font: Default::default() }; + let placed = PlacedDocument { + link, + key, + bounding: false, + page_box: PageBox::Crop, + width: b.width(), + height: b.height(), + xf, + placement: Default::default(), + }; + Some((placed, blob)) + } + + /// `placed` ([`Self::placed_eps`]) added as an object, its bytes `blob` kept under its key. + /// Placements of the same bytes share one blob. + fn add_placed_eps(&mut self, placed: PlacedDocument, blob: ImageBlob, hidden: bool) -> Result<(), String> { + self.doc.images.entry(placed.key.clone()).or_insert(blob); + let gs = self.gs.clone(); + let mut node = self.new_node(NodeKind::PlacedDocument(Box::new(placed)), &gs); + node.opacity = gs.opacity; + node.blend = gs.blend; + node.knockout_shape = gs.knockout_shape; + self.add(node, hidden) + } + pub(super) fn warn(&mut self, w: &str) { if !self.warnings.iter().any(|x| x == w) && self.warnings.len() < 64 { self.warnings.push(w.to_string()); @@ -1083,6 +1247,65 @@ fn placed_crop(v: f64) -> Option<(bool, PageBox)> { } } +/// The bytes of a placed file the data includes (`doc`: between the `%%BeginDocument:` line and +/// the `%%EndDocument` one), as the file has them: on `%_` lines (`hidden`) without the `%_` that +/// starts each line, then without a line end the data adds before `%%EndDocument` after the file's +/// own last one. A single line end at the end is the file's own. The line end added is `sep`, the +/// one the data ends its `%%BeginDocument:` line with, when the bytes end with it; otherwise the +/// last line end they end with. An LF `sep` after a CR isn't taken apart from it when the file's +/// first line ends with CRLF: that CRLF is one line end of the file's. +pub(super) fn included_document(doc: &[u8], hidden: bool, sep: Option<&[u8]>) -> Vec { + let mut out = if hidden { unhidden(doc) } else { doc.to_vec() }; + let eol = |b: &[u8]| b.ends_with(b"\r") || b.ends_with(b"\n"); + let first_eol = out.iter().position(|&b| b == b'\r' || b == b'\n').and_then(|i| out.get(i..i + 2)); + let crlf_file = first_eol == Some(b"\r\n") && out.ends_with(b"\r\n"); + let added = sep + .filter(|s| out.ends_with(s) && !(crlf_file && *s == b"\n")) + .or_else(|| [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| out.ends_with(e))) + .map(|e| out.len() - e.len()); + if let Some(n) = added.filter(|&n| out.get(..n).is_some_and(eol)) { + out.truncate(n); + } + out +} + +/// The bounding box an EPS file's comments give (`%%HiResBoundingBox` when it has one), in its +/// own space; `None` without one, or when it is empty or out of range. +fn eps_box(eps: &[u8]) -> Option { + let [x0, y0, x1, y1] = crate::import::bounding_box(eps)?; + Some(Rect::new(x0, y0, x1, y1)).filter(|r| sane(*r) && r.width() > 0.0 && r.height() > 0.0) +} + +/// Does `eps` have a native document's begin comment line, without reading that document? +fn native_eps(eps: &[u8]) -> bool { + eps.split(|b| *b == b'\r' || *b == b'\n') + .any(|line| line.strip_prefix(crate::BEGIN_DATA.as_bytes()).is_some_and(|name| name.trim_ascii() == crate::NATIVE.as_bytes())) +} + +/// Does the file name at the end of `path` (`/` or `\` separators) end in `.ai` or `.ait`, any case? +fn ai_named(path: &str) -> bool { + let name = path.rsplit(['/', '\\']).next().unwrap_or(path); + name.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("ai") || ext.eq_ignore_ascii_case("ait")) +} + +/// `doc` without the `%_` that starts each of its lines. +fn unhidden(doc: &[u8]) -> Vec { + let mut out = Vec::with_capacity(doc.len()); + let mut line_start = true; + let mut i = 0; + while let Some(&b) = doc.get(i) { + if line_start && doc.get(i..i + 2) == Some(b"%_") { + i += 2; + line_start = false; + continue; + } + out.push(b); + line_start = b == b'\r' || b == b'\n'; + i += 1; + } + out +} + /// A placed file's path relative to the document's folder (`/` separators): its relative `folder` /// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the /// document's own folder). `None` when the folder is absolute or holds control characters, or @@ -1155,3 +1378,36 @@ pub(crate) fn join_and(items: &[&str]) -> String { [rest @ .., last] => format!("{} and {last}", rest.join(", ")), } } + +#[cfg(test)] +mod tests { + use super::{ReadingEps, readable_eps}; + + /// Check results keep their warnings and failures, respect depth, and expire with the outer check. + #[test] + fn included_eps_checks_keep_the_depth_limit_and_expire() { + let eps = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor 0 0 60 60 rectfill nosuchoperator\n%%EOF\n"; + { + let _outer = ReadingEps::enter().unwrap(); + let warnings = readable_eps(eps).unwrap(); + assert!(!warnings.is_empty(), "a partly read file still passes, with warnings"); + let reads = crate::included_eps_reads(); + assert_eq!(readable_eps(eps).unwrap(), warnings); + assert_eq!(crate::included_eps_reads(), reads, "the repeated check did not parse again"); + let limits: Vec<_> = std::iter::from_fn(ReadingEps::enter).collect(); + assert!(!limits.is_empty()); + assert!(readable_eps(eps).unwrap().is_empty(), "past the depth limit, warnings are not read"); + drop(limits); + assert_eq!(readable_eps(eps).unwrap(), warnings, "the deeper check did not replace the cached warnings"); + let broken = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + assert!(readable_eps(broken).is_none()); + let reads = crate::included_eps_reads(); + assert!(readable_eps(broken).is_none()); + assert_eq!(crate::included_eps_reads(), reads, "a repeated failed check did not parse again"); + } + let _outer = ReadingEps::enter().unwrap(); + let reads = crate::included_eps_reads(); + assert!(readable_eps(eps).is_some()); + assert!(crate::included_eps_reads() > reads, "the outer check's results were discarded"); + } +} diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 2a14ce1c24..ad97b7b47b 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -917,6 +917,7 @@ impl<'a> Reader<'a> { } let Some(p) = self.envelopes.pop() else { return }; let scale = self.space_scale(); + let pages = self.pages_in_doc(); let drawn = self.frames.last().filter(|f| f.children.len() == p.siblings + 1).and_then(|f| f.children.last()); let Some(drawn) = drawn else { self.warn(crate::import::ai::envelope::drawn_note(p.typed)); @@ -959,8 +960,7 @@ impl<'a> Reader<'a> { (shown.visible, shown.opacity) = (true, 1.0); let mut plain = drawn.clone(); (plain.visible, plain.opacity) = (true, 1.0); - let page = self.page_in_doc(); - let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent); + let mut alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent); // In Edit Contents, a grid that draws the contents elsewhere than the drawn art is checked // again moved onto that art. if !alike @@ -969,7 +969,7 @@ impl<'a> Reader<'a> { { self.envelope_checks -= 1; (envelope.kind, shown.kind) = (kind.clone(), kind); - alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, page, &mut self.envelope_spent); + alike = crate::import::ai::envelope::drawn_alike(&shown, &plain, layer, &shared, &pages, &mut self.envelope_spent); } if !alike { self.warn(crate::import::ai::envelope::DRAWN); diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 8492cca6f0..9621e7a9b0 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -55,6 +55,22 @@ impl AiArtboard { } } +/// The pages the art may be compared with in the document's space, art space being moved there by +/// `to_doc` (none before the art starts): each of `artboards` (else `first`, the first artboard), +/// then `art_box`, the art's bounding box. A page that is an earlier one to half a point is left out. +fn pages_of(to_doc: Option, artboards: &[AiArtboard], first: Option, art_box: Option) -> Vec { + let Some(to_doc) = to_doc else { return vec![] }; + let boards: Vec = if artboards.is_empty() { first.into_iter().collect() } else { artboards.iter().map(|b| b.rect).collect() }; + let mut pages: Vec = vec![]; + for page in boards.into_iter().chain(art_box).map(|r| to_doc.transform_rect_bbox(r)) { + let same = |p: &Rect| [p.x0 - page.x0, p.y0 - page.y0, p.x1 - page.x1, p.y1 - page.y1].iter().all(|d| d.abs() <= 0.5); + if !pages.iter().any(same) { + pages.push(page); + } + } + pages +} + /// The number of entry `key` in `o` when it is written as one finite number of the type `ty` /// (`/Int`, `/Real`, `/Bool`; a whole number unless `/Real`), else `None`. fn typed(o: &Obj, key: &str, ty: &str) -> Option { @@ -923,10 +939,21 @@ impl<'a> Reader<'a> { self.artboards.first().map(|b| b.rect).or(self.cropmarks).or_else(|| self.sized_board()) } - /// The page the art is compared with in the document's space, once the art has started. - pub(super) fn page_in_doc(&self) -> Option { - let board = self.first_board().or_else(|| self.bbox_board())?; - Some(self.to_doc?.transform_rect_bbox(board)) + /// Every page the art may be compared with, in the document's space, once the art has started: + /// each artboard (else the first artboard [`Self::first_board`] gives), since a page of a file's + /// PDF part can show any of them, and the art's bounding box ([`Self::bbox_board`]), which a page + /// cropped to the art and the page of the legacy format show ([`pages_of`]). Worked out again + /// only when the artboards, the art's box or the move into the document have changed. + pub(super) fn pages_in_doc(&mut self) -> Arc<[Rect]> { + let sources = (self.to_doc, self.artboards.len(), self.first_board(), self.bbox_board()); + if let Some((from, pages)) = &self.page_cache + && *from == sources + { + return pages.clone(); + } + let pages: Arc<[Rect]> = pages_of(sources.0, &self.artboards, sources.2, sources.3).into(); + self.page_cache = Some((sources, pages.clone())); + pages } /// The page of a file that says nothing of its artboard (the legacy format as other apps write @@ -1239,8 +1266,8 @@ impl<'a> Reader<'a> { } let to_doc = self.ensure_space(); let artboard = self.first_board(); - // Before the artboards are taken below: the page is the first artboard's. - let page = self.page_in_doc(); + // Before the artboards are taken below: the pages are the artboards' and the art's box. + let pages = self.pages_in_doc(); self.check_symbols(); self.order_symbols(); drop_commented_copies(&mut self.doc.layers, &self.hidden_ids); @@ -1441,13 +1468,14 @@ impl<'a> Reader<'a> { placeholders: self.placeholders, placed_elsewhere: self.placed_elsewhere, placed_pages: self.placed_pages, + placed_eps: self.placed_eps, envelopes_drawn: self.envelopes_drawn, warped_type: super::super::envelope::WarpedType { looks: self.warped_type, envelopes: self.typed_envelopes, checks: self.envelope_checks, spent: self.envelope_spent, - page, + pages: pages.to_vec(), alone: None, type_clips: self.type_clips, }, diff --git a/crates/eps/src/import/ai/read/on_path.rs b/crates/eps/src/import/ai/read/on_path.rs index 1e33e09a1b..682739c27d 100644 --- a/crates/eps/src/import/ai/read/on_path.rs +++ b/crates/eps/src/import/ai/read/on_path.rs @@ -123,6 +123,18 @@ impl Reader<'_> { } } +#[cfg(test)] +thread_local! { + /// How many paths and objects the records on this thread have measured. + static MEASURED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`MEASURED`] of this thread. +#[cfg(test)] +pub(crate) fn on_path_measured() -> u64 { + MEASURED.get() +} + /// Give each group that a record of `found` names exactly its [`ObjectsOnPath`] record. pub(super) fn apply(doc: &mut Document, found: &OnPath) { if found.records.is_empty() { @@ -174,11 +186,15 @@ fn apply_one(doc: &mut Document, found: &OnPath, at: &HashMap if !tried.insert(g.id) { return None; } + #[cfg(test)] + MEASURED.set(MEASURED.get() + 1); attachable_path(children.iter().find(|c| c.id == path)?)?; let mut members = Vec::with_capacity(placed.len()); for (id, place, angle) in placed { // The frame the object is drawn in: turned by its angle (the document's y points down) // about the center of its bounds. + #[cfg(test)] + MEASURED.set(MEASURED.get() + 1); let center = doc.node_at(place)?.geometric_bounds()?.center(); members.push(Member { id, frame: Affine::rotate_about(angle, center), angle }); } diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index fcdffd4580..881d3b3703 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -9,6 +9,29 @@ use super::{ use vectorcraft_doc::{ArrowAlign, Arrowhead}; use vectorcraft_geom::PathData; +#[cfg(test)] +thread_local! { + /// The operand stack slots that `[` and `]` have looked at on this thread, to find the open + /// `[` or to take an array's items: their work. + static ARRAY_SLOTS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The point-to-segment distances [`draws_look_outline`] has worked out on this thread. + static OUTLINE_PAIRS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// [`ARRAY_SLOTS`] of this thread. +#[cfg(test)] +pub(crate) fn array_slots() -> u64 { + ARRAY_SLOTS.get() +} + +/// Count `slots` that `[` or `]` looked at in [`ARRAY_SLOTS`]; nothing outside tests. +fn array_slots_looked_at(slots: usize) { + #[cfg(test)] + ARRAY_SLOTS.set(ARRAY_SLOTS.get().saturating_add(u64::try_from(slots).unwrap_or(u64::MAX))); + #[cfg(not(test))] + let _ = slots; +} + impl<'a> Reader<'a> { // ---- operators ------------------------------------------------------------------------- @@ -16,11 +39,13 @@ impl<'a> Reader<'a> { // The innermost `[` still on the stack (the stack is cut back by operators). let mut at = self.stack.len(); while let Some(m) = self.marks.pop() { + array_slots_looked_at(1); if matches!(self.stack.get(m), Some(V::Mark)) { at = m; break; } } + array_slots_looked_at(self.stack.len() - at); let items: Vec = self.stack.split_off(at).into_iter().skip(1).collect(); self.push(V::Arr(items)) } @@ -172,6 +197,7 @@ impl<'a> Reader<'a> { "[" => { // Drop marks that operators have taken off, so `marks` is the open nesting. while self.marks.last().is_some_and(|&m| !matches!(self.stack.get(m), Some(V::Mark))) { + array_slots_looked_at(1); self.marks.pop(); } // Arrays nest as deep as their `[`s; dropping a deeper one would overflow the stack. @@ -787,7 +813,7 @@ impl<'a> Reader<'a> { } let space = self.space(); self.note_brushes_kept(); - let page = self.page_in_doc(); + let pages = self.pages_in_doc(); let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); let (Some(object), Some(look)) = (n.checked_sub(1).and_then(|i| f.children.get(i)), n.checked_sub(2).and_then(|i| f.children.get(i))) else { @@ -873,7 +899,8 @@ impl<'a> Reader<'a> { let layer = self.doc.alloc_id(); let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; let shown = !hidden && object.visible && look.visible; - look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + let on: &[Rect] = if shown { &pages } else { &[] }; + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, on, &mut self.envelope_spent) }; alike.then_some(ap) } @@ -885,7 +912,7 @@ impl<'a> Reader<'a> { let layer = self.doc.alloc_id(); let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; let mut spent = crate::import::ai::envelope::Spent::default(); - look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, None, &mut spent) + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, &[], &mut spent) }; alike.then_some(ap) } @@ -1314,7 +1341,7 @@ fn look_alike( hidden: bool, layer: NodeId, shared: &crate::import::ai::envelope::Shared<'_>, - page: Option, + pages: &[Rect], spent: &mut crate::import::ai::envelope::Spent, ) -> bool { let mut live = object.clone(); @@ -1329,7 +1356,7 @@ fn look_alike( for n in [&mut live, &mut plain] { (n.visible, n.opacity, n.blend) = (true, 1.0, BlendMode::Normal); } - crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent) + crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, pages, spent) } /// Does `appearance` stroke with dashes aligned to corners and path ends? @@ -1635,7 +1662,13 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo /// projection onto it) is taken from `budget`: `false` once that runs out. fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool { use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; - let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT); + let close = |p: kurbo::Point| { + b.iter().any(|t| { + #[cfg(test)] + OUTLINE_PAIRS.set(OUTLINE_PAIRS.get() + 1); + t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT + }) + }; for s in a { let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil(); let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 }; @@ -2019,7 +2052,8 @@ mod tests { /// The outline check works from one budget for the object: a look of the outline drawn twice /// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn - /// look instead of comparing every copy. + /// look instead of comparing every copy, having worked out no more distances than the budget + /// holds. #[test] fn the_outline_check_has_one_budget_for_the_object() { let zig = vectorcraft_doc::Effect { @@ -2035,10 +2069,17 @@ mod tests { let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect(); Node::group(NodeId(2), drawn) }; - assert!(draws_look_outline(&object, &appearance, &look(2))); - let started = std::time::Instant::now(); - assert!(!draws_look_outline(&object, &appearance, &look(5_000))); - assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + // Whether the object draws `look`, and how many distances the check worked out. + let check = |look: &Node| { + let before = OUTLINE_PAIRS.get(); + let drawn = draws_look_outline(&object, &appearance, look); + (drawn, OUTLINE_PAIRS.get() - before) + }; + let (drawn, two) = check(&look(2)); + assert!(drawn); + let (drawn, many) = check(&look(5_000)); + assert!(many <= u64::try_from(MAX_OUTLINE_PAIRS).unwrap(), "5,000 copies: {many} distances; 2 copies: {two}"); + assert!(!drawn); } /// The outline check reshapes the object as it is drawn, its effects working from its bounds diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index a155d9f505..27eb8a8576 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -312,6 +312,9 @@ pub(super) struct Place { pub(super) folder: Option, /// The operand stack's height at `%AI28_BeginPlacedRelativePath`, until its end. pub(super) folder_at: Option, + /// The file's bytes, when the data includes them between `%%BeginDocument:` and + /// `%%EndDocument` (at most [`MAX_PLACED_DOCUMENT`]). + pub(super) document: Option>, /// Its `` ` `` was read. pub(super) ticked: bool, /// It began on a `%_` line, in a hidden object or on a layer that doesn't show. @@ -361,8 +364,26 @@ pub struct PlacedPage { pub size: (f64, f64), } +/// An included EPS whose linked preview becomes a placed document after variable binding. +#[derive(Debug)] +pub struct PlacedEps { + /// The linked image. + pub id: NodeId, + /// The document that replaces the image unless an image variable binds it. + pub placed: vectorcraft_doc::PlacedDocument, + /// The EPS bytes stored under the placed document's key only when it replaces the image. + pub blob: vectorcraft_doc::ImageBlob, +} + +/// The largest placed file kept from the bytes the data includes (the largest file File › Place +/// reads). +pub(super) const MAX_PLACED_DOCUMENT: usize = 256 << 20; + +/// The type a placed EPS file's bytes are stored with. +pub(super) const EPS_MIME: &str = "application/postscript"; + /// What the open result says of placed files: they show the preview the file keeps of them. -pub(super) const LINKED_PREVIEWS: &str = +pub(crate) const LINKED_PREVIEWS: &str = "linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel"; /// What the open result says of linked images the data keeps no pixels of (`XF`): they show a diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 242d433b7b..9e309bc458 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -12,7 +12,9 @@ use super::*; /// [`super::read`] as an EPS reads it. fn read(data: &[u8]) -> Result { - super::read(data, true) + let mut r = super::read(data, true)?; + super::super::native::placed_documents(&mut r.doc, &[], &r.placed_eps); + Ok(r) } /// Editing data: header comments (crop marks 0 0 200 100), then `body`. @@ -3495,6 +3497,178 @@ fn a_placed_file_keeps_its_folder_relative_to_the_document() { assert_eq!(relative_of(&cut), None); } +/// An EPS file of `w` × `h` points filled red, its lines ended by `eol`. +fn red_eps(w: u32, h: u32, eol: &str) -> Vec { + format!("%!PS-Adobe-3.0 EPSF-3.0{eol}%%BoundingBox: 0 0 {w} {h}{eol}%%EndComments{eol}1 0 0 setrgbcolor{eol}0 0 {w} {h} rectfill{eol}%%EOF{eol}") + .into_bytes() +} + +/// `data` with the first `from` in it replaced by `to`. +fn splice(data: &[u8], from: &[u8], to: &[u8]) -> Vec { + let at = data.windows(from.len()).position(|w| w == from).unwrap(); + [&data[..at], to, &data[at + from.len()..]].concat() +} + +/// [`placed`]'s file with the placed file `/old/place/src/shape.eps` in the box 0 0 80 50, in the +/// folder `src/`, without a preview, and `doc` included between `%%BeginDocument:` and +/// `%%EndDocument` in place of `%%IncludeFile:` (`%%FileType: 0`). +fn placed_eps_file(doc: &[u8]) -> Vec { + let data = placed(true, "[5 0 0 -5 0 200]", "/old/place/src/shape.eps", None, ""); + let data = splice(&data, b"10 20 14 22 4 4 0", b"0 0 80 50 4 4 0"); + let data = splice(&data, b"\r()\r", b"\r(src/)\r"); + let data = splice(&data, b"%%FileType: 1", b"%%FileType: 0"); + let included = [&b"%%BeginDocument: /old/place/src/shape.eps\r"[..], doc, b"\r%%EndDocument\r"].concat(); + splice(&data, b"%%IncludeFile:/old/place/src/shape.eps\r", &included) +} + +/// The one placed document of `data`, with the blob its key names. +fn one_placed(data: &[u8]) -> (Node, vectorcraft_doc::PlacedDocument, vectorcraft_doc::ImageBlob, Structure) { + let r = read(data).unwrap(); + let a = art(&r.doc); + let [n] = &a[..] else { panic!("one object: {a:?}") }; + let NodeKind::PlacedDocument(p) = &n.kind else { panic!("a placed document: {:?}", n.kind) }; + let blob = r.doc.images[&p.key].clone(); + ((**n).clone(), (**p).clone(), blob, r) +} + +#[test] +fn a_placed_eps_file_whose_bytes_the_data_includes_is_a_placed_document_of_them() { + let eps = red_eps(80, 50, "\n"); + let (_, p, blob, r) = one_placed(&placed_eps_file(&eps)); + assert_eq!(*blob.bytes, eps, "the file's own bytes, without the line end the data adds"); + assert_eq!((blob.mime.as_str(), blob.proxy.is_none()), ("application/postscript", true)); + assert_eq!((p.link.path.as_str(), p.link.relative.as_deref()), ("/old/place/src/shape.eps", Some("src/shape.eps"))); + assert_eq!((p.link.page, p.link.size, p.link.hash.clone()), (Some(1), Some(eps.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&eps)))); + assert_eq!((p.width, p.height, p.bounding, p.page_box), (80.0, 50.0, false, vectorcraft_doc::PageBox::Crop)); + assert!(r.unread.is_empty() && r.hidden_unread.is_empty() && r.unread_elsewhere.is_empty(), "{:?}", r.unread); + assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{:?}", r.warnings); + // The matrix takes the file's own space (y up) into art space; the box's top left corner is the + // file's (0, 50). + let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]); + for (corner, file) in [((0.0, 0.0), (0.0, 50.0)), ((80.0, 50.0), (80.0, 0.0)), ((80.0, 0.0), (80.0, 50.0))] { + let (got, want) = (p.xf * Point::from(corner), r.to_doc * m * Point::from(file)); + assert!((got - want).hypot() < 1e-9, "{corner:?}: {got:?} {want:?}"); + } +} + +#[test] +fn a_placed_eps_file_with_included_bytes_and_a_preview_keeps_only_the_bytes() { + let eps = red_eps(80, 50, "\n"); + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let section = + [&b"%AI17_Begin_Content_if_version_gt:24 5\r%AI26_BeginPlacedObjectPreview\r"[..], &preview, b"\r%AI26_EndPlacedObjectPreview\r"].concat(); + let data = splice(&placed_eps_file(&eps), b"%AI17_Begin_Content_if_version_gt:24 5\r", §ion); + // The placed document has no preview, so a save keeps its bytes. + let (_, _, blob, _) = one_placed(&data); + assert_eq!((&*blob.bytes, blob.proxy.is_none()), (&eps, true)); + // The same bytes placed twice share the blob. + let one = placed_eps_file(&eps); + let (from, to) = (|d: &[u8], w: &[u8]| d.windows(w.len()).position(|x| x == w).unwrap(), b"%AI5_EndPlace\r"); + let first = &one[from(&one, b"%AI5_BeginPlace")..from(&one, to) + to.len()]; + let twice = splice(&data, b"%AI5_BeginPlace", &[first, b"%AI5_BeginPlace"].concat()); + let r = read(&twice).unwrap(); + let a = art(&r.doc); + let keys: Vec<_> = a.iter().filter_map(|n| if let NodeKind::PlacedDocument(p) = &n.kind { Some(p.key.clone()) } else { None }).collect(); + assert!(keys.len() == 2 && keys[0] == keys[1], "{keys:?}"); + assert!(r.doc.images[&keys[0]].proxy.is_none()); +} + +#[test] +fn a_placed_eps_files_box_is_its_high_resolution_bounding_box() { + let eps = splice(&red_eps(80, 50, "\n"), b"%%EndComments", b"%%HiResBoundingBox: 0.5 0.5 79.5 49.5\n%%EndComments"); + let (_, p, _, r) = one_placed(&placed_eps_file(&eps)); + assert_eq!((p.width, p.height), (79.0, 49.0)); + // The box's top left corner is the file's (0.5, 49.5), where the matrix puts it. + let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]); + let (got, want) = (p.xf * Point::ZERO, r.to_doc * m * Point::new(0.5, 49.5)); + assert!((got - want).hypot() < 1e-9, "{got:?} {want:?}"); +} + +#[test] +fn a_placed_eps_files_box_with_its_corners_reversed_leaves_it_unread() { + let data = splice(&placed_eps_file(&red_eps(80, 50, "\n")), b"0 0 80 50 4 4 0", b"80 50 0 0 4 4 0"); + let r = read(&data).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc)); +} + +#[test] +fn an_included_eps_files_own_last_line_end_is_kept() { + // The data's line end after the file's own is taken off; a single one is the file's. + let (lf, crlf) = ("%!PS\n%%BoundingBox: 0 0 80 50\n%%EOF\n", "%!PS\r\n%%BoundingBox: 0 0 80 50\r\n%%EOF\r\n"); + for (eps, written) in [(lf, format!("{lf}\r")), (lf, lf.to_string()), (crlf, format!("{crlf}\r\n"))] { + let data = splice(&placed_eps_file(b"%!@@"), b"%!@@\r%%EndDocument", format!("{written}%%EndDocument").as_bytes()); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), eps, "{written:?}"); + } + // The line end added is the one the `%%BeginDocument:` line ends with: an LF after a file whose + // lines end with CR isn't read as a CRLF of the file's. + let data = + splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", b"shape.eps\n%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r\n%%EndDocument"); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), "%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r"); + // A file whose lines end with CRLF, included as it is after an LF: its last CRLF is its own. + let data = splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", format!("shape.eps\n{crlf}%%EndDocument").as_bytes()); + let (_, _, blob, _) = one_placed(&data); + assert_eq!(String::from_utf8_lossy(&blob.bytes), crlf); +} + +#[test] +fn a_placed_eps_file_on_commented_lines_keeps_its_bytes() { + let eps = red_eps(80, 50, "\r"); + let hidden = hide_placed(&placed_eps_file(&eps)); + let (_, _, blob, _) = one_placed(&hidden); + assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the `%_` that starts each line taken off"); + // The line end added before `%%EndDocument` on a `%_` line of its own. + let (_, _, blob, _) = one_placed(&splice(&hidden, b"%%EOF\r\r%_%%EndDocument", b"%%EOF\r%_\r%_%%EndDocument")); + assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the added line end taken off"); +} + +#[test] +fn an_included_postscript_file_named_as_an_ai_file_stays_unread() { + // Read through its name with the artboard its header gives, not the box the placed one shows. + for name in ["shape.ai", "SHAPE.AIT"] { + let mut data = placed_eps_file(&red_eps(80, 50, "\n")); + while data.windows(9).any(|w| w == b"shape.eps") { + data = splice(&data, b"shape.eps", name.as_bytes()); + } + let r = read(&data).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{name}: {:?}", art(&r.doc)); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{name}: {:?}", r.unread); + } +} + +#[test] +fn included_eps_with_a_native_document_leaves_the_placed_file_unread() { + // Even unreadable native data leaves the file unread: the loader can read an artboard + // larger than the EPS bounding box, which would shrink and offset the art when placed. + for eol in ["\n", "\r", "\r\n"] { + let section = format!("%VectorCraft_BeginData: native \t{eol}%unreadable native data{eol}%VectorCraft_EndData{eol}%%EOF"); + let eps = splice(&red_eps(80, 50, eol), b"%%EOF", section.as_bytes()); + let r = read(&placed_eps_file(&eps)).unwrap(); + assert!( + !art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), + "included EPS with a native document must stay on the fallback path" + ); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread); + } +} + +#[test] +fn included_bytes_that_arent_an_eps_file_leave_the_placed_file_unread() { + // A DCS file, which the placed document reader doesn't read (File › Place makes it a linked + // image), stays unread too. + let dcs = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%PlateFile: (Black) EPS Local pic.K\n%%EndComments\n%%EOF\n"; + // An EPS file without a bounding box, whose art is read on a page of another size, stays unread. + let boxless = b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n1 0 0 setrgbcolor\n0 0 80 50 rectfill\n%%EOF\n"; + // An EPS file whose program doesn't read draws nothing, so it stays unread too. + let broken = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 80 50\n%%EndComments\n0 0 80 50 nosuchoperator\n%%EOF\n"; + for bytes in [&b"hello\rworld"[..], dcs, boxless, broken] { + let r = read(&placed_eps_file(bytes)).unwrap(); + assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc)); + assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread); + } +} + #[test] fn hidden_placed_file_ended_by_comment_stays_hidden() { let mut data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", None, "")); @@ -3588,6 +3762,7 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> { NodeKind::Group { .. } => "group", NodeKind::Path { .. } => "path", NodeKind::Image(_) => "image", + NodeKind::PlacedDocument(_) => "placed", _ => "other", }) .collect() @@ -3596,13 +3771,16 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> { #[test] fn version7_placed_file_included_whole_is_read() { // The included document's operators, a `~`, a nested document and counted data in it aren't - // the editing data's. - let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor frobnicate ~\n\ + // the editing data's (the file defines them, so its program reads). + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n/frobnicate {} def /~ {} def\n1 0 0 setrgbcolor frobnicate ~\n\ %%BeginDocument: inner.eps\n~\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n"; let body = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n"); let r = placed_read7(true, &body).unwrap(); - assert_eq!(art_kinds(&r.doc), ["path"]); - assert_unread(&r, "placed files"); + // A placed document of the file's bytes. + assert_eq!(art_kinds(&r.doc), ["placed"]); + let NodeKind::PlacedDocument(p) = &art(&r.doc)[0].kind else { panic!() }; + assert_eq!(r.doc.images[&p.key].bytes.as_slice(), eps.as_bytes()); + assert!(r.unread.is_empty(), "{:?}", r.unread); // One that doesn't end leaves the layer without its end. let cut = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}~\n"); assert!(placed_read7(true, &cut).is_err()); @@ -6440,13 +6618,16 @@ fn a_zstandard_frame_ending_in_a_zero_byte_is_read_whole() { } } +/// A `]` without its `[` looks at a few operand stack slots, not at every slot below it: hundreds +/// of thousands of them look at no more than four slots each. #[test] fn closing_brackets_without_their_opening_dont_rescan_the_stack() { let n = 200_000; let body = format!("{}\n{}\n", "1 ".repeat(n), "] ".repeat(n)); - let started = std::time::Instant::now(); + let before = read::array_slots(); let _ = read(stream(&layer(&body)).as_bytes()); - assert!(started.elapsed() < std::time::Duration::from_secs(20), "{:?}", started.elapsed()); + let slots = read::array_slots() - before; + assert!(slots <= 4 * u64::try_from(n).unwrap(), "{n} brackets looked at {slots} slots"); } #[test] @@ -9395,24 +9576,35 @@ fn warped_type_gets_what_the_envelopes_left_of_the_budget() { let exact = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)))); let beside = format!("{RED}{}f\n", rect_path(40.5, 20.0, 160.5, 80.0)); let shifted = read_ok(&layer(&envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &beside))); + let page = Rect::new(0.0, 0.0, 200.0, 100.0); for r in [&exact, &shifted] { assert_eq!(r.warped_type.checks, super::envelope::MAX_CHECKED - 1); - assert!(r.warped_type.page.is_some()); + assert_eq!(r.warped_type.pages, [page]); } live_envelope(&art(&shifted.doc)[0]); - assert!(shifted.warped_type.spent.any > exact.warped_type.spent.any); + assert!(shifted.warped_type.spent.on(page).0 > exact.warped_type.spent.on(page).0); } -/// In a file with an artboard list, warped type is held to the first artboard, not to the crop marks. +/// In a file with an artboard list, warped type is held to every artboard, not to the crop marks. #[test] -fn warped_type_is_held_to_the_first_artboard() { +fn warped_type_is_held_to_every_artboard() { let boards = "%_/Document :\n%_/Dictionary :\n%_/Array :\n\ %_/Dictionary :\n%_0 200 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_300 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n\ %_/Dictionary :\n%_400 0 /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_600 -150 /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_; ,\n\ %_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n"; let r = read_ok(&format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0))))); assert_eq!(r.doc.artboards[0].rect, Rect::new(0.0, 0.0, 300.0, 200.0)); - assert_eq!(r.warped_type.page, Some(Rect::new(0.0, 0.0, 300.0, 200.0))); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 300.0, 200.0), Rect::new(400.0, 200.0, 600.0, 350.0)]); +} + +/// Artboards that are an earlier one to half a point, and an art box that is one of them, add no +/// page of their own. +#[test] +fn pages_that_repeat_an_artboard_are_held_once() { + let boards = boards_at(&[[0.0, 0.0, 200.0, 100.0], [0.2, 0.0, 200.0, 100.3], [0.0, 0.0, 200.0, 100.0], [300.0, 0.0, 400.0, 100.0]]); + let data = format!("{boards}{}", layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 40.0, 40.0)))); + let r = read(stream_with_header("%%HiResBoundingBox: 300 0 400 100.4\n", &data).as_bytes()).unwrap(); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 200.0, 100.0), Rect::new(300.0, 0.0, 400.0, 100.0)]); } /// Type whose Warp is hidden draws no warp, so it stays type even with no check left. @@ -9454,17 +9646,39 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { w.look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10 - i as u64), vec![Arc::new(w.look.clone()), mark.clone()]); } let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; - let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); + let page = Rect::new(0.0, 60.0, 60.0, 100.0); let settle = |w: &super::envelope::WarpedLook, spent| { - let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page, ..Default::default() }; + let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, pages: vec![page], ..Default::default() }; warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) }; - let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; + let spent = || super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() }; assert_eq!(settle(&looks[1], Default::default()), 0); assert_eq!(settle(&looks[1], spent()), 1); assert_eq!(settle(&looks[0], spent()), 0); } +/// Each page the art may be compared with has its own share of the budget: warped type on the +/// second page spends that page's share, whatever is left of the first page's. +#[test] +fn warped_type_on_a_later_page_spends_that_pages_share_of_the_budget() { + use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE}; + let (doc, mut looks) = warped_type_doc(2); + // The second object shows. Its look draws a little more than it. + let mark = read_ok(&layer(&format!("{RED}{}f\n", rect_path(2.0, 2.0, 2.6, 2.6)))); + let mark = art(&mark.doc)[0].clone(); + let w = looks.remove(1); + let look = Node::group(vectorcraft_doc::NodeId(u64::MAX - 10), vec![Arc::new(w.look.clone()), mark]); + let (first, second) = (Rect::new(200.0, 0.0, 260.0, 40.0), Rect::new(0.0, 60.0, 60.0, 100.0)); + let settle = |spent| { + let looks = vec![super::envelope::WarpedLook { slot: w.slot, look: look.clone(), left_out: None }]; + let warped = super::envelope::WarpedType { looks, checks: 1, spent, pages: vec![first, second], ..Default::default() }; + warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) + }; + let full = |page| super::envelope::Spent { pages: vec![(page, MAX_DIFFERENCE / 2.0, MAX_SOLID_DIFFERENCE / 2.0)], ..Default::default() }; + assert_eq!(settle(full(first)), 0); + assert_eq!(settle(full(second)), 1); +} + /// An envelope that comes out close to its drawn art, but with more of the page differing than the /// page check can take from the live envelopes (its drawn art 2 pt to the side on a 200 × 100 /// page), keeps the drawn art, so the file still opens from its layers. @@ -9479,6 +9693,58 @@ fn an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it() { assert_eq!(r.warnings, [super::envelope::DRAWN]); } +/// The document data of artboards in art space, each `[x0, y0, x1, y1]`. +fn boards_at(boards: &[[f64; 4]]) -> String { + let boards: String = boards + .iter() + .map(|[x0, y0, x1, y1]| { + format!("%_/Dictionary :\n%_{x0} {y1} /RealPointRelToROrigin\n%_ (PositionPoint1) ,\n%_{x1} {y0} /RealPointRelToROrigin\n%_ (PositionPoint2) ,\n%_; ,\n") + }) + .collect(); + format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{boards}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n") +} + +/// The envelope of [`an_envelope_that_differs_from_its_drawn_art_over_the_page_keeps_it`] on the +/// second artboard, the first a strip along the top that it doesn't reach: a page of the second +/// artboard can be compared with the layers, so it is held to that page and keeps its drawn art. +/// One that draws as its drawn art opens live there. +#[test] +fn an_envelope_on_a_later_artboard_that_differs_over_its_page_keeps_its_drawn_art() { + let boards = boards_at(&[[0.0, 98.0, 20.0, 100.0], [0.0, 0.0, 200.0, 100.0]]); + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted); + let r = read_ok(&format!("{boards}{}", layer(&body))); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]); + let flat = vectorcraft_doc::live::EnvelopeKind::Mesh { + rows: 1, + cols: 1, + points: vec![Point::new(40.0, 20.0), Point::new(160.0, 20.0), Point::new(40.0, 80.0), Point::new(160.0, 80.0)], + handles: vec![], + }; + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &drawn_content(&flat)); + let r = read_ok(&format!("{boards}{}", layer(&body))); + live_envelope(&art(&r.doc)[0]); +} + +/// The same envelope on no artboard, inside the art's bounding box: a page cropped to the art +/// shows it, so it is held to that page too. +#[test] +fn an_envelope_off_the_artboards_that_differs_over_the_arts_box_keeps_its_drawn_art() { + let shifted = format!("{RED}{}f\n", rect_path(42.0, 20.0, 162.0, 80.0)); + let body = envelope_of(&straight_mesh(1, 1, (120.0, 60.0)), ENVELOPE_KEYS, &envelope_content(), 2, &shifted); + let data = format!("{}{}", boards_at(&[[0.0, 98.0, 20.0, 100.0]]), layer(&body)); + let r = read(stream_with_header("%%HiResBoundingBox: 0 0 200 100\n", &data).as_bytes()).unwrap(); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Group { .. }), "{a:#?}"); + assert_eq!(r.warnings, [super::envelope::DRAWN]); + assert_eq!(r.warped_type.pages, [Rect::new(0.0, 0.0, 20.0, 2.0), Rect::new(0.0, 0.0, 200.0, 100.0)]); +} + /// An envelope whose drawn art holds an object the reader can't read keeps that drawn art, which /// the page's art replaces. #[test] @@ -10833,9 +11099,9 @@ fn an_objects_on_path_record_that_doesnt_fit_leaves_a_plain_group() { } /// The path and objects of a group are measured once however many records name it: a thousand -/// copies of a record open about as fast as one copy followed by 999 records whose path id is -/// missing, when the group opens live, when its long path has no length, and when its first object -/// is a group of many paths and its last object has no bounds. +/// copies of a record measure as many paths and objects as one copy followed by 999 records whose +/// path id is missing, when the group opens live, when its long path has no length, and when its +/// first object is a group of many paths and its last object has no bounds. #[test] fn repeated_objects_on_path_records_dont_measure_the_objects_again() { use vectorcraft_testkit::ai::{on_path_member, on_path_options, on_path_record}; @@ -10860,23 +11126,18 @@ fn repeated_objects_on_path_records_dont_measure_the_objects_again() { let unresolved = copy.replace(ids[0], "0a6d1e52-ffff-4000-8000-000000000000"); let one = format!("{}{copy}{}{}", &record[..start], unresolved.repeat(999), &record[end..]); let many = format!("{}{}{}", &record[..start], copy.repeat(1000), &record[end..]); - let time = |data: &str| { - let started = std::time::Instant::now(); + let measure = |data: &str| { + let before = read::on_path_measured(); let doc = read_ok(&format!("{data}{}", layer(&group))).doc; - let elapsed = started.elapsed(); + let measured = read::on_path_measured() - before; let g = art(&doc)[0].clone(); assert_eq!(g.children().unwrap().len(), n, "{why}"); assert_eq!(g.extras().objects_on_path.is_some(), live, "{why}"); - elapsed + measured }; - // The fastest of three runs each, taken in turn, so that other tests running at the same - // time weigh on both. - let (mut fastest_one, mut fastest_many) = (std::time::Duration::MAX, std::time::Duration::MAX); - for _ in 0..3 { - fastest_one = fastest_one.min(time(&one)); - fastest_many = fastest_many.min(time(&many)); - } - assert!(fastest_many < fastest_one * 5, "{why}: one copy: {fastest_one:?}, 1000 copies: {fastest_many:?}"); + let (measured_one, measured_many) = (measure(&one), measure(&many)); + assert!(measured_one > 0, "{why}"); + assert_eq!(measured_many, measured_one, "{why}: 1000 copies measured {measured_many} times, one copy {measured_one}"); } } diff --git a/crates/eps/src/import/file_fonts.rs b/crates/eps/src/import/file_fonts.rs index 83e51bb7ee..de6f044cd3 100644 --- a/crates/eps/src/import/file_fonts.rs +++ b/crates/eps/src/import/file_fonts.rs @@ -38,6 +38,12 @@ struct Gathered { chars: HashMap, } +#[cfg(test)] +thread_local! { + /// How many glyphs [`FileFontGlyphs::fits`] has compared with another glyph on this thread. + static COMPARED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + impl FileFontGlyphs { /// The font of `family` and `style` (made with `info` the first time): its index. pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize { @@ -59,6 +65,10 @@ impl FileFontGlyphs { let mut new: HashMap = HashMap::new(); for g in glyphs { let kept = f.chars.get(&g.ch).and_then(|&k| f.glyphs.get(k)).or_else(|| new.get(&g.ch).copied()); + #[cfg(test)] + if kept.is_some() { + COMPARED.set(COMPARED.get() + 1); + } match kept { Some(k) if k.outline != g.outline || k.advance != g.advance => return false, Some(_) => {} @@ -178,15 +188,16 @@ mod tests { } /// A long string of one character compares each glyph with that character's once, not with - /// every one before it: a quarter of a million of them fit at once. + /// every one before it: a quarter of a million of them fit at once, with fewer comparisons + /// than glyphs. #[test] fn a_long_string_of_one_character_fits_in_linear_time() { - let (tx, rx) = std::sync::mpsc::channel(); - std::thread::spawn(move || { - let mut g = FileFontGlyphs::default(); - let f = g.font("F", "Regular", FileFontInfo::default); - tx.send(g.fits(f, &vec![glyph('A'); 250_000])).ok(); - }); - assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(20)), Ok(true)); + let n = 250_000; + let mut g = FileFontGlyphs::default(); + let f = g.font("F", "Regular", FileFontInfo::default); + let before = COMPARED.get(); + assert!(g.fits(f, &vec![glyph('A'); n])); + let compared = COMPARED.get() - before; + assert!(compared < u64::try_from(n).unwrap(), "{n} glyphs: {compared} comparisons"); } } diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index dad13c569f..df97114506 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -50,6 +50,8 @@ mod slots; #[cfg(test)] pub(crate) use build::READ_AFRESH; #[cfg(test)] +pub(super) use build::placed_documents; +#[cfg(test)] use build::{Frame, MADE, prune_unseen}; pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols}; #[cfg(test)] diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 1ef5706e68..d5d7dbc1c8 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -334,6 +334,7 @@ pub(super) fn build_weighing( placeholders, placed_elsewhere, placed_pages, + placed_eps, envelopes_drawn, styles_read, text_paints, @@ -644,33 +645,50 @@ pub(super) fn build_weighing( } doc.limit_depth_noting(&mut notes); bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); - placed_documents(&mut doc, &placed_pages); + if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) { + notes.push(ai::LINKED_PREVIEWS.to_string()); + } if small.is_some() { scale_read_document(&mut doc, unit, styles_read, symbols_own_size); } Ok((doc, notes)) } -/// The linked images of `pages` that are still in `doc`, opacity-mask art included, as placed -/// documents of their page and box, over the same place, each showing the same preview until its -/// file is read. An image bound to an image variable stays a linked image, the object an image -/// variable binds. -fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage]) { - if pages.is_empty() { - return; +/// The linked images of `pages` and included `eps` still in `doc`, opacity-mask art included, as placed +/// documents of their page and box. PDF pages keep their previews, and EPS files keep their included +/// bytes. An image bound to an image variable stays a linked image, the object an image variable binds. +/// Returns whether an included EPS file stays a linked image that way, showing its preview. +pub(in crate::import) fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage], eps: &[ai::PlacedEps]) -> bool { + if pages.is_empty() && eps.is_empty() { + return false; } let vars = &doc.variables; let image_bound = |id: &NodeId| { vars.bindings.get(id).is_some_and(|names| names.iter().any(|v| vars.variable(v).is_some_and(|v| v.kind == VariableKind::Image))) }; let pages: std::collections::HashMap = pages.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, *p)).collect(); + let previews = eps.iter().any(|p| image_bound(&p.id)); + let eps: std::collections::HashMap = eps.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, p)).collect(); for layer in &mut doc.layers { - to_placed_documents(Arc::make_mut(layer), &pages); + to_placed_documents(Arc::make_mut(layer), &pages, &eps, &mut doc.images); } + previews } /// [`placed_documents`] in `n` and everything in it. -fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap) { +fn to_placed_documents( + n: &mut Node, + pages: &std::collections::HashMap, + eps: &std::collections::HashMap, + images: &mut std::collections::BTreeMap, +) { + if let Some(eps) = eps.get(&n.id) + && let NodeKind::Image(im) = &n.kind + && im.link.is_some() + { + images.entry(eps.placed.key.clone()).or_insert_with(|| eps.blob.clone()); + n.kind = NodeKind::PlacedDocument(Box::new(eps.placed.clone())); + } // A box too small to take the image's pixels to (its transform not finite) keeps the linked image. if let Some(page) = pages.get(&n.id) && let NodeKind::Image(im) = &n.kind @@ -694,10 +712,10 @@ fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap>], doc: &Document, placed: &[(N } /// Where the placed files that show in `nodes` are: the linked images the editing data's reader -/// makes of them. +/// makes of them, and the placed documents it makes of the EPS files whose bytes it includes. fn placed_files(nodes: &[Arc], out: &mut Vec) { for n in nodes.iter().filter(|n| n.visible) { match &n.kind { NodeKind::Image(im) if im.link.is_some() => out.extend(n.visual_bounds()), + NodeKind::PlacedDocument(_) => out.extend(n.visual_bounds()), _ => { if let Some(c) = n.children() { placed_files(c, out); diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index 4cae36ac52..2cbcde3551 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -56,6 +56,19 @@ fn tree(nodes: &[Arc]) -> String { nodes.iter().map(one).collect::>().join(" ") } +/// Placed EPS files drawn as the app draws them: the art of the file read as it opens, in its +/// bounding box (the engine registers the app's own loader). +fn draw_placed_eps() { + fn load(_: &vectorcraft_doc::PlacedDocument, bytes: &[u8]) -> Option<(vectorcraft_doc::Document, Node, Rect)> { + let mut doc = import(bytes).ok()?.document; + let frame = doc.artboards.first()?.rect; + let layers = std::mem::take(&mut doc.layers); + let children = layers.iter().flat_map(|l| l.children().map(|c| c.to_vec()).unwrap_or_default()).collect(); + Some((doc, Node::new(vectorcraft_doc::NodeId(0), NodeKind::Group { children, clip: false }), frame)) + } + vectorcraft_doc::placed_document::set_loader(load); +} + fn read(header: &str, ugroup: &str, body: &str) -> (String, Vec) { let r = import(&ai(header, ugroup, body)).unwrap(); (tree(r.document.layers[0].children().unwrap()), r.warnings) @@ -424,9 +437,10 @@ fn a_postscript_ai_with_a_template_box_and_no_art_size_opens_on_a_letter_artboar } /// A placed EPS in the legacy format (version 7 specification §16, no `%AI5_BeginPlace`), its file -/// included whole: the layers come in, the placed file as the art the page draws in its box. +/// included whole: the layers come in, the placed file as a placed document of its bytes in its box. #[test] fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() { + draw_placed_eps(); // `` ` `` takes the file's user space into the page's (`concat`); `~` restores it. let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\ /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; @@ -440,14 +454,35 @@ fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() { let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); assert_eq!(names, ["Back"], "{:?}", r.warnings); let art = r.document.layers[0].children().unwrap(); - assert_eq!(tree(art), "p g[p]", "{:?}", r.warnings); + let NodeKind::PlacedDocument(p) = &art[1].kind else { panic!("{}: {:?}", tree(art), r.warnings) }; + assert_eq!(r.document.images[&p.key].bytes.as_slice(), eps.as_bytes(), "the file's bytes"); + assert_eq!(p.link.path, "art.eps"); // The file's box, moved by the matrix: 20 40 60 70 on the page, y up. let bounds = art[1].geometric_bounds().unwrap(); assert!( (bounds.x0 - 20.0).abs() < 0.01 && (bounds.y0 - 30.0).abs() < 0.01 && (bounds.x1 - 60.0).abs() < 0.01 && (bounds.y1 - 60.0).abs() < 0.01, "{bounds:?}" ); - assert!(r.warnings.iter().any(|w| w.contains("placed files")), "{:?}", r.warnings); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); +} + +/// A legacy file whose placed EPS file, included whole, has type: the page's type is the placed +/// file's, so the layers come in with it as a placed document. +#[test] +fn a_legacy_file_with_a_placed_eps_with_type_comes_in_through_its_layers() { + draw_placed_eps(); + let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /k {setcmykcolor} def\n\ + /` {gsave 5 {pop} repeat concat} def /~ {grestore} def"; + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\ + /Helvetica findfont 12 scalefont setfont 15 30 moveto (Hi) show\n%%EOF\n"; + let placed = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n"); + let body = format!("%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n0 0 0 1 k\n{} {placed}LB\n%AI5_EndLayer--\n", tri(10)); + let file = String::from_utf8(ai(AI8, "", &body)).unwrap().replace("%%EndProlog", &format!("{prolog}\n%%EndProlog")); + let r = import(file.as_bytes()).unwrap(); + let names: Vec<_> = r.document.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Back"], "{:?}", r.warnings); + let art = r.document.layers[0].children().unwrap(); + assert!(matches!(art[1].kind, NodeKind::PlacedDocument(_)), "{}: {:?}", tree(art), r.warnings); } /// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 0d69d248e5..e55d2fe4da 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -8358,6 +8358,119 @@ fn a_placed_pdf_page_bound_to_an_image_variable_stays_a_linked_image() { assert_eq!(d.variables.objects_of("v_file"), [n.id], "{notes:?}"); } +/// An included EPS keeps its linked preview and binding when an image variable binds it. +#[test] +fn a_placed_eps_with_a_preview_preserves_its_image_variable_binding() { + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_node}; + let declared = vec![xml_node( + 1, + "variable", + XmlValue::Str(""), + &[("trait", XmlValue::Str("fileref")), ("varName", XmlValue::Unicode("v_file")), ("docRef", XmlValue::Raw("/XMLUIDREF : (eps) ;"))], + &[], + )]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n"; + let place = format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\ + %%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n\ + %AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n~\n%AI5_EndPlace\n\ + %_/ArtDictionary :\n%_/XMLUID : (eps) ; (AI10_ArtUID) ,\n%_;\n%_\n", + "\x7f\0\0\0".repeat(4) + ); + let art = layer("Jig", true, &place); + let (bound, notes) = crate::ai_alone(&private(&native(&(library + &art)))).unwrap(); + let n = &bound.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) }; + assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps"); + assert_eq!((im.width, im.height), (2, 2)); + assert_eq!(bound.images[&im.key].mime, "image/png"); + assert!(bound.images.values().all(|b| b.mime != "application/postscript")); + assert_eq!(bound.variables.objects_of("v_file"), [n.id], "{notes:?}"); + assert!(!notes.iter().any(|n| n.contains("variable bindings")), "{notes:?}"); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "the preview it shows is noted: {notes:?}"); + let (unbound, notes) = crate::ai_alone(&private(&native(&art))).unwrap(); + assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "it draws its bytes: {notes:?}"); + let converted = &unbound.layers[0].children().unwrap()[0]; + assert_eq!(converted.id, n.id); + let NodeKind::PlacedDocument(p) = &converted.kind else { panic!("{:?} {notes:?}", converted.kind) }; + assert_eq!(&*unbound.images[&p.key].bytes, eps.as_bytes()); + assert!(unbound.images[&p.key].proxy.is_none()); +} + +/// What reading an included EPS file warns of, such as art left out, is in the open result. +#[test] +fn a_placed_eps_read_in_part_warns_of_what_it_leaves_out() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 30 30 rectfill\n0 0 60 60 nosuchoperator\n%%EOF\n"; + let own = crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).unwrap().warnings; + assert!(!own.is_empty(), "the file read alone warns"); + for place in [placed_eps_with_preview(eps), placed_eps_with_preview(eps).replace(&placed_eps_preview(), "")] { + let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap(); + let n = &d.layers[0].children().unwrap()[0]; + assert!(matches!(n.kind, NodeKind::PlacedDocument(_)), "{:?} {notes:?}", n.kind); + for w in &own { + assert!(notes.contains(&format!("a placed EPS file: {w}")), "{w}: {notes:?}"); + } + } +} + +/// An unreadable included EPS keeps the preview that the linked image can show. +#[test] +fn a_placed_eps_with_an_unreadable_program_keeps_its_preview() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n"; + assert!(crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).is_err()); + let place = placed_eps_with_preview(eps); + let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap(); + let n = &d.layers[0].children().unwrap()[0]; + let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) }; + assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps"); + assert_eq!((im.width, im.height), (2, 2)); + let preview = &d.images[&im.key]; + assert_eq!(preview.mime, "image/png"); + assert_eq!(preview.proxy.as_deref(), Some(&*preview.bytes)); + assert!(d.images.values().all(|b| b.mime != "application/postscript")); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); +} + +/// A pattern's included EPS keeps its bytes without waiting for image variable binding. +#[test] +fn a_placed_eps_with_a_preview_in_a_pattern_keeps_its_bytes() { + let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n"; + let place = placed_eps_with_preview(eps); + let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{place}E\n%AI3_EndPattern\n"); + let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap(); + let art = &d.pattern("Pic").unwrap().art; + assert_eq!(art.len(), 1, "{art:?} {notes:?}"); + let NodeKind::PlacedDocument(p) = &art[0].kind else { panic!("{art:?} {notes:?}") }; + assert_eq!(&*d.images[&p.key].bytes, eps.as_bytes()); + assert_eq!(d.images[&p.key].mime, "application/postscript"); + assert!(d.images[&p.key].proxy.is_none()); + assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); + + // One whose bytes can't be read keeps its preview there too. + let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 nosuchoperator\n%%EOF\n"; + let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{}E\n%AI3_EndPattern\n", placed_eps_with_preview(broken)); + let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap(); + let art = &d.pattern("Pic").unwrap().art; + assert!(matches!(&art[..], [n] if matches!(&n.kind, NodeKind::Image(im) if im.link.is_some())), "{art:?} {notes:?}"); + assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}"); +} + +/// A placed EPS file at `/files/shape.eps` whose bytes `eps` the data includes, with a 2 × 2 preview. +fn placed_eps_with_preview(eps: &str) -> String { + format!( + "%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\ + %%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n{}~\n%AI5_EndPlace\n", + placed_eps_preview() + ) +} + +/// The 2 × 2 preview of [`placed_eps_with_preview`]. +fn placed_eps_preview() -> String { + format!("%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n", "\x7f\0\0\0".repeat(4)) +} + #[test] fn a_small_placed_file_goes_where_it_draws_closer_to_the_page() { // A 2 × 2 placed file (a small logo on a large page) whose box corner the matrix takes to diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 6f5ff3d7a2..1abfd0210e 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -61,6 +61,18 @@ pub use print::{PrintFonts, PrintJob, PrintPage, print}; use vectorcraft_doc::Document; use vectorcraft_geom::{Point, Rect}; +#[cfg(any(test, feature = "work-count"))] +std::thread_local! { + /// Included EPS files parsed by open checks on this thread. + pub(crate) static INCLUDED_EPS_READS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Included EPS files parsed by open checks on this thread, for tests that count work instead of timing it. +#[cfg(any(test, feature = "work-count"))] +pub fn included_eps_reads() -> usize { + INCLUDED_EPS_READS.with(std::cell::Cell::get) +} + /// The PostScript language level the file needs. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] pub enum Level { diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index 109493a03d..beec94c6a5 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -5,7 +5,7 @@ //! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only. use super::{arg, constructor, create_at, data, method, native, new_array}; -use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes}; +use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES}; use crate::interp::{Hint, Interp, JsResult}; use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown}; use crate::value::{Str, Value}; @@ -90,11 +90,12 @@ fn symbol_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool) - fn symbol_for(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let key = interp.to_str(&arg(args, 0))?; let units = crate::string_builtins::flat_charged(interp, &key)?; + crate::string_builtins::charge_units(interp, units.len())?; if let Some(v) = interp.symbols.registry.get(&*units) { return Ok(v.clone()); } - let extra = REGISTRY_ENTRY_BYTES.saturating_add(string_bytes(units.len())); - let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, extra)?; + crate::string_builtins::charge_units(interp, units.len())?; + let sym = new_symbol(interp, Some(Str::from_rc(units.clone())), true, REGISTRY_ENTRY_BYTES)?; interp.symbols.registry.insert(units, Value::Symbol(sym.clone())); Ok(Value::Symbol(sym)) } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 22c8dc1b06..498d849f3e 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -86,7 +86,8 @@ //! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a //! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator //! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry -//! entry counts against the heap limit. +//! entry counts against the heap limit. Registry lookups and insertions take fuel for the key's +//! code units, and a registered description shares the key's existing buffer. //! //! With [`Options::es2015`], the realm also provides `Promise` (ECMA-262 11th edition, section //! 25.6, ): the constructor, `then`, diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index 2ddd86828a..c91a493424 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -57,6 +57,34 @@ fn symbol_for_and_key_for_use_the_registry() { throws("Symbol.for(Symbol())", "TypeError"); } +#[test] +fn symbol_registry_hashing_charges_flat_keys_on_hits_and_misses() { + for hit in [false, true] { + let mut realm = es2015(Limits::default()); + let key = "x".repeat(32_768); + assert_eq!(realm.run(&format!("var registryKey = '{key}';")), Ok(JsValue::Undefined)); + if hit { + assert_eq!(realm.run("typeof Symbol.for(registryKey)"), Ok(JsValue::String("symbol".into()))); + } + realm.set_limits(Limits { fuel: 500, ..Limits::default() }); + assert!(matches!(realm.run("Symbol.for(registryKey)"), Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. })), "hit={hit}"); + realm.set_limits(Limits { fuel: 10_000, ..Limits::default() }); + assert_eq!(realm.run("Symbol.for(registryKey) === Symbol.for(registryKey)"), Ok(JsValue::Bool(true))); + } +} + +#[test] +fn symbol_registry_keeps_a_flat_key_buffer_only_once() { + let mut realm = es2015(Limits::default()); + let key = "x".repeat(32_768); + assert_eq!(realm.run(&format!("var sharedKey = '{key}';")), Ok(JsValue::Undefined)); + let used = realm.collect_garbage(); + let room = crate::heap::SYMBOL_BYTES + crate::symbol::REGISTRY_ENTRY_BYTES + 4_096; + realm.set_limits(Limits { heap_bytes: used + room, ..Limits::default() }); + assert_eq!(realm.run("var registered = Symbol.for(sharedKey); Symbol.keyFor(registered) === sharedKey"), Ok(JsValue::Bool(true))); + assert!(realm.collect_garbage() <= used + room); +} + #[test] fn implicit_conversion_of_a_symbol_throws_a_type_error() { throws("Symbol() + ''", "TypeError"); diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index e0c15c4cf6..b954c1c087 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -1030,31 +1030,46 @@ fn promise_builtins_run() { handle.join().unwrap(); } -/// Runs one `test/built-ins/Promise` test in a new realm with [`Options::es2015`] and a global -/// `print` that collects its output; an `async` test passes when it prints -/// `Test262:AsyncTestComplete`. +#[test] +fn promise_async_completion_requires_an_exact_print_argument() { + assert!(run_promise_one("print('not Test262:AsyncTestComplete');", None, true).is_err()); + assert!(run_promise_one("print('Test262:AsyncTestComplete suffix');", None, true).is_err()); + assert!(run_promise_one("print('message', 'Test262:AsyncTestComplete');", None, true).is_ok()); + assert!(run_promise_one("print('Test262:AsyncTestComplete');", None, true).is_ok()); +} + +#[test] +fn promise_async_failure_checks_each_print_argument() { + assert!(run_promise_one("print('Test262:AsyncTestComplete', 'Test262:AsyncTestFailure: failed');", None, true).is_err()); + assert!(run_promise_one("print('not Test262:AsyncTestFailure'); print('Test262:AsyncTestComplete');", None, true).is_ok()); +} + +/// Runs one Promise test with a global `print` that collects every argument. An `async` test +/// needs an exact `Test262:AsyncTestComplete` argument and no `Test262:AsyncTestFailure` prefix. fn run_promise_one(script: &str, negative_type: Option<&str>, asynchronous: bool) -> Result<(), String> { let options = Options { es2015: true, ..Options::default() }; let mut realm = Realm::with_options(options, Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); - let printed = std::rc::Rc::new(std::cell::RefCell::new(String::new())); + let printed = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); let out = printed.clone(); realm.define_function("print", move |args| { - let line = match args.first() { - Some(JsValue::String(s)) => s.clone(), - Some(other) => format!("{other:?}"), - None => String::new(), - }; - out.borrow_mut().push_str(&line); - out.borrow_mut().push('\n'); + let mut printed = out.borrow_mut(); + for arg in args { + printed.push(match arg { + JsValue::String(s) => s.clone(), + other => format!("{other:?}"), + }); + } Ok(JsValue::Undefined) }); let result = realm.run(script); if asynchronous && result.is_ok() && negative_type.is_none() { let printed = printed.borrow(); - return if printed.contains("Test262:AsyncTestComplete") && !printed.contains("Test262:AsyncTestFailure") { + return if printed.iter().any(|arg| arg == "Test262:AsyncTestComplete") + && !printed.iter().any(|arg| arg.starts_with("Test262:AsyncTestFailure")) + { Ok(()) } else { - Err(format!("printed {:?}", printed.trim())) + Err(format!("printed {printed:?}")) }; } match (result, negative_type) { diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index be8ff636e6..2579064919 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1942,6 +1942,32 @@ fn selection_preferences_apply_to_pointer_gestures() { assert_eq!(click(&mut s, 7, 250.0, json!({})), json!([front]), "the path does"); } +/// A Selection tool click inside a closed shape with no fill selects it (#9175), and with Object +/// Selection by Path Only on it selects nothing. +#[test] +fn a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only() { + let mut s = server(); + let r = call( + &mut s, + 1, + "draw_shape", + json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 100, "fill": "none", "stroke": "#000000"}), + ); + let id = serde_json::from_str::(&text_of(&r)).unwrap()["id"].as_u64().unwrap(); + let click = |s: &mut Server, n: u64| { + let r = call(s, n, "run_command", json!({"command": "select.none", "params": {}})); + assert_eq!(r["isError"], false, "{r}"); + let events = json!([{"kind": "down", "x": 150, "y": 150}, {"kind": "up", "x": 150, "y": 150}]); + let r = call(s, n + 1, "pointer_gesture", json!({"tool": "selection", "events": events})); + assert_eq!(r["isError"], false, "{r}"); + serde_json::from_str::(&text_of(&r)).unwrap()["selection"].clone() + }; + assert_eq!(click(&mut s, 2), json!([id])); + let r = call(&mut s, 4, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); + assert_eq!(r["isError"], false, "{r}"); + assert_eq!(click(&mut s, 5), json!([]), "path only"); +} + #[test] fn pointer_gesture_forwards_backquote_on_each_event() { let mut s = server(); diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index be4cfb5f77..c8b37acbc7 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -672,6 +672,9 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO /// linear part. With `brush` true, the members of a group or layer are measured with the room /// their brushed strokes leave for brush art ([`member_cull_bounds`]). fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: bool) -> Option { + // A layer is measured in the mode its Layer Options draw it in, as the renderer measures the + // members of a group or layer without effects ([`crate::Renderer::bounds_of`]). + let _mode = crate::placed_document::enter_layer(n); let inner = |c: &Node| cull_bounds_in(symbols, c, after_reshape, false); let member = |c: &Node| member_cull_bounds(symbols, c, after_reshape, brush); // The art that a group's or layer's crop marks or Vector Halftone draw holds its members. The diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index b34f562ca1..8267ef278a 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -7,22 +7,18 @@ use super::{ use crate::kept_paths::{self, KeptPath}; use crate::node_checks::{holds_measured_three_d, measures_three_d}; use crate::placed_document::{InMode, LayerMode, enter_layer}; -use vectorcraft_doc::placed_document::crossed; /// The key of `a`'s cull bounds in [`Renderer::geom`]: its address, and in its lowest bits what the -/// bounds depend on besides `a`. For a layer that is the mode its sublayers are measured in -/// ([`LayerMode`], [`enter_layer`]); for an object other than a path, whether placed documents are -/// crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the art its effects make from a -/// placed document in it is the crossed box then. A node's address is aligned to 8 bytes, so no -/// other node has that key. +/// bounds depend on besides `a`. For an object other than a path that is the mode it is measured in +/// ([`LayerMode`]): it sets the mode of the layers in it ([`enter_layer`]), a group's included, and +/// whether placed documents are crossed ([`vectorcraft_doc::placed_document::Crossed`]), since the +/// art its effects make from a placed document in it is the crossed box then. Placed documents are +/// crossed only in a mode. A node's address is aligned to 8 bytes, so no other node has that key. fn geom_key(a: &Node) -> usize { let at = std::ptr::from_ref(a) as usize; match a.kind { NodeKind::Path { .. } | NodeKind::Compound { .. } => at, - NodeKind::Layer { .. } => { - at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2) - } - _ => at | usize::from(crossed()), + _ => at | LayerMode::now().map_or(0, |m| usize::from(m.options) | usize::from(m.outline) << 1 | usize::from(m.images) << 2), } } diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index 738fd44488..fcb402ca51 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -335,6 +335,57 @@ fn outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a sublayer whose Preview is off"); } +#[test] +fn a_group_is_measured_again_when_show_images_in_outline_mode_changes_for_a_sublayer_in_it() { + // As above, in a sublayer whose Preview is off, held in a group. With Show Images in Outline + // Mode the file that can't be read draws nothing; turned off, the sublayer draws the moved box + // crossed, and the same renderer measures the group again. + let mut d = doc_with("outline-cull-2", b"bad"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let placed = d.remove(NodeId(50)).unwrap(); + let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { children, preview, .. } = &mut sub.kind { + children.push(placed); + *preview = false; + } + let l = d.layers[0].id; + d.insert(Some(l), 0, Node::group(NodeId(91), vec![Arc::new(sub)])).unwrap(); + let view = Affine::translate((0.0, -55.0)); + let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + d.setup.outline_images = true; + r.render(&d, 100, 100, view, &preview); + d.setup.outline_images = false; + let crossed = r.render(&d, 100, 100, view, &preview); + assert!(crossed.pixel(30, 5)[0] < 200, "the moved box is drawn crossed"); + assert!(crossed.pixels == Renderer::new().render(&d, 100, 100, view, &preview).pixels, "as a new renderer draws it"); +} + +#[test] +fn a_group_with_a_drop_shadow_measures_a_sublayer_in_it_in_the_sublayers_own_mode() { + // As above, in a sublayer whose Preview is off, held in a group with a Drop Shadow effect: the + // sublayer draws the moved box crossed, and the group's cull bounds reach it. + let mut d = doc_with("outline-cull-3", b"bad"); + let params = serde_json::json!({"moveV": 40}); + d.node_mut(NodeId(50)).unwrap().appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params, visible: true }); + let placed = d.remove(NodeId(50)).unwrap(); + let mut sub = Node::layer(NodeId(90), "Sublayer", vectorcraft_doc::LayerColor::Preset(1)); + if let NodeKind::Layer { children, preview, .. } = &mut sub.kind { + children.push(placed); + *preview = false; + } + let shadow = serde_json::json!({"x": 0, "y": 0, "blur": 0, "opacity": 0}); + let mut g = Node::group(NodeId(91), vec![Arc::new(sub)]); + g.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: shadow, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let view = Affine::translate((0.0, -55.0)); + let preview = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let r = Renderer::new().render(&d, 100, 100, view, &preview); + assert!(r.pixel(30, 5)[0] < 200, "the moved box is drawn crossed in a group with a drop shadow"); +} + #[test] fn an_edit_in_outline_mode_redraws_where_the_effects_move_the_crossed_box() { // A file that can't be read, in the box (10, 10)–(90, 50): a Transform effect added to it moves diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index 845379311d..1c6bca721c 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -18,7 +18,12 @@ //! segment's shape differs from the one they were found on. With the `addPoints` option on (Alt at //! the release turns it the other way, and a dot beside the pointer shows when it is in effect), the //! segments the circle touches get an anchor point at each touch, which splits them without changing -//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. +//! their shape, in the same undo step as the circle; a touch at an existing anchor adds none. With the +//! `askRadius` option on, a click on the second segment (not a drag, which sets the radius itself) +//! opens the [`RADIUS_DIALOG`] instead of drawing: it starts at the radius of the circle found and +//! draws the circle of the radius typed ([`radius_circle`]); the first segment stays picked until it +//! does. While the dialog is open, an edit to either segment leaves it without a circle +//! ([`segments_unchanged`]). //! //! The tool's options (its options dialog, `tool.setOption`; kept with the preferences): `radius`; //! `addPoints`; `center` and `radii` show or hide the circle's center cross and the lines from its center to the @@ -29,11 +34,12 @@ //! within the selection tolerance, as a click on a path picks it, and that is also the least reach //! snapping has. Of the segments within reach the nearest is picked ([`pick_at`]). By default //! `addPoints` is off, the cross and the lines show, the color is red, the tolerance is 3 px and -//! `snapWithoutGuides` is on. +//! `snapWithoutGuides` is on. `askRadius` (above) and `autoUpdateDefault`, which makes the radius +//! given in the dialog the tool's `radius`, are off by default. use kurbo::{CubicBez, ParamCurveNearest, Shape}; use serde_json::{Value, json}; -use vectorcraft_doc::NodeId; +use vectorcraft_doc::{Document, NodeId}; use vectorcraft_geom::{BezPath, ParamCurve, Point}; use vectorcraft_pathops::addons::pathtools::{SegmentCircle, circles_of_radius, circles_through}; @@ -53,6 +59,9 @@ const STEP_PX: f64 = 4.0; const SLOW: f64 = 0.1; /// The note shown over a second segment that gives no circle. pub const NO_CIRCLE: &str = "No tangent circle here"; +/// The dialog a click on the second segment opens with `askRadius` on: its parameters hold the two +/// segments, the click and the circle found ([`radius_circle`]). +pub const RADIUS_DIALOG: &str = "tangentCircleRadius"; const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; const GREY: [u8; 3] = [0x80, 0x80, 0x80]; @@ -77,7 +86,7 @@ pub const SNAP_PX: f64 = 3.0; /// The snapping tolerance the `snapTolerance` option takes (screen pixels). pub const SNAP_RANGE: (f64, f64) = (0.0, 25.0); /// The option keys that are true or false. -const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides"]; +const SWITCHES: &[&str] = &["addPoints", "center", "radii", "snapWithoutGuides", "askRadius", "autoUpdateDefault"]; /// A segment under the pointer: where on it, and the segment itself. #[derive(Clone, Debug, PartialEq)] @@ -124,6 +133,10 @@ pub struct TangentCircleTool { /// The snapping tolerance (screen pixels), and whether the tool snaps with Smart Guides off. snap_px: f64, snap_without_guides: bool, + /// Whether a click on the second segment asks for the radius (`askRadius`), and whether the + /// radius given there becomes `radius` (`autoUpdateDefault`, which the dialog reads). + ask_radius: bool, + auto_update: bool, first: Option, hover: Option, press: Option, @@ -153,6 +166,8 @@ impl Default for TangentCircleTool { color: 0, snap_px: SNAP_PX, snap_without_guides: true, + ask_radius: false, + auto_update: false, first: None, hover: None, press: None, @@ -193,10 +208,24 @@ fn pick_at(cx: &ToolContext, p: Point, reach: f64) -> Option { Some(Pick { id, subpath, segment, t, p: curve.eval(t), curve }) } +/// A segment's place in the document: its path, subpath and index. +type Place = (NodeId, usize, usize); + +impl Pick { + fn place(&self) -> Place { + (self.id, self.subpath, self.segment) + } +} + /// The document's segment at `pick` as it is now: none when its path, subpath or segment is gone. fn segment_now(cx: &ToolContext, pick: &Pick) -> Option { - let sp = cx.doc.node(pick.id)?.path_data()?.subpaths.get(pick.subpath)?; - (pick.segment < sp.segment_count()).then(|| sp.segment(pick.segment)) + segment_at(cx.doc, pick.place()) +} + +/// The segment of `doc` at `place`: none when its path, subpath or segment is gone. +fn segment_at(doc: &Document, (id, subpath, segment): Place) -> Option { + let sp = doc.node(id)?.path_data()?.subpaths.get(subpath)?; + (segment < sp.segment_count()).then(|| sp.segment(segment)) } /// Whether the document's segment at `pick` still has the shape it had when it was picked. @@ -207,17 +236,31 @@ fn unchanged(cx: &ToolContext, pick: &Pick) -> bool { /// The segments a circle may touch when `second` is picked: it and the segments on either side of /// it, without `first`. None when `second` is the first segment again. fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { - second_segments(cx, first, second).into_iter().map(|(_, c)| c).collect() + second_set_at(cx.doc, first.place(), second.place()) +} + +/// [`second_set`] for the segments of `doc` at `first` and `second`. +fn second_set_at(doc: &Document, first: Place, second: Place) -> Vec { + second_segments_at(doc, first, second).into_iter().map(|(_, c)| c).collect() } /// [`second_set`] with each segment's index on the second pick's subpath. fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, CubicBez)> { - if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { + second_segments_at(cx.doc, first.place(), second.place()) +} + +/// [`second_segments`] for the segments of `doc` at `first` and `second`. +fn second_segments_at(doc: &Document, first: Place, second: Place) -> Vec<(usize, CubicBez)> { + if first == second { return vec![]; } - let Some(sp) = cx.doc.node(second.id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(second.subpath)) else { return vec![] }; + let (id, subpath, i) = second; + let Some(sp) = doc.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(subpath)) else { return vec![] }; + // A subpath edited down to no segments (while the radius dialog is open) has nothing to touch. let n = sp.segment_count(); - let i = second.segment; + if n == 0 { + return vec![]; + } let mut indices = vec![i]; if i > 0 || sp.closed { indices.push((i + n - 1) % n); @@ -227,7 +270,7 @@ fn second_segments(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec<(usize, } indices.sort_unstable(); indices.dedup(); - let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; + let is_first = |k: usize| first == (id, subpath, k); indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| (k, sp.segment(k))).collect() } @@ -325,6 +368,93 @@ fn segment_path(c: &CubicBez) -> BezPath { bp } +fn point_json(p: Point) -> Value { + json!([p.x, p.y]) +} + +fn curve_json(c: &CubicBez) -> Value { + json!([point_json(c.p0), point_json(c.p1), point_json(c.p2), point_json(c.p3)]) +} + +/// A finite point written by [`point_json`]. +fn point_of(v: &Value) -> Option { + let [x, y] = v.as_array()?.as_slice() else { return None }; + let p = Point::new(x.as_f64()?, y.as_f64()?); + (p.x.is_finite() && p.y.is_finite()).then_some(p) +} + +/// A segment written by [`curve_json`]. +fn curve_of(v: &Value) -> Option { + let [a, b, c, d] = v.as_array()?.as_slice() else { return None }; + Some(CubicBez::new(point_of(a)?, point_of(b)?, point_of(c)?, point_of(d)?)) +} + +fn place_json((id, subpath, segment): Place) -> Value { + json!([id.0, subpath, segment]) +} + +/// A place written by [`place_json`]. +fn place_of(v: &Value) -> Option { + let [id, subpath, segment] = v.as_array()?.as_slice() else { return None }; + let index = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()); + Some((NodeId(id.as_u64()?), index(subpath)?, index(segment)?)) +} + +/// The [`RADIUS_DIALOG`]'s parameters for circle `c`, found by a click at `at` on `first` and on +/// `picked`, whose segments a circle may touch are `second`, which `points` (from [`draw`]) draws: +/// the segments and their places, the click, the circle's radius and points, and the tolerance +/// [`draw`] checked them with. +fn dialog_params(first: &Pick, picked: &Pick, second: &[CubicBez], at: Point, c: &SegmentCircle, points: &Value, tol: f64) -> Value { + json!({ + "first": curve_json(&first.curve), + "second": second.iter().map(curve_json).collect::>(), + "places": [place_json(first.place()), place_json(picked.place())], + "at": point_json(at), + "radius": c.circle.radius, + "points": points, + "tol": tol, + }) +} + +/// Whether the segments the [`RADIUS_DIALOG`] opened with parameters `p` holds are still those of +/// `doc`: false when a path was edited or removed since the click, in another document, or for +/// parameters the tool did not write. +pub fn segments_unchanged(doc: &Document, p: &Value) -> bool { + let check = || -> Option { + let [first, second] = p.get("places")?.as_array()?.as_slice() else { return None }; + let (first, second) = (place_of(first)?, place_of(second)?); + let second_then: Vec = p.get("second")?.as_array()?.iter().map(curve_of).collect::>()?; + Some(segment_at(doc, first)? == curve_of(p.get("first")?)? && second_then == second_set_at(doc, first, second)) + }; + check() == Some(true) +} + +/// The `shape.circleThroughPoints` parameters that draw the circle of `radius` the [`RADIUS_DIALOG`] +/// opened with parameters `p` gives: at the radius the click found, the circle found; at any other, +/// the circle of `radius` touching the second segments nearest the click, anywhere along the first +/// segment (as with Shift). None for a radius that is not a finite number above 0, when no circle of +/// that radius can be drawn there, or for parameters the tool did not write. +pub fn radius_circle(p: &Value, radius: f64) -> Option { + if !(radius.is_finite() && radius > 0.0) { + return None; + } + if p.get("radius").and_then(Value::as_f64) == Some(radius) { + let points = p.get("points")?; + let [a, b, c] = points.as_array()?.as_slice() else { return None }; + return [a, b, c].into_iter().all(|q| point_of(q).is_some()).then(|| json!({ "points": points })); + } + let first = curve_of(p.get("first")?)?; + // The second segment and at most one on either side of it. + let second: Vec = p.get("second")?.as_array().filter(|s| (1..=3).contains(&s.len()))?.iter().map(curve_of).collect::>()?; + let at = point_of(p.get("at")?)?; + let tol = p.get("tol").and_then(Value::as_f64).filter(|t| t.is_finite() && *t > 0.0)?; + let c = nearest_to(circles_of_radius(first, &second, radius), at, tol)?; + match draw(&c, tol)? { + Action::Exec(_, params) => Some(params), + _ => None, + } +} + impl TangentCircleTool { /// How near (document units) the pointer picks a segment: with Smart Guides on, the snapping /// tolerance or Smart Guides' Snapping Tolerance, whichever is larger; with them off, the @@ -490,9 +620,20 @@ impl Tool for TangentCircleTool { // No circle, or one the three points cannot draw: the first segment stays picked, // for another try. It also stays when the command fails: only a drawn circle tells // the tool (`notify`) to forget it. + let tol = cx.tol(DRAW_PX); let Some(c) = self.found.take() else { return vec![] }; - let Some(params) = circle_params(&c, cx.tol(DRAW_PX)) else { return vec![] }; + let Some(params) = circle_params(&c, tol) else { return vec![] }; self.looked = false; + // Asked for: a click, not a drag (which set the radius), opens the radius dialog, + // which draws the circle. Until then the first segment stays picked, so Cancel + // leaves it for another try. + if self.ask_radius + && press.radius.is_none() + && let Some(first) = &self.first + { + let params = dialog_params(first, &press.pick, &press.second, press.at, &c, ¶ms["points"], tol); + return vec![Action::Dialog(RADIUS_DIALOG.into(), params)]; + } // Alt at the release turns `addPoints` the other way. let steps = match &self.first { Some(first) if self.add_points != ev.mods.alt => { @@ -628,6 +769,8 @@ impl Tool for TangentCircleTool { "color": COLORS.get(self.color).map_or("red", |(name, _)| *name), "snapTolerance": self.snap_px, "snapWithoutGuides": self.snap_without_guides, + "askRadius": self.ask_radius, + "autoUpdateDefault": self.auto_update, }) } @@ -644,6 +787,8 @@ impl Tool for TangentCircleTool { "color" => self.color = v.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)).unwrap_or(self.color), "snapTolerance" => self.snap_px = v.as_f64().unwrap_or(self.snap_px), "snapWithoutGuides" => self.snap_without_guides = v.as_bool().unwrap_or(self.snap_without_guides), + "askRadius" => self.ask_radius = v.as_bool().unwrap_or(self.ask_radius), + "autoUpdateDefault" => self.auto_update = v.as_bool().unwrap_or(self.auto_update), _ => {} } } @@ -721,6 +866,121 @@ mod tests { [(a.0, b.0), (a.1, b.1), (a.2, b.2), (a.3, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-4) } + /// The circle `shape.circleThroughPoints` parameters `p` draw, as [`drawn`] gives it. + fn boxed(p: &Value) -> (f64, f64, f64, f64) { + drawn(&[Action::Exec("shape.circleThroughPoints".into(), p.clone()), Action::Notify(DRAWN.into())]) + } + + /// The radius dialog's parameters in `actions`, which hold nothing else. + fn asked(actions: &[Action]) -> Value { + let [Action::Dialog(kind, p)] = actions else { panic!("{actions:?}") }; + assert_eq!(kind, RADIUS_DIALOG); + p.clone() + } + + #[test] + fn ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!((t.options()["askRadius"].clone(), t.options()["autoUpdateDefault"].clone()), (json!(false), json!(false))); + for key in ["askRadius", "autoUpdateDefault"] { + assert_eq!(t.check_option(key, &json!(true)), Ok(())); + for bad in [json!(1), json!("true"), Value::Null] { + assert_eq!(t.check_option(key, &bad), Err(format!("`{key}` must be true or false")), "{bad}"); + t.set_option(key, &bad); + assert_eq!(t.options()[key], json!(false), "{bad}"); + } + t.set_option(key, &json!(true)); + assert_eq!(t.options()[key], json!(true)); + } + // A click on the second line: the dialog, at the click's circle (radius 20), and nothing + // drawn yet; the first segment stays picked. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let p = asked(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert!((p["radius"].as_f64().unwrap() - 20.0).abs() < 1e-6, "{p}"); + assert!(t.first.is_some() && !t.busy()); + let r = p["radius"].as_f64().unwrap(); + assert!(close(boxed(&radius_circle(&p, r).unwrap()), (130.0, 100.0, 40.0, 40.0)), "{p}"); + // Lines 40 pt apart take no other radius; nor is there a circle without a radius above 0. + for no in [25.0, 0.0, -20.0, f64::NAN, f64::INFINITY] { + assert_eq!(radius_circle(&p, no), None, "{no}"); + } + // Shift on the L's corner: the dialog at the tool's radius, and another radius gives that + // radius's fillet. + t.key(&cx, ToolKey::Escape, Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let p = asked(&up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0))); + assert_eq!(p["radius"], json!(RADIUS)); + assert!(close(boxed(&radius_circle(&p, RADIUS).unwrap()), (300.0 - 72.0, 300.0, 72.0, 72.0)), "{p}"); + assert!(close(boxed(&radius_circle(&p, 10.0).unwrap()), (280.0, 300.0, 20.0, 20.0)), "{p}"); + // Parameters the tool did not write give no circle. + assert_eq!(radius_circle(&json!({}), 10.0), None); + let second = p["second"].as_array().unwrap()[0].clone(); + for (key, bad) in [ + ("second", json!([])), + ("second", json!([second, second, second, second])), + ("at", json!([1.0])), + ("tol", json!(0)), + ("first", json!("x")), + ("points", json!([[0, 0]])), + ] { + let mut q = p.clone(); + q[key] = bad; + let r = if key == "points" { RADIUS } else { 10.0 }; + assert_eq!(radius_circle(&q, r), None, "{key}"); + } + // A drag sets the radius itself: drawn at once, with no dialog. + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 365.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 300.0, 365.0)); + assert!(close(drawn(&released), (300.0 - 30.0, 300.0, 30.0, 30.0)), "{released:?}"); + assert!(t.first.is_none()); + // A click that finds no circle opens no dialog. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0)); + assert!(t.pointer(&cx, &shifted(PointerKind::Up, 200.0, 139.0)).is_empty()); + assert!(t.first.is_some()); + } + + #[test] + fn the_radius_dialog_knows_when_its_segments_changed() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("askRadius", &json!(true)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let p = asked(&up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0))); + assert!(segments_unchanged(&d, &p)); + assert!(segments_unchanged(&doc_at(100.0, 140.0), &p), "the same paths"); + // Either line moved, or another document: changed. + for (a, b) in [(100.0, 150.0), (110.0, 140.0)] { + assert!(!segments_unchanged(&doc_at(a, b), &p), "{a} {b}"); + } + assert!(!segments_unchanged(&Document::new(500.0, 500.0), &p)); + // The second line edited down to a closed subpath without segments: changed. + let mut emptied = d.clone(); + let (second, ..) = place_of(&p["places"][1]).unwrap(); + emptied.node_mut(second).and_then(|n| n.path_data_mut()).unwrap().subpaths[0] = SubPath::polyline(&[], true); + assert!(!segments_unchanged(&emptied, &p)); + // Parameters the tool did not write. + for key in ["places", "first", "second"] { + let mut q = p.clone(); + q[key] = json!("x"); + assert!(!segments_unchanged(&d, &q), "{key}"); + } + } + #[test] fn two_clicks_draw_the_circle_tangent_at_the_first_click() { let d = doc(); diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index fd9776837d..bbdbd28c7e 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -467,16 +467,20 @@ impl ToolContext<'_> { clip_outlines: false, area_type_interior: false, ignore_layer_preview: false, + unfilled_interiors: false, } } /// [`Self::hit_options`] for the selection tools (Selection, Direct Selection, Group - /// Selection): a clipping path is also hit on its outline ([`HitOptions::clip_outlines`]). + /// Selection): a clipping path is also hit on its outline ([`HitOptions::clip_outlines`]), and + /// where nothing else is hit, an unfilled closed path is hit inside unless Object Selection by + /// Path Only is on ([`HitOptions::unfilled_interiors`]). /// Only for what a press or a hover selects: a double-click, loaded text or a guide's release /// acts on what is drawn and takes [`Self::hit_options`]. /// /// [`HitOptions::clip_outlines`]: vectorcraft_doc::hit::HitOptions::clip_outlines + /// [`HitOptions::unfilled_interiors`]: vectorcraft_doc::hit::HitOptions::unfilled_interiors pub fn selection_hit_options(&self) -> vectorcraft_doc::hit::HitOptions { - vectorcraft_doc::hit::HitOptions { clip_outlines: true, ..self.hit_options() } + vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..self.hit_options() } } } diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index 5e943c8463..3d02e37aa0 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -203,6 +203,35 @@ impl CornerWidgets { out.insert(key.into(), value); Value::Object(out) } + + /// The cut corner whose widget is within `tol` (document units) of `p`, as the path draws it in + /// the document, with the object it belongs to: what the canvas highlights while the pointer + /// is over that widget. `None` away from the widgets and for a corner with no cut. + pub fn hovered_cut(&self, doc: &Document, p: Point, tol: f64) -> Option<(NodeId, BezPath)> { + let (i, k) = self.hit(p, tol)?; + let (id, w) = (self.paths.get(i)?.id, self.widget(i, k)?); + let node = doc.node(id)?; + let NodeKind::Path { path, .. } = &node.kind else { return None }; + let lc = LiveCorners::of(node)?; + let mut out = BezPath::new(); + for (sp, from) in path.subpaths.iter().zip(lc.sources()) { + // A subpath whose anchors do not match its sources gives no cut rather than a wrong one. + if from.len() != sp.anchors.len() { + continue; + } + // A corner's cut is the segment between its two anchors (the last one, for a closed + // subpath's first corner); a square corner is one anchor and has none. + for s in 0..sp.segment_count() { + let (a, b) = (from.get(s), from.get(s + 1).or(from.first())); + if a == Some(&w.corner.index) && b == a { + let c = sp.segment(s); + out.move_to(c.p0); + out.curve_to(c.p1, c.p2, c.p3); + } + } + } + (!out.elements().is_empty()).then_some((id, out)) + } } /// The angle between corner `c`'s sides once `xf` maps them into the document, in degrees. diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index e9235b33e9..ff190c6493 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -538,3 +538,77 @@ fn a_pen_path_shows_widgets_on_its_corners_only() { assert_eq!(w.corners(), [1, 2]); assert_eq!(pts(&w)[0], Point::new(290.0, 110.0)); } + +/// The bounds of the cut `w` gives for the pointer at `at`, rounded to 1e-6. +fn hovered_bounds(w: &CornerWidgets, d: &Document, at: Point) -> Option<(NodeId, [f64; 4])> { + let (id, cut) = w.hovered_cut(d, at, 5.0)?; + let b = vectorcraft_geom::Shape::bounding_box(&cut); + Some((id, [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 1e6).round() / 1e6))) +} + +/// #1232: the pointer within a press's reach of a widget gives the cut of the corner that widget +/// controls, for each corner of a rounded rectangle, the first one included; nothing away from +/// the widgets. +#[test] +fn a_widget_under_the_pointer_gives_its_corners_cut() { + let (d, id) = live_rect(20.0, Affine::translate((100.0, 100.0))); + let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap(); + assert_eq!(pts(&w), [Point::new(120.0, 120.0), Point::new(180.0, 120.0), Point::new(180.0, 180.0), Point::new(120.0, 180.0)]); + let cuts = [[100.0, 100.0, 120.0, 120.0], [180.0, 100.0, 200.0, 120.0], [180.0, 180.0, 200.0, 200.0], [100.0, 180.0, 120.0, 200.0]]; + for (at, cut) in pts(&w).into_iter().zip(cuts) { + assert_eq!(hovered_bounds(&w, &d, at + Vec2::new(3.0, -3.0)), Some((id, cut)), "{at:?}"); + } + assert_eq!(hovered_bounds(&w, &d, Point::new(127.0, 120.0)), None, "past a press's reach"); + assert_eq!(hovered_bounds(&w, &d, Point::new(150.0, 150.0)), None); +} + +/// #1232: a square corner has no cut to give, and a plain path cut in one corner gives that +/// corner's cut from its own widget, with the corners Direct Selection shows, for each corner +/// kind. +#[test] +fn a_square_corner_gives_no_cut_and_a_plain_paths_corner_gives_its_own() { + let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0))); + let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap(); + assert_eq!(hovered_bounds(&w, &d, Point::new(110.0, 110.0)), None); + for kind in [CornerKind::Round, CornerKind::InvertedRound, CornerKind::Chamfer] { + let (mut d, id) = doc_with_rect(); + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + vectorcraft_doc::corners::set_corners(path, live, &[2].into(), Some(30.0), Some(kind)); + } + let w = CornerWidgets::of(&d, &selected(id), 1.0, true).unwrap(); + assert_eq!(w.corners(), [0, 1, 2, 3], "{kind:?}"); + assert_eq!(hovered_bounds(&w, &d, Point::new(110.0, 110.0)), None, "{kind:?}: the square top-left corner"); + let at = pts(&w)[2]; + assert_eq!(hovered_bounds(&w, &d, at), Some((id, [170.0, 170.0, 200.0, 200.0])), "{kind:?}"); + } +} + +/// #1232: a live polygon's widget gives its corner's cut, and a widget hidden by Hide Corner +/// Widget for angles greater than gives none at its place. +#[test] +fn a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none() { + let live = + LiveShape::Polygon { radius: 80.0, sides: 6, xf: Affine::translate((200.0, 200.0)), radii: vec![], kinds: vec![], radii_relative: false }; + let (mut d, id) = doc_with(live.to_path(), Some(live)); + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + vectorcraft_doc::corners::set_corners(path, live, &[0].into(), Some(10.0), None); + } + let w = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap(); + let at = pts(&w)[0]; + let (got, b) = hovered_bounds(&w, &d, at).unwrap(); + assert_eq!(got, id); + // The arc of a 10 pt radius at a 120° corner spans 10 pt between its ends. + let (wide, high) = (b[2] - b[0], b[3] - b[1]); + assert!(wide.max(high) <= 10.5 && wide.max(high) > 5.0, "{b:?}"); + let centre = Point::new((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0); + assert!(centre.distance(at) < 15.0, "{b:?} {at:?}"); + // Sheared by 30°: the rectangle's 120° corners (1 and 3) hide above 100°. + let shear = Affine::translate((100.0, 100.0)) * Affine::new([1.0, 0.0, 30f64.to_radians().tan(), 1.0, 0.0, 0.0]); + let (d, id) = live_rect(10.0, shear); + let all = CornerWidgets::of(&d, &selected(id), 1.0, false).unwrap(); + let shown = all.clone().within_angle(100.0).unwrap(); + assert_eq!(shown.corners(), [0, 2]); + assert!(hovered_bounds(&shown, &d, pts(&all)[0]).is_some()); + assert!(hovered_bounds(&all, &d, pts(&all)[1]).is_some(), "shown, the 120° corner has a cut"); + assert_eq!(hovered_bounds(&shown, &d, pts(&all)[1]), None, "hidden, it gives none"); +} diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 2a1ceb0b12..4ee67bde6c 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -18,6 +18,10 @@ //! the drag makes it select only the objects entirely inside it, whole. //! In isolation mode both pick only the isolated object and what is inside it: anchors, segments, //! paths and groups outside it stay put. +//! An object inside a selected group counts as selected whole: a click on its fill keeps the group +//! selected, a drag from its fill or one of its anchors moves the group whole, and a click on an +//! anchor or a segment selects that anchor or segment alone. With Group Selection a click there +//! adds the next group up, if any. //! Both move objects selected as a whole as the Selection tool does, snapping alike. When the //! selection also holds direct-selected anchors or segments, a drag from an object moves those //! anchors and the objects selected whole, as an anchor drag does, and while Alt is held it @@ -53,7 +57,7 @@ //! moves its anchors. use std::borrow::Cow; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde_json::{Value, json}; use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view}; @@ -559,12 +563,14 @@ fn line_end_leave(cx: &ToolContext, grab: Point) -> Option { /// objects behind it (#3405). fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, Point)> { let mut owners = anchor_owners(cx, |n| matches!(n.kind, NodeKind::Path { .. }) || is_area_type(n) || is_path_type(n)); - owners.sort_by_key(|id| !cx.selection.contains(*id)); + // The members of a selected group count as selected. + let selected = in_selection_all(cx); + owners.sort_by_key(|id| !selected.contains(id)); // 1. Check selected objects first. Selected objects are NEVER occluded (#1508). let mut unselected_idx = owners.len(); for (i, &id) in owners.iter().enumerate() { - if !cx.selection.contains(id) { + if !selected.contains(&id) { unselected_idx = i; break; } @@ -624,9 +630,22 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { if spines.iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) || spine_segment_in(&spines, p, seg_tol).is_some() { return true; } - // The editable paths' control bounds are listed once per document state and selection; a - // hover measures only the paths whose bounds it is near. - let boxes = crate::select::selected_part_boxes(cx, || { + selected_part_boxes(cx).iter().any(|&(id, b)| { + b.inflate(tol, tol).contains(p) + && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { + #[cfg(test)] + MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); + nearest_anchor(&pd, p, tol, None).is_some() + }) + }) +} + +/// The editable paths of the selected objects and inside them (a selected group's members), with +/// their control bounds, topmost first across the whole document: the order [`hit_anchor`] tries +/// them in. The list is made once per document state and selection; a hover measures only the +/// paths whose bounds it is near. +fn selected_part_boxes(cx: &ToolContext) -> std::sync::Arc<[(NodeId, vectorcraft_geom::Rect)]> { + crate::select::selected_part_boxes(cx, || { let editable = cx.doc.editable(); let mut v = vec![]; for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { @@ -638,15 +657,21 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { } }); } + // The paint order of every node, a Shaper Group's original shapes included (isolation can + // select them); the topmost path comes first. + fn walk_all(n: &Node, order: &mut std::collections::HashMap) { + let i = order.len(); + order.insert(n.id, i); + for c in n.children().into_iter().flatten() { + walk_all(c, order); + } + } + let mut order = std::collections::HashMap::new(); + for l in &cx.doc.layers { + walk_all(l, &mut order); + } + v.sort_by_key(|(id, _)| std::cmp::Reverse(order.get(id).copied())); v.into() - }); - boxes.iter().any(|&(id, b)| { - b.inflate(tol, tol).contains(p) - && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { - #[cfg(test)] - MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); - nearest_anchor(&pd, p, tol, None).is_some() - }) }) } @@ -823,13 +848,37 @@ struct SegmentHit { fn next_group(cx: &ToolContext, ancestry: &[NodeId]) -> Option { // Skip the layer and its sublayers: they are not objects. let layers = ancestry.iter().take_while(|id| cx.doc.node(**id).is_some_and(Node::is_layer)).count().max(1); - ancestry + let chain: Vec = ancestry .iter() .skip(layers) .rev() .copied() .take_while(|id| in_scope(cx.doc, cx.isolation, *id) && !cx.doc.node(*id).is_some_and(Node::is_layer)) - .find(|id| !cx.selection.contains(*id)) + .collect(); + // The groups inside a selected group are selected with it: the next one is above the outermost + // selected one. + let outermost = chain.iter().rposition(|id| cx.selection.contains(*id)); + chain.get(outermost.map_or(0, |i| i + 1)).copied() +} + +/// Is `id` selected as an object: itself, or inside a selected group or other selected object? A +/// press on a member of a selected group keeps the group selected, and a drag moves the group +/// whole, as for a path that is itself selected. +fn in_selection(cx: &ToolContext, id: NodeId) -> bool { + !cx.selection.objects.is_empty() + && (cx.selection.contains(id) || cx.doc.ancestry(id).is_some_and(|a| a.iter().any(|x| cx.selection.contains(*x)))) +} + +/// The selected objects and the objects inside them that Direct Selection may pick: the objects +/// among those [`walk_pickable`] visits that [`in_selection`] accepts. +fn in_selection_all(cx: &ToolContext) -> HashSet { + let mut set = HashSet::new(); + for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { + walk_pickable_from(root, &mut |n| { + set.insert(n.id); + }); + } + set } /// Is an object of instance `id`'s art selected ([`vectorcraft_doc::Selection::symbol_part`]), @@ -1332,7 +1381,7 @@ impl DirectSelectionTool { // anchors on mouse over finds them: walking every path on each hover is too slow. let hit = hit_test(cx.doc, p, cx.selection_hit_options()); if let Some((id, _)) = hovered_anchor_with_hit(cx, p, hit.as_ref()) { - return Some(if cx.selection.contains(id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor }); + return Some(if in_selection(cx, id) { Cursor::DirectAnchorSelected } else { Cursor::DirectAnchor }); } if hit_frame_edge(cx, p, tol).is_some() { return None; @@ -1344,7 +1393,7 @@ impl DirectSelectionTool { return None; } let h = hit?; - let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none(); + let whole = in_selection(cx, h.leaf) && cx.selection.partial(h.leaf).is_none(); let curved = matches!(h.kind, HitKind::Stroke | HitKind::Outline) && segment_at(cx, h.leaf, p).is_some_and(|s| s.curved); (!whole && curved).then_some(Cursor::ReshapeSegment) } @@ -1360,7 +1409,11 @@ fn hovered_anchor(cx: &ToolContext, p: Point) -> Option<(NodeId, Point)> { fn hovered_anchor_with_hit(cx: &ToolContext, p: Point, hit: Option<&Hit>) -> Option<(NodeId, Point)> { let tol = cx.point_tol(); let under = hit.map(|h| cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)).unwrap_or(h.leaf)); - cx.selection.objects.iter().copied().filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| { + // The paths inside a selected group come before an object above them, as a press takes them + // ([`hit_anchor`]). + let selected = if cx.selection.objects.is_empty() { None } else { Some(selected_part_boxes(cx)) }; + let near = selected.iter().flat_map(|boxes| boxes.iter()).filter(|(_, b)| b.inflate(tol, tol).contains(p)).map(|&(id, _)| id); + near.filter(|id| in_scope(cx.doc, cx.isolation, *id)).chain(under).find_map(|id| { let path = cx.doc.node(id).and_then(editable_path)?; nearest_anchor(&path, p, tol, None).map(|(.., a)| (id, a)) }) @@ -1481,7 +1534,9 @@ impl DirectSelectionTool { h.ancestry.push(part); h.leaf = part; } - let target = if cx.selection.contains(h.leaf) { next_group(cx, &h.ancestry).unwrap_or(h.leaf) } else { h.leaf }; + // On an object selected itself or inside a selected group, a click adds the next group up, + // and keeps the selection when the outermost group is selected already. + let inside = in_selection(cx, h.leaf); let mut deselect = None; let mut out = vec![]; if ev.mods.shift { @@ -1490,15 +1545,13 @@ impl DirectSelectionTool { if cx.selection.contains(h.leaf) { deselect = Some(h.leaf); } else { - out.push(Action::Exec("select.toggle".into(), json!({"id": target.0}))); - } - } else if !cx.selection.contains(target) { - if cx.selection.contains(h.leaf) { - // A completed click climbs the group; a drag moves only the selected art. - self.click_group = Some(target); - } else { - out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]}))); + out.push(Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))); } + } else if !inside { + out.push(Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))); + } else if let Some(target) = next_group(cx, &h.ancestry) { + // A completed click climbs the group; a drag moves only the selected art. + self.click_group = Some(target); } self.state = Self::move_object(cx, &h, p, deselect); out @@ -1539,15 +1592,16 @@ impl DirectSelectionTool { // already selected whole, an Alt-click adds the next enclosing group on release. if ev.mods.alt { self.state = State::MoveObject { start: p, grab: Some(grab), hold: grab, edge: false, began: false, deselect: None }; - let whole = cx.selection.contains(id) && cx.selection.partial(id).is_none(); + let whole = in_selection(cx, id) && cx.selection.partial(id).is_none(); if whole && !ev.mods.shift { self.click_group = cx.doc.ancestry(id).and_then(|a| next_group(cx, &a)); } return if whole { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] }; } - // A path with all its anchors selected is stored whole (no partial entry). + // A path with all its anchors selected is stored whole (no partial entry), and so is each + // path inside a selected group. let already = - cx.selection.contains(id) && !cx.selection.segments.contains_key(&id) && cx.selection.partial(id).is_none_or(|s| s.contains(&(si, ai))); + in_selection(cx, id) && !cx.selection.segments.contains_key(&id) && cx.selection.partial(id).is_none_or(|s| s.contains(&(si, ai))); // Paths all selected whole move as objects, held by this anchor, so Alt can turn // the copy on and off during the drag as with the Selection tool. self.state = if already && cx.selection.anchors.is_empty() { @@ -1625,7 +1679,7 @@ impl DirectSelectionTool { // A segment pick keeps its endpoints available for movement without selecting // the anchors themselves. Dragging reshapes a curve, else moves it. Alt picks // the whole path (and Alt-drag copies it), as with Group Selection. - let whole = cx.selection.contains(h.leaf) && cx.selection.partial(h.leaf).is_none() && !part_picked(cx, h.leaf); + let whole = in_selection(cx, h.leaf) && cx.selection.partial(h.leaf).is_none() && !part_picked(cx, h.leaf); if !ev.mods.alt && matches!(h.kind, HitKind::Stroke | HitKind::Outline) && let Some(s) = segment_at(cx, h.leaf, p) @@ -1661,7 +1715,8 @@ impl DirectSelectionTool { return vec![Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))]; } self.frame.clear(); - if !cx.selection.contains(h.leaf) || cx.selection.partial(h.leaf).is_some() || part_picked(cx, h.leaf) { + // A press inside a selected group keeps the group: a drag moves it whole. + if !whole { return vec![Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))]; } vec![] @@ -1869,7 +1924,9 @@ impl DirectSelectionTool { (true, ..) => vec![Action::Commit], (false, Some(id), _, _) => vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))], (false, None, Some((id, si, ai)), _) => { - if has_multiple_selected_anchors(cx) { + // The key anchor is on a path selected itself (`select.key`); a click on an anchor of + // a path inside a selected group selects that anchor alone. + if cx.selection.contains(id) && has_multiple_selected_anchors(cx) { if cx.selection.key_anchor == Some((id, (si, ai))) { vec![Action::Exec("select.key".into(), json!({}))] } else { diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index f7b359f8d0..c788c8c87c 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1306,6 +1306,83 @@ fn group_selection_distinguishes_selected_leaf_drags_from_clicks() { assert!(t.pointer(&context, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty()); } +/// A path inside a selected group counts as selected whole. With Direct Selection a click on its +/// fill keeps the group, a drag from its fill or an anchor moves the group whole, and a click on an +/// anchor selects that anchor alone; its anchors show the selected-anchor cursor and an object +/// above the group does not take a press on one. With Group Selection a click adds the next group +/// up and keeps the selection at the outermost one, and a drag moves the selection. +#[test] +fn a_press_inside_a_selected_group_keeps_the_group() { + let (mut d, inside, _, inner, outer) = nested_group_doc(); + let p = paint(); + let mut s = Selection::default(); + s.set([outer]); + let moves = |a: &[Action]| matches!(a, [Action::Begin(n), Action::Preview(c, _)] if n == "Move" && c == "object.transform"); + for group in [false, true] { + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(group); + let down = PointerEvent::new(PointerKind::Down, 150.0, 150.0); + assert!(t.pointer(&c, &down).is_empty(), "a press on the fill (group: {group})"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)).is_empty(), "a click on the fill (group: {group})"); + assert!(t.pointer(&c, &down).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 180.0, 165.0)); + assert!(moves(&a), "a drag from the fill (group: {group}): {a:?}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 180.0, 165.0)), vec![Action::Commit]); + } + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + let corner = PointerEvent::new(PointerKind::Down, 100.0, 100.0); + assert!(t.pointer(&c, &corner).is_empty(), "a press on an anchor"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 115.0)); + assert!(moves(&a), "a drag from an anchor: {a:?}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 115.0)); + t.pointer(&c, &corner); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), + vec![Action::Exec("select.anchors".into(), json!({"id": inside.0, "anchors": [[0, 0]], "mode": "set"}))], + "a click on an anchor" + ); + assert_eq!(DirectSelectionTool::new(false).cursor(&c, Point::new(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0)).is_empty(), "a press on a segment"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0)); + assert!(matches!(a.as_slice(), [Action::Exec(c, v)] if c == "select.segments" && v["id"] == inside.0), "a click on a segment: {a:?}"); + // Group Selection climbs from a selected inner group to the group around it. + let mut climb = Selection::default(); + climb.set([inner]); + let c = cx(&d, &climb, &p); + let mut t = DirectSelectionTool::new(true); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 150.0)), vec![Action::Exec("select.add".into(), json!({"ids": [outer.0]}))]); + // With two anchors of a path beside the group selected too, the click still selects the anchor + // alone: the key anchor is on a path selected itself. + let l = d.layers[0].id; + let beside = d.alloc_id(); + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0)); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::path(beside, rect, vectorcraft_doc::Appearance::default_art())).unwrap(); + let mut mixed = Selection::default(); + mixed.set([outer, beside]); + mixed.anchors.insert(beside, BTreeSet::from([(0, 0), (0, 1)])); + let c = cx(&d, &mixed, &p); + let mut t = DirectSelectionTool::new(false); + assert!(t.pointer(&c, &corner).is_empty()); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 100.0, 100.0)), + vec![Action::Exec("select.anchors".into(), json!({"id": inside.0, "anchors": [[0, 0]], "mode": "set"}))], + "a click on an anchor with anchors of {beside:?} selected" + ); + // An opaque object above the group, over the anchor. + let cover = d.alloc_id(); + let rect = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 250.0, 250.0)); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::path(cover, rect, vectorcraft_doc::Appearance::default_art())).unwrap(); + let c = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(false); + assert_eq!(hovered_anchor(&c, Point::new(100.0, 100.0)), Some((inside, Point::new(100.0, 100.0))), "the anchor under {cover:?} is highlighted"); + assert_eq!(t.cursor(&c, Point::new(100.0, 100.0), Mods::default()), Cursor::DirectAnchorSelected); + assert!(t.pointer(&c, &corner).is_empty(), "a press on an anchor under {cover:?}"); + assert!(moves(&t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 115.0)))); +} + /// Isolation mode: a marquee and an anchor click take the path inside the isolated group and /// leave the path beside it. Group Selection stops at the isolated group instead of adding /// the group around it. @@ -1735,13 +1812,18 @@ fn the_centre_point_selects_and_moves_the_object_whole() { let moved = json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(Vec2::new(20.0, -10.0))), "copy": false}); assert_eq!(a, vec![Action::Begin("Move".into()), Action::Preview("object.transform".into(), moved)]); assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 140.0)), vec![Action::Commit]); - // Unselected, the centre isn't shown and a press there starts a marquee. + // Unselected, the centre isn't shown and a press there starts a marquee (with Object Selection + // by Path Only, where the inside of the unfilled square takes no press). let none = Selection::default(); let mut t = DirectSelectionTool::new(false); - let c = cx(&d, &none, &p); + let c = ToolContext { path_only: true, ..cx(&d, &none, &p) }; assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)).is_empty()); t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 140.0)); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Marquee(_)))); + // Without it, a press inside the unfilled square selects it (#9175). + let mut t = DirectSelectionTool::new(false); + let c = cx(&d, &none, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)), vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); } /// Group Selection: E pressed during a marquee drag makes it select the objects entirely inside @@ -2997,3 +3079,31 @@ fn select_behind_is_measured_once_for_a_point() { assert!(crate::select::selects_behind_at(&c, at)); assert_eq!(MEASURED_PARTS.get() - before, 1, "measured for the first ask only"); } + +/// With two selected groups whose anchors sit on the same point, the highlighted anchor is the one +/// a press takes: the front group's, whatever order the groups were selected in. +#[test] +fn the_highlighted_anchor_of_two_selected_groups_is_the_one_a_press_takes() { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (back_path, back, front_path, front) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = |id, x| { + std::sync::Arc::new(vectorcraft_doc::Node::path( + id, + vectorcraft_geom::shapes::rectangle(Rect::new(x, x, x + 100.0, x + 100.0)), + vectorcraft_doc::Appearance::default_art(), + )) + }; + d.insert(Some(l), 0, vectorcraft_doc::Node::group(back, vec![path(back_path, 100.0)])).unwrap(); + d.insert(Some(l), usize::MAX, vectorcraft_doc::Node::group(front, vec![path(front_path, 100.0)])).unwrap(); + let p = paint(); + let corner = Point::new(100.0, 100.0); + for order in [[back, front], [front, back]] { + let mut s = Selection::default(); + s.set(order); + let c = cx(&d, &s, &p); + let pressed = hit_anchor(&c, corner, c.point_tol()).map(|(id, ..)| id); + assert_eq!(pressed, Some(front_path), "a press takes the front anchor (selected {order:?})"); + assert_eq!(hovered_anchor(&c, corner), Some((front_path, corner)), "the front anchor is highlighted (selected {order:?})"); + } +} diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index ff95ef68ce..d575fda573 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2917,14 +2917,15 @@ fn a_double_click_on_a_symbol_instance_edits_its_symbol() { /// #4891 for the Selection tool: a press on a selected object's centre point (Attributes › Show /// Center) moves the selection, also where no art is painted (an unfilled shape), which the press -/// would otherwise take for a marquee; anywhere else a press still starts one. +/// would otherwise take for a marquee; anywhere else a press still starts one. With Object +/// Selection by Path Only, so that the inside of the unfilled shape takes no press of its own. #[test] fn a_press_on_the_centre_point_moves_an_unfilled_shape() { let (d, id) = doc_with_live_rect(); let mut s = Selection::default(); s.add(id); let p = paint(); - let c = cx(&d, &s, &p); + let c = ToolContext { path_only: true, ..cx(&d, &s, &p) }; let centre = Point::new(150.0, 150.0); let mut t = SelectionTool::default(); assert_eq!(t.cursor(&c, centre, Mods::default()), Cursor::Move); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 7c9bd3ce81..f9cf5f51cd 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -110,7 +110,11 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), - (&[crate::addons::tangent_circle::ID], None, &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides"]), + ( + &[crate::addons::tangent_circle::ID], + None, + &["radius", "addPoints", "center", "radii", "color", "snapTolerance", "snapWithoutGuides", "askRadius", "autoUpdateDefault"], + ), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 6ddf340de4..03f69718b9 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -34,6 +34,8 @@ pub(crate) struct Spec { pub(crate) struct AddonDialogs { open: Option, preview: LivePreview, + /// The open Tangent Circle Tool radius dialog. + pub(crate) tangent_radius: Option, } #[derive(Clone, Copy)] @@ -105,6 +107,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option Vec { Param::new("color", tl!("Color"), ParamKind::choice(colors, Some("red".into()))), Param::new("snapTolerance", tl!("Snap Tolerance"), snap).unit(UnitKind::Pixels), Param::new("snapWithoutGuides", tl!("Snap When Smart Guides Are Off"), ParamKind::bool(true)), + Param::new("askRadius", tl!("Ask For Circle Radius"), ParamKind::bool(false)), + Param::new("autoUpdateDefault", tl!("Auto-Update Default"), ParamKind::bool(false)), ]; } let (size, tolerance) = (anchor_eraser::SIZE_RANGE, anchor_eraser::TOLERANCE_RANGE); diff --git a/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs new file mode 100644 index 0000000000..92ad231a96 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/tangent_circle_radius.rs @@ -0,0 +1,551 @@ +//! The Tangent Circle Tool's radius dialog, which a click on the second segment opens when the +//! tool's Ask For Circle Radius option is on. It starts at the radius of the circle the click found, +//! and each radius previews on the canvas the circle of that radius touching the two segments +//! nearest the click ([`tangent_circle::radius_circle`]). A radius that gives no circle there shows +//! the tool's note and leaves OK off, as does an edit to either segment after the click. OK draws +//! the circle with `shape.circleThroughPoints` in one undo step, and with Auto-Update Default on +//! also sets the tool's `radius` to the one given when it is in the tool's range; Cancel draws nothing. + +use craft::ui::contract::Bind; +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamResult}; +use craft::ui::runtime::env::Label; +use serde_json::{Value, json}; +use vectorcraft_doc::Document; +use vectorcraft_tools::addons::tangent_circle; + +use crate::VectorcraftApp; +use crate::canvas::rulers::general_lengths; +use crate::dialogs::host::{HeldOptions, open_held_with}; +use crate::dialogs::preview::LivePreview; + +/// The dialog's kind. +pub const KIND: &str = tangent_circle::RADIUS_DIALOG; +/// The command that draws the circle. +const DRAW: &str = "shape.circleThroughPoints"; +/// The error for a radius outside the tool's range. +const RADIUS_RANGE: &str = "`radius` must be from 0.01 to 1000000 pt"; + +/// The open radius dialog: the dialog, what the tool found (the segments, the click and its circle), the id of the +/// document the click was in (`DocState::uid`), the circle last looked for and the live preview. +pub(crate) struct Open { + id: DialogId, + click: Value, + doc: Option, + /// The radius the circle was last looked for at, and the circle's parameters for [`DRAW`] (`None`: no circle). + tried: Option<(f64, Option)>, + /// Why there is no circle at the radius the dialog held at the last frame (in English), which the dialog shows + /// under its rows with OK off; `None` while there is one. + note: Option, + preview: LivePreview, + /// The document that was active when the preview last ran (`DocState::uid`). + shown_in: Option, +} + +/// Open the dialog on what the tool found (its [`tangent_circle::RADIUS_DIALOG`] parameters). +pub(crate) fn open(app: &mut VectorcraftApp, p: &Value) { + let radius = p.get("radius").and_then(Value::as_f64).unwrap_or(tangent_circle::RADIUS); + let doc = app.session.doc().ok().map(|s| s.uid); + let Some(ctx) = app.ui_ctx.clone() else { + app.status("no window"); + return; + }; + // A dialog still open from an earlier click closes without an answer, and its preview is rolled back. The new + // dialog has the same id (the dialog's kind), and its own held answer and cancel hook replace the earlier ones. + if let Some(mut old) = app.addon_dialogs.tangent_radius.take() { + if let Some(host) = app.dialogs() { + host.with(|h| { + h.cancel_by_id(&ctx, old.id); + let _ = h.take_by_id::(old.id); + }); + } + take_preview(app, &mut old).cancel(app); + } + let lengths = general_lengths(app); + let fields = DialogFields::from_pairs([("radius", FieldValue::Number(radius))]); + // The field has no bounds: a radius typed outside the tool's range is kept as typed and shows [`RADIUS_RANGE`]. + let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| { + let rows = vec![Param::number("radius", tl!("Radius:"), radius, 1.0, 2).length(lengths)]; + ParamDialog::new(KIND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true) + }); + let cancel: Box = Box::new(|app| { + if let Some(mut open) = app.addon_dialogs.tangent_radius.take() { + take_preview(app, &mut open).cancel(app); + } + }); + match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) { + Some(id) => { + app.addon_dialogs.tangent_radius = + Some(Open { id, click: p.clone(), doc, tried: None, note: None, preview: LivePreview::default(), shown_in: doc }); + } + None => app.status("no window"), + } +} + +/// The document the click was in, while it is the active one. A preview adds the circle to it and +/// leaves the two segments as they are. +fn doc<'a>(app: &'a VectorcraftApp, open: &Open) -> Option<&'a Document> { + let clicked = open.doc?; + app.session.doc().ok().filter(|s| s.uid == clicked).map(|s| &*s.doc) +} + +/// The id of the active document (`DocState::uid`). +fn active_uid(app: &VectorcraftApp) -> Option { + app.session.doc().ok().map(|s| s.uid) +} + +/// The dialog's live preview, taken out of `open`. With another document active than the one it previewed in, the +/// preview is forgotten instead: the switch already rolled it back there, and rolling back here would cancel an +/// interaction of the document now active. +fn take_preview(app: &VectorcraftApp, open: &mut Open) -> LivePreview { + let preview = std::mem::take(&mut open.preview); + if open.shown_in == active_uid(app) { preview } else { LivePreview::default() } +} + +/// Whether `r` is in the tool's radius range. +fn in_range(r: f64) -> bool { + let (lo, hi) = tangent_circle::RADIUS_RANGE; + (lo..=hi).contains(&r) +} + +/// The radius `fields` hold, when it is in the tool's range or is the radius of the circle the click found +/// (which a click without Shift may find outside that range). +fn radius(open: &Open, fields: &DialogFields) -> Result { + let found = open.click.get("radius").and_then(Value::as_f64); + fields.number("radius").filter(|r| in_range(*r) || Some(*r) == found).ok_or_else(|| RADIUS_RANGE.to_string()) +} + +/// The radius `fields` hold and the circle of that radius, as [`DRAW`]'s parameters. `Err` says why there is none: +/// a radius outside the tool's range, no document clicked in, either segment in it no longer the one clicked (a +/// control request edited or removed its path), or no circle of that radius there. The circle is looked for again +/// only when the radius changed. +fn circle(app: &VectorcraftApp, open: &mut Open, fields: &DialogFields) -> Result<(f64, Value), String> { + let r = radius(open, fields)?; + let no_circle = || tangent_circle::NO_CIRCLE.to_string(); + if !doc(app, open).is_some_and(|doc| tangent_circle::segments_unchanged(doc, &open.click)) { + return Err(no_circle()); + } + let found = match &open.tried { + Some((tried, found)) if *tried == r => found.clone(), + _ => { + let found = tangent_circle::radius_circle(&open.click, r); + open.tried = Some((r, found.clone())); + found + } + }; + found.map(|points| (r, points)).ok_or_else(no_circle) +} + +/// Why the active document cannot take a new circle now: its target layer is locked or hidden. The draw would be +/// refused, with or without a preview. +fn target_refusal(app: &VectorcraftApp) -> Option { + app.session.doc().ok()?.target_parent().err().map(|e| e.to_string()) +} + +/// The words the dialog shows for `why` ([`circle`]'s error), in the interface's language. +fn shown(why: &str) -> String { + if why == tangent_circle::NO_CIRCLE { tl!(tangent_circle::NO_CIRCLE).to_string() } else { crate::i18n::msg(why) } +} + +/// Once a frame: previews the circle of the radius the dialog holds, or rolls the preview back and shows why there +/// is none, with OK off. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(mut open) = app.addon_dialogs.tangent_radius.take() else { return }; + let Some(host) = app.dialogs() else { + app.addon_dialogs.tangent_radius = Some(open); + return; + }; + let id = open.id; + let Some((previewing, fields)) = host.with(|h| h.get_by_id::(id).map(|d| (d.is_previewing(), d.fields().clone()))) else { + app.addon_dialogs.tangent_radius = Some(open); + return; + }; + let mut preview = take_preview(app, &mut open); + let found = circle(app, &mut open, &fields); + // Without a circle the preview rolls back; the preview reports its own failures on the status line. + let previewed = match &found { + Ok((_, points)) => (previewing, points.clone()), + Err(_) => (false, Value::Null), + }; + let _ = preview.run(app, previewed.0, "Tangent Circle", DRAW, &previewed.1); + open.preview = preview; + open.shown_in = active_uid(app); + // A target layer locked or hidden after the circle previewed refuses the draw: OK stays off. The preview stays, + // since rolling it back would also roll back the edit that locked or hid the layer. + open.note = found.err().or_else(|| target_refusal(app)); + let ready = open.note.as_deref().map_or(Ok(()), |why| Err(Label::from(shown(why)))); + app.addon_dialogs.tangent_radius = Some(open); + host.with(|h| { + if let Some(d) = h.get_mut_by_id::(id) { + d.set_notes(ready.as_ref().err().cloned().into_iter().collect()); + d.set_ready(ready); + } + }); +} + +/// OK: draw the circle (keeping its preview) and close; with Auto-Update Default on, the radius +/// becomes the tool's when it is in the tool's range. Without a circle the dialog stays open. +fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> { + let Some(mut open) = app.addon_dialogs.tangent_radius.take() else { return Err(shown(tangent_circle::NO_CIRCLE)) }; + let (r, points) = match circle(app, &mut open, &result.fields) { + Ok(found) => found, + Err(why) => { + app.addon_dialogs.tangent_radius = Some(open); + return Err(shown(&why)); + } + }; + let auto = app.session.tool_options_of(tangent_circle::ID).get("autoUpdateDefault").and_then(Value::as_bool) == Some(true); + // A failed commit leaves the interaction running: the dialog keeps its preview, so Cancel still ends it. + if let Err(e) = open.preview.clone().commit(app, DRAW, points) { + app.addon_dialogs.tangent_radius = Some(open); + return Err(e); + } + if auto && in_range(r) { + app.run("tool.setOption", json!({ "tool": tangent_circle::ID, "key": "radius", "value": r }))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + use vectorcraft_engine::{Session, ViewInfo}; + use vectorcraft_tools::addons::tangent_circle as tool; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + use crate::VectorcraftApp; + use crate::addons::dialogs::tests::{cancel, confirm, dialog_id, frame, read, set}; + + fn count(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers[0].children().unwrap().len() + } + + fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// A test window with a 500 pt document, the lines `ys` from x 100 to 300, and the tool with Ask For Circle + /// Radius on. + fn app_with_lines(ys: &[i64]) -> VectorcraftApp { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 500, "height": 500})).unwrap(); + for y in ys { + app.run("path.create", json!({"anchors": [{"x": 100, "y": y}, {"x": 300, "y": y}]})).unwrap(); + } + app.session.select_tool(tool::ID, ViewInfo::default()).unwrap(); + app.run("tool.setOption", json!({"tool": tool::ID, "key": "askRadius", "value": true})).unwrap(); + app + } + + /// A click with the active tool at (`x`, `y`), Shift held when `shift`, with what it asks the + /// interface for done. + fn click(app: &mut VectorcraftApp, x: f64, y: f64, shift: bool) { + for kind in [PointerKind::Down, PointerKind::Up] { + let mut ev = PointerEvent::new(kind, x, y); + ev.mods.shift = shift; + let r = app.session.pointer(&ev, ViewInfo::default()); + crate::canvas::apply_requests(app, r); + } + } + + fn is_open(app: &VectorcraftApp) -> bool { + app.addon_dialogs.tangent_radius.is_some() + } + + /// Why the dialog shows no circle and leaves OK off, at the last frame. + fn note(app: &VectorcraftApp) -> Option { + app.addon_dialogs.tangent_radius.as_ref()?.note.clone() + } + + /// Presses OK and lets the held answer through: whether the dialog closed. + fn press_ok(app: &mut VectorcraftApp) -> bool { + let id = dialog_id(app); + let enabled = confirm(app, id); + frame(app); + frame(app); + enabled && !is_open(app) + } + + /// Presses OK while it is off: it takes no press, and the dialog stays open. + fn press_ok_while_off(app: &mut VectorcraftApp) { + let id = dialog_id(app); + assert!(!confirm(app, id), "OK is off"); + frame(app); + assert!(is_open(app)); + } + + #[test] + fn the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok() { + let mut app = app_with_lines(&[100, 140]); + app.run("path.create", json!({"anchors": [{"x": 100, "y": 300}, {"x": 300, "y": 300}, {"x": 300, "y": 400}]})).unwrap(); + let (paths, steps) = (count(&app), undo_steps(&app)); + // A click on each line: the dialog at the click's circle (radius 20), previewed. + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + assert!(is_open(&app), "{}", app.ui.status); + let id = dialog_id(&app); + assert!((read(&app, id, |f| f.number("radius")).unwrap() - 20.0).abs() < 1e-6); + frame(&mut app); + assert_eq!(count(&app), paths + 1, "previewed: {}", app.ui.status); + assert_eq!(note(&app), None); + // Lines 40 pt apart take no other radius: the note, nothing previewed, and OK off. + set(&app, id, "radius", json!(25)); + frame(&mut app); + assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE)); + assert_eq!(count(&app), paths); + press_ok_while_off(&mut app); + assert_eq!(count(&app), paths); + // A radius outside the tool's range (as a control request can set it) is an error. + for bad in [json!(0), json!(-20), json!(2e6)] { + set(&app, id, "radius", bad.clone()); + frame(&mut app); + assert_eq!(note(&app).as_deref(), Some(super::RADIUS_RANGE), "{bad}"); + press_ok_while_off(&mut app); + assert_eq!(count(&app), paths, "{bad}"); + } + // Back at 20, previewed again; Cancel draws nothing and leaves no undo step. + set(&app, id, "radius", json!(20)); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + cancel(&app, id); + frame(&mut app); + assert!(!is_open(&app)); + assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); + // The first line stays picked: a click on the second asks again, and OK draws the circle in + // one undo step; the tool's radius stays. + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert!(press_ok(&mut app), "{}", app.ui.status); + assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1)); + let st = app.session.doc().unwrap(); + let b = st.doc.bounds_of(&[st.doc.layers[0].children().unwrap()[paths].id], false).unwrap(); + assert!((b.x0 - 130.0).abs() < 1e-3 && (b.y0 - 100.0).abs() < 1e-3 && (b.width() - 40.0).abs() < 1e-3, "{b:?}"); + assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); + // Auto-Update Default: Shift in the L's corner asks at the tool's radius; Cancel keeps the + // tool's radius, and OK with another radius draws that fillet and makes it the tool's. + app.run("tool.setOption", json!({"tool": tool::ID, "key": "autoUpdateDefault", "value": true})).unwrap(); + click(&mut app, 150.0, 300.0, false); + click(&mut app, 300.0, 350.0, true); + let id = dialog_id(&app); + assert_eq!(read(&app, id, |f| f.number("radius")), Some(tool::RADIUS)); + set(&app, id, "radius", json!(12)); + frame(&mut app); + cancel(&app, id); + frame(&mut app); + assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); + click(&mut app, 300.0, 350.0, true); + let id = dialog_id(&app); + set(&app, id, "radius", json!(10)); + frame(&mut app); + assert!(press_ok(&mut app), "{}", app.ui.status); + assert_eq!((count(&app), undo_steps(&app)), (paths + 2, steps + 2)); + assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(10.0)); + } + + #[test] + fn another_document_or_a_segment_changed_after_the_click_gives_no_circle() { + let mut app = app_with_lines(&[100, 140]); + let paths = count(&app); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(note(&app), None); + assert_eq!(count(&app), paths + 1); + // Clicked in another document than the active one: no circle and OK off, until that one is + // active again. + let clicked = app.addon_dialogs.tangent_radius.as_ref().and_then(|o| o.doc); + assert_eq!(clicked, Some(app.session.doc().unwrap().uid)); + let set_doc = |app: &mut VectorcraftApp, doc: Option| app.addon_dialogs.tangent_radius.as_mut().unwrap().doc = doc; + set_doc(&mut app, clicked.map(|d| d + 1)); + frame(&mut app); + assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE)); + assert_eq!(count(&app), paths); + press_ok_while_off(&mut app); + set_doc(&mut app, clicked); + frame(&mut app); + assert_eq!(note(&app), None); + assert_eq!(count(&app), paths + 1); + // The dialog holds a first segment the document no longer has (as when a control request + // moves that line): no circle, nothing previewed, and OK refused. + app.addon_dialogs.tangent_radius.as_mut().unwrap().click["first"] = json!([[100.0, 110.0], [100.0, 110.0], [300.0, 110.0], [300.0, 110.0]]); + frame(&mut app); + assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE)); + assert_eq!(count(&app), paths); + press_ok_while_off(&mut app); + assert_eq!(count(&app), paths); + } + + #[test] + fn a_failed_ok_keeps_the_preview_for_cancel() { + let mut app = app_with_lines(&[100, 140]); + let (paths, steps) = (count(&app), undo_steps(&app)); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + // The layer the preview started from is locked before OK, so OK's draw is refused and the dialog stays open. + { + let st = app.session.doc_mut().unwrap(); + let layer = st.doc.layers[0].id; + let it = st.interaction.as_mut().unwrap(); + std::sync::Arc::make_mut(&mut it.doc).node_mut(layer).unwrap().locked = true; + } + let id = dialog_id(&app); + assert!(confirm(&app, id), "OK is on"); + frame(&mut app); + assert!(is_open(&app)); + assert!(app.session.in_interaction()); + // The dialog still owns the interaction: a radius with no circle there ends it. + set(&app, id, "radius", json!(25)); + frame(&mut app); + assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE)); + assert!(!app.session.in_interaction()); + // Cancel closes it with nothing drawn and no undo step. + cancel(&app, id); + frame(&mut app); + assert!(!is_open(&app)); + assert!(!app.session.in_interaction()); + assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); + } + + #[test] + fn cancel_right_after_a_failed_ok_rolls_the_preview_back() { + let mut app = app_with_lines(&[100, 140]); + let (paths, steps) = (count(&app), undo_steps(&app)); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + { + let st = app.session.doc_mut().unwrap(); + let layer = st.doc.layers[0].id; + let it = st.interaction.as_mut().unwrap(); + std::sync::Arc::make_mut(&mut it.doc).node_mut(layer).unwrap().locked = true; + } + let id = dialog_id(&app); + assert!(confirm(&app, id), "OK is on"); + frame(&mut app); + assert!(is_open(&app)); + assert!(app.session.in_interaction()); + // Cancel is the next press after the refused OK, with no radius change or other frame in between. + cancel(&app, id); + frame(&mut app); + assert!(!is_open(&app)); + assert!(!app.session.in_interaction()); + assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); + } + + #[test] + fn a_click_found_radius_outside_the_tool_range_can_be_drawn() { + // Lines 2,400,000 pt apart: a click on each finds the circle of radius 1,200,000, past the + // largest radius the tool takes. + let mut app = app_with_lines(&[100, 2_400_100]); + app.run("tool.setOption", json!({"tool": tool::ID, "key": "autoUpdateDefault", "value": true})).unwrap(); + let (paths, steps) = (count(&app), undo_steps(&app)); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 2_400_100.0, false); + let id = dialog_id(&app); + assert!((read(&app, id, |f| f.number("radius")).unwrap() - 1_200_000.0).abs() < 1e-3, "{}", app.ui.status); + frame(&mut app); + assert_eq!(note(&app), None); + // OK draws it; the tool's radius stays, since the tool does not take that radius. + assert!(press_ok(&mut app), "{}", app.ui.status); + assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1)); + assert_eq!(app.session.tool_options_of(tool::ID)["radius"], json!(tool::RADIUS)); + } + + #[test] + fn a_second_click_replaces_the_open_dialog() { + let mut app = app_with_lines(&[100, 140]); + let (paths, steps) = (count(&app), undo_steps(&app)); + let open_ids = |app: &VectorcraftApp| app.dialogs().unwrap().with(|h| h.open_dialogs().iter().map(|d| d.id).collect::>()); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + // The first line stays picked: another click on the second (as a control request can send while the dialog + // is open) asks again in one dialog, previewing one circle. + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(open_ids(&app).len(), 1); + assert!(is_open(&app)); + assert_eq!(count(&app), paths + 1); + // Cancel closes it and rolls its preview back, with no undo step. + cancel(&app, dialog_id(&app)); + frame(&mut app); + assert!(!is_open(&app)); + assert!(open_ids(&app).is_empty()); + assert_eq!((count(&app), undo_steps(&app)), (paths, steps)); + // Asked again, OK draws one circle in one undo step. + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert!(press_ok(&mut app), "{}", app.ui.status); + assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps + 1)); + } + + #[test] + fn a_switch_to_another_document_leaves_its_interaction_alone() { + let mut app = app_with_lines(&[100, 140]); + let paths = count(&app); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(count(&app), paths + 1); + // Another document comes to the front (which rolls the preview back in the first) and starts an interaction + // of its own before the dialog's next frame: the dialog leaves that interaction running. + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.begin_interaction("Other").unwrap(); + app.session.preview("path.create", &json!({"anchors": [{"x": 10, "y": 10}, {"x": 50, "y": 10}]})).unwrap(); + frame(&mut app); + assert_eq!(note(&app).as_deref(), Some(tool::NO_CIRCLE)); + assert!(app.session.in_interaction()); + assert_eq!(count(&app), 1); + // Cancel leaves it running too. + cancel(&app, dialog_id(&app)); + frame(&mut app); + assert!(!is_open(&app)); + assert!(app.session.in_interaction()); + assert_eq!(count(&app), 1); + } + + #[test] + fn a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off() { + let mut app = app_with_lines(&[100, 140]); + let paths = count(&app); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + frame(&mut app); + assert_eq!(note(&app), None); + assert_eq!(count(&app), paths + 1); + // A control request locks the only layer while the dialog is open: no layer takes the circle, and OK is off. + app.run("layer.setProps", json!({"locked": true})).unwrap(); + let steps = undo_steps(&app); + frame(&mut app); + assert!(note(&app).is_some_and(|n| n.contains("locked")), "{:?}", note(&app)); + press_ok_while_off(&mut app); + assert_eq!((count(&app), undo_steps(&app)), (paths + 1, steps)); + // Unlocked again at the same radius: previewed, and OK draws the circle. + app.run("layer.setProps", json!({"locked": false})).unwrap(); + frame(&mut app); + assert_eq!(note(&app), None); + assert_eq!(count(&app), paths + 1); + assert!(press_ok(&mut app), "{}", app.ui.status); + assert_eq!(count(&app), paths + 1); + } + + #[test] + fn a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle() { + let mut app = app_with_lines(&[100, 140]); + let paths = count(&app); + click(&mut app, 150.0, 100.0, false); + click(&mut app, 200.0, 140.0, false); + let id = dialog_id(&app); + let ctx = crate::addons::dialogs::tests::ctx(&app); + for bad in [json!("x"), Value::Null] { + assert!(app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "radius", bad.clone())).is_err(), "{bad}"); + frame(&mut app); + assert_eq!(note(&app), None, "{bad}"); + assert_eq!(count(&app), paths + 1, "{bad}"); + } + } +} diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 9a63194c34..b516412e61 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -110,18 +110,22 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("straight")); ok(&mut app, &[("mode", FieldValue::Text("arc".into()))]); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); - // The Tangent Circle tool's radius for Shift, and Add Points to Existing Paths (off to start). + // The Tangent Circle tool's radius for Shift, Add Points to Existing Paths (off to start), Ask For + // Circle Radius and Auto-Update Default. app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); let shown = held(&app, |d| { let f = d.expect("the held dialog").fields(); - (f.number("radius"), f.bool("addPoints")) + (f.number("radius"), f.bool("addPoints"), f.bool("askRadius"), f.bool("autoUpdateDefault")) }); - assert_eq!(shown, (Some(36.0), Some(false))); + assert_eq!(shown, (Some(36.0), Some(false), Some(false), Some(false))); let rows = super::options_params("tangentCircle", crate::canvas::rulers::general_lengths(&app)); assert!(rows.iter().any(|p| p.key == "addPoints" && p.label.as_str() == "Add Points to Existing Paths"), "the option has a row"); - ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true))]); - assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); - assert_eq!(app.session.tool_options_of("tangentCircle")["addPoints"], json!(true)); + ok(&mut app, &[("radius", FieldValue::Number(12.5)), ("addPoints", FieldValue::Bool(true)), ("askRadius", FieldValue::Bool(true))]); + let o = app.session.tool_options_of("tangentCircle"); + assert_eq!( + (o["radius"].clone(), o["addPoints"].clone(), o["askRadius"].clone(), o["autoUpdateDefault"].clone()), + (json!(12.5), json!(true), json!(true), json!(false)) + ); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); assert_eq!(KIND, "pathToolOptions"); } @@ -189,6 +193,8 @@ fn the_tangent_circle_options_have_their_rows_and_a_fractional_tolerance() { ("color", "Color"), ("snapTolerance", "Snap Tolerance"), ("snapWithoutGuides", "Snap When Smart Guides Are Off"), + ("askRadius", "Ask For Circle Radius"), + ("autoUpdateDefault", "Auto-Update Default"), ] ); let colors = params.iter().find_map(|p| match &p.kind { diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index a134adeab4..e5fde5725e 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -1,11 +1,12 @@ //! The 3D Box and customizable shapes add-on in the interface: its submenu (Object › Plug-ins › //! 3D Box), which selects the 3D Box tool, and the context-sensitive Control bar options shown //! when a shape tool (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `spiral`, -//! `box3d`) is active. +//! `box3d`) is active. Canceling a numeric edit restores its future-tool options, including coupled +//! scalar and per-corner radii; a retired edit cannot restore options into a different tool. use std::ops::RangeInclusive; -use craft::behavior::{IconId, NumberCodec}; +use craft::behavior::{CancelReason, EditEvent, GestureId, IconId, NumberCodec}; use craft::menu::Node; use craft::ui::buttons::{Button, ToggleButton}; use craft::ui::choice::Segmented; @@ -16,7 +17,7 @@ use craft::ui::layout_components::Row; use craft::ui::runtime::env::{Env, LengthUnits, UnitKind}; use craft::ui::text::NumberField; use egui::Ui; -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use vectorcraft_geom::shapes::EllipseMode; use vectorcraft_tools::addons::box3d::{self, CustomShape}; @@ -171,7 +172,7 @@ fn number( response = field.take().map(|field| field.show(ui).edit); }); if let Some(response) = response { - edits::apply_edits(app, &response, EditPath::Preview, |app, value, phase| { + shape_number_edits(app, ui.ctx(), key, &response, |app, value, phase| { if let Some(value) = *value { apply(app, value, phase); } @@ -180,6 +181,104 @@ fn number( }); } +#[derive(Clone)] +struct ShapeToolGesture { + id: GestureId, + tool: String, + target: Option<(u64, u64, Vec)>, + opening: Map, + latest: Value, +} + +fn shape_target(app: &VectorcraftApp) -> Option<(u64, u64, Vec)> { + app.session.active().map(|st| (st.uid, st.reverts, st.selection.objects.clone())) +} + +/// Tool options are outside the document preview snapshot. A canceled scrub restores this +/// field's complete option group, including settings that the rollback changes indirectly. +fn shape_number_edits( + app: &mut VectorcraftApp, + ctx: &egui::Context, + field: &'static str, + response: &EditResponse>, + mut apply: impl FnMut(&mut VectorcraftApp, &Option, Live), +) { + let keys: &[&str] = match field { + "arc-start" => &["arcStart", "arcMode"], + "arc-end" => &["arcEnd", "arcMode"], + "rect-r" => &["cornerRadius", "cornerRadii"], + "rect-tl" | "rect-tr" | "rect-br" | "rect-bl" => &["cornerRadii", "cornerRadius"], + "poly-corners" => &["sides", "points"], + "poly-spoke" => &["starRatio"], + "poly-round" => &["rounded"], + "poly-rand" => &["randomized"], + "spiral-turns" => &["turns"], + "spiral-div" => &["divergence"], + "spiral-inner" => &["innerRadius"], + _ => std::slice::from_ref(&field), + }; + let key = response.response.id.with("shape-tool-gesture"); + let mut held = ctx.data(|data| data.get_temp::(key)); + for event in response.events.iter() { + if let EditEvent::Begin { id, .. } = event { + let latest = app.session.tool_options(); + held = Some(ShapeToolGesture { + id: *id, + tool: app.session.tool_id().to_owned(), + target: shape_target(app), + opening: keys.iter().filter_map(|key| latest.get(*key).cloned().map(|value| ((*key).to_owned(), value))).collect(), + latest, + }); + } + let restore = if let EditEvent::Cancel { id, before, reason, .. } = event { + if held.as_ref().is_some_and(|snapshot| snapshot.id == *id) { + held.take().filter(|snapshot| { + before.is_some() + && !reason.document_moved() + && *reason != CancelReason::Removed + && snapshot.tool == app.session.tool_id() + && snapshot.target == shape_target(app) + && snapshot.latest == app.session.tool_options() + }) + } else { + None + } + } else { + None + }; + edits::apply_event(app, event, &EditPath::Preview, &mut apply); + if let Some(snapshot) = restore { + // Radius writes the array with symmetry on; the array writes the scalar either way. + // Each row's order restores its full representation rather than sorted JSON keys. + for key in keys { + if let Some(value) = snapshot.opening.get(*key) + && let Err(error) = app.run("tool.setOption", json!({"tool": snapshot.tool, "key": key, "value": value})) + { + app.status(error); + break; + } + } + } + match event { + EditEvent::Update { id, .. } => { + if let Some(snapshot) = held.as_mut().filter(|snapshot| snapshot.id == *id) { + let latest = app.session.tool_options(); + snapshot.latest = latest; + } + } + EditEvent::Commit { id, .. } if held.as_ref().is_some_and(|snapshot| snapshot.id == *id) => held = None, + EditEvent::Set { .. } => held = None, + _ => {} + } + } + ctx.data_mut(|data| { + data.remove::(key); + if let Some(snapshot) = held { + data.insert_temp(key, snapshot); + } + }); +} + /// A click's change of the shape: the tool's options, and the selected live shapes in one step. fn apply_shape(app: &mut VectorcraftApp, tool_kvs: &[(&str, Value)], live_patch: Value) { shape_edit(app, tool_kvs, live_patch, Live::Released); @@ -423,6 +522,190 @@ fn mode_str(m: EllipseMode) -> &'static str { } } +#[cfg(test)] +mod cancel_tests { + use super::*; + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers, vec2}; + + fn window(app: &mut VectorcraftApp, ui: &mut Ui) { + app.tick(ui.ctx()); + app.ui(ui); + } + + fn application() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + app.run("window.control", json!({})).unwrap(); + app + } + + fn radius(panel: &Panel, node: vectorcraft_doc::NodeId) -> [f64; 4] { + let app = panel.app(); + let shape = CustomShape::read_for_update(app.session.active().unwrap().doc.node(node).unwrap(), false).unwrap(); + let CustomShape::Rectangle { radii, .. } = shape else { panic!("the fixture is a live rectangle") }; + radii + } + + #[test] + fn a_canceled_radius_scrub_restores_future_tool_options_and_selected_geometry() { + for tool in ["roundedRectangle", "box3d"] { + for selected in [false, true] { + for cancel in [false, true] { + let mut app = application(); + let node = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 80, "radius": 3.5})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("tool.select", json!({"tool": tool})).unwrap(); + let values = if tool == "box3d" { + json!({"shape": "rectangle", "cornerSymmetry": true, "cornerRadius": 7.25, "cornerRadii": [7.25, 8.25, 9.25, 10.25]}) + } else { + json!({"cornerRadius": 7.25}) + }; + app.run("tool.setOption", json!({"values": values})).unwrap(); + if tool == "box3d" { + app.run("tool.setOption", json!({"key": "cornerRadii", "value": [7.25, 8.25, 9.25, 10.25]})).unwrap(); + assert_eq!(app.session.tool_options()["cornerRadii"], json!([7.25, 8.25, 9.25, 10.25])); + } + app.run("select.set", json!({"ids": if selected { vec![node] } else { vec![] }})).unwrap(); + let options = app.session.tool_options(); + let original = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, window); + panel.room(vec2(2200.0, 1000.0)); + panel.frame(); + panel.frame(); + panel.drag_hold_role("Radius", Role::LABEL, vec2(12.0, 0.0)); + let changed = panel.app().session.tool_options(); + assert_ne!(changed, options, "the actual side-label scrub updates the future shape settings"); + if selected { + assert_ne!(radius(&panel, vectorcraft_doc::NodeId(node)), [3.5; 4], "the selected shape previews the scrub"); + } + if cancel { + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!( + panel.app().session.tool_options(), + options, + "Escape restores the exact original tool settings, including coupled radii" + ); + assert_eq!(panel.app().session.active().unwrap().doc, original); + } + panel.release(); + assert_eq!( + panel.app().session.tool_options(), + if cancel { options.clone() } else { changed.clone() }, + "release after Escape cannot reapply the scrub" + ); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + usize::from(selected && !cancel)); + if selected && !cancel { + panel.app().run("edit.undo", json!({})).unwrap(); + } + assert_eq!(panel.app().session.active().unwrap().doc, original); + + // A normal subsequent canvas drag uses the settings that the field left behind. + let from = panel.app().canvas_view().unwrap().rect.min + vec2(120.0, 120.0); + panel.drag_between(from, from + vec2(100.0, 80.0), Modifiers::NONE); + let created = panel.app().session.active().unwrap().selection.objects[0]; + assert_ne!(created.0, node, "the canvas drag creates new art rather than grabbing the selected shape's widgets"); + let expected = if cancel { &options } else { &changed }; + let radii = if tool == "box3d" && expected["cornerSymmetry"].as_bool() == Some(false) { + std::array::from_fn(|i| expected["cornerRadii"][i].as_f64().unwrap()) + } else { + [expected["cornerRadius"].as_f64().unwrap(); 4] + }; + assert_eq!(radius(&panel, created), radii, "the next shape uses the accepted or restored defaults"); + } + } + } + } + + #[test] + fn a_retired_shape_scrub_cannot_restore_options_into_the_new_tool() { + let mut app = application(); + app.run("tool.select", json!({"tool": "roundedRectangle"})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadius", "value": 7.25})).unwrap(); + let mut panel = Panel::new(app, window); + panel.room(vec2(2200.0, 1000.0)); + panel.frame(); + panel.frame(); + panel.drag_hold_role("Radius", Role::LABEL, vec2(12.0, 0.0)); + assert_ne!(panel.app().session.tool_options()["cornerRadius"], json!(7.25)); + panel.app().run("tool.select", json!({"tool": "ellipse"})).unwrap(); + let before = panel.app().session.tool_options(); + let document = panel.app().session.active().unwrap().doc.clone(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + panel.frame(); + panel.key(Key::Escape, Modifiers::NONE); + panel.release(); + assert_eq!(panel.app().session.tool_id(), "ellipse"); + assert_eq!(panel.app().session.tool_options(), before, "retired Radius events cannot edit the replacement tool"); + assert_eq!(panel.app().session.active().unwrap().doc, document); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + + #[test] + fn a_canceled_corner_edit_restores_a_scalar_changed_only_by_rollback() { + let mut app = application(); + app.run("tool.select", json!({"tool": "box3d"})).unwrap(); + app.run("tool.setOption", json!({"values": {"shape": "rectangle", "cornerSymmetry": false}})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadii", "value": [7.25, 8.25, 9.25, 10.25]})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadius", "value": 4.125})).unwrap(); + let before = app.session.tool_options(); + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, window); + panel.room(vec2(2200.0, 1000.0)); + panel.frame(); + panel.click_role("TL", Role::SPIN_BUTTON); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("4.125"); + panel.frame(); + let proposed = panel.app().session.tool_options(); + assert_ne!(proposed["cornerRadii"], before["cornerRadii"]); + assert_eq!(proposed["cornerRadius"], before["cornerRadius"], "the edit leaves the hidden scalar unchanged"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert_eq!(panel.app().session.tool_options(), before, "rollback must restore the scalar even when only restoring the array would change it"); + assert_eq!(panel.app().session.active().unwrap().doc, document); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + + #[test] + fn canceled_individual_corner_scrubs_preserve_the_distinct_hidden_scalar_radius() { + for label in ["TL", "TR"] { + for cancel in [false, true] { + let mut app = application(); + app.run("tool.select", json!({"tool": "box3d"})).unwrap(); + app.run("tool.setOption", json!({"values": {"shape": "rectangle", "cornerSymmetry": false}})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadii", "value": [7.25, 8.25, 9.25, 10.25]})).unwrap(); + app.run("tool.setOption", json!({"key": "cornerRadius", "value": 4.125})).unwrap(); + let before = app.session.tool_options(); + assert_eq!(before["cornerRadius"], json!(4.125)); + assert_eq!(before["cornerRadii"], json!([7.25, 8.25, 9.25, 10.25])); + let document = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, window); + panel.room(vec2(2200.0, 1000.0)); + panel.frame(); + panel.frame(); + panel.drag_hold_role(label, Role::LABEL, vec2(12.0, 0.0)); + let proposed = panel.app().session.tool_options(); + assert_ne!(proposed["cornerRadii"], before["cornerRadii"]); + assert_ne!(proposed["cornerRadius"], before["cornerRadius"], "the array setter also changes the hidden scalar"); + if cancel { + panel.key(Key::Escape, Modifiers::NONE); + assert_eq!(panel.app().session.tool_options(), before, "both the array and its distinct scalar restore before release"); + } + panel.release(); + assert_eq!(panel.app().session.tool_options(), if cancel { before } else { proposed }); + assert_eq!(panel.app().session.active().unwrap().doc, document); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + } + } + } +} + #[cfg(test)] mod tests { use craft::behavior::IconId; diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 03b8e4da67..0d70e1a78a 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -218,10 +218,13 @@ pub(super) fn hit_at(app: &VectorcraftApp, p: Point, zoom: f64) -> Option Option { - hit_with(app, p, zoom, |doc, p, opt| vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { clip_outlines: true, ..opt })) + hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { clip_outlines: true, unfilled_interiors: true, ..opt }) + }) } /// `test` on the active document at document point `p`, with the options the selection tools hit diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index 2545d16761..a91db6681a 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -9,8 +9,9 @@ use craft::draw::ui::corner::{CornerPoint, CornerTarget}; use craft::draw::ui::transform::TransformReach; use craft::draw::ui::{CornerKind, CornerWidgets, TransformBox}; use craft::ui::canvas::canvas_space; +use craft::ui::canvas_controls::path_runs; use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; -use craft::ui::primitives::{PaintShape, StrokeColor, StrokeWidth}; +use craft::ui::primitives::{DataWidth, PaintShape, StrokeColor, StrokeWidth}; use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx}; use egui::{Color32, Pos2, Response, vec2}; use vectorcraft_doc::{Document, LiveCorners, LiveShape, NodeId, NodeKind, OrientedBox}; @@ -21,6 +22,12 @@ use super::BodyKind; use crate::VectorcraftApp; use crate::doc_windows::Win; +/// How near the pointer comes to a Live Corners widget, in screen points, for the corner it controls to be +/// highlighted: the distance at which a press picks the widget. +const CORNER_HOVER_REACH: f64 = 5.0; +/// The width, in screen points, of the cut corner drawn while the pointer is over its Live Corners widget. +const CORNER_HOVER_WIDTH: f32 = 2.0; + /// The bounding box on show: the box and the layer colour it is drawn in. #[derive(Clone, Copy, Debug, PartialEq)] pub(super) struct ShownBox { @@ -112,6 +119,19 @@ fn corner_target(doc: &Document, id: NodeId, indices: &[usize]) -> Option Option { + let direct = tool == "directSelection"; + if !(matches!(tool, "selection" | "directSelection") || shape_tool_idle(app, tool)) { + return None; + } + let st = app.session.active()?; + let on = app.ui.view.corner_widgets && (direct || app.ui.view.shape_widgets); + vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, zoom, direct, on, app.session.prefs.hide_corner_widget_above) +} + /// The Live Corners widgets on show, one group per layer colour so each draws in its object's colour: Selection /// and the shape tools on a live rectangle or polygon while Show Shape Widgets is on, Direct Selection on any /// path. Only the corners the tool hit-tests are listed, those within the Hide Corner Widget angle. `tool` is the tool @@ -119,14 +139,8 @@ fn corner_target(doc: &Document, id: NodeId, indices: &[usize]) -> Option Option)>> { - let direct = tool == "directSelection"; - if !(matches!(tool, "selection" | "directSelection") || shape_tool_idle(app, tool)) { - return None; - } + let shown = shown_corners(app, tool, zoom)?; let st = app.session.active()?; - let on = app.ui.view.corner_widgets && (direct || app.ui.view.shape_widgets); - let shown = - vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, zoom, direct, on, app.session.prefs.hide_corner_widget_above)?; // `visible_on` and `corners` list the same corners in the same order: path after path. let mut per_path: Vec<(NodeId, Vec)> = vec![]; for ((id, _), index) in shown.visible_on().zip(shown.corners()) { @@ -147,6 +161,26 @@ pub(super) fn corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option, + button_down: bool, +) -> Option<(DataColor, vectorcraft_geom::BezPath)> { + if button_down || app.session.tool_busy() { + return None; + } + let shown = shown_corners(app, tool, zoom)?; + let st = app.session.active()?; + let (id, cut) = shown.hovered_cut(&st.doc, at?, CORNER_HOVER_REACH / zoom.max(1e-9))?; + Some((data_color(st.doc.layer_color(id)), cut)) +} + fn corner_kind(kind: DocCornerKind) -> CornerKind { match kind { DocCornerKind::Round => CornerKind::Round, @@ -342,6 +376,65 @@ impl Component for ShapeWidgets { } } +/// The cut of the corner whose Live Corners widget the pointer is over, drawn under the widgets in its layer colour +/// as one paint-only canvas control. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(canvas_control)] +pub struct CornerHover { + #[common] + common: Common, + cut: vectorcraft_geom::BezPath, + color: DataColor, +} + +impl CornerHover { + fn new(cut: vectorcraft_geom::BezPath, color: DataColor) -> Self { + CornerHover { common: Common::new(), cut, color }.label("Corner highlight") + } +} + +/// The style of the corner highlight. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct CornerHoverStyle { + #[style(metrics)] + metrics: Metrics, +} + +impl Component for CornerHover { + const ROLE: Role = Role::GRAPHICS_OBJECT; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + type Style = CornerHoverStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: CornerHoverStyleKey) -> CornerHoverStyle { + CornerHoverStyle { metrics: Metrics::new() } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 { + egui::Vec2::ZERO + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let Some(space) = canvas_space(&cx.env) else { return }; + let draw = ui.draw(); + for (points, _) in path_runs(&space.view, &self.cut) { + draw.stroke(&PaintShape::Path(points), DataWidth::points(CORNER_HOVER_WIDTH), StrokeColor::Data(self.color)); + } + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.description("Corner highlight"); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + /// Shows the bounding box, Live Corners and the shape widgets over the selection of the live document. The box, /// Live Corners, type, side and pie widgets need View › Show Edges; the blend and Objects on Path widgets do not. /// Nothing here is shown while a revolve is edited. @@ -357,6 +450,12 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &craft::u let tool = super::shown_tool(app, ui.ctx()); let shown = if edges { bounding_box(app, tool) } else { None }; if edges { + // The pointer of this pass: `hover_doc` is only set after the canvas body has been shown. + let (pointer, button_down) = ui.input(|i| (i.pointer.hover_pos(), i.pointer.any_down())); + let at = pointer.filter(|_| ui.rect_contains_pointer(rect)).map(|p| space.view.to_doc(p)); + if let Some((color, cut)) = corner_hover(app, tool, space.view.zoom, at, button_down) { + CornerHover::new(cut, color).show_at(ui, rect); + } for (at, (color, targets)) in corners(app, tool, space.view.zoom).into_iter().flatten().enumerate() { CornerWidgets::new("Live Corners", Bind::given(targets)).id_salt(at).reach(TransformReach::Shown).color(color).show_at(ui, rect); } diff --git a/crates/ui-egui/src/canvas/widgets/tests.rs b/crates/ui-egui/src/canvas/widgets/tests.rs index c8670f7be9..68e70867bd 100644 --- a/crates/ui-egui/src/canvas/widgets/tests.rs +++ b/crates/ui-egui/src/canvas/widgets/tests.rs @@ -101,6 +101,50 @@ fn corner_widgets_hide_above_the_preference_angle() { assert!(corners(&app, app.session.tool_id(), app.view_info().zoom).is_none()); } +/// #1232: the pointer within 5 screen points of a corner widget gives the cut of the corner it controls, in the +/// layer colour, with Direct Selection, the Selection tool and the Rectangle tool. It gives none with a mouse button +/// down (a press on the widget or a pan), during a drag from the widget, off the canvas, away from the widgets, or +/// where the widget is hidden by Hide Corner Widget for angles greater than. +#[test] +fn hovering_a_corner_widget_highlights_its_corner() { + let mut app = new_app(&[]); + let id = make(&mut app, "shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})); + app.session.execute("object.setLiveShape", &json!({"id": id, "radius": 20})).unwrap(); + let color = layer(&app, id); + let zoom = app.view_info().zoom; + let bounds = |cut: &vectorcraft_geom::BezPath| { + let b = vectorcraft_geom::Shape::bounding_box(cut); + [b.x0, b.y0, b.x1, b.y1].map(|v| (v * 1e6).round() / 1e6) + }; + let mut top_left = vectorcraft_geom::Point::ZERO; + for tool in ["directSelection", "selection", "rectangle"] { + app.select_tool(tool); + let st = app.session.active().unwrap(); + top_left = + vectorcraft_tools::corners::CornerWidgets::of(&st.doc, &st.selection, zoom, tool == "directSelection").unwrap().visible().next().unwrap(); + let (got, cut) = corner_hover(&app, tool, zoom, Some(top_left), false).unwrap_or_else(|| panic!("{tool}: over the widget")); + assert_eq!(got, color, "{tool}"); + assert_eq!(bounds(&cut), [100.0, 100.0, 120.0, 120.0], "{tool}: the top-left arc"); + let near = top_left + vectorcraft_geom::Vec2::new(3.0 / zoom, -3.0 / zoom); + assert!(corner_hover(&app, tool, zoom, Some(near), false).is_some(), "{tool}: within reach"); + let far = top_left + vectorcraft_geom::Vec2::new(7.0 / zoom, 0.0); + assert!(corner_hover(&app, tool, zoom, Some(far), false).is_none(), "{tool}: past a press's reach"); + assert!(corner_hover(&app, tool, zoom, Some(vectorcraft_geom::Point::new(150.0, 150.0)), false).is_none(), "{tool}: away from the widgets"); + assert!(corner_hover(&app, tool, zoom, None, false).is_none(), "{tool}: off the canvas"); + assert!(corner_hover(&app, tool, zoom, Some(top_left), true).is_none(), "{tool}: a button down"); + let inward = (top_left.x + 8.0, top_left.y + 8.0); + drag(&mut app, (top_left.x, top_left.y), inward); + assert!(app.session.tool_busy(), "{tool}"); + assert!(corner_hover(&app, tool, zoom, Some(top_left), false).is_none(), "{tool}: during the drag"); + pointer(&mut app, PointerKind::Up, inward); + app.session.execute("edit.undo", &json!({})).unwrap(); + } + app.select_tool("directSelection"); + assert!(corner_hover(&app, "directSelection", zoom, Some(top_left), false).is_some(), "Direct Selection, before the preference"); + app.session.execute("prefs.set", &json!({"key": "hideCornerWidgetAbove", "value": 80})).unwrap(); + assert!(corner_hover(&app, "directSelection", zoom, Some(top_left), false).is_none(), "hidden above the angle"); +} + #[test] fn a_resize_drag_keeps_the_bounding_box_at_the_new_bounds() { for real_time in [true, false] { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 9dbf91b4e7..0caf6ca592 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -772,6 +772,10 @@ fn current_tool_names_the_selection_tool_cmd_lends() { /// color profile. #[test] fn the_status_bar_info_field_shows_the_chosen_readout() { + // Assigning a profile to the front document changes the process's active color settings. + if !crate::testing::in_own_process("chrome::tests::the_status_bar_info_field_shows_the_chosen_readout") { + return; + } let mut bar = status_readout_app(); let texts = status_readout_frame(&mut bar); assert!(texts.iter().any(|t| t.text == "Selection"), "Current Tool by default: {texts:?}"); diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 4b2b79a02d..6e29fc182f 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -307,9 +307,7 @@ impl ActionDialog for BatchDialog { /// A row that picks one of `entries` for `value`. fn select_row(ui: &mut Ui, name: &str, value: &mut T, entries: &[Entry]) { Field::new(label(name)).show(ui, |ui, _| { - if let Some(picked) = Select::new(label(name), Bind::given(*value), entries).show(ui).value().copied() { - *value = picked; - } + Select::new(label(name), Bind::bound(value), entries).show(ui); }); } @@ -417,10 +415,13 @@ impl StackDialog for BatchDialog { #[cfg(test)] mod tests { use craft::automation::actions::{Action, ActionStep}; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; use vectorcraft_engine::Session; use super::*; use crate::dialogs::actions::pump; + use crate::tests::panel_harness::Panel; /// An app with one set holding `steps` as the action "Draw", and a window to show dialogs in. fn app_with(steps: Vec) -> VectorcraftApp { @@ -498,6 +499,42 @@ mod tests { assert!(!app.session.replaying()); } + #[test] + fn canceled_choices_keep_the_batch_source_destination_and_file_name() { + let mut app = app_with(vec![ActionStep::new("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))]); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.run("dataset.new", json!({"name": "a"})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + open(&mut panel.app(), 0, 0).unwrap(); + set_fields(&panel.app(), &[("source", json!("datasets"))]); + panel.frame(); + let fields = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.get::().unwrap().fields().clone()); + let is_open = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.is_open::()); + let original = fields(&panel); + for (name, key) in [("Play", Key::ArrowUp), ("Destination", Key::ArrowUp), ("File Name", Key::ArrowDown)] { + panel.click_role(name, Role::COMBO_BOX); + panel.key(key, Modifiers::NONE); + assert_ne!(fields(&panel), original, "the popup previews {name}"); + panel.key(Key::Escape, Modifiers::NONE); + panel.frame(); + assert!(is_open(&panel), "Escape closes only the {name} popup"); + assert_eq!(fields(&panel), original, "Escape restores {name}"); + } + panel.click_role("Destination", Role::COMBO_BOX); + panel.key(Key::Home, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + panel.frame(); + let chosen = fields(&panel); + assert_eq!((chosen.source, chosen.destination), (BatchSource::DataSets, BatchDestination::None)); + panel.click("OK"); + panel.frame(); + panel.frame(); + assert!(!is_open(&panel)); + let app = panel.app(); + assert_eq!(app.session.active().unwrap().doc.layers[0].children().unwrap().len(), 1); + assert!(!app.session.replaying()); + } + #[test] fn data_set_naming_params_follow_dialog_choice() { let mut fields = BatchFields::default(); diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 0c6e1b5f56..94ff0e8339 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -316,7 +316,6 @@ fn bleed_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext let bare_points = fields.bool("numbersWithoutUnitsArePoints").unwrap_or(true); let lengths = crate::fields::bare_points(LengthUnits::new(UnitKind::Points, unit_kind(unit), 72.0), bare_points); let parts = bleed_of(fields).map(|b| Mixed::Same(Some(b))); - // PLAN: assumed the linked fields' output reads as `out.edit.value()`, as the shape dialog uses it. let out = LinkedFields::<4>::new(tl!("Bleed:"), Bind::given(parts), Bind::bound(&mut linked)) .mode(LinkMode::Equal) .layout(LinkedLayout::Columns) @@ -324,7 +323,7 @@ fn bleed_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext .range(0.0..=MAX_BLEED) .lengths(lengths) .show(ui); - if let Some([Mixed::Same(Some(t)), Mixed::Same(Some(b)), Mixed::Same(Some(l)), Mixed::Same(Some(r))]) = out.edit.value().copied() { + if let Some([Mixed::Same(Some(t)), Mixed::Same(Some(b)), Mixed::Same(Some(l)), Mixed::Same(Some(r))]) = out.edit.events.committed().copied() { fields.set("bleed", FieldValue::List([t, b, l, r].map(FieldValue::Number).to_vec())); } if fields.bool("bleedLinked") != Some(linked) { @@ -397,7 +396,8 @@ fn grid_colors_row(setup: DocSetup) -> Param { let mut picked = None; let (mut wells, mut edits) = ([None; 2], [None; 2]); let shown = Stack::new().show(ui, |ui, _| { - picked = Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).value().cloned(); + picked = + Select::new(tl!("Grid Colors:"), Bind::given(grid_preset_name(resolved).to_string()), &menu).show(ui).events.committed().cloned(); Row::new().show(ui, |ui, _| { for (i, color) in resolved.iter().enumerate() { let number = (i + 1).to_string(); @@ -411,7 +411,7 @@ fn grid_colors_row(setup: DocSetup) -> Param { let [r, g, b, _] = color.to_rgba8(1.0); let srgb = box_color(color); wells[i] = Swatch::new(name.clone(), srgb).well().show(ui).clicked.then_some(srgb); - edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).value().copied(); + edits[i] = HexField::hex(name, Bind::given(Rgba::rgb(r, g, b))).show(ui).events.committed().copied(); } }); }); @@ -548,7 +548,7 @@ fn typography() -> Vec { fn language_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext) -> egui::Response { let languages: Vec> = LANGUAGES.iter().map(|(l, _, _)| Entry::new(l.to_string(), l.to_string())).collect(); let current = fields.text("language").unwrap_or_default().to_string(); - let picked = Select::new(tl!("Language:"), Bind::given(current), &languages).show(ui).value().cloned(); + let picked = Select::new(tl!("Language:"), Bind::given(current), &languages).show(ui).events.committed().cloned(); if let Some(language) = picked { if let Some(q) = language_quotes(&language) { fields.set("quotes.double", q.double.iter().collect::()); @@ -581,15 +581,18 @@ fn color(mode: ColorMode) -> Vec { #[cfg(test)] mod tests { use craft::theme::Srgba; + use craft::ui::contract::Role; use craft::ui::dialog::{DialogId, HeldOk, dialog_id}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedPropertiesDialog}; - use egui::{Pos2, Rect, vec2}; + use egui::{Key, Modifiers, Pos2, Rect, vec2}; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint, cms}; - use vectorcraft_doc::{ColorMode, NodeId}; + use vectorcraft_doc::setup::{GRID_COLOR_PRESETS, LANGUAGES}; + use vectorcraft_doc::{ColorMode, NodeId, Quotes}; use vectorcraft_engine::Session; use crate::VectorcraftApp; + use crate::tests::panel_harness::Panel; /// The dialog's id. fn id() -> DialogId { @@ -656,6 +659,138 @@ mod tests { app.session.active().unwrap().history.undo.len() } + /// Document Setup open on `tab` over a 200 × 200 document, drawn in the panel harness. + fn setup_panel(tab: &str) -> Panel { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1280.0, 1100.0)); + panel.app().run("file.documentSetup", json!({})).unwrap(); + set(&panel.app(), panel.ctx(), "tab", json!(tab)); + panel.frame(); + panel.frame(); + panel + } + + /// The dialog's values in the panel harness. + fn panel_values(panel: &Panel) -> serde_json::Map { + super::json_map(&fields(&panel.app())) + } + + /// Clicks OK in the panel harness: the dialog closes with the values applied. + fn panel_ok(panel: &mut Panel) { + panel.click("OK"); + let app = panel.app(); + assert!(!is_open(&app), "{}", app.ui.status); + } + + /// A language highlighted in the Language menu changes neither the language nor the quotes, and + /// Escape closes the menu with the dialog open and its values as they were. + #[test] + fn a_highlighted_language_changes_nothing_until_it_is_chosen() { + let mut panel = setup_panel("Type"); + let before = panel_values(&panel); + panel.click_role("Language", Role::COMBO_BOX); + panel.key(Key::End, Modifiers::NONE); + assert_eq!(panel_values(&panel), before, "a highlighted language changes no field"); + panel.key(Key::Escape, Modifiers::NONE); + assert!(is_open(&panel.app()), "Escape closes the menu, not the dialog"); + assert_eq!(panel_values(&panel), before, "Escape leaves the language and quotes as they were"); + panel_ok(&mut panel); + let setup = panel.app().session.active().unwrap().doc.setup.clone(); + assert_eq!((setup.language.as_str(), setup.quotes), (LANGUAGES[0].0, Quotes::ENGLISH)); + } + + /// A language chosen with Enter brings its quotes, and OK applies both. + #[test] + fn a_language_chosen_with_enter_brings_its_quotes() { + let mut panel = setup_panel("Type"); + let (language, _, quotes) = LANGUAGES[LANGUAGES.len() - 1]; + panel.click_role("Language", Role::COMBO_BOX); + panel.key(Key::End, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + let values = panel_values(&panel); + assert_eq!(values["language"], json!(language)); + assert_eq!(values["quotes.double"], json!(quotes.double.iter().collect::())); + assert_eq!(values["quotes.single"], json!(quotes.single.iter().collect::())); + panel_ok(&mut panel); + let setup = panel.app().session.active().unwrap().doc.setup.clone(); + assert_eq!((setup.language.as_str(), setup.quotes), (language, quotes)); + } + + /// A preset highlighted in the Grid Colors menu changes no color, and Escape closes the menu with + /// the dialog open and the grid colors as they were. + #[test] + fn a_highlighted_grid_colors_preset_changes_nothing_until_it_is_chosen() { + let mut panel = setup_panel("Transparency"); + let before = panel_values(&panel); + panel.click_role("Grid Colors:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + assert_eq!(panel_values(&panel), before, "a highlighted preset changes no field"); + panel.key(Key::Escape, Modifiers::NONE); + assert!(is_open(&panel.app()), "Escape closes the menu, not the dialog"); + assert_eq!(panel_values(&panel), before, "Escape leaves the grid colors as they were"); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); + } + + /// A Grid Colors preset chosen with Enter sets both colors, and OK applies them. + #[test] + fn a_grid_colors_preset_chosen_with_enter_sets_both_colors() { + let mut panel = setup_panel("Transparency"); + panel.click_role("Grid Colors:", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Enter, Modifiers::NONE); + let medium = GRID_COLOR_PRESETS[1].1; + assert_eq!(dialog_grid(&panel.app()), medium.to_vec()); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, medium); + } + + /// A hex code typed into a grid color's field changes no color while it is a draft; Tab commits + /// it, and OK applies it. + #[test] + fn a_grid_color_hex_draft_applies_once_committed() { + let mut panel = setup_panel("Transparency"); + let before = panel_values(&panel); + panel.click_role("Grid Colors: 1", Role::TEXT_INPUT); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("123456"); + assert_eq!(panel_values(&panel), before, "the typed draft changes no field"); + panel.key(Key::Tab, Modifiers::NONE); + assert_eq!(dialog_grid(&panel.app()), ["#123456", LIGHT[1]].map(hex).to_vec()); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.grid_colors, ["#123456", LIGHT[1]].map(hex)); + } + + /// A bleed typed into Top changes no side while it is a draft; Tab commits it to the four linked + /// sides, and OK applies them. + #[test] + fn a_bleed_draft_applies_once_committed() { + let mut panel = setup_panel("General"); + let before = panel_values(&panel); + panel.click("Top"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("3"); + assert_eq!(panel.value("Top").as_deref(), Some("3"), "the field holds the typed draft"); + assert_eq!(panel_values(&panel), before, "the typed draft changes no field"); + panel.key(Key::Tab, Modifiers::NONE); + assert_eq!(super::bleed_of(&fields(&panel.app())), [3.0; 4]); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.bleed, [3.0; 4]); + } + + /// A bleed draft still in the focused field when OK is clicked is applied. + #[test] + fn ok_applies_the_focused_bleed_draft() { + let mut panel = setup_panel("General"); + panel.click("Top"); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("3"); + panel_ok(&mut panel); + assert_eq!(panel.app().session.active().unwrap().doc.setup.bleed, [3.0; 4]); + } + fn check_source_document(edit_artboards: bool) { let (mut app, ctx) = new_app(); let source = app.session.active().unwrap().uid; diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index bf048d3e28..8ec5e10ba1 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -907,6 +907,8 @@ mod tests { #[test] fn new_document_choice_enter_commits_before_create() { + // Preview Mode's last choice, Overprint, turns on the whole process's Overprint Preview. + let _view = crate::testing::DefaultProofView::new(); let mut panel = actual_preset_dialog(); panel.click("Advanced Options"); for (label, key) in [ diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index e0534d4d7a..4b90db0045 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -105,6 +105,8 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { let r = super::slices::open_options(app); reported(app, r); } + // A Tangent Circle Tool click with Ask For Circle Radius on: the circle's radius. + crate::addons::pathtools::tangent_circle_radius::KIND => crate::addons::pathtools::tangent_circle_radius::open(app, &p), // A click or double-click that would edit type set in fonts that aren't available. vectorcraft_tools::text::MISSING_FONT_EDIT => super::confirm::ask_missing_font_edit(app, &p), _ => {} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 105343c30d..dddab15455 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -8297,6 +8297,8 @@ breakText Glyphs Глифи Tangent Circle Допирателна окръжност Tangent Circle Tool Инструмент „Допирателна окръжност“ No tangent circle here Тук няма допирателна окръжност + Ask For Circle Radius Питане за радиуса на окръжността + Auto-Update Default Автоматично обновяване на стойността по подразбиране Circle: Окръжност: @msg `ids` names an object twice `ids` посочва обект два пъти @msg select two or three paths or compound paths изберете два или три пътя или съставни пътя diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 3bcc73ee5a..87350e98e1 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7675,6 +7675,8 @@ shape Open Otvoren Tangent Circle Tangentna kružnica Tangent Circle Tool Alat tangentna kružnica No tangent circle here Ovdje nema tangentne kružnice + Ask For Circle Radius Pitaj za poluprečnik kružnice + Auto-Update Default Automatski ažuriraj zadanu vrijednost Circle: Kružnica: @msg `ids` names an object twice `ids` navodi objekat dvaput @msg select two or three paths or compound paths odaberite dvije ili tri putanje ili složene putanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f5cc0aa158..3c16e1c64c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8594,6 +8594,8 @@ breakText Glyphs Glifs Tangent Circle Cercle tangent Tangent Circle Tool Eina de cercle tangent No tangent circle here Aquí no hi ha cap cercle tangent + Ask For Circle Radius Demana el radi del cercle + Auto-Update Default Actualitza automàticament el valor predeterminat Circle: Cercle: @msg `ids` names an object twice `ids` indica un objecte dues vegades @msg select two or three paths or compound paths seleccioneu dos o tres camins o camins compostos diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 44e2c75bcb..5d3c18ca16 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8575,6 +8575,8 @@ breakText Glyphs Glyfy Tangent Circle Tečná kružnice Tangent Circle Tool Nástroj Tečná kružnice No tangent circle here Zde není žádná tečná kružnice + Ask For Circle Radius Ptát se na poloměr kružnice + Auto-Update Default Automaticky aktualizovat výchozí hodnotu Circle: Kružnice: @msg `ids` names an object twice `ids` uvádí některý objekt dvakrát @msg select two or three paths or compound paths vyberte dvě nebo tři cesty nebo složené cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 42ac68ba3a..20e0ebcd9b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10627,6 +10627,8 @@ breakText Glyphs Glyffer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkel-værktøj No tangent circle here Ingen tangentcirkel her + Ask For Circle Radius Spørg om cirklens radius + Auto-Update Default Opdater standard automatisk Circle: Cirkel: @msg `ids` names an object twice `ids` nævner et objekt to gange @msg select two or three paths or compound paths vælg to eller tre stier eller sammensatte stier diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index a89e75bad9..dee986b362 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8198,6 +8198,8 @@ breakText Glyphs Glyphen Tangent Circle Tangentialkreis Tangent Circle Tool Tangentialkreis-Werkzeug No tangent circle here Hier kein Tangentialkreis + Ask For Circle Radius Nach Kreisradius fragen + Auto-Update Default Standardwert automatisch aktualisieren Circle: Kreis: @msg `ids` names an object twice `ids` nennt ein Objekt zweimal @msg select two or three paths or compound paths wählen Sie zwei oder drei Pfade oder zusammengesetzte Pfade aus diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f4f1e5604e..7a1f77363a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8566,6 +8566,8 @@ breakText Glyphs Γλύφοι Tangent Circle Εφαπτόμενος κύκλος Tangent Circle Tool Εφαπτόμενος κύκλος (Tangent Circle Tool) No tangent circle here Δεν υπάρχει εφαπτόμενος κύκλος εδώ + Ask For Circle Radius Ερώτηση για την ακτίνα του κύκλου + Auto-Update Default Αυτόματη ενημέρωση προεπιλογής Circle: Κύκλος: @msg `ids` names an object twice το `ids` αναφέρει ένα αντικείμενο δύο φορές @msg select two or three paths or compound paths επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 8ca6ba9493..a470c3a68e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8552,6 +8552,8 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Herramienta Círculo tangente No tangent circle here No hay círculo tangente aquí + Ask For Circle Radius Preguntar el radio del círculo + Auto-Update Default Actualizar automáticamente el valor predeterminado Circle: Círculo: @msg `ids` names an object twice `ids` indica un objeto dos veces @msg select two or three paths or compound paths seleccione dos o tres trazados o trazados compuestos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bd916ad330..359a9e4521 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8642,6 +8642,8 @@ breakText Glyphs Merkit Tangent Circle Sivuava ympyrä Tangent Circle Tool Sivuava ympyrä -työkalu No tangent circle here Tässä ei ole sivuavaa ympyrää + Ask For Circle Radius Kysy ympyrän säde + Auto-Update Default Päivitä oletus automaattisesti Circle: Ympyrä: @msg `ids` names an object twice `ids` mainitsee saman objektin kahdesti @msg select two or three paths or compound paths valitse kaksi tai kolme polkua tai yhdistelmäpolkua diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4fd43d30c7..de762ee5b3 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8571,6 +8571,8 @@ breakText Glyphs Glyphes Tangent Circle Cercle tangent Tangent Circle Tool Outil Cercle tangent No tangent circle here Aucun cercle tangent ici + Ask For Circle Radius Demander le rayon du cercle + Auto-Update Default Mettre à jour automatiquement la valeur par défaut Circle: Cercle : @msg `ids` names an object twice `ids` désigne deux fois le même objet @msg select two or three paths or compound paths sélectionnez deux ou trois tracés ou tracés transparents diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 68a9f0607e..732178a5a6 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4365,6 +4365,8 @@ arrowhead Feather પીંછું Tangent Circle સ્પર્શક વર્તુળ Tangent Circle Tool સ્પર્શક વર્તુળ ટૂલ No tangent circle here અહીં કોઈ સ્પર્શક વર્તુળ નથી + Ask For Circle Radius વર્તુળની ત્રિજ્યા પૂછો + Auto-Update Default ડિફૉલ્ટ આપમેળે અપડેટ કરો Tangent Circle… સ્પર્શક વર્તુળ… Taper ટેપર Target લક્ષ્ય diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 76c70e4573..147e1ad3ad 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5914,6 +5914,8 @@ arrowhead Feather पंख Tangent Circle स्पर्शी वृत्त Tangent Circle Tool स्पर्शी वृत्त टूल No tangent circle here यहाँ कोई स्पर्शी वृत्त नहीं है + Ask For Circle Radius वृत्त की त्रिज्या पूछें + Auto-Update Default डिफ़ॉल्ट स्वचालित रूप से अपडेट करें Tangent Circle… स्पर्शी वृत्त… Taper टेपर Target लक्ष्य diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index acb50f7467..c353c82913 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8561,6 +8561,8 @@ breakText Glyphs Glifák Tangent Circle Érintőkör Tangent Circle Tool Érintőkör eszköz No tangent circle here Itt nincs érintőkör + Ask For Circle Radius Kérdés a kör sugaráról + Auto-Update Default Alapértelmezett érték automatikus frissítése Circle: Kör: @msg `ids` names an object twice `ids`: egy objektumot kétszer nevez meg @msg select two or three paths or compound paths jelölj ki két vagy három útvonalat vagy összetett útvonalat diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7c1290ba2c..bf40c9a838 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -8409,6 +8409,8 @@ breakText Glyphs Glif Tangent Circle Lingkaran singgung Tangent Circle Tool Alat lingkaran singgung No tangent circle here Tidak ada lingkaran singgung di sini + Ask For Circle Radius Tanyakan Radius Lingkaran + Auto-Update Default Perbarui Default Otomatis Circle: Lingkaran: @msg `ids` names an object twice `ids` menyebut satu objek dua kali @msg select two or three paths or compound paths pilih dua atau tiga jalur atau jalur gabungan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b4097a2e05..29f2291dc0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8236,6 +8236,8 @@ breakText Glyphs Glifi Tangent Circle Cerchio tangente Tangent Circle Tool Strumento Cerchio tangente No tangent circle here Nessun cerchio tangente qui + Ask For Circle Radius Chiedi il raggio del cerchio + Auto-Update Default Aggiorna automaticamente il valore predefinito Circle: Cerchio: @msg `ids` names an object twice `ids` indica due volte lo stesso oggetto @msg select two or three paths or compound paths seleziona due o tre tracciati o tracciati composti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6332c95eb6..8cd285d99d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -10127,6 +10127,8 @@ breakText Glyphs 字形 Tangent Circle 接円 Tangent Circle Tool 接円ツール No tangent circle here ここに接円はありません + Ask For Circle Radius 円の半径を確認 + Auto-Update Default デフォルトを自動更新 Circle: 円: @msg `ids` names an object twice `ids` に同じオブジェクトが 2 回指定されています @msg select two or three paths or compound paths パスまたは複合パスを 2 つか 3 つ選択してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0ab8a2090e..edfe2109d7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10751,6 +10751,8 @@ breakText Glyphs გლიფები Tangent Circle მხები წრე Tangent Circle Tool მხები წრის ხელსაწყო No tangent circle here აქ მხები წრე არ არის + Ask For Circle Radius წრის რადიუსის კითხვა + Auto-Update Default ნაგულისხმევის ავტომატური განახლება Circle: წრე: @msg `ids` names an object twice `ids` ერთსა და იმავე ობიექტს ორჯერ მიუთითებს @msg select two or three paths or compound paths მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9430598388..fa5c376f34 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8208,6 +8208,8 @@ breakText Glyphs 글리프 Tangent Circle 접원 Tangent Circle Tool 접원 도구 No tangent circle here 여기에는 접원이 없음 + Ask For Circle Radius 원 반지름 묻기 + Auto-Update Default 기본값 자동 업데이트 Circle: 원: @msg `ids` names an object twice `ids`에 같은 오브젝트가 두 번 있습니다 @msg select two or three paths or compound paths 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 976eda3d02..bea75205b0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -10471,6 +10471,8 @@ breakText Glyphs Glyphs Tangent Circle Raakcirkel Tangent Circle Tool Raakcirkel-gereedschap No tangent circle here Hier geen raakcirkel + Ask For Circle Radius Vragen naar cirkelradius + Auto-Update Default Standaard automatisch bijwerken Circle: Cirkel: @msg `ids` names an object twice `ids` noemt een object twee keer @msg select two or three paths or compound paths selecteer twee of drie paden of samengestelde paden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index b6bd995613..0dc2afe500 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8432,6 +8432,8 @@ breakText Glyphs Glify Tangent Circle Okrąg styczny Tangent Circle Tool Narzędzie Okrąg styczny No tangent circle here Brak okręgu stycznego w tym miejscu + Ask For Circle Radius Pytaj o promień okręgu + Auto-Update Default Automatycznie aktualizuj wartość domyślną Circle: Okrąg: @msg `ids` names an object twice `ids` wskazuje ten sam obiekt dwa razy @msg select two or three paths or compound paths zaznacz dwie lub trzy ścieżki lub ścieżki złożone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e757ef311f..43e8ca76f8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8594,6 +8594,8 @@ breakText Glyphs Glifos Tangent Circle Círculo tangente Tangent Circle Tool Ferramenta Círculo tangente No tangent circle here Nenhum círculo tangente aqui + Ask For Circle Radius Perguntar o Raio do Círculo + Auto-Update Default Atualizar o Padrão Automaticamente Circle: Círculo: @msg `ids` names an object twice `ids` indica um objeto duas vezes @msg select two or three paths or compound paths selecione dois ou três caminhos ou caminhos compostos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 1cb3d8c510..84edfc7d71 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8566,6 +8566,8 @@ breakText Glyphs Глифы Tangent Circle Касательная окружность Tangent Circle Tool Инструмент «Касательная окружность» No tangent circle here Здесь нет касательной окружности + Ask For Circle Radius Запрашивать радиус окружности + Auto-Update Default Автоматически обновлять значение по умолчанию Circle: Окружность: @msg `ids` names an object twice `ids` указывает объект дважды @msg select two or three paths or compound paths выделите два или три контура или составных контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c8f566b73e..e9611dcd53 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8583,6 +8583,8 @@ breakText Glyphs Glyfer Tangent Circle Tangentcirkel Tangent Circle Tool Tangentcirkelverktyget No tangent circle here Ingen tangentcirkel här + Ask For Circle Radius Fråga efter cirkelradie + Auto-Update Default Uppdatera standard automatiskt Circle: Cirkel: @msg `ids` names an object twice `ids` anger ett objekt två gånger @msg select two or three paths or compound paths markera två eller tre banor eller sammansatta banor diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c17d8f13aa..0ede2da0a9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -10467,6 +10467,8 @@ breakText Glyphs Glifler Tangent Circle Teğet Daire Tangent Circle Tool Teğet Daire Aracı No tangent circle here Burada teğet daire yok + Ask For Circle Radius Daire Yarıçapını Sor + Auto-Update Default Varsayılanı Otomatik Güncelle Circle: Daire: @msg `ids` names an object twice `ids` bir nesneyi iki kez belirtiyor @msg select two or three paths or compound paths iki veya üç yol ya da bileşik yol seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bf4d38097e..25978ab078 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8218,6 +8218,8 @@ breakText Glyphs Гліфи Tangent Circle Дотичне коло Tangent Circle Tool Інструмент «Дотичне коло» No tangent circle here Тут немає дотичного кола + Ask For Circle Radius Запитувати радіус кола + Auto-Update Default Автоматично оновлювати значення за замовчуванням Circle: Коло: @msg `ids` names an object twice `ids` указує об’єкт двічі @msg select two or three paths or compound paths виділіть два або три контури чи складені контури diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 031807ee6c..d82a764cd4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -8264,6 +8264,8 @@ breakText Glyphs Glyph Tangent Circle Đường tròn tiếp xúc Tangent Circle Tool Công cụ Đường tròn tiếp xúc No tangent circle here Không có đường tròn tiếp xúc ở đây + Ask For Circle Radius Hỏi bán kính đường tròn + Auto-Update Default Tự động cập nhật mặc định Circle: Đường tròn: @msg `ids` names an object twice `ids` nêu một đối tượng hai lần @msg select two or three paths or compound paths chọn hai hoặc ba đường dẫn hoặc đường dẫn phức hợp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 415a2d5fd6..3d3e70b205 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8444,6 +8444,8 @@ breakText Glyphs 字形 Tangent Circle 相切圆 Tangent Circle Tool 相切圆工具 No tangent circle here 此处没有相切圆 + Ask For Circle Radius 询问圆半径 + Auto-Update Default 自动更新默认值 Circle: 圆: @msg `ids` names an object twice `ids` 重复指定了同一个对象 @msg select two or three paths or compound paths 请选择两个或三个路径或复合路径 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6302425bc0..735995ad33 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8266,6 +8266,8 @@ breakText Glyphs 字符 Tangent Circle 相切圓 Tangent Circle Tool 相切圓工具 No tangent circle here 此處沒有相切圓 + Ask For Circle Radius 詢問圓半徑 + Auto-Update Default 自動更新預設值 Circle: 圓: @msg `ids` names an object twice `ids` 將同一個物件指定了兩次 @msg select two or three paths or compound paths 請選取兩個或三個路徑或複合路徑 diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 40699f7804..aad5a37d1f 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -44,7 +44,8 @@ const WRAPPED: &[(&str, &str)] = &[ /// every preference, Forget Import Matches forgets every saved match, Begin Undo Group and End /// Undo Group begin and end a group, the six Save … Preset commands save a new preset (Save /// Gradient Preset the selection's gradient), Delete Gradient Preset deletes the saved preset the -/// selection's gradient matches, the three Asset Export commands open the Asset Export panel (#4864), New +/// selection's gradient matches, the six Asset Export commands open the Asset Export panel (#4864), +/// Rename Artboards opens the Rename dialog for the selected artboards, New /// Symbol makes a symbol of the selection, Gradient Vector gives the selection the default /// gradient, Define Perspective Grid makes the document's grid, Select Slice deselects the /// slices, and Find Next goes on from the last Find and Replace search or opens its dialog, as @@ -65,8 +66,12 @@ const PICK_RUNS: &[&str] = &[ "gradient.presets.save", "gradient.presets.delete", "assets.export", + "assets.remove", + "assets.rename", "assets.export3D", + "assets.set3DFormat", "assets.settings.set", + "artboard.rename", "symbol.new", "paint.setGradientGeom", "perspective.grid.set", @@ -80,23 +85,11 @@ const PANEL_PATH: &str = "Window › Show Panel"; /// The menu path ([`context`]) a result takes when another result has its name: (id, English /// path), for commands that no item of the menu bar runs and whose id names no parent command. const CONTEXTS: &[(&str, &str)] = &[ - ("addon.pen.close", "Pen"), - ("addon.pen.reshape", "Pen"), - ("addon.pen.togglePoint", "Pen"), - ("charStyle.setAttrs", "Character Styles"), ("file.exportInBackground", "Export"), ("file.openInBackground", "Open"), ("imageTrace.hideRuns", "Image Trace"), ("links.reveal", "Links"), - ("livePaint.fill", "Live Paint"), - ("object.blend.spine.convertAnchor", "Blend"), - ("paraStyle.setAttrs", "Paragraph Styles"), - ("path.close", "Path"), - ("path.convertAnchor", "Path"), - ("path.knife", "Path"), - ("path.reshapeSegment", "Path"), ("plugin.hideRuns", "Plug-ins"), - ("text.editRange", "Text"), ("ui.layersPanelOptions", "Layers"), ("ui.navigatorPanelOptions", "Navigator"), ]; @@ -1563,15 +1556,8 @@ mod tests { ("ui.paraStyleOptions.resetPanel", "Paragraph Style Options › Reset Panel"), ("window.swatchLibrary.other", "Window › Swatch Libraries › Other Library…"), ("window.brushLibrary.other", "Window › Brush Libraries › Other Library…"), - ("tool:knife", "Tools › Knife"), - ("path.knife", "Path › Knife"), - ("addon.pen.close", "Pen › Close Path"), - ("path.close", "Path › Close Path"), ("type.fitHeadline", "Type › Fit Headline (type.fitHeadline)"), ("text.fitHeadline", "Type › Fit Headline (text.fitHeadline)"), - ("shape.ellipse", "Ellipse (shape.ellipse)"), - ("addon.shapes.ellipse", "Ellipse (addon.shapes.ellipse)"), - ("perspective.editText", "Object › Perspective › Edit Text"), ("ui.action.play", "Play Action (ui.action.play)"), ("ui.action.playAt", "Play Action (ui.action.playAt)"), ("ui.batchDialog", "Batch…"), @@ -1690,7 +1676,8 @@ mod tests { /// Of the engine commands the palette listed before, it leaves out only the ones /// [`crate::shortcut_editor::needs_a_value`] marks: queries with no default key and no item of - /// the menu bar, and commands that need a value no menu item gives. A pick of each one it leaves + /// the menu bar, and commands that need a value no menu item gives, with a menu path of their own + /// or without one. A pick of each one it leaves /// out (with no document, one object selected or several) changes neither the document, its /// selection, history and layer state, nor the interface. Every [`PICK_RUNS`] query is still /// listed. @@ -1706,7 +1693,8 @@ mod tests { let listed: std::collections::HashSet = items().into_iter().map(|(_, id)| id).collect(); let dropped: Vec<&vectorcraft_engine::CommandSpec> = before.iter().copied().filter(|c| !listed.contains(c.id)).collect(); let ids: Vec<&str> = dropped.iter().map(|c| c.id).collect(); - for id in ["document.json", "brush.unused", "symbol.unused", "transparency.set"] { + // Close Path, Set Handle and Knife have no menu path, and each needs an `id`. + for id in ["document.json", "brush.unused", "symbol.unused", "transparency.set", "path.close", "path.setHandle", "path.knife"] { assert!(ids.contains(&id), "{id} is left out: {ids:?}"); } // What a pick can change: the document with its selection, history, revision and layer @@ -1733,8 +1721,8 @@ mod tests { look(&app) != before }) }; - // `layer.setProps {}` records an undo step that changes nothing. - let changed: Vec<&str> = ids.iter().copied().filter(|id| *id != "layer.setProps" && acts(id)).collect(); + // `layer.setProps {}` and `path.moveAnchors {}` record an undo step that changes nothing. + let changed: Vec<&str> = ids.iter().copied().filter(|id| !["layer.setProps", "path.moveAnchors"].contains(id) && acts(id)).collect(); assert!(changed.is_empty(), "a pick of these does something: {changed:?}"); for c in &dropped { assert!(c.shortcut.is_none() && crate::shortcut_editor::menu_bar_path(c.id).is_none(), "{}", c.id); @@ -1767,7 +1755,7 @@ mod tests { for id in PICK_RUNS.iter().filter(|id| !session_only.contains(id)) { assert!(acts(id), "a pick of {id} does something"); } - for id in PICK_RUNS.iter().chain(&["object.group", "select.key", "view.preciseCursors", "path.close"]) { + for id in PICK_RUNS.iter().chain(&["object.group", "select.key", "view.preciseCursors"]) { assert!(listed.contains(*id), "{id} stays"); } } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 52649d6400..7e18b51179 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -167,9 +167,10 @@ fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node) { } /// A select of the corner kinds named `name`, showing `current` (blank for None), as wide as its -/// widest kind, so it fits beside a corner's radius field. Returns the kind picked. +/// widest kind, so it fits beside a corner's radius field. Returns the kind chosen, not one only +/// highlighted in the open list. fn corner_select(ui: &mut Ui, name: &'static str, current: Option, entries: &[Entry]) -> Option { - Select::new(name, Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), entries).sizing(Sizing::Content).show(ui).value().copied() + Select::new(name, Bind::given(current.map_or(Mixed::Mixed, Mixed::Same)), entries).sizing(Sizing::Content).show(ui).events.committed().copied() } /// Set `kind` on corner `corner` (every corner for None) of each selected live rectangle diff --git a/crates/ui-egui/src/panels/actions/tests_edits.rs b/crates/ui-egui/src/panels/actions/tests_edits.rs index d83e306f05..1fe2f13711 100644 --- a/crates/ui-egui/src/panels/actions/tests_edits.rs +++ b/crates/ui-egui/src/panels/actions/tests_edits.rs @@ -925,6 +925,8 @@ fn insert_menu_item_refuses_what_no_menu_item_runs_and_changes_nothing() { /// artboard to both. #[test] fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() { + // The View menu's proof items change the whole process's proof view. + let _view = crate::testing::DefaultProofView::new(); for item in crate::menus::insertable_items(false, &crate::menus::Listed::default()) { let (mut app, _) = app_with_three_moves(); app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": item.command, "params": item.params})).unwrap(); diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index f63f831cc4..41ec089303 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -97,10 +97,13 @@ pub(crate) fn copy_shown(ui: &mut Ui, shown: &egui::Response, value: &str) -> bo None => d.remove::(press_id), }); } - ui.ctx().accesskit_node_builder(shown.id, |node| { - node.set_description(tl!("Copy")); - node.add_action(egui::accesskit::Action::Click); - }); + // A value that cannot be copied (empty, disabled or clipped away) offers no Copy action. + if eligible { + ui.ctx().accesskit_node_builder(shown.id, |node| { + node.set_description(tl!("Copy")); + node.add_action(egui::accesskit::Action::Click); + }); + } let activated = ui.input(|i| i.num_accesskit_action_requests(shown.id, egui::accesskit::Action::Click) > 0); eligible && (activated diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index 53961fb0ab..96d558186a 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -546,6 +546,10 @@ mod tests { /// model's profile stays as it was. #[test] fn assign_rows_follow_the_document_color_mode() { + // Assigning a profile to the front document changes the process's active color settings. + if !crate::testing::in_own_process("panels::separations::tests::assign_rows_follow_the_document_color_mode") { + return; + } let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({})).unwrap(); for (mode, key, kind, other) in [("rgb", "rgb", ProfileKind::Rgb, "cmyk"), ("cmyk", "cmyk", ProfileKind::Cmyk, "rgb")] { diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index bfad19d09b..a5f37234e1 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -158,6 +158,72 @@ fn a_rectangle_shows_linked_and_unlinked_corner_types() { assert!(!p.shows("Corner") && p.shows("Top Left Corner") && p.shows("Bottom Left Corner")); } +/// Checks a live rectangle's Corner menu `menu` drawn by `draw`, with Corner Radius linked +/// (`single`) or not: a kind highlighted in the open menu leaves the rectangle as it is, Escape +/// closes the menu with the kind and the undo history unchanged, and Enter sets the highlighted +/// kind, on the corners `changed` marks, as one undo step. +fn check_corner_kind_menu(draw: fn(&mut VectorcraftApp, &mut Ui), single: bool, menu: &str, changed: [bool; 4]) { + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + use vectorcraft_doc::{LiveCorners, NodeId}; + use vectorcraft_geom::shapes::CornerKind; + let mut app = new_app(); + let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 120, "height": 80, "radius": 10})).unwrap()["id"].as_u64().unwrap(); + set_pref(&mut app, "singleCornerRadius", single); + let mut p = Panel::new(app, draw); + let kinds = |p: &Panel| { + let app = p.app(); + let corners = LiveCorners::of(app.session.active().unwrap().doc.node(NodeId(id)).unwrap()).unwrap(); + [0, 1, 2, 3].map(|k| corners.kind(k)) + }; + let original = p.app().session.active().unwrap().doc.clone(); + assert_eq!(kinds(&p), [CornerKind::ALL[0]; 4]); + let undo = undo_depth(&p.app()); + + p.click_role(menu, Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + assert!(p.app().session.active().unwrap().doc == original, "{menu}: highlighting a kind leaves the rectangle as it was"); + p.key(Key::Escape, Modifiers::NONE); + assert!(p.shows(menu), "{menu}: the panel still shows the menu after Escape"); + assert!(p.app().session.active().unwrap().doc == original, "{menu}: Escape leaves the rectangle as it was"); + assert_eq!(undo_depth(&p.app()), undo, "{menu}: Escape records no undo step"); + + p.click_role(menu, Role::COMBO_BOX); + p.key(Key::ArrowDown, Modifiers::NONE); + p.key(Key::Enter, Modifiers::NONE); + let expected = changed.map(|c| if c { CornerKind::ALL[1] } else { CornerKind::ALL[0] }); + assert_eq!(kinds(&p), expected, "{menu}: Enter sets the highlighted kind"); + assert_eq!(undo_depth(&p.app()), undo + 1, "{menu}: the kind is one undo step"); +} + +/// The Transform panel's Corner menu for all four corners of a live rectangle applies only the +/// kind chosen. +#[test] +fn transform_panel_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(show, true, "Corner", [true; 4]); +} + +/// The Transform panel's Corner menu for one corner of a live rectangle applies only the kind +/// chosen. +#[test] +fn transform_panel_single_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(show, false, "Top Right Corner", [false, true, false, false]); +} + +/// The Properties panel's Corner menu for all four corners of a live rectangle applies only the +/// kind chosen. +#[test] +fn properties_panel_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(crate::panels::properties::transform_section, true, "Corner", [true; 4]); +} + +/// The Properties panel's Corner menu for one corner of a live rectangle applies only the kind +/// chosen. +#[test] +fn properties_panel_single_rectangle_corner_kind_applies_only_when_chosen() { + check_corner_kind_menu(crate::panels::properties::transform_section, false, "Top Right Corner", [false, true, false, false]); +} + /// The four corner labels of an unlinked Corner Radius, in the Transform panel and in the /// Properties panel, start at one edge of their column whatever their widths, and the radius /// fields after them line up. diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a96f77c18a..bec5647de9 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -798,8 +798,9 @@ pub(crate) fn menu_target(id: &str) -> Option<(String, Value)> { /// Is `key` a command with no default shortcut that a key press can't run: no item of the menu /// bar runs it without params or with one set of params ([`menu_target`]), it opens no dialog when /// run without them (as the Variables panel's commands do), and it is a query, whose answer a key -/// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a menu command whose params -/// doc names a field a call must give (File › Document Setup › Units, `{units}`)? +/// press drops (Select All Unused), a command of [`NEEDS_A_PARAM`], or a command whose params doc +/// names a field a call must give, with a menu path (File › Document Setup › Units, `{units}`) or +/// without one (Close Path, `{id}`)? pub(crate) fn needs_a_value(key: &str) -> bool { static KEYS: OnceLock> = OnceLock::new(); KEYS.get_or_init(|| { @@ -809,7 +810,7 @@ pub(crate) fn needs_a_value(key: &str) -> bool { c.shortcut.is_none() && !a_menu_bar_item_runs(c.id, c.params) && !crate::dialogs::variables::opens(c.id) - && (!c.journal || NEEDS_A_PARAM.contains(&c.id) || (!c.menu.is_empty() && names_a_required_field(c.params))) + && (!c.journal || NEEDS_A_PARAM.contains(&c.id) || names_a_required_field(c.params)) }) .map(|c| c.id) .collect() @@ -2437,6 +2438,8 @@ mod tests { #[test] fn listed_commands_run_from_a_key_without_a_missing_param() { use vectorcraft_testkit::fixtures::Fixture; + // The View menu's proof commands change the whole process's proof view. + let _view = crate::testing::DefaultProofView::new(); // These need a state the fixtures lack: text being edited, a pattern being edited, an // object linked to a graphic style, a plug-ins folder. let context = ["text.insertInline", "pattern.options", "graphicStyle.redefine", "plugin.reload"]; diff --git a/crates/ui-egui/src/testing.rs b/crates/ui-egui/src/testing.rs index 1af93e507d..3650c423f8 100644 --- a/crates/ui-egui/src/testing.rs +++ b/crates/ui-egui/src/testing.rs @@ -94,8 +94,11 @@ pub(crate) fn custom_dictionary() -> std::sync::MutexGuard<'static, ()> { /// Runs the test `name` (its path in the crate, such as `canvas::tests::a_test`) alone in a child test process, for a /// test that loads or removes a color profile. The loaded profiles are the whole process's, and the canvas's frame key /// holds their generation ([`vectorcraft_color::cms::profiles_generation`]), so a profile loaded in this process while -/// another test renders changes that test's keys. In the child it returns `true`, and the test goes on. Here it waits -/// for the child, fails when the child's test fails, and returns `false`. +/// another test renders changes that test's keys. A test that assigns a profile to its front document, or changes +/// Color Settings, also runs here: the active color settings ([`vectorcraft_color::cms::active`]) are the whole +/// process's too, and another test converting a color while they are changed gets that profile's values. In the child +/// it returns `true`, and the test goes on. Here it waits for the child, fails when the child's test fails, and returns +/// `false`. pub(crate) fn in_own_process(name: &str) -> bool { const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS"; if std::env::var_os(CHILD).is_some_and(|v| v == name) { diff --git a/crates/ui-egui/tests/panel_readout_copy.rs b/crates/ui-egui/tests/panel_readout_copy.rs index 5b5e048d09..e3145401ae 100644 --- a/crates/ui-egui/tests/panel_readout_copy.rs +++ b/crates/ui-egui/tests/panel_readout_copy.rs @@ -369,6 +369,114 @@ fn panel_readout_info_names_and_truncated_link_metadata_copy_full_displayed_text copy_long_link_value(&mut a); } +#[test] +fn empty_link_info_values_do_not_offer_copy() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + + let mut a = App::new(); + let folder = vectorcraft_testkit::TempDir::new("empty-link-readout"); + let path = folder.join("Original.vectorcraft"); + // The linked file is saved from this test's two generated rectangles. + let bytes = vectorcraft_format::save_with(&a.app.session.active().unwrap().doc, &vectorcraft_format::SaveOptions::default()).unwrap(); + std::fs::write(&path, bytes).unwrap(); + let placed = a.app.run("file.place", json!({"path": path})).unwrap(); + let info = a.app.run("links.info", json!({"id": placed["ids"][0]})).unwrap(); + assert_eq!(info["document"], true, "the fixture places the original document as a link"); + assert!(info["colorMode"].is_null(), "the linked document has no image color-mode value"); + a.panel("links"); + // A tall float shows every Link Info row, so no row is clipped away. + a.app.run("window.panel.float", json!({"panel": "links", "x": 520, "y": 120, "width": 300, "height": 700})).unwrap(); + a.app.run("window.panel.activate", json!({"panel": "links"})).unwrap(); + let out = a.settle(); + let nodes = &out.platform_output.accesskit_update.as_ref().unwrap().nodes; + assert!( + nodes.iter().any(|(_, node)| node.value() == Some("Original.vectorcraft") && node.supports_action(Action::Click)), + "the nonempty Name remains copyable" + ); + let empty: Vec<_> = nodes.iter().filter(|(_, node)| node.label() == Some("Color Space")).collect(); + assert!(!empty.is_empty(), "the actual Color Space row is present"); + assert!(empty.iter().all(|(_, node)| node.description() != Some("Copy")), "the empty Color Space value must not advertise Copy"); + let values: Vec<_> = empty.iter().filter(|(_, node)| node.value() == Some("")).collect(); + assert!(!values.is_empty(), "the actual empty value is present in the accessibility tree"); + assert!(values.iter().all(|(_, node)| !node.supports_action(Action::Click)), "the empty value has no copy action"); + let requests = empty + .iter() + .map(|(id, _)| { + Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node: *id, target_tree: TreeId::ROOT, data: None }) + }) + .collect(); + let before = a.snapshot(); + let sets = a.app.ui.status_sets; + assert!(copies(&a.frame(requests)).is_empty(), "a forged empty-value action does not copy"); + assert_no_delayed_copy(&mut a, "empty value"); + assert_eq!(a.app.ui.status_sets, sets, "an empty-value action reports no copy"); + assert_eq!(a.snapshot(), before, "an empty-value action leaves the document and history intact"); +} + +#[test] +fn link_info_stays_visible_while_a_long_image_list_scrolls() { + use egui::accesskit::{Action, Role}; + + // Each layout places 32 generated images before scrolling and copying. + for size in ["none", "small", "medium", "large"] { + let mut a = App::new(); + for index in 0..32 { + place_original_png(&mut a, &format!("Original-image-{index:02}.png")); + } + let selected = "Original-image-31.png"; + a.app.run("ui.links.thumbnails", json!({"size": size})).unwrap(); + a.panel("links"); + a.app.run("window.panel.float", json!({"panel": "links", "x": 520, "y": 120, "width": 220, "height": 700})).unwrap(); + a.app.run("window.panel.activate", json!({"panel": "links"})).unwrap(); + let out = a.settle(); + let nodes = &out.platform_output.accesskit_update.as_ref().unwrap().nodes; + let body = nodes + .iter() + .filter(|(_, node)| node.role() == Role::TabPanel) + .map(|(_, node)| location_node_rect(node)) + .find(|rect| (rect.left() - 520.0).abs() < 1.0) + .unwrap(); + let name_rect = |out: &egui::FullOutput| { + let fields: Vec<_> = out + .platform_output + .accesskit_update + .as_ref() + .unwrap() + .nodes + .iter() + .filter(|(_, node)| node.label() == Some("Name") && node.value() == Some(selected) && node.supports_action(Action::Click)) + .collect(); + assert_eq!(fields.len(), 1, "{size}: the selected image has one visible Name copy target"); + let rect = location_node_rect(&fields[0].1); + assert!(body.contains_rect(rect), "{size}: the selected image's Name remains inside the panel"); + rect + }; + let before = name_rect(&out); + let row = nodes.iter().find(|(_, node)| node.role() == Role::ListItem && node.label() == Some(selected)).unwrap(); + let row = location_node_rect(&row.1); + let snapshot = a.snapshot(); + let first_visible = |out: &egui::FullOutput| { + out.platform_output.accesskit_update.as_ref().unwrap().nodes.iter().any(|(_, node)| { + node.role() == Role::ListItem && node.label() == Some("Original-image-00.png") && body.contains_rect(location_node_rect(node)) + }) + }; + assert!(!first_visible(&out), "{size}: the list starts with its oldest image scrolled out of view"); + let mut scrolled = out; + for _ in 0..32 { + a.frame(vec![Event::PointerMoved(row.center())]); + a.frame(vec![craft::ui::testing::pointer::wheel(-body.height() * 32.0)]); + scrolled = a.settle(); + assert_eq!(name_rect(&scrolled), before, "{size}: scrolling the list keeps Link Info in place"); + if first_visible(&scrolled) { + break; + } + } + assert!(first_visible(&scrolled), "{size}: scrolling the list reaches its oldest image"); + copy_at(&mut a, before.center(), selected); + assert_eq!(a.snapshot(), snapshot, "{size}: scrolling and copying leave the drawing and history unchanged"); + } +} + fn assert_no_delayed_copy(a: &mut App, kind: &str) { let copied = copies(&a.deadline()); assert!(copied.is_empty(), "{kind}: unexpected delayed copy {copied:?}"); @@ -705,3 +813,33 @@ fn review_4714788866_readout_copy_requires_an_inside_primary_press() { assert_no_delayed_copy(&mut a, "accepted inside readout press"); assert_eq!(a.snapshot(), before); } + +#[test] +fn info_readout_copy_requires_the_press_and_release_inside_its_bounds() { + for same_frame in [true, false] { + let mut a = App::new(); + let out = a.panel("info"); + let value = "W: 37 pt"; + let id = review_8826_readout_node(&out, value); + let node = &out.platform_output.accesskit_update.as_ref().unwrap().nodes.iter().find(|(key, _)| *key == id).unwrap().1; + let bounds = location_node_rect(node); + let outside = egui::pos2(bounds.left() - 1.0, bounds.center().y); + let inside = egui::pos2(bounds.left() + 1.0, bounds.center().y); + assert!(!bounds.contains(outside) && bounds.contains(inside)); + assert!(outside.distance(inside) < a.ctx.options(|o| o.input_options.max_click_dist), "CONTROL: the motion is a click, not a drag"); + let before = a.snapshot(); + let sets = a.app.ui.status_sets; + let mut events = vec![Event::PointerMoved(outside), button(outside, true)]; + if !same_frame { + assert!(copies(&a.frame(events)).is_empty()); + events = Vec::new(); + } + events.extend([Event::PointerMoved(inside), button(inside, false)]); + let release = a.frame(events); + assert!(copies(&release).is_empty(), "a press outside cannot copy on a release inside; same frame: {same_frame}"); + assert_no_delayed_copy(&mut a, "outside press"); + assert_eq!(a.app.ui.status_sets, sets, "the rejected gesture does not report a copy"); + assert_eq!(a.snapshot(), before, "the rejected gesture preserves the document, selection and history"); + copy_at(&mut a, bounds.center(), value); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index d9a1a7046a..c933bf1f6d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2701,6 +2701,9 @@ vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' ``` `script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. + +In an ES2015 realm, `Symbol.for` lookups and insertions take fuel for the key's code units. A registered description +shares the key's existing string buffer. File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any @@ -2783,8 +2786,9 @@ other files through `$`: [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) describes; in VectorCraft that holds for `activeDocument`, `documents` and `selection`. VectorCraft's own rules: assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level - `var selection = ...` does the same and does not make a variable of the script. Assigning `documents` keeps its - value. `app.documents` + `var selection = ...` does the same and does not make a variable of the script. An assignment to `documents` + leaves its value unchanged. Outside strict mode the assignment is ignored, and in strict mode code + (`'use strict'`) or with `#strict on` it throws a `TypeError`. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -7957,6 +7961,11 @@ own, and the corner keeps its place and the directions the path arrives and leav `fidelity`. A call that changes no anchor returns `{ids: [], before: 0, after: 0}` and adds no undo step. The 57.5° threshold is VectorCraft's own value. +`path.smoothRegion` measures each curved segment of the paths it searches once whole against `points`, and cuts all of +them together into no more than 131,072 further pieces while it finds where `radius` reaches them, shared equally by +the segments in reach. A segment searched after those pieces run out is still smoothed where its middle, or its point +nearest `points`, is within `radius`. The limit is VectorCraft's own value. + `path.smoothRegion`'s `smoothness` (0 to 100, 50 when left out) sets how strongly the path is smoothed before it is refitted within `fidelity`: each point is averaged with the stretch of path around it, over a stretch that grows in proportion to `smoothness`, so a higher value leaves a smoother path. At 0 the path is only refitted within @@ -8592,6 +8601,11 @@ and files saved without it open with it off. {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"Letter","alignNewObjectsToPixelGrid":true}}} ``` +The shape Control bar's numeric edits preview changes to selected shapes and future tool settings together. +Cancel restores both, including the separate scalar radius and per-corner radii. Accept keeps the new settings; +Undo restores the selected artwork. A canceled edit whose tool or document ownership has ended cannot overwrite +the new tool's settings. + ## Live Corners `object.setLiveShape {id?, ids?, radius?, kind?, corners?, rectanglesOnly?, items?}` sets the corners of any path (one undo step): a live @@ -8630,6 +8644,10 @@ and those shape tools: hidden widgets are not drawn, and those tools do not answ on them. `on`, when given and not `null`, must be `true` or `false` and sets the state; without it, or with `null`, the command toggles. The reply is the new state (`true` when shown, the default). The bounding box, the center point and Direct Selection's corner widgets, which follow `view.cornerWidget` alone, stay as they are, and no undo step is added. +While the pointer is within 5 px of a corner widget that shows, with any tool that shows it, the desktop app draws the +cut of that widget's corner (round, inverted round or chamfer) in a 2 px line of the layer color. A square corner has +no cut and gets no line, and no line is drawn while a mouse button is down. The 5 px reach, the 2 px width and the +color are VectorCraft's own values. No command runs and no undo step is added. In the desktop app, the Corners link in the Control bar (beside the anchor controls) and in the Properties panel (with Direct Selection, while a corner is selected or one live rectangle or polygon is selected) opens the Corners pop-up for the picked corners of every selected path: the corners holding a Direct-Selected anchor, or every corner of a path selected whole; a path whose selected anchors @@ -9146,6 +9164,10 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture handle or segment for Direct Selection, the Anchor Point, Add and Delete Anchor Point and Scissors tools, and the Pen with Alt. A handle shorter than that leaves its anchor to be picked when pressed nearer the anchor. - `objectSelectionByPathOnly`: a click inside a filled path or compound path doesn't select it, one on its path does. + Off (the default), a selection tool click inside the closed subpaths of a path or compound path with no fill selects + it when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, + is hit anywhere in its bounds), the topmost such path first, except in Outline view and on a layer whose Preview is + off; guides and clipping paths are still picked by their path only (#9175). - `ctrlClickSelectsBehind` (on by default): after a first Selection tool click with `mods: {cmd: true}` (Command on macOS, Ctrl elsewhere), which Direct Selection or Group Selection takes, each further such click with Cmd held selects the object under the selected one there, members of groups one by one, the next such click the one under @@ -15918,8 +15940,20 @@ Tools: `snapTolerance` (screen pixels, 0 to 25, 3; VectorCraft's own range and default) is how near the pointer picks a segment while Smart Guides are on (their Snapping Tolerance counts instead when it is larger) or while they are off with `snapWithoutGuides` (true or false, true) on. Otherwise a segment is picked within the Selection Tolerance, which is also the least reach with snapping. + `askRadius` (Ask For Circle Radius) and `autoUpdateDefault` (Auto-Update Default) are true or false, both false. `tool.setOption` gives an error for a value outside an option's range, of the wrong type, or a color not listed, and - for any other option, and then sets none of the values. + for any other option, and then sets none of the values. With `askRadius` on, a click on the second segment that finds + a circle (with or without Shift) opens the Tangent Circle dialog (`tangentCircleRadius`) instead of drawing; a drag, + which sets the radius, draws at once. The dialog's Radius starts at the radius of the circle found, and each radius + previews the circle of that radius touching the second segments nearest the click, anywhere along the first segment + (at the radius it opened with, the circle found). A radius that gives no circle there shows the note and leaves OK + off, as do an edit to either segment's path after the click and another active document; a circle the target layer + cannot take (locked or hidden) shows why and leaves OK off; a radius outside 0.01 to + 1000000 pt, typed or set, shows the radius error and leaves OK off, except the radius the dialog opened with. + `ui.dialog.set` gives an error for a radius that is not a number. OK draws the circle in one undo + step, with `shape.circleThroughPoints`, and with `autoUpdateDefault` on also sets `radius` to the radius given when + it is in that range. Cancel draws nothing, leaves no undo step and + keeps the first segment picked. - **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed, on any path that can be edited, selected or not. A click runs `addon.pathtools.trim` with `at`, for the path within 4 screen pixels of the pointer. A drag draws a rectangle and runs it with `rect` on release; once the pointer has @@ -17224,6 +17258,7 @@ the error text. The interactive fallback applies only to ordinary File > Save, n | Date | Change | |---|---| | 2026-11-27 | Brush Options: untouched approval preserves the brush, document revision and Undo; changed settings save in one step. Native UI and automation covered. Scores and estimates unchanged. | +| 2026-11-27 | Shape Control bar: canceled numeric edits restore future-tool settings and coupled radii along with selected artwork; retired edits cannot overwrite a different tool. Native scrub, keyboard, next-shape and Undo cases covered. Scores and estimates unchanged. | | 2026-11-27 | Anchor Inspector: Cancel restores Corner radius/kind and Shared Edge diameter/coincidence tool values; accepted settings leave document history unchanged. Native numeric and menu cases covered. Scores and estimates unchanged. | | 2026-11-18 | Production Preflight: output and artboard scope, four check summaries, clickable canvas ids, effective PPI and explicit unchecked resolution coverage. | | 2026-11-14 | Built-in Tech Circuit brush library (id `tech-circuit`): Circuit Trace, Bus Lines and Terminal Nodes; ten built-in libraries. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 638d1baab2..75efe3bf2e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -47,6 +47,8 @@ XMP array insertion with `XMPConst.ARRAY_LAST_ITEM` precedes the last existing i XMP parsing rejects invalid qualified names, text other than XML whitespace beside descriptions or properties, and conflicting explicit `rdf:about` values, including empty values. Packet scanning skips other processing instructions inside a packet. Packet padding requires a real wrapper trailer and allows leading XML declarations, comments, and processing instructions. Array appends charge their added bytes without scanning existing items, and indexed property reads copy only the selected value. Pending packets count once toward the heap limit. ES5 and ES2015 library installation checks every published member against that limit. Failed serialization and packet-info scans consume fuel. Sidecar writes allow packets up to VectorCraft's 8 MiB packet limit through the host binding. +`Symbol.for` lookups and insertions take fuel for the key's code units, including registry hits on flat strings. A registered description shares the key's existing buffer. Regressions in `crates/js/src/symbol_tests.rs` cover hits, misses, and registering a rooted flat key when the heap has room for metadata but not another key buffer. + - Fold Preview orders overlapping coplanar panels by their fold tree, draws distinct planes and crossing panels by depth, and calculates poses relative to the blank's center. Each plane uses one comparison depth, and every member of a plane group must match every other member. A hinge uses its longest line across all split pieces. Tests cover flat, near-flat, nested and offset folds in `crates/three-d/src/fold/tests.rs` and `crates/three-d/src/fold/raster/tests.rs`. - `addon.packaging.setFoldAngle` stores or resets individual fold angles for editable Crease, Partial Cut, and Perforation lines. The fold commands read those angles, and role queries report their shared value and stored-angle counts. Engine tests cover validation, locked compound members, one-step undo, native save, and SVG exports. `vectorcraft-js` ends a paused or waiting run before `Realm::run` or `Realm::start` compiles new source. Its globals remain available. The earlier run's remaining code and queued jobs do not run. Regressions in `crates/js/src/host_tests.rs` cover paused scripts, Promise reactions, waiting host calls, invalid replacement source, and deferred language settings. @@ -701,7 +703,9 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. + +- **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. - **PDF stroked type (#7741):** `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs` covers round, projecting and butt caps, round, bevel and miter joins and a miter limit of 3 on type stroked in rendering modes 1, 2, 5 and 6, shown as a word, a glyph at a time and under `ActualText`; glyphs stroked with another join as runs of their own; and a glyph filled and stroked after one stroked otherwise, which keeps the join of the glyph before it. Synthetic PDFs written in the test (standard Helvetica, not embedded); no fonts or fixtures added. The dash array is not yet carried to the characters. @@ -848,6 +852,7 @@ since 2026-10-01. - **Existing-guide Escape cancellation (G1):** Escape clears a pending guide press or drag through Selection and Direct/Group Selection, cancelling a begun preview. Eight app-input regressions cover both axes, move/copy, temporary selection-tool borrowing from idle Pen, preselected-guide document/interaction-start selection and Undo/Redo/saved-state preservation, later on-canvas motion/release, Shift-press cancellation, and ordinary-release/Enter/idle controls. Historical focused checks on `8ab574b7` recorded five expected RED failures with three passing controls, then all eight GREEN tests and the Direct Selection Escape control passed. All nine also passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. The original 1280×960 headless app capture from `b076025a` was reviewed for one vertical Selection guide after Escape; source review found its scene unchanged on `a0671777`. Scores and hours unchanged. - **Escape in more tool drags:** Escape during an Anchor Point drag, a Mesh tool drag, a Direct Selection drag of a mesh point, a corner widget or the brackets of type on a path, or a Shape Builder drag cancels it: the art goes back to how the press found it, no undo step is added, the release does nothing, and the tool stays chosen. Escape during a Measure tool drag brings back the measurement before it. Regression tests: `escape_cancels_*` in `draw2/anchor/tests.rs`, `meshedit.rs`, `direct/tests.rs`, `builder/tests.rs` and `xform/measure.rs`, and `escape_cancels_an_anchor_point_mesh_shape_builder_or_measure_drag` in `tests/toolescape.rs`. - **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of a path is selected (the path selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. The other corners' widgets then hide; a Shift-click on another corner's anchor adds that corner and shows its widget, and a Shift-click on a showing widget deselects its corner. Adding a corner by Shift-clicking its widget while it is hidden stays open (#1232). Corner widgets are chosen by clicking one and Shift-clicking the others ([Logos By Nick, rounded corners in Illustrator](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. +- **A press inside a selected group** (VectorCraft's own rule): with Direct Selection, a path inside a selected group counts as selected whole. A click on its fill keeps the group selected, a drag from its fill or one of its anchors moves the group whole, and a click on an anchor or a segment selects it alone. The path's anchors show the selected-anchor cursor and highlight, and an object above the group does not take a press on one. Group Selection adds the group above the outermost selected one. This also applies to the Cmd/Ctrl press the Selection tool lends Direct Selection. Test: `direct::tests::a_press_inside_a_selected_group_keeps_the_group`. - **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF. - **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`). - **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html). @@ -1602,6 +1607,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. + With the pointer on a Direct Selection corner widget or close to it, the canvas marks the cut of that widget's corner with a thicker line (#1232). The help page describes this marking of a widget's corner while the pointer is on the widget or close to it ([Live Corners help page, archived](https://web.archive.org/web/2016id_/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, the mark also shows with the Selection tool and the shape tools on the widgets they show, it is a 2 px line of the layer color within 5 px of the widget, a square corner gets none, and none is drawn while a mouse button is down. Tests: `corners::tests::a_widget_under_the_pointer_gives_its_corners_cut`, `corners::tests::a_square_corner_gives_no_cut_and_a_plain_paths_corner_gives_its_own`, `corners::tests::a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none`, `canvas::widgets::tests::hovering_a_corner_widget_highlights_its_corner`. - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_without_live_corners_adds_no_undo_step`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). @@ -1663,6 +1669,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. + A Smooth drag measures each curved segment of the paths it searches once whole, and cuts all of them together into no more than 131,072 further pieces, shared equally by the segments in its reach, however many curved segments it passes over (`path.smoothRegion`). A segment searched after those pieces run out is still smoothed where its middle, or its point nearest the drag, is in reach. The limit is VectorCraft's own (engine tests `a_drag_over_many_curved_segments_measures_at_most_its_pieces_past_the_first_of_each` and `every_curved_segment_is_searched_after_the_drags_pieces_run_out`). A Smooth drag measures only the anchors and curved segments near the drag, and each against only the stretches of the drag near it. A release still looks up every anchor and curved segment of a path in the drag's grid, so the lookups still grow with the path's length. The grid reduces the number of stretch measures. On a curved path of 100,000 anchors, a drag of 200 points over 200 pt of it makes 7,533 stretch measures to find the curved segments in its reach, where it made 19,899,801 (99,999 segments times 199 stretches). The smoothed path is the same as before (engine tests `a_drag_over_a_long_path_measures_only_what_is_near_it` and `the_drag_grid_gives_the_results_of_measuring_the_whole_drag` in `crates/engine/src/cmd/draw2/smooth.rs`). A segment leading out of the stretch a Smooth drag smooths that is in the drag's reach for no more than 1/64 of the reach from the stretch's anchor is left as it is, and the stretch ends at that anchor, so a drag that reaches an anchor an earlier drag added at the edge of its reach does not split the segment beyond it again or leave a corner there (`path.smoothRegion`). The 1/64 share is VectorCraft's own value (`tests/draw2.rs`, `smooth_drags_again_and_again_along_part_of_an_ellipse_add_no_anchors_or_corners`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). @@ -2436,6 +2443,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). + A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified. The placed file stays as before when its bytes are larger than 256 MiB, are a DCS file, have no bounding box of their own, carry a VectorCraft document, don't read as an EPS file, or belong to a file named `.ai` or `.ait`, and a placed EPS file with a preview that an image variable binds stays the linked image showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`). In a `.ai` or EPS opened from its editing data, and in a legacy `.ai`, each anchor is smooth or a corner as the case of the segment operator ending on it says (`l`, `c`, `v`, `y` smooth; `L`, `C`, `V`, `Y` corner), and a closed path's first anchor takes the case of the segment back to it; points and handles stay where they are. Paths, compound paths, clipping paths, guide paths, area type frames and type-on-a-path paths all keep it (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/legacy_ai/tests.rs`). In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`). `.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). @@ -3166,6 +3174,8 @@ Add Points to Existing Paths (2026-11-20): the tool's `addPoints` option (in its The tool's options dialog also sets the preview and how a segment is picked, the options the help page lists (https://docs.astutegraphics.com/subscribe/tangent-circle-tool): Circle Center and Circle Radii Lines (`center`, `radii`) show or hide the center cross and the radii, Color (`color`: red, blue, magenta, green, black or gray) colors the circle, the cross, the radii and the note, Snap Tolerance (`snapTolerance`, screen pixels) is how near the pointer picks a segment with Smart Guides on, the Smart Guides Snapping Tolerance counting when it is larger, and Snap When Smart Guides Are Off (`snapWithoutGuides`) keeps that reach with Smart Guides off; without it the Selection Tolerance applies. Of the segments within reach the nearest is picked. The defaults (both shown, red, 3 px, snapping on) and the 0 to 25 px range are VectorCraft's own; they are kept with the preferences, and `tool.setOption` gives an error for a value an option does not take. Tests: `addons::tangent_circle::tests` in `vectorcraft-tools` (the preview options, the snapping reach, the options' values) and `the_tangent_circle_options_set_the_preview_and_snapping` in `vectorcraft-ui-egui`. +Ask For Circle Radius and Auto-Update Default (2026-11-20): two options of the tool (`askRadius`, `autoUpdateDefault`, both off to start with). With Ask For Circle Radius on, a click on the second segment that finds a circle, with or without Shift, opens a Tangent Circle dialog at that circle's radius instead of drawing; a drag draws at once. Each radius typed previews the circle of that radius nearest the click, a radius with no circle there, an edit to either segment after the click, or another active document, shows the note and leaves OK off, a target layer that is locked or hidden says so and leaves OK off, a radius typed outside 0.01 to 1,000,000 pt (other than the click's own) shows an error and leaves OK off, OK draws the circle in one undo step, and Cancel draws nothing and keeps the first segment picked. With Auto-Update Default on, OK also makes the radius given the tool's Shift radius when it is from 0.01 to 1,000,000 pt. Tests: `ask_for_circle_radius_opens_the_dialog_after_a_click_but_not_after_a_drag` and `the_radius_dialog_knows_when_its_segments_changed` in `vectorcraft-tools`, and `the_radius_dialog_previews_says_when_there_is_none_cancels_and_draws_on_ok`, `another_document_or_a_segment_changed_after_the_click_gives_no_circle`, `a_failed_ok_keeps_the_preview_for_cancel`, `a_click_found_radius_outside_the_tool_range_can_be_drawn`, `a_circle_the_target_layer_cannot_take_shows_why_and_leaves_ok_off`, `a_switch_to_another_document_leaves_its_interaction_alone`, `a_second_click_replaces_the_open_dialog` and `a_radius_that_is_not_a_number_is_refused_and_keeps_the_circle` in `vectorcraft-ui-egui`. + ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, since 2026-11-16; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut) removes stretches of paths between the places where they are crossed by another path or by themselves, on any path that can be edited, selected or not. A click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; each is one undo step, and Escape during a drag removes nothing. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, a path that nothing crosses is removed whole, and the stretches that stay get no new anchors. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing. Add Points at / Split at Crossings share the crossing search: segments that meet at an anchor now count where they cross again elsewhere, and with Self Crossings a curved segment that loops over itself crosses itself. Command `addon.pathtools.trim`; `vectorcraft_pathops::addons::pathtools::{crossings_on, spans, without_spans}`. Hovering shows in red the stretch a click would remove, worked out by the same code the command uses (`vectorcraft_tools::addons::trim::plan`), and a drag that reaches at most 32 paths shows what its release would remove; a preview spends at most a twentieth of the crossing work a click may (2026-11-15; tests `hovering_*`, `in_isolation_mode_*`, `a_path_whose_crossings_*` and `a_small_drag_*` in `addons::trim` in `vectorcraft-tools`, `hovering_with_the_tool_shows_the_stretch_its_click_removes` and `what_the_tool_shows_*` in `vectorcraft-engine`). Not yet: crossings with type, images and symbol instances. Tests: `crossings_on_*`, `segments_*`, `a_segment_that_loops_over_itself_crosses_itself`, `one_work_budget_*`, `spans_divide_*`, `a_subpath_without_*` and `a_slice_*` in `addons::pathtools::tests` in `vectorcraft-pathops`, `addons::trim` in `vectorcraft-tools` (click, rectangle, freehand line, Escape), `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine` (a middle and an end stretch, a closed path opening, a rectangle and a line as one undo step, locked and hidden paths, guides and clipping paths, paths nothing crosses, compound path members, the selection, 3,000 other paths, a path too large to search left alone until touched, bad params refused), `the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector` in `vectorcraft-ui-egui`, `edit_toolbar::tests` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. The tool shows the Knife's cursor, now drawn as a knife with the blade's point on the hotspot (2026-11-16; tests `trim_at_crossings_is_in_the_scissors_flyout` and `a_saved_toolbar_without_trim_at_crossings_keeps_its_layout` in `edit_toolbar::tests`, `trim_at_crossings_is_in_the_scissors_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`, `the_knife_shows_a_knife_with_its_point_on_the_hotspot` in `cursors::tests` and `drawing_tools_show_their_own_cursor` in `vectorcraft-tools`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4246d86407..4d05851b10 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -367,6 +367,7 @@ tools, never checked side by side) isn't captured row by row. | Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | | Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | | Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and, with Measurement Labels on, the radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | +| Shapes panel restores canceled control gestures | done | Escape restores the opening field values, including coupled radii and settings for the next shape. | ## Modifier keys and temporary tools @@ -559,7 +560,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | | Overprint Preview draws a white canvas around the artboards, with no artboard shadows | done | VectorCraft's own rule, in Overprint Preview and in Separations Preview, which turns it on: while the artboards show, the canvas outside the artboards is white in every interface brightness and Canvas Color, and the artboards keep their paper and edges and draw no shadows. With a display profile, translucent art around the artboards is blended with the white canvas. Turning the preview off brings back the pasteboard color and the shadows. Tests `overprint_preview_draws_a_white_canvas_without_shadows`, `translucent_art_around_the_artboards_is_blended_with_overprint_previews_white_canvas`, `translucent_pixels_around_the_artboards_are_blended_with_the_white_canvas` | | Outline view: a click selects by the outlines drawn, so it reaches a path behind an image (picked on its frame, unless Show Images in Outline Mode draws its pixels) or a gradient mesh (picked on its mesh lines) | done | #6437; in Outline mode the path is selected directly ([Object selection methods and preferences](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/object-selection-methods-and-preferences.html), Object Selection by Path Only). Type, symbol instances, blends, envelopes and placed documents are still picked within their bounds. Tests `outline_mode_picks_paths_through_images_and_meshes`, `outline_view_click_through_an_image_selects_the_path_behind` | -| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Preview mode and output draw them as before. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | +| Outline view draws a linked image or placed document as its box with an X inside, unless Show Images in Outline Mode is on | done | A linked file draws in Outline mode as a box with an X in it, and its contents show only after the Document Setup option Show Images in Outline Mode is turned on ([View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). The rest are VectorCraft's own rules. A linked image's frame is crossed from corner to corner, following the corners of a turned or distorted image. An embedded image, and each piece that an envelope cuts an image into, shows its frame alone. A click selects a linked image on its frame, as before, and not on the lines. A placed document shows its box crossed and none of its art, also with raster effects such as a drop shadow and with color adjustments. Effects that change geometry, its own or its group's, reshape the crossed box instead of the file's art, and an envelope holding a placed document distorts its crossed box. Each step of a blend of placed documents is crossed too. With the option on, images show their pixels in gray and placed documents show their art in outline, uncrossed, and the art inside a placed document follows the option of the document it is placed in. Output draws them as before, and so does Preview mode, except in a layer that is not a template and whose Preview is off, which draws them by these rules. In Outline mode, a template layer draws them as Preview mode does. Tests `outline_mode_crosses_a_linked_images_frame_unless_the_setup_shows_images`, `outline_mode_crosses_a_linked_image_with_a_color_mask`, `outline_mode_does_not_cross_the_pieces_of_an_enveloped_linked_image`, `outline_mode_crosses_a_linked_image_moved_into_a_warp_piece`, `outline_mode_crosses_a_turned_or_distorted_linked_image_through_its_corners`, `outline_mode_draws_a_placed_document_as_its_box_crossed_unless_the_setup_shows_images`, `outline_mode_reshapes_the_crossed_box_of_a_placed_document_by_its_groups_effects`, `outline_mode_draws_the_crossed_box_its_effects_move_into_view_after_a_preview_frame`, `outline_mode_warps_an_enveloped_placed_documents_crossed_box`, `outline_mode_draws_each_step_of_a_blend_of_placed_documents_crossed` | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools runs Arrange in Grid… (grid by row, one row or one column; columns, H and V spacing, Center on Artboard; Preview), Swap Objects, Swap Objects and Sizes, Replace with Top Object… (Actual Size, Bounds or Bounds (Fit Proportionally); Keep Original; Scale Strokes & Effects; Preview), Set Size of Each… (Width and Height each ticked on or off, Constrain Width and Height Proportions with one side, the reference point, Scale Strokes & Effects; Preview) and Zoom to Selection, each one undo step | done | `addon.arrange.*`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group Overlapping Objects groups the selected objects whose visual bounds overlap or touch (chains included, within one layer or group), each group at its frontmost member's stacking place, one undo step | done | #4928; `addon.arrange.groupOverlapping`, `crates/engine/src/cmd/addons/arrange.rs` and its tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index 734073aba3..a284579d16 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -9,6 +9,7 @@ import importlib.util import io import os from pathlib import Path +import re import subprocess import unittest from unittest import mock @@ -78,15 +79,49 @@ class Deadline(unittest.TestCase): before_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS - 60) after_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS + 60) self.assertGreater((before_limit - self.began).total_seconds(), clear.GIVE_UP_SECONDS) - self.assertFalse(clear.gave_up(late, before_limit, self.began)) - self.assertTrue(clear.gave_up(late, after_limit, self.began)) + self.assertFalse(clear.gave_up(late, before_limit)) + self.assertTrue(clear.gave_up(late, after_limit)) + self.assertFalse(clear.start_overdue(late, after_limit, self.began)) def test_a_leg_that_never_starts_is_timed_from_the_script_start(self): queued = warm_job("queued", started_at="2026-11-28T03:38:00Z") - later = self.began + timedelta(seconds=clear.GIVE_UP_SECONDS + 60) - self.assertFalse(clear.gave_up(None, self.began + timedelta(minutes=10), self.began)) - self.assertTrue(clear.gave_up(None, later, self.began)) - self.assertTrue(clear.gave_up(queued, later, self.began)) + before_limit = self.began + timedelta(seconds=clear.START_SECONDS - 60) + after_limit = self.began + timedelta(seconds=clear.START_SECONDS + 60) + self.assertFalse(clear.start_overdue(None, before_limit, self.began)) + self.assertTrue(clear.start_overdue(None, after_limit, self.began)) + self.assertTrue(clear.start_overdue(queued, after_limit, self.began)) + self.assertFalse(clear.gave_up(queued, after_limit)) + + def test_a_leg_that_starts_after_the_start_limit_fails(self): + at = lambda seconds: warm_job("in_progress", started_at=(self.began + timedelta(seconds=seconds)).isoformat()) + self.assertTrue(clear.started_late(at(clear.START_SECONDS + 5), self.began)) + self.assertFalse(clear.started_late(at(clear.START_SECONDS - 10), self.began)) + self.assertFalse(clear.started_late(warm_job("queued"), self.began)) + self.assertFalse(clear.started_late(None, self.began)) + + +class Workflow(unittest.TestCase): + ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text() + + def timeout_minutes(self, job): + """The first `timeout-minutes` under `job` in ci.yml.""" + lines = self.ci.splitlines() + start = lines.index(f" {job}:") + 1 + for line in lines[start:]: + if re.match(r" \S", line): + break + match = re.match(r"\s+timeout-minutes: (\d+)$", line) + if match: + return int(match.group(1)) + self.fail(f"no timeout-minutes under {job}") + + def test_the_job_outlasts_the_start_wait_and_the_save_wait(self): + # Five minutes are left for the steps before the script and for the deletion. + spare = self.timeout_minutes("cold-cache-clear") * 60 - clear.START_SECONDS - clear.GIVE_UP_SECONDS + self.assertGreaterEqual(spare, 5 * 60) + + def test_the_save_wait_outlasts_the_gate(self): + self.assertGreater(clear.GIVE_UP_SECONDS, self.timeout_minutes("gate") * 60) class Jobs(unittest.TestCase): @@ -187,6 +222,22 @@ class AfterDeletion(unittest.TestCase): canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")]) self.assertEqual(self.run_main(canceled), 1) + def test_a_leg_that_starts_late_and_saves_deletes_nothing(self): + # Clock.now() is 04:00, so the leg starts 120 minutes 5 seconds after the script. + late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T06:00:05Z") + deleted = [] + + def run(args, **kwargs): + deleted.append(args[-1]) + return subprocess.CompletedProcess(args, 0, "", "") + + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", lambda url: {"jobs": ME + [late]}), mock.patch.object(clear.subprocess, "run", run), \ + mock.patch.object(clear.time, "sleep"), mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), \ + contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(clear.main(), 1) + self.assertEqual(deleted, []) + def test_a_save_that_fails_after_the_deletion_exits_1(self): failed = warm_job("completed", "failure", [("Gate", "completed", "success"), ("Post Setup", "completed", "failure")]) self.assertEqual(self.run_main(failed), 1) diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index e9b52d2493..3b913d68f7 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -16,8 +16,8 @@ save step started saves nothing: its old entries stay, and this exits 1, so "Re- runs it again beside the re-run leg. A save step that is canceled or fails after the old entries were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure in a later post step does not count once the save step has succeeded. This also exits 1 when the -leg has not reached its save, or its save has not finished, GIVE_UP_SECONDS after the leg started. -An absent warm leg is treated as finished only +leg has not started START_SECONDS after this script started, and when the leg has not reached its +save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only when the most recent earlier attempt that lists it reports success and the current attempt lists no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling because reusable-workflow dependencies may still be scheduling it. @@ -46,6 +46,12 @@ PAGE_SIZE = 100 # Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold # leg that starts late and runs to its limit still reaches its save before this gives up. GIVE_UP_SECONDS = 160 * 60 +# How long the leg may take to start, timed from this script's start: the leg waits for +# `gate / select legs` and then for a runner, which took 44 minutes on a push to main on +# 2026-11-28. The `cold-cache-clear` job's `timeout-minutes` in ci.yml is longer than +# START_SECONDS and GIVE_UP_SECONDS together, so this exits with its own error before the job +# times out. +START_SECONDS = 120 * 60 STOPPED = ('failure', 'cancelled', 'timed_out') # Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. TOLERATED_FAILURES = ('Trim the cache entry to this build',) @@ -85,11 +91,28 @@ def save_finished(job): return job.get('status') == 'completed' or (step is not None and step['status'] == 'completed') -def gave_up(job, now, began): - """True once GIVE_UP_SECONDS have passed since the warm leg started, or since `began` (this - script's start) while the leg has not started.""" +def started_at(job): + """The warm leg's start time, or None while the leg has not started.""" started = job.get('started_at') if job and job.get('status') in ('in_progress', 'completed') else None - return (now - (parse_time(started) if started else began)).total_seconds() > GIVE_UP_SECONDS + return parse_time(started) if started else None + + +def start_overdue(job, now, began): + """True once START_SECONDS have passed since `began` (this script's start) and the warm leg + has not started.""" + return started_at(job) is None and (now - began).total_seconds() > START_SECONDS + + +def started_late(job, began): + """True when the warm leg started more than START_SECONDS after `began` (this script's start).""" + started = started_at(job) + return started is not None and (started - began).total_seconds() > START_SECONDS + + +def gave_up(job, now): + """True once GIVE_UP_SECONDS have passed since the warm leg started.""" + started = started_at(job) + return started is not None and (now - started).total_seconds() > GIVE_UP_SECONDS def all_caches(fetch): @@ -150,6 +173,9 @@ def main(): while True: jobs = gh(jobs_url) or {} job = warm_job(jobs.get('jobs', [])) + if started_late(job, began): + print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') + return 1 if job and saving(job): break if job is None: @@ -171,7 +197,11 @@ def main(): return 1 print('the cache warm leg finished without a save step; nothing deleted') return - if gave_up(job, datetime.now(timezone.utc), began): + now = datetime.now(timezone.utc) + if start_overdue(job, now, began): + print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') + return 1 + if gave_up(job, now): print('::error::the cache warm leg never reached its save; nothing deleted') return 1 time.sleep(POLL_SECONDS) @@ -190,7 +220,7 @@ def main(): print(result.stderr, end='', file=sys.stderr) return result.returncode while not save_finished(job): - if gave_up(job, datetime.now(timezone.utc), began): + if gave_up(job, datetime.now(timezone.utc)): print(f'::error::{SAVE_LOST}') return 1 time.sleep(POLL_SECONDS)