Merge main into fix/brush-options-unchanged-approval-b-verify

This commit is contained in:
dotCooCoo committed 2026-11-28 05:07:36 -08:00
commit 3d06a3caad
109 files changed
+4362 -403

No files matched your search

+5 -4
View File
@@ -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:
+9
View File
@@ -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.
+23 -12
View File
@@ -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<std::path::Path> 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<Candidate> {
/// 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"",
-14
View File
@@ -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;
+83 -10
View File
@@ -16,12 +16,38 @@ static SESSION: Mutex<Option<Session>> = 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<u8>,
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<Option<Self>> {
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<bool> {
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<Self> {
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();
+2
View File
@@ -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");
+27 -2
View File
@@ -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();
+110 -20
View File
@@ -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<bool> = 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<T>(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<NodeI
// The locks first: they copy the kept art boxes that `symbols` takes, and `symbols` keeps theirs.
let locks = doc.locked_artboards_kept();
let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols);
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
}
if !objects_at_layer(layer, p, opt, &symbols, &mut tops, &mut seen) {
// An envelope in Edit Contents may expose objects *within* a top-level group.
// The repeated traversal handles that mixed hierarchy precisely. The objects found
// so far lie above the envelope and stay first; the repeated traversal finds the
// rest with what is left of the limit of symbol art to walk.
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
break;
// As [`hit_test`] does: the objects hit by what they paint first, then those hit only inside
// an unfilled closed path ([`HitOptions::unfilled_interiors`]).
let painted = HitOptions { unfilled_interiors: false, ..opt };
let interiors = opt.unfilled_interiors && !opt.path_only && !opt.outline;
'passes: for pass in [Some(painted), interiors.then_some(opt)].into_iter().flatten() {
for layer in doc.layers.iter().rev() {
if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) {
continue;
}
if !objects_at_layer(layer, p, pass, &symbols, &mut tops, &mut seen) {
// An envelope in Edit Contents may expose objects *within* a top-level group.
// The repeated traversal handles that mixed hierarchy precisely. The objects found
// so far lie above the envelope and stay first; the repeated traversal finds the
// rest with what is left of the limit of symbol art to walk.
tops = objects_at_repeated_after(doc, p, opt, scope, tops);
break 'passes;
}
}
}
// The objects on a locked artboard can't be selected, as `hit_test_skipping` passes over them.
@@ -980,7 +1016,18 @@ fn object_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, editab
/// `editable_only` over the objects of layers and sublayers on a locked artboard, and over all of
/// an isolated group on one ([`crate::LockedArtboards::holds`]). Symbol instances are measured by their art
/// ([`Node::geometric_bounds_with`]), and are also hit outside that box where their art paints.
/// With [`HitOptions::unfilled_interiors`], a second walk looks inside the unfilled closed paths
/// only when the first, without it, hits nothing.
fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(NodeId) -> bool, editable_only: bool) -> Option<Hit> {
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<Hit> {
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<Item = &'a PathData>, 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<Vec<u32>> {
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.
+163
View File
@@ -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<Point> = 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,
};
+43 -1
View File
@@ -380,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>;
static LOADER: OnceLock<Loader> = OnceLock::new();
std::thread_local! {
/// Open checks use previews rather than loading placed documents for drawing.
static PREVIEWS_ONLY: std::cell::Cell<bool> = 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<T>(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<Vec<u8>>) -> Option<Arc<ReadDocument>> {
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]
+2 -1
View File
@@ -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.
+155 -32
View File
@@ -333,11 +333,18 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec<A
}
/// Pieces of curve that one Smooth drag measures against the drag while it searches the segments
/// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach,
/// each of which gets at least one: enough to search 300,000 pt of curve within the default reach
/// of the drag.
/// under it ([`reach_samples`]), besides the whole of each curved segment, which is measured once
/// however many there are: a drag measures no more than this many pieces plus one for each curved
/// segment of the paths it searches. Shared equally by the curved segments that come within its
/// reach, it is enough to search 300,000 pt of curve within the default reach of the drag.
const MAX_REACH_PIECES: usize = 1 << 17;
#[cfg(test)]
thread_local! {
/// Tests: how many pieces of curve [`reach_samples`] measured against a drag on this thread.
static PIECES_MEASURED: std::cell::Cell<usize> = 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<bool>) {
/// 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<bool>) {
let (pts, radius) = (reach.pts, reach.radius);
let n = sp.anchors.len();
let marked: Vec<bool> = 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<SubPath> {
/// 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<SubPath> {
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<Value> {
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<SubPath> = 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<Point> = (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<Anchor> = 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::<Vec<_>>());
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::<Vec<_>>());
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()
);
}
}
}
+32 -7
View File
@@ -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<usize> = 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<super::fonts::UsedFont> {
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<super::fonts::UsedFont> {
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::<String, Copied>::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::<String, PlacedPages>::new();
let linked_files = |doc: &Document| match lookup {
+34 -1
View File
@@ -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<usize> = 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<Self> {
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<Node>, clip: Option<Rect>) -> Node {
let mut children: Vec<Arc<Node>> = nodes.into_iter().map(Arc::new).collect();
@@ -234,11 +256,22 @@ fn group(nodes: Vec<Node>, clip: Option<Rect>) -> 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<usize> = 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<Vec<u8>> {
+2 -1
View File
@@ -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
+76
View File
@@ -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 {
+121
View File
@@ -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, &copy);
std::fs::remove_file(dir.file("src/shape.eps")).unwrap();
open(&mut s, &copy);
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");
+4 -1
View File
@@ -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"));
+6
View File
@@ -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]
+37
View File
@@ -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<Value = String> {
"\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",
+2 -1
View File
@@ -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]
+6
View File
@@ -280,6 +280,12 @@ pub fn page(bytes: &[u8]) -> Result<Rect, String> {
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<Imported, String> {
+4 -4
View File
@@ -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;
+85 -34
View File
@@ -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<TypedEnvelope>,
pub(super) checks: usize,
pub(super) spent: Spent,
pub(super) page: Option<Rect>,
/// The pages the art may be compared with, each with its own share of the budget ([`Spent`]).
pub(super) pages: Vec<Rect>,
/// [`super::Structure::type_clips`]: type in an envelope's contents clips its clipping group too.
pub(super) type_clips: HashMap<NodeId, NodeId>,
/// 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<Rect> = 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<NodeId>,
restyled: &mut Vec<Rect>,
) -> 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<Rect>, 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<Rect>, 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<Rect>, layer: NodeId, shared: &Shared<'_>, page: Option<Rect>, spent: &mut Spent) -> bool {
fn alike_within(live: &Node, drawn: &Node, reach: Option<Rect>, 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<Rect>, 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 }))))
+41 -7
View File
@@ -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<PlacedPage>,
/// Included EPS files whose previews wait for variable binding before conversion.
pub placed_eps: Vec<PlacedEps>,
/// 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<String, f64>,
}
/// 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<Affine>, usize, Option<Rect>, Option<Rect>);
struct Reader<'a> {
lex: Lexer<'a>,
stack: Vec<V>,
@@ -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<PlacedPage>,
/// See [`Structure::placed_eps`].
placed_eps: Vec<PlacedEps>,
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));
}
}
}
+263 -7
View File
@@ -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<Vec<String>>)>;
/// 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<usize> = 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<EpsChecks> = 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<Self> {
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<Vec<String>> {
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<u8>, folder: Option<String>, 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<u8> {
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<Rect> {
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<u8> {
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");
}
}
+3 -3
View File
@@ -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);
+35 -7
View File
@@ -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<Affine>, artboards: &[AiArtboard], first: Option<Rect>, art_box: Option<Rect>) -> Vec<Rect> {
let Some(to_doc) = to_doc else { return vec![] };
let boards: Vec<Rect> = if artboards.is_empty() { first.into_iter().collect() } else { artboards.iter().map(|b| b.rect).collect() };
let mut pages: Vec<Rect> = 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<f64> {
@@ -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<Rect> {
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,
},
+16
View File
@@ -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<u64> = 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<NodeId, Vec<usize>
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 });
}
+52 -11
View File
@@ -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<u64> = 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<u64> = 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<V> = 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<Rect>,
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
+22 -1
View File
@@ -312,6 +312,9 @@ pub(super) struct Place {
pub(super) folder: Option<String>,
/// The operand stack's height at `%AI28_BeginPlacedRelativePath`, until its end.
pub(super) folder_at: Option<usize>,
/// The file's bytes, when the data includes them between `%%BeginDocument:` and
/// `%%EndDocument` (at most [`MAX_PLACED_DOCUMENT`]).
pub(super) document: Option<Vec<u8>>,
/// 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
+291 -30
View File
@@ -12,7 +12,9 @@ use super::*;
/// [`super::read`] as an EPS reads it.
fn read(data: &[u8]) -> Result<Structure, String> {
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<u8> {
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<u8> {
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<u8> {
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", &section);
// 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}");
}
}
+19 -8
View File
@@ -38,6 +38,12 @@ struct Gathered {
chars: HashMap<char, usize>,
}
#[cfg(test)]
thread_local! {
/// How many glyphs [`FileFontGlyphs::fits`] has compared with another glyph on this thread.
static COMPARED: std::cell::Cell<u64> = 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<char, &FileGlyph> = 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");
}
}
+2
View File
@@ -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)]
+32 -13
View File
@@ -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<NodeId, ai::PlacedPage> = 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<NodeId, &ai::PlacedEps> = 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<NodeId, ai::PlacedPage>) {
fn to_placed_documents(
n: &mut Node,
pages: &std::collections::HashMap<NodeId, ai::PlacedPage>,
eps: &std::collections::HashMap<NodeId, &ai::PlacedEps>,
images: &mut std::collections::BTreeMap<String, vectorcraft_doc::ImageBlob>,
) {
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<NodeId, a
n.kind = NodeKind::PlacedDocument(Box::new(placed));
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
to_placed_documents(Arc::make_mut(&mut m.art), pages);
to_placed_documents(Arc::make_mut(&mut m.art), pages, eps, images);
}
for c in n.children_mut().into_iter().flatten() {
to_placed_documents(Arc::make_mut(c), pages);
to_placed_documents(Arc::make_mut(c), pages, eps, images);
}
}
@@ -1905,11 +1923,12 @@ fn outside_placed_files(objects: &[Vec<Arc<Node>>], 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<Node>], out: &mut Vec<Rect>) {
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);
+38 -3
View File
@@ -56,6 +56,19 @@ fn tree(nodes: &[Arc<Node>]) -> String {
nodes.iter().map(one).collect::<Vec<_>>().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<String>) {
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
+113
View File
@@ -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
+12
View File
@@ -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<usize> = 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 {
+4 -3
View File
@@ -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<Value> {
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))
}
+2 -1
View File
@@ -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, <https://262.ecma-international.org/11.0/#sec-promise-objects>): the constructor, `then`,
+28
View File
@@ -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");
+28 -13
View File
@@ -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) {
+26
View File
@@ -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::<Value>(&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::<Value>(&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();
+3
View File
@@ -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<Rect> {
// 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
+6 -10
View File
@@ -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),
}
}
@@ -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
+272 -12
View File
@@ -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<Pick>,
hover: Option<Pick>,
press: Option<Press>,
@@ -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<Pick> {
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<CubicBez> {
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<CubicBez> {
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<CubicBez> {
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<CubicBez> {
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<Point> {
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<CubicBez> {
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<Place> {
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::<Vec<_>>(),
"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<bool> {
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<CubicBez> = p.get("second")?.as_array()?.iter().map(curve_of).collect::<Option<_>>()?;
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<Value> {
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<CubicBez> = p.get("second")?.as_array().filter(|s| (1..=3).contains(&s.len()))?.iter().map(curve_of).collect::<Option<_>>()?;
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, &params["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();
+6 -2
View File
@@ -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() }
}
}
+29
View File
@@ -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.
+74
View File
@@ -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");
}
+91 -34
View File
@@ -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<Leave> {
/// 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<NodeId, usize>) {
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<NodeId> {
// 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<NodeId> = 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<NodeId> {
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 {
+112 -2
View File
@@ -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:?})");
}
}
+3 -2
View File
@@ -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);
+5 -1
View File
@@ -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"]),
+3
View File
@@ -34,6 +34,8 @@ pub(crate) struct Spec {
pub(crate) struct AddonDialogs {
open: Option<Open>,
preview: LivePreview,
/// The open Tangent Circle Tool radius dialog.
pub(crate) tangent_radius: Option<super::pathtools::tangent_circle_radius::Open>,
}
#[derive(Clone, Copy)]
@@ -105,6 +107,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option<Resul
/// by type: two hosted parameter dialogs would take each other's answers.
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
pump_commit(app);
super::pathtools::tangent_circle_radius::pump(app, ctx);
super::color::nearest::pump(app, ctx);
super::select::pump(app, ctx);
super::select::link_status::pump(app, ctx);
+6 -2
View File
@@ -3,8 +3,9 @@
//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle…, Add Bounding Circle… and Add Inscribed Circle; the Anchor Inspector panel (the selected
//! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values,
//! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel
//! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and
//! `tool.setOption`.
//! ([`shape`]); its tools' options dialog (a double-click on the tool); and the Tangent Circle Tool's radius dialog
//! ([`tangent_circle_radius`]). Everything acts through `addon.pathtools.*` and `tool.setOption`, except that the radius
//! dialog draws its circle with `shape.circleThroughPoints`.
pub mod bridge;
pub mod corner;
@@ -13,6 +14,7 @@ pub mod set_corners;
pub mod shape;
pub mod shared_edge;
pub mod tangent_circle;
pub mod tangent_circle_radius;
use craft::behavior::ColumnWidth;
use craft::menu::Node;
@@ -317,6 +319,8 @@ fn options_params(tool: &str, lengths: LengthUnits) -> Vec<Param> {
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);
@@ -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<u64>,
/// The radius the circle was last looked for at, and the circle's parameters for [`DRAW`] (`None`: no circle).
tried: Option<(f64, Option<Value>)>,
/// 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<String>,
preview: LivePreview,
/// The document that was active when the preview last ran (`DocState::uid`).
shown_in: Option<u64>,
}
/// 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::<HostedParamDialog>(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<dyn FnOnce(&mut VectorcraftApp)> = 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<u64> {
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<f64, String> {
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<String> {
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::<HostedParamDialog>(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::<HostedParamDialog>(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<String> {
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<u64>| 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::<Vec<_>>());
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}");
}
}
}
+12 -6
View File
@@ -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 {
+287 -4
View File
@@ -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<vectorcraft_doc::NodeId>)>,
opening: Map<String, Value>,
latest: Value,
}
fn shape_target(app: &VectorcraftApp) -> Option<(u64, u64, Vec<vectorcraft_doc::NodeId>)> {
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<Option<f64>>,
mut apply: impl FnMut(&mut VectorcraftApp, &Option<f64>, 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::<ShapeToolGesture>(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::<ShapeToolGesture>(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;
+6 -3
View File
@@ -218,10 +218,13 @@ pub(super) fn hit_at(app: &VectorcraftApp, p: Point, zoom: f64) -> Option<vector
/// The topmost editable object under document point `p` at `zoom`, as the selection tools pick
/// it: [`hit_at`], and a clipping path on its outline before the art it clips
/// ([`vectorcraft_doc::hit::HitOptions::clip_outlines`]). Object Highlighting and a right-click's
/// selection show and take what a click of those tools would.
/// ([`vectorcraft_doc::hit::HitOptions::clip_outlines`]), and an unfilled closed path inside where
/// nothing else is hit ([`vectorcraft_doc::hit::HitOptions::unfilled_interiors`]). Object
/// Highlighting and a right-click's selection show and take what a click of those tools would.
pub(super) fn selection_hit_at(app: &VectorcraftApp, p: Point, zoom: f64) -> Option<vectorcraft_doc::hit::Hit> {
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
+107 -8
View File
@@ -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<Corner
(!corners.is_empty()).then(|| CornerTarget::new(id.0, corners, individual))
}
/// The Live Corners widgets `tool` shows at `zoom`: Selection and the shape tools on a live rectangle or polygon
/// while Show Shape Widgets is on, Direct Selection on any path, within the Hide Corner Widget angle. `tool` is the
/// tool whose widgets the canvas shows ([`super::shown_tool`]).
fn shown_corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option<vectorcraft_tools::corners::CornerWidgets> {
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<Corner
// PLAN: the decision's `(.., f64)` is dropped: the corners listed are already those within the angle, so no
// angle is left to hand on.
pub(super) fn corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option<Vec<(DataColor, Vec<CornerTarget>)>> {
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<usize>)> = 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<Vec
Some(groups)
}
/// The cut of the corner whose Live Corners widget is on show within 5 screen points of `at` (the distance at which
/// a press picks the widget), with its layer colour: what the canvas highlights under the pointer. `None` while the
/// tool is busy or a mouse button is down (`button_down`; a pan drag leaves the tool idle), away from the widgets,
/// and for a square corner, which has no cut. `tool` is the tool whose widgets the canvas shows.
pub(super) fn corner_hover(
app: &VectorcraftApp,
tool: &str,
zoom: f64,
at: Option<vectorcraft_geom::Point>,
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);
}
@@ -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] {
+4
View File
@@ -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:?}");
+40 -3
View File
@@ -307,9 +307,7 @@ impl ActionDialog for BatchDialog {
/// A row that picks one of `entries` for `value`.
fn select_row<T: Copy + Eq + Hash + std::fmt::Debug + Send + Sync + 'static>(ui: &mut Ui, name: &str, value: &mut T, entries: &[Entry<T>]) {
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<ActionStep>) -> 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::<BatchDialog>().unwrap().fields().clone());
let is_open = |panel: &Panel| panel.app().dialogs().unwrap().with(|host| host.is_open::<BatchDialog>());
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();
+142 -7
View File
@@ -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<PropertyRow> {
fn language_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut CustomContext) -> egui::Response {
let languages: Vec<Entry<String>> = 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::<String>());
@@ -581,15 +581,18 @@ fn color(mode: ColorMode) -> Vec<PropertyRow> {
#[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<String, Value> {
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::<String>()));
assert_eq!(values["quotes.single"], json!(quotes.single.iter().collect::<String>()));
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;
@@ -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 [
+2
View File
@@ -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),
_ => {}
+2
View File
@@ -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 изберете два или три пътя или съставни пътя
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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 επιλέξτε δύο ή τρεις διαδρομές ή σύνθετες διαδρομές
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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 લક્ષ્ય
Can't render this file because it contains an unexpected character in line 72 and column 5.
+2
View File
@@ -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 लक्ष्य
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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 つ選択してください
Can't render this file because it is too large.
+2
View File
@@ -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 მონიშნეთ ორი ან სამი ტრაექტორია ან შედგენილი ტრაექტორია
Can't render this file because it is too large.
+2
View File
@@ -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 패스나 컴파운드 패스를 두 개 또는 세 개 선택하세요
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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 выделите два или три контура или составных контура
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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 виділіть два або три контури чи складені контури
Can't render this file because it is too large.
+2
View File
@@ -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
Can't render this file because it is too large.
+2
View File
@@ -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 请选择两个或三个路径或复合路径
Can't render this file because it is too large.
+2
View File
@@ -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 請選取兩個或三個路徑或複合路徑
Can't render this file because it is too large.
+13 -25
View File
@@ -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<String> = 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");
}
}
+3 -2
View File
@@ -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<CornerKind>, entries: &[Entry<CornerKind>]) -> Option<CornerKind> {
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
@@ -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();
+7 -4
View File
@@ -97,10 +97,13 @@ pub(crate) fn copy_shown(ui: &mut Ui, shown: &egui::Response, value: &str) -> bo
None => d.remove::<egui::Pos2>(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
+4
View File
@@ -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")] {
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more