From 3a617b13243f592ee8cedb7e708db891752d117f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 06:09:05 -0800 Subject: [PATCH 01/46] CI: the cache warm on main builds its five shards in parallel `cargo xtask ci warm` builds only shard GATE_SHARD of GATE_SHARDS when the gate sets them, and every shard when neither is set; one set without the other, a non-number, a count other than the shard count, or a shard out of range is an error. ci.yml turns on the gate's `warm-split`, so main's warm runs as five `cache warm /5` legs and a `cache warm` leg that saves the entry. The cold-cache cleanup waits for the split legs before it times the saving leg's start, and fails when a split leg fails. The cache-prune watch and both jobs' timeouts cover a split leg followed by the saving leg. --- .github/workflows/ci.yml | 23 +++-- scripts/ci-clear-rolling-cache-tests.py | 111 +++++++++++++++++++++++- scripts/ci-clear-rolling-cache.py | 50 +++++++---- xtask/src/main.rs | 30 ++++++- xtask/src/shards.rs | 39 +++++++++ 5 files changed, 222 insertions(+), 31 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e7ae30d3ca..a5aba0515d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,6 +46,9 @@ jobs: test-shards: 5 shard-command: cargo xtask ci shard warm-command: cargo xtask ci warm + # The warm build runs as one `cache warm /5` leg per shard, in parallel (each builds what + # its shard builds), and `cache warm` puts their files into the one entry it saves. + warm-split: true # The dependency cache also keeps the compiled workspace crates and test executables, so a # pull request's shards rebuild only the crates its changes reach. Each main run's `cache # warm` leg saves a rolling entry of its own, every leg restores the newest one, and @@ -61,13 +64,14 @@ jobs: # Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache # budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A # failed prune warns instead of failing the run, and cache-prune.yml prunes again after every - # attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's - # `timeout-minutes`, so the watch outlasts a cold `cache warm` leg. + # attempt, re-runs of failed jobs included. `watch-minutes` is longer than twice the gate's + # `timeout-minutes`, so the watch outlasts a cold `cache warm /5` leg followed by a + # `cache warm` leg. cache-prune: name: cache prune if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' runs-on: ubuntu-24.04 - timeout-minutes: 170 + timeout-minutes: 320 permissions: actions: write steps: @@ -80,7 +84,7 @@ jobs: continue-on-error: true with: watch: true - watch-minutes: 160 + watch-minutes: 310 saving-jobs: | ^gate( / cache warm \(.*\))?$ @@ -90,14 +94,17 @@ jobs: # 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 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. + # free runner, and with `warm-split` after every `cache warm /5` leg. The script suspends its + # start deadline while any split leg is queued or running, then allows 180 minutes from the last + # split completion for the saving leg to start. Without split legs, it allows 180 minutes from + # the script's start. A failed split leg fails this job too. The script then waits up to 160 + # minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the + # script's deadlines expire when split builds or runner waits take too long. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' runs-on: ubuntu-24.04 - timeout-minutes: 290 + timeout-minutes: 360 permissions: actions: write steps: diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index a284579d16..2bb689c5c0 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -36,6 +36,11 @@ def earlier(conclusion): return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}] +def split_job(shard, status, completed_at=None): + return {"name": f"gate / cache warm {shard}/5 (ubuntu-24.04)", "status": status, + "conclusion": "success" if status == "completed" else None, "completed_at": completed_at} + + class SaveStep(unittest.TestCase): def test_the_leg_is_saving_once_its_save_step_starts(self): self.assertFalse(clear.saving(warm_job("in_progress", steps=[("Setup", "completed", "success"), ("Gate", "in_progress", None)]))) @@ -99,6 +104,34 @@ class Deadline(unittest.TestCase): self.assertFalse(clear.started_late(warm_job("queued"), self.began)) self.assertFalse(clear.started_late(None, self.began)) + def test_split_progress_suspends_the_start_deadline(self): + for status in ("queued", "in_progress"): + with self.subTest(status=status): + jobs = [split_job(1, "completed", "2026-11-28T06:00:00Z"), split_job(2, status)] + ready = clear.start_wait_began(jobs, self.began) + self.assertIsNone(ready) + now = self.began + timedelta(seconds=clear.START_SECONDS + 60) + self.assertFalse(clear.start_overdue(None, now, ready)) + self.assertFalse(clear.started_late(warm_job("in_progress", started_at=now.isoformat()), ready)) + + def test_the_last_split_completion_starts_the_wait(self): + jobs = [split_job(1, "completed", "2026-11-28T08:00:00Z"), + split_job(2, "completed", "2026-11-28T07:00:00Z")] + ready = clear.start_wait_began(jobs, self.began) + self.assertEqual(ready, clear.parse_time("2026-11-28T08:00:00Z")) + self.assertFalse(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS), ready)) + self.assertTrue(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS + 1), ready)) + self.assertFalse(clear.started_late(warm_job("in_progress", started_at="2026-11-28T08:01:00Z"), ready)) + late = warm_job("in_progress", started_at=(ready + timedelta(seconds=clear.START_SECONDS + 1)).isoformat()) + self.assertTrue(clear.started_late(late, ready)) + + def test_without_split_legs_the_script_start_starts_the_wait(self): + self.assertEqual(clear.start_wait_began([], self.began), self.began) + self.assertEqual(clear.start_wait_began(ME + [warm_job("queued")], self.began), self.began) + + def test_a_split_completion_without_a_timestamp_does_not_start_the_wait(self): + self.assertIsNone(clear.start_wait_began([split_job(1, "completed")], self.began)) + class Workflow(unittest.TestCase): ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text() @@ -116,10 +149,17 @@ class Workflow(unittest.TestCase): self.fail(f"no timeout-minutes under {job}") def test_the_job_outlasts_the_start_wait_and_the_save_wait(self): - # Five minutes are left for the steps before the script and for the deletion. + # Without split legs, five minutes remain for setup and deletion. spare = self.timeout_minutes("cold-cache-clear") * 60 - clear.START_SECONDS - clear.GIVE_UP_SECONDS self.assertGreaterEqual(spare, 5 * 60) + def test_the_job_allows_both_warm_builds_within_the_hosted_job_limit(self): + # Runner waits and the full start allowance may exceed the 360-minute job limit. + timeout = self.timeout_minutes("cold-cache-clear") + spare = timeout * 60 - self.timeout_minutes("gate") * 60 - clear.GIVE_UP_SECONDS + self.assertGreaterEqual(spare, 5 * 60) + self.assertEqual(timeout, 360) + def test_the_save_wait_outlasts_the_gate(self): self.assertGreater(clear.GIVE_UP_SECONDS, self.timeout_minutes("gate") * 60) @@ -148,6 +188,9 @@ class Jobs(unittest.TestCase): self.assertTrue(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (ubuntu-24.04)", "cancelled")])) self.assertFalse(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (${{ matrix.os }})", "skipped")])) self.assertFalse(clear.legs_stopped([done("gate / test 1/5 (ubuntu-24.04)", "failure")])) + # With warm-split, the saving `cache warm ()` leg also needs every `cache warm /` leg. + self.assertTrue(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "failure")])) + self.assertFalse(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "success")])) class Caches(unittest.TestCase): @@ -184,6 +227,60 @@ class Clock(datetime): return datetime(2026, 11, 28, 4, 0, tzinfo=timezone.utc) +class BeforeSaving(unittest.TestCase): + def run_main(self, polls): + began = Clock.now() + current = began + remaining = iter(polls) + + class PollClock(datetime): + @classmethod + def now(cls, tz=None): + return current + + def gh(url): + nonlocal current + if "/jobs?" in url: + minutes, jobs = next(remaining) + current = began + timedelta(minutes=minutes) + return {"jobs": ME + jobs} + if "/caches?" in url: + return {"actions_caches": []} + return {"run_started_at": began.isoformat()} + + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", gh), mock.patch.object(clear.time, "sleep"), \ + mock.patch.object(clear, "datetime", PollClock), mock.patch.dict(os.environ, env), \ + mock.patch.object(clear.subprocess, "run") as delete, contextlib.redirect_stdout(io.StringIO()): + status = clear.main() + delete.assert_not_called() + return status + + def test_queued_and_running_split_legs_can_outlast_the_original_start_deadline(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + saved = warm_job("completed", "success", [("Post Setup", "completed", "success")], + started_at="2026-11-28T07:50:00Z") + self.assertFalse(self.run_main([ + (181, [split_job(1, "queued")]), + (201, [split_job(1, "in_progress"), warm_job("queued")]), + (220, [done, warm_job("queued")]), + (230, [done, saved]), + ])) + + def test_a_saving_leg_that_never_starts_expires_after_the_last_split_completion(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + self.assertEqual(self.run_main([ + (220, [done, warm_job("queued")]), + (401, [done, warm_job("queued")]), + ]), 1) + + def test_a_late_start_after_split_completion_is_rejected_even_if_already_saving(self): + done = split_job(1, "completed", "2026-11-28T07:40:00Z") + late = warm_job("in_progress", steps=[("Post Setup", "in_progress", None)], + started_at="2026-11-28T10:40:01Z") + self.assertEqual(self.run_main([(401, [done, late])]), 1) + + class AfterDeletion(unittest.TestCase): SAVING = [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)] @@ -222,9 +319,17 @@ class AfterDeletion(unittest.TestCase): canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")]) self.assertEqual(self.run_main(canceled), 1) + def test_a_saving_leg_skipped_after_a_failed_split_warm_leg_fails_this_job(self): + skipped = warm_job("completed", conclusion="skipped") + failed = {"name": "gate / cache warm 2/5 (ubuntu-24.04)", "status": "completed", "conclusion": "failure"} + env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"} + with mock.patch.object(clear, "gh", lambda url: {"jobs": ME + [failed, skipped]}), mock.patch.object(clear.time, "sleep"), \ + mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(clear.main(), 1) + def test_a_leg_that_starts_late_and_saves_deletes_nothing(self): - # Clock.now() is 04:00, so the leg starts 120 minutes 5 seconds after the script. - late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T06:00:05Z") + # Clock.now() is 04:00, so the leg starts 180 minutes 5 seconds after the script. + late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T07:00:05Z") deleted = [] def run(args, **kwargs): diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index 3b913d68f7..fd33ffa4a4 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -16,8 +16,10 @@ save step started saves nothing: its old entries stay, and this exits 1, so "Re- runs it again beside the re-run leg. A save step that is canceled or fails after the old entries were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure in a later post step does not count once the save step has succeeded. This also exits 1 when the -leg has not started START_SECONDS after this script started, and when the leg has not reached its -save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only +leg has not started START_SECONDS after the last split warm leg completed (or after this script +started when there are no split legs). The start deadline does not expire while a split leg is +queued or running. This exits 1 when the leg has not reached its save, or its save has not finished, +GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only when the most recent earlier attempt that lists it reports success and the current attempt lists no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling because reusable-workflow dependencies may still be scheduling it. @@ -33,9 +35,11 @@ import time REF = 'refs/heads/main' WARM_JOB = re.compile(r'^gate / cache warm \(') +SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(') # The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of -# them fails or is canceled, the legs are skipped and no warm leg is listed. -NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') +# them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the +# saving leg also needs every `cache warm /` leg. +NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \(|cache warm \d+/\d+ \()') PRUNE_JOB = 'cache prune' ROLLING = '-gate-crates-' # The gate-setup action's post step, which saves the dependency cache (craft-common-actions @@ -46,12 +50,11 @@ PAGE_SIZE = 100 # Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold # leg that starts late and runs to its limit still reaches its save before this gives up. GIVE_UP_SECONDS = 160 * 60 -# How long the leg may take to start, timed from this script's start: the leg waits for -# `gate / select legs` and then for a runner, which took 44 minutes on a push to main on -# 2026-11-28. The `cold-cache-clear` job's `timeout-minutes` in ci.yml is longer than -# START_SECONDS and GIVE_UP_SECONDS together, so this exits with its own error before the job -# times out. -START_SECONDS = 120 * 60 +# How long the saving leg may take to start after the last split warm leg completed, or after +# this script started when there are no split legs. Queued or running split legs suspend this +# deadline. The `cold-cache-clear` job's 360-minute timeout in ci.yml can end the wait before +# this deadline or GIVE_UP_SECONDS expires when split builds or runner waits take too long. +START_SECONDS = 180 * 60 STOPPED = ('failure', 'cancelled', 'timed_out') # Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. TOLERATED_FAILURES = ('Trim the cache entry to this build',) @@ -97,16 +100,25 @@ def started_at(job): return parse_time(started) if started else None +def start_wait_began(jobs, began): + """The last split warm completion, the script's start without splits, or None while waiting.""" + splits = [j for j in jobs if SPLIT_WARM_JOB.match(j['name'])] + if not splits: + return began + if any(j['status'] != 'completed' or not j.get('completed_at') for j in splits): + return None + return max(parse_time(j['completed_at']) for j in splits) + + def start_overdue(job, now, began): - """True once START_SECONDS have passed since `began` (this script's start) and the warm leg - has not started.""" - return started_at(job) is None and (now - began).total_seconds() > START_SECONDS + """True once START_SECONDS have passed since the start wait began and the leg has not started.""" + return began is not None and started_at(job) is None and (now - began).total_seconds() > START_SECONDS def started_late(job, began): - """True when the warm leg started more than START_SECONDS after `began` (this script's start).""" + """True when the warm leg started more than START_SECONDS after the start wait began.""" started = started_at(job) - return started is not None and (started - began).total_seconds() > START_SECONDS + return began is not None and started is not None and (started - began).total_seconds() > START_SECONDS def gave_up(job, now): @@ -173,7 +185,8 @@ def main(): while True: jobs = gh(jobs_url) or {} job = warm_job(jobs.get('jobs', [])) - if started_late(job, began): + ready = start_wait_began(jobs.get('jobs', []), began) + if started_late(job, ready): print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') return 1 if job and saving(job): @@ -192,13 +205,14 @@ def main(): print('::error::the gate stopped before its cache warm leg started; nothing deleted') return 1 if job and job['status'] == 'completed': - if job.get('conclusion') in STOPPED: + # A saving leg skipped because a leg it needs failed (a `cache warm /` leg). + if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])): print(f'::error::{NO_SAVE}') return 1 print('the cache warm leg finished without a save step; nothing deleted') return now = datetime.now(timezone.utc) - if start_overdue(job, now, began): + if start_overdue(job, now, ready): print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted') return 1 if gave_up(job, now): diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 28f0622914..2af79daea4 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -43,6 +43,7 @@ commands: ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs the tests and doctests of its crates, the last shard the other steps ci warm build what every shard builds, without running it (fills the gate's cache); with + GATE_SHARD of GATE_SHARDS set, only what that shard builds; with CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file shards list the crates each shard tests; fails when a member is in no shard or in two, or builds with other features in its shard than in the whole workspace @@ -354,13 +355,31 @@ fn cmd_ci_shard() -> Result<(), String> { /// features over the packages each command selects). The integration tests are left out: they /// build no dependency that the library tests do not, since both take the crate's dev-dependencies. /// +/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that +/// shard builds: a test shard's tests, or the checks shard's builds. +/// /// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS` /// (xtask/src/cache_units.rs), xtask's own build included. fn cmd_ci_warm() -> Result<(), String> { + let var = |key: &str| match std::env::var(key) { + Ok(value) => Ok(Some(value)), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")), + }; + let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?); + let only = shards::warm_only(shard.as_deref(), count.as_deref())?; cache_units::record_xtask()?; let checked = shards::run()?; + let builds = |i: usize| only.is_none_or(|k| k == i); let mut steps: Vec = Vec::new(); - for shard in checked { + let mut checks = only.is_none(); + for (i, shard) in checked.into_iter().enumerate() { + if !builds(i) { + continue; + } + if shard == shards::Shard::Checks { + checks = true; + } if let shards::Shard::Tests(crates) = shard { steps.push(( "build tests", @@ -372,6 +391,14 @@ fn cmd_ci_warm() -> Result<(), String> { )); } } + if checks { + push_warm_checks(&mut steps); + } + run_steps(&steps) +} + +/// The builds of the checks shard that [`cmd_ci_warm`] runs. +fn push_warm_checks(steps: &mut Vec) { steps.push(( "clippy", Box::new(|| { @@ -395,7 +422,6 @@ fn cmd_ci_warm() -> Result<(), String> { }), )); steps.push(("wasm", Box::new(cmd_wasm))); - run_steps(&steps) } /// Runs `steps` in turn, stopping at the first that fails; the summary names the steps that passed diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index a885619b15..b3519d1f8d 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -214,10 +214,49 @@ pub fn run() -> Result, String> { Ok(shards) } +/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's +/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one, +/// a value that is not a number, a count other than the number of shards, or a shard out of range +/// is an error. +pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result, String> { + let (shard, count) = match (shard, count) { + (None, None) => return Ok(None), + (Some(shard), Some(count)) => (shard, count), + _ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()), + }; + let number = + |key: &str, value: &str| -> Result { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) }; + let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?); + if count != GROUPS.len() { + return Err(format!( + "ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)", + GROUPS.len() + )); + } + if !(1..=count).contains(&shard) { + return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}")); + } + Ok(Some(shard - 1)) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn warm_builds_every_shard_unless_the_gate_names_one() { + let n = GROUPS.len().to_string(); + assert_eq!(warm_only(None, None), Ok(None)); + assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0))); + assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1))); + for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] { + assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}"); + } + let past = (GROUPS.len() + 1).to_string(); + assert!(warm_only(Some(&past), Some(&n)).is_err()); + assert!(warm_only(Some("1"), Some(&past)).is_err()); + } + fn m(name: &str) -> Member { Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into() } } From 314ee3681e38396520ad27ac9b7e4b77960a145e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 12:57:12 -0800 Subject: [PATCH 02/46] Arrange Tools: Mark Bounds of Each draws corner marks or a rectangle on each selected object's bounds Object > Plug-ins > Arrange Tools > Mark Bounds of Each... runs the new command addon.arrange.markBounds. For each selected object it draws a group of four inward L-shaped corner marks (10 pt legs by default, each at most half the side it runs along) or a rectangle, with no fill and a red 1 pt stroke by default, on the object's geometric or visual bounds. Visual bounds count strokes, brush art and effects as drawn. - Clip groups are measured by their clipping path, other groups by their members together. Guides and objects without bounds, such as empty groups, are skipped; a selection with nothing to mark is an error that makes no undo step. - The marks go directly above their object, or above the outermost clip group or clipping sublayer that holds it, so the mask does not clip them. The run is one undo step and selects the marks. - Out-of-range lengths and weights, unknown styles and bounds, and bad colors are errors; defaults apply only to omitted values. At most 20000 objects are marked at once. - The dialog has Preview; Length is off unless Draw is Corner Marks. - vectorcraft-render gains drawn_bounds_with, drawn_bounds with a shared symbol cache, so a large selection measures each symbol once. Docs: docs/mcp.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/arrange.rs | 9 +- crates/engine/src/cmd/addons/arrange/marks.rs | 147 ++++++++ .../src/cmd/addons/arrange/marks/tests.rs | 336 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 4 + crates/render/src/bounds.rs | 8 +- crates/render/src/lib.rs | 4 +- crates/ui-egui/src/addons/arrange.rs | 31 +- crates/ui-egui/src/addons/arrange/tests.rs | 66 ++++ docs/mcp.md | 4 +- 11 files changed, 603 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/cmd/addons/arrange/marks.rs create mode 100644 crates/engine/src/cmd/addons/arrange/marks/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index d40c33e9e1..aa31ed21ba 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -163,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922). - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). +- 2026-11-29: Mark Bounds of Each joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own inward corner marks, or a rectangle, on its geometric or visual bounds, stroked in the color and weight given, stacked directly above it; clip groups are measured by their clipping path. A dialog with Preview, one undo step (`addon.arrange.markBounds`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index f81d7a599a..43a3e51ada 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -5,9 +5,11 @@ //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the //! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in -//! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection -//! (a view command) are the UI's. +//! that order. Mark Bounds of Each ([`marks`]) draws marks on the bounds of each selected object. +//! Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection (a view +//! command) are the UI's. +pub mod marks; #[cfg(test)] mod tests; @@ -107,6 +109,9 @@ pub fn specs() -> Vec { sort ), ] + .into_iter() + .chain(marks::specs()) + .collect() } /// Exactly two objects are selected (Swap Objects). diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs new file mode 100644 index 0000000000..5e59924827 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -0,0 +1,147 @@ +//! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds +//! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than +//! around the whole selection, stroked in a colour of their own and stacked directly above the +//! object, as one undo step. + +#[cfg(test)] +mod tests; + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{PathData, Point, Rect, SubPath, shapes}; +use vectorcraft_render::drawn_bounds_with; + +use super::super::super::edit::selected_roots; +use super::super::super::object::choice; +use super::super::super::paint::new_color; +use super::super::super::{CommandSpec, bad, cmd, color_param, has_selection}; +use super::{LEAST, LIMIT, MAX_OBJECTS, number_in}; +use crate::{Result, Session}; + +/// The command. +pub const COMMAND: &str = "addon.arrange.markBounds"; +/// The heaviest stroke (pt) the marks take, and the lightest. +const MAX_WEIGHT: f64 = 1000.0; +const MIN_WEIGHT: f64 = 0.01; +/// A side shorter than this (pt) is no side: its marks are drawn as lines along the other one. +const FLAT: f64 = 1e-9; + +pub fn specs() -> Vec { + vec![cmd!( + "addon.arrange.markBounds", + "Mark Bounds of Each", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: colour (\"#ff0000\"; an RGB colour takes the document's colour mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + has_selection, + mark_bounds + )] +} + +/// The four corners of `r`, each with the directions its legs run in (inward), the corners that +/// fall on an earlier one left out. +fn corners(r: Rect) -> Vec<(Point, f64, f64)> { + let mut out: Vec<(Point, f64, f64)> = vec![]; + for (x, y, sx, sy) in [(r.x0, r.y0, 1.0, 1.0), (r.x1, r.y0, -1.0, 1.0), (r.x1, r.y1, -1.0, -1.0), (r.x0, r.y1, 1.0, -1.0)] { + let at = Point::new(x, y); + if out.iter().all(|(p, _, _)| (p.x - at.x).abs() > FLAT || (p.y - at.y).abs() > FLAT) { + out.push((at, sx, sy)); + } + } + out +} + +/// The corner marks of `r` with legs `length` long, each at most half its side: one open path per +/// corner, a line where `r` has no width or no height. +fn corner_paths(r: Rect, length: f64) -> Vec { + let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0)); + corners(r) + .into_iter() + .filter_map(|(p, sx, sy)| { + let across = Point::new(p.x + sx * lx, p.y); + let down = Point::new(p.x, p.y + sy * ly); + let points = match (lx > FLAT, ly > FLAT) { + (true, true) => vec![across, p, down], + (true, false) => vec![across, p], + (false, true) => vec![p, down], + (false, false) => return None, + }; + Some(PathData::single(SubPath::polyline(&points, false))) + }) + .collect() +} + +/// Where the marks of object `id` go: directly above it, or above the outermost clip group or +/// clipping sublayer that holds it at any depth, which would otherwise clip them. A top-level layer +/// with a clipping mask holds its marks too, since nothing lies outside it. +fn anchor(d: &Document, id: NodeId) -> NodeId { + let (mut at, mut outermost) = (id, id); + while let Some(up) = d.parent_of(at) { + if d.node(up).is_some_and(|n| n.clips()) && d.parent_of(up).is_some() { + outermost = up; + } + at = up; + } + outermost +} + +fn mark_bounds(s: &mut Session, p: &Value) -> Result { + const C: &str = COMMAND; + let rectangle = choice(p, C, "style", &["corners", "rectangle"])? == Some("rectangle"); + let visual = choice(p, C, "bounds", &["geometric", "visual"])? == Some("visual"); + let length = number_in(p, "length", 10.0, (LEAST, LIMIT), C)?; + let weight = number_in(p, "weight", 1.0, (MIN_WEIGHT, MAX_WEIGHT), C)?; + let color = new_color(s, p, color_param(p, "color", C)?.unwrap_or(Color::rgb(1.0, 0.0, 0.0))); + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + let symbols = d.symbol_boxes(); + let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len()); + for id in roots { + let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue }; + let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) }; + if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) { + marked.push((anchor(d, id), r)); + } + } + if marked.is_empty() { + return Err(bad(C, "nothing to mark: the selection has no bounds")); + } + let ap = Appearance::basic(Paint::None, Paint::solid(color), weight); + let ids = s.edit("Mark Bounds of Each", |d, sel| { + // Each anchor once, its objects' marks in stacking order from the back. + let mut lists: Vec<(NodeId, Vec)> = vec![]; + let mut at: HashMap = HashMap::new(); + let mut out = Vec::with_capacity(marked.len()); + for (anchor, r) in &marked { + let node = if rectangle { + let mut n = Node::path(d.alloc_id(), shapes::rectangle(*r), ap.clone()); + n.name = Some("Bounds".into()); + n + } else { + let children = corner_paths(*r, length).into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, ap.clone()))).collect(); + let mut g = Node::group(d.alloc_id(), children); + g.name = Some("Corner Marks".into()); + g + }; + out.push(node.id); + let k = *at.entry(*anchor).or_insert_with(|| { + lists.push((*anchor, vec![])); + lists.len() - 1 + }); + if let Some((_, nodes)) = lists.get_mut(k) { + nodes.push(node); + } + } + d.insert_beside(lists, false)?; + sel.set(out.iter().copied()); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "count": ids.len() })) +} diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs new file mode 100644 index 0000000000..c00085c701 --- /dev/null +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -0,0 +1,336 @@ +//! Mark Bounds of Each: the marks each object gets, where they go in the stacking order, how +//! groups, clip groups, strokes and guides are measured, one undo step, and bad params refused. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Node, NodeId}; +use vectorcraft_geom::Rect; + +use super::COMMAND; +use crate::Session; + +/// A new document whose new art has no stroke, so visual and geometric bounds agree. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +/// The ids of the children of `parent`, in stacking order from the back. +fn children(s: &Session, parent: NodeId) -> Vec { + node(s, parent).children().unwrap().iter().map(|n| n.id).collect() +} + +fn parent(s: &Session, id: NodeId) -> NodeId { + s.doc().unwrap().doc.parent_of(id).unwrap() +} + +/// Each path of the mark `id` (a group's members, or the path itself) as its points. +fn lines(s: &Session, id: NodeId) -> Vec> { + let n = node(s, id); + let paths: Vec = match n.children() { + Some(c) => c.iter().map(|c| (**c).clone()).collect(), + None => vec![n], + }; + paths + .iter() + .map(|p| { + let path = p.path_data().unwrap(); + path.subpaths[0].anchors.iter().map(|a| ((a.p.x * 1e6).round() / 1e6, (a.p.y * 1e6).round() / 1e6)).collect() + }) + .collect() +} + +fn near(a: Rect, b: (f64, f64, f64, f64)) -> bool { + [(a.x0, b.0), (a.y0, b.1), (a.x1, b.2), (a.y1, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-6) +} + +fn marks_bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +#[test] +fn each_object_gets_inward_corner_marks_above_it_in_one_step() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 50.0); + let b = rect(&mut s, 200.0, 100.0, 40.0, 40.0); + let layer = parent(&s, a); + select(&mut s, &[a, b]); + let n = steps(&s); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + let marks = ids_of(&r); + assert_eq!((marks.len(), r["count"].as_u64()), (2, Some(2))); + // Directly above each object, not around the selection. + assert_eq!(children(&s, layer), vec![a, marks[0], b, marks[1]]); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), marks, "the marks are selected"); + assert_eq!(node(&s, marks[0]).name.as_deref(), Some("Corner Marks")); + assert_eq!( + lines(&s, marks[0]), + vec![ + vec![(10.0, 0.0), (0.0, 0.0), (0.0, 10.0)], + vec![(90.0, 0.0), (100.0, 0.0), (100.0, 10.0)], + vec![(90.0, 50.0), (100.0, 50.0), (100.0, 40.0)], + vec![(10.0, 50.0), (0.0, 50.0), (0.0, 40.0)], + ] + ); + assert!(near(marks_bounds(&s, marks[1]), (200.0, 100.0, 240.0, 140.0))); + // A red 1 pt stroke and no fill. + let group = node(&s, marks[1]); + let ap = &group.children().unwrap()[0].appearance; + assert_eq!((ap.fill_paint(), ap.stroke_paint(), ap.stroke_width()), (Paint::None, Paint::solid(Color::rgb(1.0, 0.0, 0.0)), 1.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![a, b]); +} + +#[test] +fn length_weight_color_and_the_rectangle_style() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 100.0); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap(); + let marks = ids_of(&r); + // A leg is never longer than half its side, so opposite marks do not meet. + assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]); + let group = node(&s, marks[0]); + let ap = &group.children().unwrap()[0].appearance; + assert_eq!((ap.stroke_paint(), ap.stroke_width()), (Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 2.5)); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let mark = ids_of(&r)[0]; + let rect = node(&s, mark); + assert!(rect.children().is_none() && rect.path_data().unwrap().subpaths[0].closed, "one closed path"); + assert_eq!(rect.name.as_deref(), Some("Bounds")); + assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0))); +} + +#[test] +fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (0.0, 0.0, 20.0, 20.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0])); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (-2.0, -2.0, 22.0, 22.0)), "{:?}", marks_bounds(&s, ids_of(&r)[0])); +} + +#[test] +fn visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out() { + let mut s = session(); + let a = rect(&mut s, 50.0, 50.0, 20.0, 20.0); + select(&mut s, &[a]); + let geometry = marks_bounds(&s, a); + let (dx, dy) = (12.0, 8.0); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null, "params": {"x": dx, "y": dy, "blur": 0}})).unwrap(); + let shadow = Rect::new(geometry.x0 + dx, geometry.y0 + dy, geometry.x1 + dx, geometry.y1 + dy); + let reach = geometry.union(shadow); + let encloses = |r: Rect| r.x0 <= reach.x0 && r.y0 <= reach.y0 && r.x1 >= reach.x1 && r.y1 >= reach.y1; + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap(); + let geometric = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1))); + assert!(!encloses(geometric), "the geometric mark leaves the shadow outside"); + s.execute("edit.undo", &json!({})).unwrap(); + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + let visual = marks_bounds(&s, ids_of(&r)[0]); + assert!(encloses(visual), "the visual mark encloses the artwork and its shadow: {visual:?}"); +} + +#[test] +fn visual_bounds_enclose_brush_art_on_paths_and_in_groups() { + for grouped in [false, true] { + let mut s = session(); + let path = NodeId(s.execute("shape.line", &json!({"x1": 50, "y1": 50, "x2": 150, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[path]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 1})).unwrap(); + s.execute("brush.apply", &json!({"name": "Dots"})).unwrap(); + let target = if grouped { + s.execute("object.group", &json!({})).unwrap(); + parent(&s, path) + } else { + path + }; + select(&mut s, &[target]); + let geometry = marks_bounds(&s, path); + let d = &s.doc().unwrap().doc; + let source = d.node(target).unwrap(); + let painted = vectorcraft_render::painted_bounds(d, source).unwrap(); + let drawn = vectorcraft_render::drawn_bounds(d, source).unwrap(); + let base = vectorcraft_render::effect_bounds(&d.symbol_boxes(), source).unwrap(); + assert!(drawn.y0 < base.y0 && drawn.y1 > base.y1, "brush art reaches past the base stroke: {drawn:?}, {base:?}"); + let encloses = |r: Rect| r.x0 <= drawn.x0 && r.y0 <= drawn.y0 && r.x1 >= drawn.x1 && r.y1 >= drawn.y1; + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "geometric"})).unwrap(); + let geometric = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(geometric, (geometry.x0, geometry.y0, geometry.x1, geometry.y1))); + assert!(!encloses(geometric), "the geometric mark leaves brush art outside"); + s.execute("edit.undo", &json!({})).unwrap(); + + let r = s.execute(COMMAND, &json!({"style": "rectangle", "bounds": "visual"})).unwrap(); + let visual = marks_bounds(&s, ids_of(&r)[0]); + assert!(near(visual, (drawn.x0, drawn.y0, drawn.x1, drawn.y1)), "the visual mark follows the drawn bounds: {visual:?}, {drawn:?}"); + assert!(encloses(visual), "the visual mark encloses the brush art: {visual:?}, {drawn:?}"); + assert!( + visual.x0 > painted.x0 && visual.y0 > painted.y0 && visual.x1 < painted.x1 && visual.y1 < painted.y1, + "the visual mark stays inside the culling margin: {visual:?}, {painted:?}" + ); + } +} + +#[test] +fn groups_by_their_members_and_clip_groups_by_the_clipping_path() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 50.0, 30.0, 10.0, 10.0); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let group = parent(&s, a); + let art = rect(&mut s, 100.0, 100.0, 200.0, 150.0); + let clip = rect(&mut s, 150.0, 120.0, 50.0, 40.0); + select(&mut s, &[art, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clip_group = parent(&s, art); + let layer = parent(&s, group); + select(&mut s, &[group, clip_group]); + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + let marks = ids_of(&r); + assert!(near(marks_bounds(&s, marks[0]), (0.0, 0.0, 60.0, 40.0)), "the members together"); + assert!(near(marks_bounds(&s, marks[1]), (150.0, 120.0, 200.0, 160.0)), "the clipping path"); + assert_eq!(children(&s, layer), vec![group, marks[0], clip_group, marks[1]]); + s.execute("edit.undo", &json!({})).unwrap(); + // An object inside the clip group: its marks go above the clip group, where it does not hide them. + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + assert_eq!(children(&s, layer), vec![group, clip_group, mark]); + assert!(near(marks_bounds(&s, mark), (100.0, 100.0, 300.0, 250.0)), "the object's own bounds"); + s.execute("edit.undo", &json!({})).unwrap(); + // And when a plain group lies between the object and the clip group. + select(&mut s, &[art]); + s.execute("object.group", &json!({})).unwrap(); + let inner = parent(&s, art); + let clip_group = parent(&s, clip); + assert_eq!(parent(&s, inner), clip_group); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(children(&s, layer), vec![group, clip_group, ids_of(&r)[0]]); +} + +#[test] +fn marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer() { + let mut s = session(); + let top = s.doc().unwrap().current_layer().unwrap(); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap()); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(children(&s, top), vec![sub, ids_of(&r)[0]], "above the clipping sublayer"); + + // A clipping top-level layer has nothing outside it to hold them: they go above the object. + let mut s = session(); + let top = s.doc().unwrap().current_layer().unwrap(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": top.0})).unwrap()["clip"].as_bool().unwrap()); + select(&mut s, &[art]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + let mark = ids_of(&r)[0]; + let stack = children(&s, top); + assert_eq!(stack.iter().position(|id| *id == mark), stack.iter().position(|id| *id == art).map(|i| i + 1), "{stack:?}"); +} + +#[test] +fn flat_objects_get_lines_and_guides_and_empty_groups_none() { + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 100, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[line]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + // No height: one mark at each end, along the line. + assert_eq!(lines(&s, ids_of(&r)[0]), vec![vec![(10.0, 50.0), (0.0, 50.0)], vec![(90.0, 50.0), (100.0, 50.0)]]); + s.execute("edit.undo", &json!({})).unwrap(); + + let guide = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[guide]); + s.execute("view.guides.make", &json!({})).unwrap(); + select(&mut s, &[guide]); + let layer = s.doc().unwrap().target_parent().unwrap(); + let empty = s + .edit("test", |d, _| { + let g = Node::group(d.alloc_id(), vec![]); + let id = g.id; + d.insert(layer, usize::MAX, g)?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[guide, empty]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("nothing to mark"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); + // With a real object as well, only it gets marks. + let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[guide, empty, a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); +} + +#[test] +fn bad_params_are_refused_and_it_is_off_without_a_selection() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 10.0); + select(&mut s, &[a]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + for p in [ + json!({"style": "cross"}), + json!({"bounds": "preview"}), + json!({"length": 0}), + json!({"length": 1e7}), + json!({"length": "10"}), + json!({"weight": 0}), + json!({"weight": 1001}), + json!({"color": "not a color"}), + json!({"color": "#ff000080"}), + json!({"color": 3}), + ] { + assert!(s.execute(COMMAND, &p).is_err(), "{p}"); + } + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.commands().into_iter().find(|c| c.id == COMMAND).unwrap().enabled); + assert!(s.execute(COMMAND, &json!({})).is_err()); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 783f971487..ab7f1b12dc 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -6,6 +6,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.arrange.grid", "addon.arrange.groupOverlapping", + "addon.arrange.markBounds", "addon.arrange.randomizeOpacity", "addon.arrange.replace", "addon.arrange.size", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..007a78962a 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1009,6 +1009,10 @@ fn structured_junk() { ("addon.arrange.sort", json!({"by": "opacity", "apply": "y", "order": "descending", "ids": [u64::MAX]})), ("addon.arrange.sort", json!({"by": "x", "apply": "opacity", "distribute": true, "seed": 1e308, "ids": []})), ("addon.arrange.sort", json!({"by": "nope", "apply": null, "order": 3, "distribute": "x"})), + ("addon.arrange.markBounds", json!({"style": "rectangle", "bounds": "visual", "weight": 1000, "color": "cmyk 0 100 100 0"})), + ("addon.arrange.markBounds", json!({"length": 1e6, "weight": 0.01, "color": [0, 0, 1]})), + ("addon.arrange.markBounds", json!({"length": f64::MAX, "weight": -1, "color": "#ff000080", "style": 3})), + ("addon.arrange.markBounds", json!({"length": 1e-308, "bounds": "nope", "color": {"swatch": 1}})), ("addon.pathtools.divideDashes", json!({"dash": 1e-308, "gap": -1e308, "fit": "x"})), ("addon.pathtools.divideDashes", json!({"dash": 0.01, "gap": 1e6, "fit": true, "removeGaps": false})), ("addon.pathtools.divideDashes", json!({"dash": f64::MAX, "gap": [0], "removeGaps": null})), diff --git a/crates/render/src/bounds.rs b/crates/render/src/bounds.rs index fafb1b188f..299d6d627a 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -61,7 +61,13 @@ pub(crate) fn effect_bounds_with( /// reach of its own and its members' raster effects, measured as [`Node::visual_bounds_with`] /// measures art without effects: what Object › Rasterize makes its image over. pub fn drawn_bounds(doc: &Document, n: &Node) -> Option { - fx::painted_reach(&doc.symbol_boxes(), n) + drawn_bounds_with(&doc.symbol_boxes(), n) +} + +/// [`drawn_bounds`] with symbol instances measured by their art in `symbols` (made with +/// [`Document::symbol_boxes`]). +pub fn drawn_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option { + fx::painted_reach(symbols, n) } /// For a path or compound path whose own Rasterize effect is followed by Transform effects that diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 457c4c48c8..544438d96f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -294,7 +294,9 @@ mod renderer; mod text_geom; mod threads; -pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage}; +pub use bounds::{ + drawn_bounds, drawn_bounds_with, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage, +}; pub use frame::FrameStats; use frame::{ ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index a26f5f7a28..0b3b2c1ed3 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,6 +1,6 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, -//! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping +//! Arrange in Grid, Replace with Top Object, Set Size of Each, Randomize Opacity, Sort Objects and +//! Mark Bounds of Each, which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping //! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. use std::borrow::Cow; @@ -26,14 +26,19 @@ const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; +const MARKS: &str = "addon.arrange.markBounds"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 5] = [ +const DIALOGS: [(&str, &str); 6] = [ (GRID, "Arrange in Grid"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), + (MARKS, "Mark Bounds of Each"), ]; +/// The mark lengths (pt) Mark Bounds of Each takes, and its stroke weights. +const MARK_LENGTHS: std::ops::RangeInclusive = 0.001..=1e6; +const WEIGHTS: std::ops::RangeInclusive = 0.01..=1000.0; /// The widths and heights Set Size of Each takes (pt), and the gaps Arrange in Grid takes. const SIZES: std::ops::RangeInclusive = 0.001..=1e6; const GAPS: std::ops::RangeInclusive = -1e6..=1e6; @@ -63,6 +68,7 @@ pub fn menu() -> Vec { cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), + c("Mark Bounds of Each…", MARKS), Sep, cp("Zoom to Selection", ZOOM, json!({})), ] @@ -73,6 +79,7 @@ static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, fou static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; +static MARKS_SPEC: Spec = Spec { command: MARKS, params: marks_params, found: None }; /// The dialog over `rows`, titled by the heading of `command`. fn dialog<'a>(command: &str, rows: Vec) -> ParamDialog<'a> { @@ -152,6 +159,22 @@ fn sort_rows() -> Vec { ] } +fn marks_rows(lengths: LengthUnits) -> Vec { + let styles = [("corners", "Corner Marks"), ("rectangle", "Rectangle")]; + let bounds = [("geometric", "Geometric Bounds"), ("visual", "Visual Bounds")]; + vec![ + choice("style", "Draw:", &styles, "corners"), + choice("bounds", "Bounds:", &bounds, "geometric"), + length("length", "Length:", 10.0, MARK_LENGTHS, lengths).enabled_when("style", "corners"), + Param::number("weight", tl!("Weight:"), 1.0, 0.25, 2).bounds(Some(*WEIGHTS.start()), Some(*WEIGHTS.end())).unit(UnitKind::Points), + Param::new("color", tl!("Color:"), ParamKind::color(Some([1.0, 0.0, 0.0]))), + ] +} + +fn marks_params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&marks_rows(POINTS), fields)) +} + fn grid_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&grid_rows(POINTS), fields)) } @@ -207,6 +230,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option (marks_rows(lengths), json!({ "style": "corners", "bounds": "geometric", "length": 10, "weight": 1, "color": "#ff0000" })), // The first selected object's size, as the command measures it (a side it lacks: the least). _ => { let (w, h) = st.selection.objects.first().and_then(|id| app.session.transform_box(&[*id])).map_or((100.0, 100.0), |b| { @@ -229,6 +253,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).values(Bind::bound(fields))), + MARKS => super::dialogs::open(app, &MARKS_SPEC, fields, move |fields| dialog(MARKS, marks_rows(lengths)).values(Bind::bound(fields))), _ => super::dialogs::open(app, &SIZE_SPEC, fields, move |fields| { let either = fields.bool("widthOn").unwrap_or(true) || fields.bool("heightOn").unwrap_or(true); dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields)) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 420bfdb01d..a56791df55 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -162,3 +162,69 @@ fn zoom_to_selection_fits_the_selection_in_the_view() { assert!(!menus::enabled(&app, ZOOM)); assert!(app.run(ZOOM, json!({})).is_err()); } + +/// The objects of the first layer, from the back. +fn layer(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +/// The points of the first corner mark in the marks group `id`. +fn first_mark(app: &VectorcraftApp, id: NodeId) -> Vec<(f64, f64)> { + let doc = &app.session.doc().unwrap().doc; + let mark = &doc.node(id).unwrap().children().unwrap()[0]; + mark.path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect() +} + +fn steps(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +#[test] +fn real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them() { + let (app, a, b) = app(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + let before = steps(&panel.app()); + click(&mut panel.app(), "Mark Bounds of Each…"); + type_number(&mut panel, "Length", "4"); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.number("length")), Some(4.0)); + // The preview: corner marks directly above each rectangle, their legs 4 pt long. + let preview = layer(&panel.app()); + assert_eq!((preview.len(), preview[0], preview[2]), (4, a, b), "{preview:?}"); + assert_eq!(first_mark(&panel.app(), preview[1]), vec![(4.0, 0.0), (0.0, 0.0), (0.0, 4.0)]); + panel.click("OK"); + panel.frame(); + { + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(layer(&app), preview); + assert_eq!(steps(&app), before + 1, "one undo step"); + } + panel.app().run("select.set", json!({"ids": [a.0]})).unwrap(); + click(&mut panel.app(), "Mark Bounds of Each…"); + type_number(&mut panel, "Length", "2"); + assert_eq!(layer(&panel.app()).len(), 5, "the preview adds marks above a"); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert_eq!(layer(&app), preview, "Cancel takes the preview away"); + assert_eq!(steps(&app), before + 1); +} + +#[test] +fn mark_bounds_sends_the_dialog_values_to_its_command() { + let (mut app, a, _) = app(); + click(&mut app, "Mark Bounds of Each…"); + let id = host::dialog_id(&app); + let opened = host::read(&app, id, |f| (f.text("style").map(str::to_owned), f.text("bounds").map(str::to_owned), f.number("weight"))); + assert_eq!(opened, (Some("corners".to_owned()), Some("geometric".to_owned()), Some(1.0))); + host::set(&app, id, "style", json!("rectangle")); + host::set(&app, id, "weight", json!(3)); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + let marks = layer(&app); + let doc = &app.session.doc().unwrap().doc; + let rect = doc.node(marks[1]).unwrap(); + assert_eq!((marks[0], rect.name.as_deref(), rect.appearance.stroke_width()), (a, Some("Bounds"), 3.0)); + assert_eq!(rect.geometric_bounds().unwrap(), vectorcraft_geom::Rect::new(0.0, 0.0, 20.0, 10.0)); +} diff --git a/docs/mcp.md b/docs/mcp.md index 7ed0eebae6..bf5a048a9a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17542,12 +17542,14 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | +| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs (`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose -fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. +fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. Mark Bounds of Each… opens a dialog of the +command's parameters with Preview; Length is off unless Draw is Corner Marks. ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} From 9693ce96aac2a7ec6caed6fdb4d89e82b14ee621 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:33:21 -0800 Subject: [PATCH 03/46] Arrange Tools: Group by Row puts each row of the selection in its own group Object > Plug-ins > Arrange Tools > Group by Row... (addon.arrange.groupRows) groups the selected top-level objects by the rows their visual bounds share: an object joins a row when its bounds overlap the row from top to bottom, and Group By Columns does the same from left to right. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard share a row; an object alone in its row stays as it is. Each new group takes its frontmost member's place in the stacking order, and the groups and the objects left alone stay selected. One undo step, none when no row holds two objects; an unknown direction is refused. At most 20000 objects, sorted once along the axis. Group Overlapping Objects and Group by Row share the step that builds the groups. The dialog has Group By (Rows or Columns) with Preview. Docs: docs/mcp.md, docs/ui-parity.md, docs/target-app-parity.md, ROADMAP. --- ROADMAP.md | 1 + crates/engine/src/cmd/addons/arrange.rs | 77 ++++++++- crates/engine/src/cmd/addons/arrange/tests.rs | 154 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 2 + crates/ui-egui/src/addons/arrange.rs | 19 ++- crates/ui-egui/src/addons/arrange/tests.rs | 58 +++++++ docs/mcp.md | 5 +- docs/target-app-parity.md | 4 + docs/ui-parity.md | 1 + 10 files changed, 317 insertions(+), 5 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index c743448b07..4a869f1d36 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -164,6 +164,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-29: Offset Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are chained one after another in a row or a column with a set gap (negative to overlap them), in stacking order or by position, either way; the first stays in place and the others move only along the row or column, as one undo step (`addon.arrange.offset`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-29: Group by Row joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap from top to bottom go into one group for each row (or, by column, from left to right), within their own layer or group and artboard, at the stacking place of their frontmost member; an object alone in its row stays as it is. One undo step, with a previewed dialog (`addon.arrange.groupRows`). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged. diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index a25f341d1c..4274932141 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -4,7 +4,8 @@ //! Replace with Top Object puts a copy of the topmost selected object in place of each of the //! others; and Set Size of Each gives every selected object an exact width and height. Places and //! sizes are measured and set as `object.setBounds` does. Group Overlapping Objects groups the -//! objects whose visual bounds overlap, Randomize Opacity gives each selected object a random +//! objects whose visual bounds overlap, Group by Row groups them by the rows (or columns) their +//! visual bounds share, Randomize Opacity gives each selected object a random //! opacity, and Sort Objects sorts the selected objects by one attribute and gives them another in //! that order. Its submenu (Object › Plug-ins › Arrange Tools), its dialogs and Zoom to Selection //! (a view command) are the UI's. @@ -98,6 +99,15 @@ pub fn specs() -> Vec { has_multi, group_overlapping ), + cmd!( + "addon.arrange.groupRows", + "Group by Row", + ["Object", "Plug-ins", "Arrange Tools"], + None, + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\")} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. An object joins a row when its visual bounds (strokes and effects as drawn; a clipping group by its mask) overlap the row's extent across it; extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row, an object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + has_multi, + group_rows + ), cmd!( "addon.arrange.randomizeOpacity", "Randomize Opacity", @@ -407,11 +417,74 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result { roots.iter().filter_map(|id| Some((*id, (d.parent_of(*id), effects::preview::bounds_of(d, &[*id], true)?)))).collect(); let keyed: Vec<(Option, Rect)> = items.iter().map(|(_, k)| *k).collect(); let sets: Vec> = overlapping(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + group_each(s, "Group Overlapping Objects", &roots, sets) +} + +/// The rows of `items` (each a key and an extent `(start, end)` along the axis across the rows): the sets of +/// two or more (each in the order given) among items of the same key whose extents overlap, chains included. +/// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it +/// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at +/// another's start stays apart from it whatever their order. +fn rows_of(items: &[(K, (f64, f64))]) -> Vec> { + let mut order: Vec = (0..items.len()).collect(); + order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1))); + let mut rows: Vec> = vec![]; + // Each key's open row: its index in `rows` and where it ends. + let mut open: HashMap = HashMap::new(); + for i in order { + let (key, (start, end)) = items[i]; + match open.get_mut(&key) { + Some((row, until)) if start < *until => { + if let Some(r) = rows.get_mut(*row) { + r.push(i); + } + *until = until.max(end); + } + _ => { + open.insert(key, (rows.len(), end)); + rows.push(vec![i]); + } + } + } + rows.retain(|r| r.len() > 1); + for r in &mut rows { + r.sort_unstable(); + } + rows +} + +fn group_rows(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.arrange.groupRows"; + let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row"; + let roots = selected_roots(s)?; + if roots.len() > MAX_OBJECTS { + return Err(bad(C, "too many objects selected (at most 20000)")); + } + let d = &s.doc()?.doc; + // Each object's row key (its parent and its artboard) and its extent across the rows. + type Keyed = ((Option, Option), (f64, f64)); + let items: Vec<(NodeId, Keyed)> = roots + .iter() + .filter_map(|id| { + let b = effects::preview::bounds_of(d, &[*id], true)?; + let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) }; + Some((*id, ((d.parent_of(*id), d.artboard_for_bounds(b)), extent))) + }) + .collect(); + let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect(); + let sets: Vec> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); + group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &roots, sets) +} + +/// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a +/// new group of its own at its frontmost member's place, as undo step `label`, and select the new groups and +/// the objects of `roots` left alone. No step when `sets` is empty. +fn group_each(s: &mut Session, label: &str, roots: &[NodeId], sets: Vec>) -> Result { if sets.is_empty() { return Ok(json!({ "groups": [], "grouped": 0 })); } let grouped: std::collections::HashSet = sets.iter().flatten().copied().collect(); - let groups = s.edit("Group Overlapping Objects", |d, sel| { + let groups = s.edit(label, |d, sel| { // Every group at once: the members behind each front one go, then each front one is // replaced by its group (one pass over the tree each, however many groups). let (mut places, mut behind, mut groups) = (vec![], vec![], vec![]); diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 498a927898..94e43a78d2 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -390,6 +390,7 @@ fn off_without_a_selection() { "addon.arrange.replace", "addon.arrange.size", "addon.arrange.groupOverlapping", + "addon.arrange.groupRows", "addon.arrange.randomizeOpacity", "addon.arrange.sort", ] { @@ -473,6 +474,159 @@ fn group_overlapping_is_off_with_one_object_and_scales_to_many() { assert!(sets.iter().all(|s| s.len() == 2 && s[1] == s[0] + 1)); } +fn layer_children(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn group_rows_groups_each_row_and_leaves_loners() { + let mut s = session(); + // Row one: a and b (y 0 to 12). c only touches it (from y 12), alone in its row. Row two: d and e. + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let d = rect(&mut s, 0.0, 40.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 2.0, 10.0, 10.0); + let c = rect(&mut s, 40.0, 12.0, 10.0, 10.0); + let e = rect(&mut s, 20.0, 45.0, 10.0, 10.0); + select(&mut s, &[a, b, c, d, e]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert_eq!(r["grouped"], json!(4)); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 2); + assert_eq!(children(&s, groups[0]), [a, b], "the top row first, its members in stacking order"); + assert_eq!(children(&s, groups[1]), [d, e]); + // Each group where its frontmost member was: a d b c e → group(ab) at b, c, group(de) at e. + assert_eq!(layer_children(&s), [groups[0], c, groups[1]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&groups[0]) && sel.contains(&groups[1]) && sel.contains(&c) && sel.len() == 3, "{sel:?}"); + assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Row")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(layer_children(&s), [a, d, b, c, e]); +} + +#[test] +fn group_rows_makes_columns_and_joins_rows_an_object_spans() { + let mut s = session(); + // Columns: a and b share x 0 to 15, c stands apart. + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 5.0, 50.0, 10.0, 10.0); + let c = rect(&mut s, 30.0, 0.0, 10.0, 10.0); + select(&mut s, &[a, b, c]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "column"})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, b]); + assert_eq!(s.doc().unwrap().history.undo.last().map(|step| step.label.as_str()), Some("Group by Column")); + // By row, p and q lie in two rows until r, reaching from one to the other, joins them. + let mut s = session(); + let p = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let q = rect(&mut s, 50.0, 20.0, 10.0, 10.0); + select(&mut s, &[p, q]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "two rows of one: no groups, no step"); + let bridge = rect(&mut s, 100.0, 5.0, 10.0, 20.0); + select(&mut s, &[p, q, bridge]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": "row"})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [p, q, bridge]); +} + +#[test] +fn group_rows_keeps_layers_and_artboards_apart_and_measures_visual_bounds() { + let mut s = session(); + s.execute("artboard.new", &json!({"x": 500, "y": 0, "width": 200, "height": 300})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + // Touching a's bottom edge: a row of its own until strokes reach over the edge. + let below = rect(&mut s, 50.0, 20.0, 20.0, 20.0); + let far = rect(&mut s, 550.0, 0.0, 20.0, 20.0); + s.execute("layer.new", &json!({})).unwrap(); + let other = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, below, far, other]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n), "another artboard, another layer, a touching edge: no groups"); + select(&mut s, &[a, below]); + s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + select(&mut s, &[a, below, far, other]); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, below], "the strokes overlap"); + let doc = &s.doc().unwrap().doc; + assert_ne!(doc.parent_of(far), Some(groups[0]), "left on its own artboard"); + assert_ne!(doc.layer_of(other), doc.layer_of(a), "left in its own layer"); +} + +#[test] +fn group_rows_measures_clipping_groups_by_their_mask() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + // A 200 tall object clipped to a 30 tall mask at y 100. + let clipped = rect(&mut s, 50.0, 0.0, 10.0, 200.0); + let mask = rect(&mut s, 40.0, 100.0, 30.0, 30.0); + select(&mut s, &[clipped, mask]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let group = s.doc().unwrap().selection.objects[0]; + let b = rect(&mut s, 100.0, 110.0, 10.0, 10.0); + select(&mut s, &[a, group, b]); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's"); +} + +#[test] +fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + assert!(!enabled(&s, "addon.arrange.groupRows")); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b, c]); + assert!(enabled(&s, "addon.arrange.groupRows")); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true})]); + select(&mut s, &[b]); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(groups.len(), 1); + assert_eq!(children(&s, groups[0]), [a, c], "the locked object stays out"); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id)); +} + +#[test] +fn group_rows_sorts_many_objects_into_rows() { + // 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps, + // neighboring pairs only touch. + let items: Vec<(u8, (f64, f64))> = (0..20_000) + .map(|i| { + let top = (10_000 - i / 2) as f64 * 10.0; + (0, (if i % 2 == 0 { top + 1.0 } else { top }, top + 10.0)) + }) + .collect(); + let rows = super::rows_of(&items); + assert_eq!(rows.len(), 10_000); + assert!(rows.iter().all(|r| r.len() == 2 && r[1] == r[0] + 1), "pairs, in the order given"); + assert_eq!(rows.first(), Some(&vec![19_998, 19_999]), "the top row first"); +} + +#[test] +fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() { + // An extent with no height at the top edge of another only touches it, whichever is in front. + let flat_behind: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (0.0, 10.0))]; + let flat_in_front: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 10.0)), (0, (0.0, 0.0))]; + assert!(super::rows_of(&flat_behind).is_empty()); + assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front)); + // Inside the row, it joins. + assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]); +} + fn opacity(s: &Session, id: NodeId) -> f32 { s.doc().unwrap().doc.node(id).unwrap().opacity } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 75074c6c3c..a0bd0d94b2 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -6,6 +6,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.arrange.grid", "addon.arrange.groupOverlapping", + "addon.arrange.groupRows", "addon.arrange.offset", "addon.arrange.randomizeOpacity", "addon.arrange.replace", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index c98cd9278e..bc72152b5c 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1003,6 +1003,8 @@ fn structured_junk() { ("addon.arrange.size", json!({"width": 1e6, "height": 0.001, "reference": 8, "scaleStrokes": true})), ("addon.arrange.size", json!({"width": 0.001, "proportional": true, "reference": u64::MAX})), ("addon.arrange.groupOverlapping", json!({"ids": "x", "junk": f64::MAX})), + ("addon.arrange.groupRows", json!({"direction": "column"})), + ("addon.arrange.groupRows", json!({"direction": "diagonal", "junk": f64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": 0, "max": 100, "seed": u64::MAX})), ("addon.arrange.randomizeOpacity", json!({"min": f64::MAX, "max": -1e308, "seed": -1, "ids": [u64::MAX]})), ("addon.arrange.randomizeOpacity", json!({"min": 100, "max": 0, "seed": 1e308, "ids": []})), diff --git a/crates/ui-egui/src/addons/arrange.rs b/crates/ui-egui/src/addons/arrange.rs index ccd32bd7aa..44eb168b3b 100644 --- a/crates/ui-egui/src/addons/arrange.rs +++ b/crates/ui-egui/src/addons/arrange.rs @@ -1,5 +1,5 @@ //! Arrange Tools in the interface: its submenu (Object › Plug-ins › Arrange Tools); the dialogs of -//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Randomize Opacity and Sort Objects, +//! Arrange in Grid, Offset Objects, Replace with Top Object, Set Size of Each, Group by Row, Randomize Opacity and Sort Objects, //! which preview on the canvas and run their `addon.arrange.*` command on OK; Group Overlapping //! Objects; and Zoom to Selection ([`ZOOM`]), which fits the active view to the selection. @@ -25,14 +25,16 @@ const GRID: &str = "addon.arrange.grid"; const OFFSET: &str = "addon.arrange.offset"; const REPLACE: &str = "addon.arrange.replace"; const SIZE: &str = "addon.arrange.size"; +const ROWS: &str = "addon.arrange.groupRows"; const OPACITY: &str = "addon.arrange.randomizeOpacity"; const SORT: &str = "addon.arrange.sort"; /// Each dialog's command and heading. -const DIALOGS: [(&str, &str); 6] = [ +const DIALOGS: [(&str, &str); 7] = [ (GRID, "Arrange in Grid"), (OFFSET, "Offset Objects"), (REPLACE, "Replace with Top Object"), (SIZE, "Set Size of Each"), + (ROWS, "Group by Row"), (OPACITY, "Randomize Opacity"), (SORT, "Sort Objects"), ]; @@ -64,6 +66,7 @@ pub fn menu() -> Vec { c("Replace with Top Object…", REPLACE), c("Set Size of Each…", SIZE), cp("Group Overlapping Objects", "addon.arrange.groupOverlapping", json!({})), + c("Group by Row…", ROWS), c("Randomize Opacity…", OPACITY), c("Sort Objects…", SORT), Sep, @@ -75,6 +78,7 @@ static GRID_SPEC: Spec = Spec { command: GRID, params: grid_params, found: None static OFFSET_SPEC: Spec = Spec { command: OFFSET, params: offset_params, found: None }; static REPLACE_SPEC: Spec = Spec { command: REPLACE, params: replace_params, found: None }; static SIZE_SPEC: Spec = Spec { command: SIZE, params: size_params, found: None }; +static ROWS_SPEC: Spec = Spec { command: ROWS, params: group_rows_params, found: None }; static OPACITY_SPEC: Spec = Spec { command: OPACITY, params: opacity_params, found: None }; static SORT_SPEC: Spec = Spec { command: SORT, params: sort_params, found: None }; @@ -149,6 +153,11 @@ fn size_rows(lengths: LengthUnits) -> Vec { ] } +fn group_rows_rows() -> Vec { + let directions = [("row", "Rows"), ("column", "Columns")]; + vec![choice("direction", "Group By:", &directions, "row")] +} + fn opacity_rows() -> Vec { vec![percent("min", "Minimum:", 30.0), percent("max", "Maximum:", 100.0), seed()] } @@ -192,6 +201,10 @@ fn size_params(fields: &DialogFields) -> Value { Value::Object(params) } +fn group_rows_params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&group_rows_rows(), fields)) +} + fn opacity_params(fields: &DialogFields) -> Value { Value::Object(form::json_of(&opacity_rows(), fields)) } @@ -217,6 +230,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option (offset_rows(lengths), json!({ "direction": "row", "gap": 10, "order": "stacking", "reverse": false })), REPLACE => (replace_rows(), json!({ "fit": "keep", "keep": false, "scaleStrokes": strokes })), + ROWS => (group_rows_rows(), json!({ "direction": "row" })), // A new seed each time the document has changed, so running it again varies the result. OPACITY => (opacity_rows(), json!({ "min": 30, "max": 100, "seed": st.revision % SEEDS })), // The random order's seed (not shown): new whenever the document has changed, so each run @@ -245,6 +259,7 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))), OFFSET => super::dialogs::open(app, &OFFSET_SPEC, fields, move |fields| dialog(OFFSET, offset_rows(lengths)).values(Bind::bound(fields))), REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_rows()).values(Bind::bound(fields))), + ROWS => super::dialogs::open(app, &ROWS_SPEC, fields, |fields| dialog(ROWS, group_rows_rows()).values(Bind::bound(fields))), OPACITY => super::dialogs::open(app, &OPACITY_SPEC, fields, |fields| { let (min, max) = (fields.number("min").unwrap_or(0.0), fields.number("max").unwrap_or(100.0)); dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields)) diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 016391d661..41686a4bd1 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -169,6 +169,64 @@ fn stacking(panel: &Harness) -> Vec { panel.app().session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() } +/// [`app`] with a third rectangle, c, in b's row and a's column; all three selected. +fn rows_app() -> (VectorcraftApp, NodeId, NodeId, NodeId) { + let (mut app, a, b) = app(); + let c = NodeId(app.run("shape.rectangle", json!({"x": 10, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.all", json!({})).unwrap(); + (app, a, b, c) +} + +fn parent(panel: &Harness, id: NodeId) -> Option { + panel.app().session.doc().unwrap().doc.parent_of(id) +} + +#[test] +fn real_group_by_row_keyboard_choice_reaches_the_preview_and_ok_groups_as_one_step() { + let (app, a, b, c) = rows_app(); + let n = steps(&app); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Group by Row…"); + panel.frame(); + let layer = panel.app().session.doc().unwrap().doc.layers[0].id; + // Rows: b and c share one, a is alone in its own. + assert_eq!(parent(&panel, b), parent(&panel, c), "the preview groups b's row"); + assert_ne!(parent(&panel, b), Some(layer)); + assert_eq!(parent(&panel, a), Some(layer)); + panel.click_role("Group By", Role::COMBO_BOX); + panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE); + panel.key(egui::Key::Enter, egui::Modifiers::NONE); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.text("direction").map(str::to_owned)), Some("column".to_owned())); + // Columns: a and c share one, b is alone in its own. + assert_eq!(parent(&panel, a), parent(&panel, c), "the preview follows the keyboard choice"); + assert_ne!(parent(&panel, a), Some(layer)); + assert_eq!(parent(&panel, b), Some(layer)); + panel.click("OK"); + panel.frame(); + let group = parent(&panel, a).unwrap(); + assert_eq!(stacking(&panel), vec![b, group], "the group takes c's place, in front of b"); + assert_eq!(parent(&panel, c), Some(group)); + assert_eq!(steps(&panel.app()), n + 1, "one undo step"); + assert!(!panel.app().any_dialog_open()); +} + +#[test] +fn real_group_by_row_cancel_leaves_the_objects_ungrouped() { + let (app, a, b, c) = rows_app(); + let n = steps(&app); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + click(&mut panel.app(), "Group by Row…"); + panel.frame(); + assert_eq!(stacking(&panel).len(), 2, "the preview groups b and c"); + panel.click("Cancel"); + panel.frame(); + assert_eq!(stacking(&panel), vec![a, b, c]); + assert_eq!(steps(&panel.app()), n); + assert!(!panel.app().any_dialog_open()); +} + #[test] fn real_replace_edits_reach_the_preview_and_confirmed_copies() { let (app, a, b) = app(); diff --git a/docs/mcp.md b/docs/mcp.md index d984e7b92d..1582662613 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17582,6 +17582,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row`) | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds, a clipping group's by its mask, overlap the row's extent from top to bottom (left to right). Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row; an object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | @@ -17591,11 +17592,13 @@ and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, (`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies. Offset Objects… opens one the same way (`ui.menuDialog {command: "addon.arrange.offset"}`), with Direction, Gap, Order -and Reverse Order. +and Reverse Order. Group by Row… opens one too (`ui.menuDialog {command: "addon.arrange.groupRows"}`), with Group By +(Rows or Columns). ```json {"name":"run_command","arguments":{"command":"addon.arrange.grid","params":{"columns":4,"gapX":12,"gapY":12}}} {"name":"run_command","arguments":{"command":"addon.arrange.offset","params":{"direction":"column","gap":6,"order":"position"}}} +{"name":"run_command","arguments":{"command":"addon.arrange.groupRows","params":{"direction":"row"}}} {"name":"run_command","arguments":{"command":"addon.arrange.replace","params":{"fit":"proportional"}}} {"name":"run_command","arguments":{"command":"addon.arrange.size","params":{"width":72,"proportional":true}}} ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ee49042298..ef8382bb36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3162,6 +3162,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Offset Objects… chains the top-level selected objects one after another in a row (left to right) or a column (top to bottom) with a gap of −1000000 to 1000000 pt (10 by default; a negative gap overlaps them). The order is the stacking order from the back, or the position (left edges in a row, top edges in a column), and Reverse Order runs it the other way. The first object stays where it is; each later one moves only along the row or column so that it starts the gap past the end of the one before it, and keeps its place across it. Objects are measured by their visual bounds, a clipping group by its mask. One undo step; no step when nothing moves. Tests: `offset_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (row and column, both orders and reversed, a negative gap, strokes and clipping groups, no step, locked objects left out, bad params), `real_offset_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Group by Row (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Group by Row… puts the top-level selected objects (at most 20000) into one group for each row: an object joins a row when its visual bounds, a clipping group's by its mask, overlap the row from top to bottom. Group By Columns does the same from left to right. Extents that only touch stay apart, an object that overlaps two rows joins them, and only objects in the same layer or group and on the same artboard share a row; an object alone in its row stays as it is. Each new group takes its frontmost member's place in the stacking order, and the groups and the objects left alone stay selected. One undo step; no step when no row holds two objects. Tests: `group_rows_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (rows and loners, columns, an object spanning two rows, layers and artboards kept apart, strokes and clipping groups, locked objects left out, bad params, 20000 objects), `real_group_by_row_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Type Tools add-on: Text Tweaker (2026-11-03) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ac20453f86..795af5c60c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -568,6 +568,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Group by Row… groups the selected objects whose visual bounds overlap from top to bottom into one group for each row, or with Group By Columns from left to right (within one layer or group and one artboard), each group at its frontmost member's stacking place; Preview; one undo step | done | `addon.arrange.groupRows`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | From 1f9238190c5e39d0112e0459384780184def951f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:16:10 -0800 Subject: [PATCH 04/46] Arrange Tools: Group by Row treats a -0.0 edge as 0.0 rows_of sorted extents with total_cmp, which puts -0.0 before 0.0, so an extent starting at -0.0 opened its row before a flat extent at 0.0 and the flat one joined a row it only touches. Both ends of each extent now go through + 0.0 first, with a test for a -0.0 start beside a flat 0.0 extent. --- crates/engine/src/cmd/addons/arrange.rs | 4 +++- crates/engine/src/cmd/addons/arrange/tests.rs | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 4274932141..9c64df9c1d 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -424,8 +424,10 @@ fn group_overlapping(s: &mut Session, _: &Value) -> Result { /// two or more (each in the order given) among items of the same key whose extents overlap, chains included. /// Extents that only touch stay apart. Sorted by start, then by end, each item joins its key's open row when it /// starts before that row ends, so the rows come out in order along the axis, and an extent with no length at -/// another's start stays apart from it whatever their order. +/// another's start stays apart from it whatever their order. Adding 0.0 turns -0.0 into 0.0, which +/// `total_cmp` would otherwise order first. fn rows_of(items: &[(K, (f64, f64))]) -> Vec> { + let items: Vec<(K, (f64, f64))> = items.iter().map(|(k, (start, end))| (*k, (start + 0.0, end + 0.0))).collect(); let mut order: Vec = (0..items.len()).collect(); order.sort_by(|a, b| items[*a].1.0.total_cmp(&items[*b].1.0).then(items[*a].1.1.total_cmp(&items[*b].1.1))); let mut rows: Vec> = vec![]; diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 94e43a78d2..2a586763b6 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -625,6 +625,9 @@ fn group_rows_keeps_a_flat_object_on_a_row_edge_apart_in_either_order() { assert!(super::rows_of(&flat_in_front).is_empty(), "{:?}", super::rows_of(&flat_in_front)); // Inside the row, it joins. assert_eq!(super::rows_of(&[(0u8, (0.0, 10.0)), (0, (5.0, 5.0))]), vec![vec![0, 1]]); + // A start of -0.0 is the same edge as 0.0, so the flat extent there still only touches. + let negative_zero: Vec<(u8, (f64, f64))> = vec![(0, (0.0, 0.0)), (0, (-0.0, 10.0))]; + assert!(super::rows_of(&negative_zero).is_empty(), "{:?}", super::rows_of(&negative_zero)); } fn opacity(s: &Session, id: NodeId) -> f32 { From aa7962ec9514a0718a5c6b3a330fe20d44704dda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:11:19 -0800 Subject: [PATCH 05/46] Arrange Tools: Group by Row leaves masks, locked objects and blend keys alone Clipping masks, locked or hidden objects and objects outside every artboard stay in place; a selection inside a live blend and a direction of null are rejected. The docs say raster effects do not count toward row bounds. --- crates/engine/src/cmd/addons/arrange.rs | 29 ++++- crates/engine/src/cmd/addons/arrange/tests.rs | 119 +++++++++++++++++- docs/mcp.md | 2 +- 3 files changed, 143 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 9c64df9c1d..d33bcfcee5 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::recolor::Rng; -use vectorcraft_doc::{Node, NodeId, OrientedBox}; +use vectorcraft_doc::{Node, NodeId, NodeKind, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use vectorcraft_render::effects; @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Group by Row", ["Object", "Plug-ins", "Arrange Tools"], None, - "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\")} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. An object joins a row when its visual bounds (strokes and effects as drawn; a clipping group by its mask) overlap the row's extent across it; extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row, an object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", has_multi, group_rows ), @@ -457,20 +457,39 @@ fn rows_of(items: &[(K, (f64, f64))]) -> Vec Result { const C: &str = "addon.arrange.groupRows"; + if p.get("direction").is_some_and(Value::is_null) { + return Err(bad(C, "`direction` must be row or column")); + } let rows = choice(p, C, "direction", &["row", "column"])?.unwrap_or("row") == "row"; let roots = selected_roots(s)?; if roots.len() > MAX_OBJECTS { return Err(bad(C, "too many objects selected (at most 20000)")); } let d = &s.doc()?.doc; + let editable_roots: Vec<_> = { + let editable = d.editable(); + roots.iter().copied().filter(|id| editable(*id)).collect() + }; + for id in &editable_roots { + if d.parent_of(*id).and_then(|parent| d.node(parent)).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { + return Err(bad(C, "selected objects must be in a layer or group")); + } + } // Each object's row key (its parent and its artboard) and its extent across the rows. - type Keyed = ((Option, Option), (f64, f64)); - let items: Vec<(NodeId, Keyed)> = roots + type Keyed = ((Option, usize), (f64, f64)); + let items: Vec<(NodeId, Keyed)> = editable_roots .iter() .filter_map(|id| { + let parent = d.parent_of(*id); + if parent + .and_then(|parent| d.node(parent)) + .is_some_and(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id)) + { + return None; + } let b = effects::preview::bounds_of(d, &[*id], true)?; let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) }; - Some((*id, ((d.parent_of(*id), d.artboard_for_bounds(b)), extent))) + Some((*id, ((parent, d.artboard_for_bounds(b)?), extent))) }) .collect(); let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect(); diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 2a586763b6..e382c2a440 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -579,6 +579,119 @@ fn group_rows_measures_clipping_groups_by_their_mask() { assert_eq!(children(&s, groups[0]), [group, b], "the mask's row, not the clipped art's"); } +#[test] +fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() { + for clipping_layer in [false, true] { + let mut s = session(); + let mask = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 40.0, 10.0, 20.0, 20.0); + select(&mut s, &[mask, a, b]); + let parent = if clipping_layer { + s.doc().unwrap().doc.layers[0].id + } else { + s.execute("object.group", &json!({})).unwrap(); + s.doc().unwrap().selection.objects[0] + }; + s.edit("Set clipping", |d, _| { + d.node_mut(parent).unwrap().set_clips(true); + Ok(()) + }) + .unwrap(); + select(&mut s, &[mask, a]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(children(&s, parent), [mask, a, b]); + select(&mut s, &[mask, a, b]); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, parent), [mask, groups[0]]); + assert_eq!(children(&s, groups[0]), [a, b]); + assert!(s.doc().unwrap().selection.objects.contains(&mask)); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } +} + +#[test] +fn group_rows_refuses_explicitly_selected_live_blend_keys() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + s.execute("object.blend.make", &json!({})).unwrap(); + let blend = s.doc().unwrap().selection.objects[0]; + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 90.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({})]); + select(&mut s, &[a, b, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({})]); + assert_eq!(children(&s, blend), [a, b]); +} + +#[test] +fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() { + for command in ["object.lock", "object.hide"] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); + select(&mut s, &[b]); + s.execute(command, &json!({})).unwrap(); + select(&mut s, &[a, b, c]); + assert!(s.doc().unwrap().selection.objects.contains(&b)); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, groups[0]), [a, c]); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id)); + } +} + +#[test] +fn group_rows_leaves_objects_outside_all_artboards_ungrouped() { + for direction in ["row", "column"] { + let mut s = session(); + let a = rect(&mut s, 500.0, 500.0, 20.0, 20.0); + let b = rect(&mut s, 505.0, 505.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert!(*s.doc().unwrap().doc == *before); + let c = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 5.0, 5.0, 20.0, 20.0); + select(&mut s, &[a, b, c, d]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + let groups = ids_of(&r["groups"]); + assert_eq!(r["grouped"], json!(2)); + assert_eq!(children(&s, groups[0]), [c, d]); + assert_eq!(layer_children(&s), [a, b, groups[0]]); + let sel = &s.doc().unwrap().selection.objects; + assert!(sel.contains(&a) && sel.contains(&b)); + } +} + +#[test] +fn group_rows_documents_and_excludes_raster_effects_from_bounds() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + select(&mut s, &[a]); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {"x": 0, "y": 5, "blur": 0}})).unwrap(); + let b = rect(&mut s, 0.0, 21.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(layer_children(&s), [a, b]); + let spec = super::specs().into_iter().find(|c| c.id == "addon.arrange.groupRows").unwrap(); + assert!(spec.params.contains("excludes raster effects")); +} + #[test] fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() { let mut s = session(); @@ -589,7 +702,11 @@ fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() let c = rect(&mut s, 60.0, 0.0, 20.0, 20.0); select(&mut s, &[a, b, c]); assert!(enabled(&s, "addon.arrange.groupRows")); - refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true})]); + refuses( + &mut s, + "addon.arrange.groupRows", + &[json!({"direction": "diagonal"}), json!({"direction": 3}), json!({"direction": true}), json!({"direction": null})], + ); select(&mut s, &[b]); s.execute("object.lock", &json!({})).unwrap(); s.execute("select.all", &json!({})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 1582662613..e01104769b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17582,7 +17582,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | -| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row`) | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds, a clipping group's by its mask, overlap the row's extent from top to bottom (left to right). Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row; an object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid) | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | From 875157116bffa2b7f9d6101599c1a40568178375 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:16:11 -0800 Subject: [PATCH 06/46] Arrange Tools: Mark Bounds of Each tests the vertical leg cap and has its docs rows - A test marks a wide, short object and checks that each vertical leg stops at half the height while each horizontal leg keeps its length. - The params text and module doc spell "color" the American way. - docs/ui-parity.md gets a row and docs/target-app-parity.md a section for Mark Bounds of Each, next to Offset Objects. - The ui-egui arrange tests keep one `steps` helper; main added the same helper for Offset Objects. --- crates/engine/src/cmd/addons/arrange/marks.rs | 4 ++-- .../src/cmd/addons/arrange/marks/tests.rs | 19 ++++++++++++++++++- crates/ui-egui/src/addons/arrange/tests.rs | 4 ---- docs/target-app-parity.md | 4 ++++ docs/ui-parity.md | 1 + 5 files changed, 25 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs index 5e59924827..fc01a8730d 100644 --- a/crates/engine/src/cmd/addons/arrange/marks.rs +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -1,6 +1,6 @@ //! Mark Bounds of Each (`addon.arrange.markBounds`; Object › Plug-ins › Arrange Tools › Mark Bounds //! of Each…): corner marks, or a rectangle, on the bounds of each selected object rather than -//! around the whole selection, stroked in a colour of their own and stacked directly above the +//! around the whole selection, stroked in a color of their own and stacked directly above the //! object, as one undo step. #[cfg(test)] @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Mark Bounds of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: colour (\"#ff0000\"; an RGB colour takes the document's colour mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", has_selection, mark_bounds )] diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs index c00085c701..dc44f47d5b 100644 --- a/crates/engine/src/cmd/addons/arrange/marks/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -111,7 +111,7 @@ fn length_weight_color_and_the_rectangle_style() { select(&mut s, &[a]); let r = s.execute(COMMAND, &json!({"length": 40, "weight": 2.5, "color": "#0000ff"})).unwrap(); let marks = ids_of(&r); - // A leg is never longer than half its side, so opposite marks do not meet. + // A leg is never longer than half its side, so opposite marks do not overlap. assert_eq!(lines(&s, marks[0])[0], vec![(15.0, 0.0), (0.0, 0.0), (0.0, 40.0)]); let group = node(&s, marks[0]); let ap = &group.children().unwrap()[0].appearance; @@ -125,6 +125,23 @@ fn length_weight_color_and_the_rectangle_style() { assert!(near(marks_bounds(&s, mark), (0.0, 0.0, 30.0, 100.0))); } +#[test] +fn a_leg_is_at_most_half_the_side_it_runs_along_vertically() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 200.0, 20.0); + select(&mut s, &[a]); + let r = s.execute(COMMAND, &json!({"length": 30})).unwrap(); + assert_eq!( + lines(&s, ids_of(&r)[0]), + vec![ + vec![(30.0, 0.0), (0.0, 0.0), (0.0, 10.0)], + vec![(170.0, 0.0), (200.0, 0.0), (200.0, 10.0)], + vec![(170.0, 20.0), (200.0, 20.0), (200.0, 10.0)], + vec![(30.0, 20.0), (0.0, 20.0), (0.0, 10.0)], + ] + ); +} + #[test] fn geometric_bounds_leave_strokes_out_and_visual_bounds_count_them() { let mut s = session(); diff --git a/crates/ui-egui/src/addons/arrange/tests.rs b/crates/ui-egui/src/addons/arrange/tests.rs index 524fc290ec..7241291cab 100644 --- a/crates/ui-egui/src/addons/arrange/tests.rs +++ b/crates/ui-egui/src/addons/arrange/tests.rs @@ -282,10 +282,6 @@ fn first_mark(app: &VectorcraftApp, id: NodeId) -> Vec<(f64, f64)> { mark.path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect() } -fn steps(app: &VectorcraftApp) -> usize { - app.session.doc().unwrap().history.undo.len() -} - #[test] fn real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them() { let (app, a, b) = app(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ee49042298..60f626d470 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3162,6 +3162,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Offset Objects… chains the top-level selected objects one after another in a row (left to right) or a column (top to bottom) with a gap of −1000000 to 1000000 pt (10 by default; a negative gap overlaps them). The order is the stacking order from the back, or the position (left edges in a row, top edges in a column), and Reverse Order runs it the other way. The first object stays where it is; each later one moves only along the row or column so that it starts the gap past the end of the one before it, and keeps its place across it. Objects are measured by their visual bounds, a clipping group by its mask. One undo step; no step when nothing moves. Tests: `offset_*` in `cmd::addons::arrange::tests` in `vectorcraft-engine` (row and column, both orders and reversed, a negative gap, strokes and clipping groups, no step, locked objects left out, bad params), `real_offset_*` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +## Arrange Tools add-on: Mark Bounds of Each (2026-11-29) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group or clipping sublayer that holds it; a clipping top-level layer keeps the marks inside it. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `flat_objects_get_lines_and_guides_and_empty_groups_none` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. + ## Type Tools add-on: Text Tweaker (2026-11-03) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Type Tools › Text Tweaker… gives one character attribute (size, baseline shift, character rotation, horizontal or vertical scale, tracking, leading or stroke weight) to the selected characters letter by letter, from a start value to an end value along a straight ramp, an ease in and out, a bow, a spike or at random with a seed, while the text stays live and editable (#4924). With Block enabled, a leading ramp sets Line Gap from the first changed character instead of varying leading across the text. Values are set as the Character panel sets them, in its units and ranges, so scaled type takes the sizes shown; spaces and line breaks are skipped unless asked for, each type object gets its own ramp, the range is the Type tool's selection or all the text of the selected type objects, and the run is one undo step from a dialog with Preview. Tests: `cmd::addons::typetools::tests` in `vectorcraft-engine` (each shape, each attribute, skipped spaces, ranges, one ramp per object, seeded random values, scaled type, one undo step, bad params refused), `addons::typetools::tests` in `vectorcraft-ui-egui` (the submenu, the dialog, Preview and Cancel, OK) and `command_sweep`. Commands: `docs/mcp.md` › Type Tools add-on. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index ac20453f86..283214dc79 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -568,6 +568,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Randomize Opacity… gives each selected object its own opacity at random between Minimum and Maximum (%), with a Seed that repeats it and Preview, one undo step | done | #4925; `addon.arrange.randomizeOpacity`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Offset Objects… chains the selected objects one after another in a Direction (Row (Left to Right) or Column (Top to Bottom)) with a Gap (negative overlaps), in an Order (Stacking Order or Position) with Reverse Order; the first stays in place and the others move only along the row or column; Preview; one undo step | done | `addon.arrange.offset`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | +| Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws inward Corner Marks or a Rectangle on each selected object's Geometric Bounds or Visual Bounds, with Length, Weight, Color and Preview; marks go above the object or its outermost clip group or clipping sublayer and become selected; one undo step | done | `addon.arrange.markBounds`, `crates/engine/src/cmd/addons/arrange/marks.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; a VectorCraft addition, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | From 6532abda434ceed8e59919e3305c490750518510 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:19:26 -0800 Subject: [PATCH 07/46] Arrange Tools: Group by Row refuses Shaper and compound shape children and non-object params Group by Row now refuses objects whose parent is a Shaper group or a live compound shape, since regrouping them breaks the Shaper group or changes the Boolean result, and refuses parameters that are not an object. Row measurements share one symbol name index instead of indexing every symbol for each instance. --- crates/engine/src/cmd/addons/arrange.rs | 14 ++- crates/engine/src/cmd/addons/arrange/tests.rs | 95 +++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 106 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index d33bcfcee5..1d6d57b0cc 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Group by Row", ["Object", "Plug-ins", "Arrange Tools"], None, - "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys, and direct children of Shaper groups or live compound shapes. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", has_multi, group_rows ), @@ -457,6 +457,9 @@ fn rows_of(items: &[(K, (f64, f64))]) -> Vec Result { const C: &str = "addon.arrange.groupRows"; + if !p.is_object() { + return Err(bad(C, "parameters must be an object")); + } if p.get("direction").is_some_and(Value::is_null) { return Err(bad(C, "`direction` must be row or column")); } @@ -471,12 +474,15 @@ fn group_rows(s: &mut Session, p: &Value) -> Result { roots.iter().copied().filter(|id| editable(*id)).collect() }; for id in &editable_roots { - if d.parent_of(*id).and_then(|parent| d.node(parent)).is_some_and(|n| !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })) { - return Err(bad(C, "selected objects must be in a layer or group")); + if d.parent_of(*id).and_then(|parent| d.node(parent)).is_some_and(|n| { + !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.is_compound_shape() || n.extras().shaper.is_some() + }) { + return Err(bad(C, "selected objects must be in a layer or group without live structural roles")); } } // Each object's row key (its parent and its artboard) and its extent across the rows. type Keyed = ((Option, usize), (f64, f64)); + let symbols = d.symbol_boxes(); let items: Vec<(NodeId, Keyed)> = editable_roots .iter() .filter_map(|id| { @@ -487,7 +493,7 @@ fn group_rows(s: &mut Session, p: &Value) -> Result { { return None; } - let b = effects::preview::bounds_of(d, &[*id], true)?; + let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?; let extent = if rows { (b.y0, b.y1) } else { (b.x0, b.x1) }; Some((*id, ((parent, d.artboard_for_bounds(b)?), extent))) }) diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index e382c2a440..5416687473 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -633,6 +633,58 @@ fn group_rows_refuses_explicitly_selected_live_blend_keys() { assert_eq!(children(&s, blend), [a, b]); } +#[test] +fn group_rows_refuses_explicitly_selected_shaper_children() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": [[25, 25], [125, 25]]})).unwrap()["id"].as_u64().unwrap()); + let members = children(&s, shaper); + assert!(members.len() >= 2); + let sources = members[0]; + let face = s + .doc() + .unwrap() + .doc + .node(shaper) + .unwrap() + .children() + .unwrap() + .iter() + .find(|n| n.name.as_deref().is_some_and(|name| name.starts_with(vectorcraft_doc::shaper::FILL_PREFIX))) + .unwrap() + .id; + let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &[sources, face]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + select(&mut s, &[sources, face, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(&s, shaper), members); + } +} + +#[test] +fn group_rows_refuses_explicitly_selected_live_compound_shape_operands() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 30.0, 30.0); + let b = rect(&mut s, 10.0, 0.0, 30.0, 30.0); + select(&mut s, &[a, b]); + s.execute("object.compoundShape.make", &json!({"mode": "subtract"})).unwrap(); + let shape = s.doc().unwrap().selection.objects[0]; + let c = rect(&mut s, 200.0, 0.0, 20.0, 20.0); + let d = rect(&mut s, 230.0, 0.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + select(&mut s, &[a, b, c, d]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(&s, shape), [a, b]); + } +} + #[test] fn group_rows_skips_explicitly_selected_locked_and_hidden_objects() { for command in ["object.lock", "object.hide"] { @@ -717,6 +769,49 @@ fn group_rows_is_off_with_one_object_skips_locked_ones_and_refuses_bad_params() assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(s.doc().unwrap().doc.layers[0].id)); } +#[test] +fn group_rows_refuses_non_object_params_without_an_edit() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let b = rect(&mut s, 30.0, 0.0, 20.0, 20.0); + select(&mut s, &[a, b]); + let selection = s.doc().unwrap().selection.objects.clone(); + refuses(&mut s, "addon.arrange.groupRows", &[json!([]), json!(["row"]), json!("row"), json!(true), json!(3)]); + assert_eq!(s.doc().unwrap().selection.objects, selection); +} + +#[test] +fn group_rows_reads_the_symbol_index_once_for_all_members() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Document, Node, NodeKind, Symbol}; + use vectorcraft_geom::Affine; + + let mut d = Document::new(400.0, 300.0); + for i in 0..200 { + let art = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + d.symbols.push(Symbol { dynamic: false, name: format!("Mark {i}"), art: Arc::new(art) }); + } + let layer = d.layers[0].id; + let ids: Vec<_> = (0..8) + .map(|i| { + let xf = Affine::translate((0.0, f64::from(i) * 20.0)); + let n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: format!("Mark {i}"), xf }); + d.insert(Some(layer), usize::MAX, n).unwrap() + }) + .collect(); + let symbol_count = d.symbols.len(); + let mut s = Session::new(); + s.add_document(d, None); + select(&mut s, &ids); + let n = steps(&s); + let before = vectorcraft_doc::symbols_read(); + let r = s.execute("addon.arrange.groupRows", &json!({})).unwrap(); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= symbol_count, "{read} symbols read, {symbol_count} in the document"); + assert_eq!((r["grouped"].clone(), steps(&s)), (json!(0), n)); + assert_eq!(layer_children(&s), ids); +} + #[test] fn group_rows_sorts_many_objects_into_rows() { // 20000 objects in pairs up the page, the front one of each pair starting higher: each pair overlaps, diff --git a/docs/mcp.md b/docs/mcp.md index e01104769b..3543a70ff2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17582,7 +17582,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | -| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid) | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys, and direct children of Shaper groups or live compound shapes. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | From 26a70bb546448a70b3290eca394668d647f5f0f3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:40:55 -0800 Subject: [PATCH 08/46] Scripts: test that eval code with a forbidden super or new.target runs none of it The tests from #10023 for `super` and `new.target` in global eval, indirect eval and `Function` bodies check only that a SyntaxError is thrown. The interpreter also throws one at run time when `super` has no home object or constructor (class_ops.rs:450 and :555), so a case the parser let through would still pass them if it threw only at run time. Two tests in es2015_tests.rs put `x = 1` ahead of the forbidden form: - eval_code_with_a_forbidden_super_or_new_target_runs_none_of_it covers 13 cases of `super.y`, `super(...)` and `new.target` in global eval, indirect eval, direct eval in a plain function, and direct eval in a method or constructor that does not allow the form. Each leaves `x` at 0 and throws a SyntaxError. - a_function_body_with_super_is_not_made covers 5 `Function` calls with `super` in the body or a parameter default. Each throws a SyntaxError from `Function` itself, so no function is returned and `x` stays 0. Every case was already rejected by the parser; the tests change no behavior. --- crates/js/src/es2015_tests.rs | 55 +++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index f134176bfc..28fb8c3408 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -1714,6 +1714,61 @@ fn a_function_body_reads_its_own_new_target() { truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined"); } +/// Eval code that uses `super` or `new.target` where it may not is a `SyntaxError` before any of +/// it runs, so `x = 1` ahead of the forbidden form leaves `x` at 0 (ECMA-262 2015 sections +/// 18.2.1.1 and 15.1.1). +#[test] +fn eval_code_with_a_forbidden_super_or_new_target_runs_none_of_it() { + let a = "class A { constructor(v) { this.a = v; } } "; + let calls = [ + "eval('x = 1; super.y');".to_string(), + "class C { m() { (0, eval)('x = 1; super.y'); } } new C().m();".to_string(), + "function F() { eval('x = 1; super.y'); } F();".to_string(), + "class C { m() { (function () { eval('x = 1; super.y'); })(); } } new C().m();".to_string(), + "eval('x = 1; super()');".to_string(), + "class C { constructor() { eval('x = 1; super()'); } } new C();".to_string(), + format!("{a}class B extends A {{ m() {{ eval('x = 1; super(1)'); }} }} new B(1).m();"), + format!("{a}class B extends A {{ constructor() {{ (0, eval)('x = 1; super(1)'); }} }} new B();"), + format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('x = 1; super(1)'); }})(); }} }} new B();"), + "function F() { eval('x = 1; super()'); } F();".to_string(), + "eval('x = 1; new.target');".to_string(), + "(() => eval('x = 1; new.target'))();".to_string(), + "function F() { (0, eval)('x = 1; new.target'); } new F();".to_string(), + ]; + let ran: Vec<&String> = calls + .iter() + .filter(|call| { + let src = format!("var x = 0, e; try {{ {call} }} catch (err) {{ e = err; }} x === 0 && e instanceof SyntaxError"); + run(&src) != JsValue::Bool(true) + }) + .collect(); + assert!(ran.is_empty(), "eval code ran or did not throw a SyntaxError: {ran:#?}"); +} + +/// The `Function` constructor throws the `SyntaxError` for `super` in the body or a parameter +/// itself, so it returns no function to call and `x = 1` in the body never runs (ECMA-262 2015 +/// section 19.2.1.1.1). +#[test] +fn a_function_body_with_super_is_not_made() { + let a = "class A { constructor(v) { this.a = v; } } "; + let calls = [ + "class C { m() { f = Function('x = 1; super.y'); } } new C().m();".to_string(), + "class C { m() { f = Function('a = super.y', 'x = 1'); } } new C().m();".to_string(), + "f = Function('x = 1; super.y');".to_string(), + format!("{a}class B extends A {{ constructor() {{ super(1); f = Function('x = 1; super(1)'); }} }} new B();"), + "f = Function('x = 1; super()');".to_string(), + ]; + let made: Vec<&String> = calls + .iter() + .filter(|call| { + let src = + format!("var x = 0, f, e; try {{ {call} f(); }} catch (err) {{ e = err; }} f === undefined && x === 0 && e instanceof SyntaxError"); + run(&src) != JsValue::Bool(true) + }) + .collect(); + assert!(made.is_empty(), "Function made a function or did not throw a SyntaxError: {made:#?}"); +} + #[test] fn deep_class_chains_stay_within_the_limits() { let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();"; From 094f59566c024a363abfead0916650e99843f0c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:05:25 -0800 Subject: [PATCH 09/46] Arrange Tools: Group by Row refuses parts of live groups and graphs and leaves layers alone Group by Row now also refuses direct children of Objects on Path and Live Paint groups and objects inside a live graph, while a whole live group or graph can still be grouped with other art. Selected layers and sublayers stay selected and are not grouped. --- crates/engine/src/cmd/addons/arrange.rs | 33 +++-- crates/engine/src/cmd/addons/arrange/tests.rs | 129 ++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 151 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange.rs b/crates/engine/src/cmd/addons/arrange.rs index 1d6d57b0cc..7768b4f62e 100644 --- a/crates/engine/src/cmd/addons/arrange.rs +++ b/crates/engine/src/cmd/addons/arrange.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Group by Row", ["Object", "Plug-ins", "Arrange Tools"], None, - "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys, and direct children of Shaper groups or live compound shapes. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", + "{direction?: \"row\" (objects whose vertical extents overlap) | \"column\" (objects whose horizontal extents overlap) (\"row\" when omitted; null is invalid)} group the selected objects (the top-level ones, at most 20000) into one group for each row (column), as one undo step. Parameters must be an object. An object joins a row when its visual bounds overlap the row's extent across it. Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is, and each new group goes where its frontmost member was in the stacking order; the new groups (top to bottom, or left to right) and the objects left alone stay selected. A run with no row of two or more objects makes no step → {groups: [id…], grouped (how many objects went into groups)}", has_multi, group_rows ), @@ -471,26 +471,33 @@ fn group_rows(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let editable_roots: Vec<_> = { let editable = d.editable(); - roots.iter().copied().filter(|id| editable(*id)).collect() + roots.iter().copied().filter(|id| editable(*id) && d.node(*id).is_some_and(|n| !n.is_layer())).collect() }; for id in &editable_roots { - if d.parent_of(*id).and_then(|parent| d.node(parent)).is_some_and(|n| { - !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.is_compound_shape() || n.extras().shaper.is_some() - }) { + let parent = d.parent_of(*id); + let valid_parent = parent.and_then(|parent| d.node(parent)).is_some_and(|n| { + matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) + && !n.is_compound_shape() + && n.extras().shaper.is_none() + && n.extras().objects_on_path.is_none() + && !vectorcraft_tools::builder::is_live_paint(n) + }); + let in_graph = parent + .and_then(|parent| d.ancestry(parent)) + .is_some_and(|ancestors| ancestors.iter().any(|ancestor| d.node(*ancestor).is_some_and(|n| n.extras().graph.is_some()))); + if !valid_parent || in_graph { return Err(bad(C, "selected objects must be in a layer or group without live structural roles")); } } // Each object's row key (its parent and its artboard) and its extent across the rows. - type Keyed = ((Option, usize), (f64, f64)); + type Keyed = ((NodeId, usize), (f64, f64)); let symbols = d.symbol_boxes(); let items: Vec<(NodeId, Keyed)> = editable_roots .iter() .filter_map(|id| { - let parent = d.parent_of(*id); - if parent - .and_then(|parent| d.node(parent)) - .is_some_and(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id)) - { + let parent = d.parent_of(*id)?; + let container = d.node(parent)?; + if container.clips() && container.children().and_then(|c| c.first()).is_some_and(|c| c.id == *id) { return None; } let b = effects::preview::visual_bounds(&symbols.unmeasured(), d.node(*id)?)?; @@ -500,7 +507,9 @@ fn group_rows(s: &mut Session, p: &Value) -> Result { .collect(); let keyed: Vec<_> = items.iter().map(|(_, k)| *k).collect(); let sets: Vec> = rows_of(&keyed).into_iter().map(|set| set.iter().filter_map(|i| Some(items.get(*i)?.0)).collect()).collect(); - group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &roots, sets) + let mut selection = roots; + selection.extend(s.doc()?.selection.objects.iter().copied().filter(|id| d.node(*id).is_some_and(|n| n.is_layer()))); + group_each(s, if rows { "Group by Row" } else { "Group by Column" }, &selection, sets) } /// Put each of `sets` (two or more of the selected top-level objects `roots`, each in stacking order) into a diff --git a/crates/engine/src/cmd/addons/arrange/tests.rs b/crates/engine/src/cmd/addons/arrange/tests.rs index 5416687473..6f50164c0c 100644 --- a/crates/engine/src/cmd/addons/arrange/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/tests.rs @@ -616,6 +616,135 @@ fn group_rows_keeps_clipping_masks_first_in_groups_and_layers() { } } +#[test] +fn group_rows_leaves_selected_layers_and_sublayers_in_place() { + for sublayers in [false, true] { + let mut s = session(); + let parent = s.doc().unwrap().doc.layers[0].id; + let mut layers = vec![]; + for _ in 0..2 { + let command = if sublayers { "layer.newSublayer" } else { "layer.new" }; + let params = if sublayers { json!({"parent": parent.0}) } else { json!({"top": true}) }; + let layer = NodeId(s.execute(command, ¶ms).unwrap()["id"].as_u64().unwrap()); + rect(&mut s, 10.0, 10.0, 20.0, 20.0); + layers.push(layer); + } + s.execute("layer.setCurrent", &json!({"id": parent.0})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + for direction in ["row", "column"] { + select(&mut s, &layers); + let before = s.doc().unwrap().doc.clone(); + let n = steps(&s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(0), "layers must not become ordinary group members"); + assert_eq!(steps(&s), n); + assert!(*s.doc().unwrap().doc == *before); + select(&mut s, &[layers[0], layers[1], a, b]); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(2)); + let groups = ids_of(&r["groups"]); + assert_eq!(children(&s, groups[0]), [a, b]); + for layer in &layers { + assert_eq!(s.doc().unwrap().doc.parent_of(*layer), sublayers.then_some(parent)); + assert!(s.doc().unwrap().selection.objects.contains(layer)); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } + } +} + +#[test] +fn group_rows_refuses_objects_without_a_parent() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let b = rect(&mut s, 15.0, 15.0, 20.0, 20.0); + s.edit("Set root objects", |d, _| { + for id in [a, b] { + let node = d.remove(id)?; + d.layers.push(node); + } + Ok(()) + }) + .unwrap(); + select(&mut s, &[a, b]); + refuses(&mut s, "addon.arrange.groupRows", &[json!({"direction": "row"}), json!({"direction": "column"})]); +} + +fn refuse_row_parts_and_group_whole(s: &mut Session, group: NodeId, parts: &[Vec]) { + let center = bounds(s, group).center(); + let a = rect(s, center.x - 10.0, center.y - 10.0, 20.0, 20.0); + let b = rect(s, center.x - 5.0, center.y - 5.0, 20.0, 20.0); + let members = children(s, group); + for direction in ["row", "column"] { + for selected in parts { + select(s, selected); + let selection = s.doc().unwrap().selection.clone(); + refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(s.doc().unwrap().selection, selection); + let mut mixed = selected.clone(); + mixed.extend([a, b]); + select(s, &mixed); + refuses(s, "addon.arrange.groupRows", &[json!({"direction": direction})]); + assert_eq!(children(s, group), members); + } + select(s, &[group, a, b]); + let before = s.doc().unwrap().doc.clone(); + let n = steps(s); + let r = s.execute("addon.arrange.groupRows", &json!({"direction": direction})).unwrap(); + assert_eq!(r["grouped"], json!(3)); + let groups = ids_of(&r["groups"]); + assert_eq!(children(s, groups[0]), [group, a, b]); + assert_eq!(children(s, group), members); + assert_eq!(steps(s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before); + } +} + +#[test] +fn group_rows_refuses_objects_on_path_children_but_groups_the_whole_group() { + let mut s = session(); + let path = rect(&mut s, 20.0, 20.0, 100.0, 100.0); + let member = rect(&mut s, 30.0, 30.0, 20.0, 20.0); + let group = NodeId(s.execute("object.objectsOnPath.attach", &json!({"path": path.0, "ids": [member.0]})).unwrap()["id"].as_u64().unwrap()); + refuse_row_parts_and_group_whole(&mut s, group, &[vec![path, member]]); + assert!(s.doc().unwrap().doc.node(group).unwrap().extras().objects_on_path.is_some()); +} + +#[test] +fn group_rows_refuses_live_paint_faces_and_edges_but_groups_the_whole_group() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0); + select(&mut s, &[a, b]); + let group = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(group).unwrap(); + let faces: Vec<_> = vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect(); + let edges: Vec<_> = vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect(); + assert!(faces.len() >= 2); + assert!(edges.len() >= 2); + refuse_row_parts_and_group_whole(&mut s, group, &[faces.clone(), edges.clone()]); + let node = s.doc().unwrap().doc.node(group).unwrap(); + assert_eq!(vectorcraft_tools::builder::faces(node).iter().map(|n| n.id).collect::>(), faces); + assert_eq!(vectorcraft_tools::builder::edges(node).iter().map(|n| n.id).collect::>(), edges); +} + +#[test] +fn group_rows_refuses_live_graph_descendants_but_groups_the_whole_graph() { + let mut s = session(); + let params = json!({"type": "column", "x": 20, "y": 20, "width": 200, "height": 200, "csv": ",Series\nA,3\nB,5"}); + let graph = NodeId(s.execute("graph.create", ¶ms).unwrap()["id"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(graph).unwrap(); + let series = node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap(); + let marks: Vec<_> = series.children().unwrap().iter().take(2).map(|n| n.id).collect(); + assert_eq!(marks.len(), 2); + let direct = children(&s, graph); + refuse_row_parts_and_group_whole(&mut s, graph, &[marks, direct]); + assert!(s.doc().unwrap().doc.node(graph).unwrap().extras().graph.is_some()); +} + #[test] fn group_rows_refuses_explicitly_selected_live_blend_keys() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 3543a70ff2..dfaf15c8b0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17582,7 +17582,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid | `addon.arrange.replace` | `fit`: `keep`, `bounds` (the replaced object's width and height), `proportional` (fits inside them) (`keep`); `scaleStrokes`; `keep` (false) | Puts a copy of the topmost selected object centred on each of the other selected objects, in that object's place in the stacking order; the replaced objects are deleted unless `keep` (the copy then goes right above each). Needs two objects or more; the copies are selected. → `{ids}` | | `addon.arrange.size` | `width`, `height` pt, 0.001…1000000 (at least one); `proportional` (false: a side not given stays; true: it follows the given one in proportion); `reference` 0…8 (4, the centre); `scaleStrokes` | Gives every selected object that width and height, keeping its reference point in place (the 9-point grid row by row from the top-left). | | `addon.arrange.groupOverlapping` | none | Groups the selected objects (at most 20000) wherever their visual bounds overlap or touch, chains included: when A overlaps B and B overlaps C, all three go in one group. Only objects in the same layer or group are grouped together; objects that overlap nothing stay as they are. Each new group goes where its frontmost member was in the stacking order, and the groups and the objects left alone stay selected; with nothing overlapping it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | -| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, and clipping masks stay in place. The command rejects selections of editable objects whose parent is neither a layer nor a group, including live blend keys, and direct children of Shaper groups or live compound shapes. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | +| `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | From cd1c3e8c9f9936c94dec8e723a05eb18c9904da3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 20:16:33 -0800 Subject: [PATCH 10/46] Docs: name Group by Row among the Arrange Tools visual-bounds exceptions The Arrange Tools overview said every command except Arrange in Grid and Offset Objects measures as object.setBounds does. Group by Row always uses visual bounds, with strokes and vector effects included and raster effects left out, so the overview now names it and points to its row. --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 17d78bcf03..d0521ef3a2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17572,7 +17572,8 @@ images and patterns keep their colours. → `{changed, swatches: [the document s Arrange Tools is a built-in add-on that lays out, swaps, replaces and sizes selected objects: its commands are `addon.arrange.*`, and in the desktop app it lives in Object › Plug-ins › Arrange Tools. Each command acts on the top-level selected objects and is one undo step; a run that moves nothing makes no step. Places and sizes are measured -as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds. +as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid and Offset Objects, which use visual bounds, and Group by Row, which always uses visual bounds +with strokes and vector effects included and raster effects left out (see its row). | Command | Parameters (default) | Does | |---|---|---| From 0b469bb7b663b23e8006a114f7af3fdd13a2f82d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 00:14:10 -0800 Subject: [PATCH 11/46] Plug-ins: typed values reach the preview and the rows they show A plug-in's parameter dialog did not bind its values to the host fields that the preview and the rows' visibleWhen read, so a check box or a typed number stayed in the form: checking a box did not show the rows that depend on it, and the preview kept running with the opening values. The dialog now binds its values with Bind::bound(fields), as Set Corners and the Arrange dialogs do. --- crates/ui-egui/src/dialogs/plugin.rs | 4 +- .../src/dialogs/tests_plugin_fields.rs | 64 +++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 8b6606e068..18d650e4bc 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -42,7 +42,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use craft::menu::Node; -use craft::ui::contract::Show as _; +use craft::ui::contract::{Bind, Show as _}; use craft::ui::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id}; use craft::ui::display::{Shade, Text}; use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog}; @@ -564,7 +564,7 @@ fn build(key: &'static str, m: Manifest, all: Arc<[Param]>, look: Look) -> impl rows.push(Param::read_only_text("description", "", look.description.clone()).full_width()); } rows.extend(all.iter().filter(|p| shown.contains(p.key.as_str())).cloned()); - let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).previews(look.previews); + let mut dialog = ParamDialog::new(key, look.heading(), Cow::Owned(rows)).values(Bind::bound(fields)).previews(look.previews); if let Some(ok) = look.ok { dialog = dialog.ok_label(ok.into()); } diff --git a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs index c02363e9f5..795c540b64 100644 --- a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs +++ b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs @@ -257,3 +257,67 @@ fn an_open_plugin_dialog_follows_a_change_of_language() { assert_eq!(shown, (false, true), "the label in German"); assert_eq!(values.unwrap()["size"].as_f64(), Some(7.0), "the value set before"); } + +/// The width of every path in the active document together, in points. +fn paths_width(app: &VectorcraftApp) -> Option { + let doc = &app.session.doc().ok()?.doc; + let mut ids = Vec::new(); + doc.walk(|n| { + if n.path_data().is_some() { + ids.push(n.id); + } + }); + doc.bounds_of(&ids, false).map(|r| r.x1 - r.x0) +} + +/// Values typed and clicked in a plug-in's dialog reach the plug-in: a check box shows the row +/// whose `visibleWhen` it meets, the number typed there previews on the canvas, and OK runs the +/// filter with it as one undo step. +#[test] +fn typed_plugin_values_show_rows_and_reach_the_preview_and_the_run() { + use crate::tests::panel_harness::Panel; + let id = "test.ui.fields.typed"; + let manifest = format!( + r#"{{"id":"{id}","name":"Typed Values","version":"1","kind":"filter","params":{{ + "grow":{{"type":"bool","default":false,"label":"Grow"}}, + "n":{{"type":"int","min":0,"max":10,"default":3,"label":"Count","visibleWhen":{{"grow":[true]}}}}}}}}"# + ); + // A 30 pt wide triangle when the filter is given `n` 7, a 50 pt square otherwise. + let triangle = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[30,0]},{"p":[15,20]}]}]}}]}"#; + let square = r#"{"objects":[{"path":{"subpaths":[{"closed":true,"anchors":[{"p":[0,0]},{"p":[50,0]},{"p":[50,50]},{"p":[0,50]}]}]}}]}"#; + let wasm = wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""n":7"#, triangle, square)).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.app().run("plugin.dialog", json!({"id": id})).unwrap(); + panel.frame(); + panel.frame(); + assert!(!panel.shows("Count"), "Count is hidden while Grow is off"); + panel.click("Grow"); + panel.frame(); + assert_eq!(fields(&panel.app())["grow"], json!(true), "the click reaches the dialog's values"); + assert!(panel.shows("Count"), "checking Grow shows Count"); + panel.click("Count"); + panel.key(egui::Key::A, egui::Modifiers::COMMAND); + panel.type_text("7"); + panel.key(egui::Key::Tab, egui::Modifiers::NONE); + panel.frame(); + panel.frame(); + let typed = fields(&panel.app())["n"].clone(); + let previewed = paths_width(&panel.app()); + let undo = panel.app().session.doc().unwrap().history.undo.len(); + panel.click("OK"); + panel.frame(); + panel.frame(); + let (closed, steps, ran) = { + let app = panel.app(); + (!app.any_dialog_open(), app.session.doc().unwrap().history.undo.len(), paths_width(&app)) + }; + panel.app().run("plugin.remove", json!({"id": id})).unwrap(); + assert_eq!(typed.as_f64(), Some(7.0), "the typed count reaches the dialog's values"); + assert_eq!(previewed, Some(30.0), "the typed count previewed"); + assert!(closed, "OK closed the dialog"); + assert_eq!(steps, undo + 1, "one undo step"); + assert_eq!(ran, Some(30.0), "the filter ran with the typed count"); +} From bd30cd9632bbfa526f9776d51eec2048a6afcd5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:12:38 -0800 Subject: [PATCH 12/46] CI: call the gate at craft-common-actions#408's head until it merges The gate on craft-common-actions main has no warm-split input yet, so every run of this branch failed at startup. #408 adds the input; this pin goes back to @main once #408 merges. --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index becfca919b..54d94137ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,9 @@ concurrency: jobs: gate: # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + # Pinned to storytold/craft-common-actions#408 (the gate's warm-split input) until it merges; + # this goes back to @main before this pull request merges. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@2dccde94f9052f8cd613ab1a35b251a58a1193a2 with: # Same craft-fonts commit as release.yml. craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From ca561c27212900ce25e05f1c4b5035bd0b1d52e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:14:37 -0800 Subject: [PATCH 13/46] CI: call #408's gate from the fork that holds its head The commit 2dccde94 exists only in dotCooCoo/craft-common-actions, so GitHub could not find the workflow under storytold. --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 54d94137ee..0e9e00e24d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,7 +25,7 @@ jobs: # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. # Pinned to storytold/craft-common-actions#408 (the gate's warm-split input) until it merges; # this goes back to @main before this pull request merges. - uses: storytold/craft-common-actions/.github/workflows/gate.yml@2dccde94f9052f8cd613ab1a35b251a58a1193a2 + uses: dotCooCoo/craft-common-actions/.github/workflows/gate.yml@2dccde94f9052f8cd613ab1a35b251a58a1193a2 with: # Same craft-fonts commit as release.yml. craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From 4082035b82d0688ed5a1d132f01081dc46e62a02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:51:02 -0800 Subject: [PATCH 14/46] Scripts: locked artboards stop path edits, and move and zOrder respect clipping paths - PathItem point, paint, stroke and transform changes on a path on a locked artboard now throw `Cannot edit` and change nothing, as the PageItem setters do. `pathItems.removeAll()` deletes nothing when a path is on a locked artboard, as `pageItems.removeAll()` does; it used to delete them. - `move` and `duplicate` with `PLACEAFTER` and the clipping path of a clip group or clipping layer as the relative object throw instead of putting the object above the clipping path, or reporting success without moving it. - `zOrder` counts the art above a clipping path and below the layer's ruler guides, as the Arrange commands do, so a method that leaves the object where it is runs no command. Docs: docs/mcp.md. --- crates/engine/src/script/dom.rs | 31 +++++--- crates/engine/src/script/dom/paths.rs | 46 ++++++++---- crates/engine/src/tests/script_dom.rs | 79 +++++++++++++++++++++ crates/engine/src/tests/script_dom_paths.rs | 28 ++++++++ docs/mcp.md | 14 ++-- 5 files changed, 170 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d8d01956f4..04285a3ca5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2657,6 +2657,14 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: (parent, Some(target)) } }; + // The clipping path stays at the bottom of its clip group or clipping layer. + if how == Placement::Below + && target != item.id + && d.node(parent).is_some_and(crate::doc::Node::clips) + && d.position(target).is_some_and(|(_, i, _)| i == 0) + { + return Err(HostError::Error("an object cannot go below a clipping mask".into())); + } if !editable(d, parent) { return Err(HostError::Error("the layer or group is hidden or locked".into())); } @@ -2784,17 +2792,22 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - let (before, after) = with_doc(h, item.doc, |_, st| { - let at = st.doc.position(item.id); - let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0); - (at.map(|(_, i, _)| i), count) + // The Arrange commands keep a clipping path at the bottom of its parent and the art below the + // parent's ruler guides, so the item's place is counted among the art above the clipping path. + let (before, floor, art) = with_doc(h, item.doc, |_, st| { + let d = &st.doc; + let at = d.position(item.id); + let parent = at.and_then(|(p, ..)| p); + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(crate::doc::Node::clips)); + let art = at.and_then(|(p, ..)| d.children(p)).map_or(0, |c| crate::doc::Node::guide_run_start(c)); + (at.map(|(_, i, _)| i), floor, art) }); let Some(i) = before else { return Err(HostError::Error(STALE_ITEM.into())) }; - let top = i + 1 >= after; - let unchanged = match id { - "object.arrange.bringToFront" | "object.arrange.bringForward" => top, - _ => i == 0, - }; + let unchanged = i < floor + || match id { + "object.arrange.bringToFront" | "object.arrange.bringForward" => i + 1 >= art, + _ => i <= floor, + }; if !unchanged { edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e4f6bb203e..274edf78a1 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -15,7 +15,9 @@ //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside //! groups and compound paths included. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden -//! or locked layer or group, throws `Cannot edit` with nothing changed. +//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing +//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked +//! artboard. //! - A path in a compound path or compound shape reads that owner's paint, which the paint //! commands change in its place, and a gradient that `filled = true` gives it is placed on that //! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and @@ -106,6 +108,18 @@ fn cannot_edit(id: NodeId) -> HostError { HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) } +/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or +/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one. +fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> { + if !editable(&st.doc, id) { + return Err(cannot_edit(id)); + } + if super::on_locked_artboard(h, st, id) { + return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0))); + } + Ok(()) +} + /// The path `d` names, which must still be in its document. fn path_of(h: &super::Host, d: &Data) -> std::result::Result { let item = item_of(h, d)?; @@ -234,7 +248,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with /// the path's other point changes until [`flush`] writes them. The first change of a path writes /// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or -/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object +/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path that is aligned to the pixel grid, or is in an object /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { forget_waiting_starts(h); @@ -246,15 +260,13 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; let r = f(&mut subs); - let (same, ok, aligned) = read_path(h, item, |st, _, pd| { + let (same, refused, aligned) = read_path(h, item, |st, _, pd| { let d = &st.doc; let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); - (pd.subpaths == subs, editable(d, item.id), aligned) + (pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned) })?; if !same { - if !ok { - return Err(cannot_edit(item.id)); - } + refused?; *h.dom.pending.borrow_mut() = Some((item, subs)); if aligned { flush(h)?; @@ -337,15 +349,12 @@ fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which -/// must be one the user could edit. +/// must be one the user could edit ([`refuse_path_edit`]). /// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { - let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)); - if !ok { - return Err(cannot_edit(item.id)); - } + with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?; if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); } @@ -434,18 +443,25 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } /// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before +/// anything is deleted, as `PageItems.removeAll()` does. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = path_items(h, st); let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 14878904fb..eb5a2ff667 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -895,6 +895,85 @@ fn a_path_inside_a_compound_path_is_not_reordered() { assert_eq!(out, vec![json!([1, 2])]); } +/// [`doc`] with `a`, `b` and a rectangle `c` on top made into a clip group `g`, clipped by `c`. The +/// page items are `g`, `b`, `a` and `c`, topmost first. +fn clip_group() -> (Session, NodeId, NodeId, NodeId, NodeId) { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 0.0, 0.0, 200.0, 200.0); + s.execute("select.set", &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(children_of(&s, g), [c, a, b], "the clipping path is at the bottom"); + (s, g, a, b, c) +} + +/// The ids of the children of `id`, bottom first. +fn children_of(s: &Session, id: NodeId) -> Vec { + s.active().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +#[test] +fn nothing_is_placed_below_a_clipping_path() { + let (mut s, g, a, b, c) = clip_group(); + let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0); + s.execute("select.none", &json!({})).unwrap(); + let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); + // From outside the group, from above the clipping path inside it, and a copy. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, mask = p[4], out = [];\ + var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\ + function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\ + function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); }];\ + for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\ + vc.log(out);", + ); + let messages = out[0].as_array().cloned().unwrap_or_default(); + assert_eq!(messages.len(), 3, "{out:?}"); + for m in &messages { + assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}"); + } + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + assert_eq!(undo_steps(&s), steps); + // Directly above the clipping path is allowed, and so is moving the clipping path beside itself. + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[4], ElementPlacement.PLACEBEFORE);"); + assert_eq!(children_of(&s, g), [c, d, a, b]); + let steps = undo_steps(&s); + log(&mut s, "var p = app.activeDocument.pageItems; p[4].move(p[4], ElementPlacement.PLACEAFTER);"); + assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, d, a, b], steps)); +} + +#[test] +fn zorder_that_leaves_an_object_in_place_runs_no_command() { + // The topmost art of a layer with a ruler guide above it. + let (mut s, a, b) = doc(); + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("guide.add", &json!({"vertical": true, "pos": 50, "layer": layer.0})).unwrap(); + let kids = s.active().unwrap().doc.layers[0].children().unwrap().clone(); + assert!(kids.len() == 3 && kids[2].is_ruler_guide(), "the guide is above the art"); + let steps = undo_steps(&s); + let r = + run(&mut s, "var p = app.activeDocument.pageItems; p[0].zOrder(ZOrderMethod.BRINGTOFRONT); p[0].zOrder(ZOrderMethod.BRINGFORWARD);").unwrap(); + assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps)); + assert_eq!(layer_order(&s)[..2], [a, b]); + // The lowest object above a clipping path, and the clipping path itself. + let (mut s, g, a, b, c) = clip_group(); + let steps = undo_steps(&s); + let r = run( + &mut s, + "var p = app.activeDocument.pageItems, ways = [ZOrderMethod.BRINGTOFRONT, ZOrderMethod.BRINGFORWARD,\ + ZOrderMethod.SENDBACKWARD, ZOrderMethod.SENDTOBACK];\ + p[2].zOrder(ZOrderMethod.SENDBACKWARD); p[2].zOrder(ZOrderMethod.SENDTOBACK);\ + for (var k = 0; k < ways.length; k++) p[3].zOrder(ways[k]);", + ) + .unwrap(); + assert_eq!((&r["slowestCommands"], undo_steps(&s)), (&json!([]), steps)); + assert_eq!(children_of(&s, g), [c, a, b]); + // A change still runs the command. + log(&mut s, "app.activeDocument.pageItems[1].zOrder(ZOrderMethod.SENDTOBACK);"); + assert_eq!((children_of(&s, g), undo_steps(&s)), (vec![c, b, a], steps + 1)); +} + #[test] fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 87f1c4f9ab..8988c042eb 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -1480,6 +1480,34 @@ fn assigning_guides_refuses_paths_that_cannot_be_selected() { assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide"); } +#[test] +fn path_changes_refuse_paths_on_a_locked_artboard() { + let (mut s, a, _) = doc(); + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let (before, steps) = (art(&s), undo_steps(&s)); + // Points (waiting and written at once), paint, stroke and a transform. + for change in [ + "p.closed = false;", + "p.pathPoints[0].anchor = [1, 2];", + "p.setEntirePath([[0, 0], [10, 10]]);", + "p.filled = false;", + "p.strokeWidth = 7;", + "p.translate(5, 5);", + ] { + let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}")); + assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}"); + } + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard"), "{e}"); + assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps)); + // A value the path has changes nothing and does not throw, and the path changes once the + // artboard is unlocked. + log(&mut s, "app.activeDocument.pathItems[0].closed = true;"); + s.execute("artboard.setProps", &json!({"index": 0, "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[0].strokeWidth = 7;"); + assert_ne!(art(&s), before); +} + fn is_guide(s: &Session, id: NodeId) -> bool { matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) } diff --git a/docs/mcp.md b/docs/mcp.md index 3b647e4c7b..87a42a3e15 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3026,14 +3026,19 @@ through `$`: `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` - directly below it. An object of another document throws `Cross-document placement is not available`, and when + directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the + object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws + `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). An object of + another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`, `locked`, `opacity`, `blendingMode`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer or on a locked artboard throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such - an object throws `Cannot edit` too. The one exception is `opacity` or `blendingMode` given the value the object already has, which + an object throws `Cannot edit` too. `zOrder()` that would leave the object where it is runs no command: bringing + forward the topmost art of a layer whose ruler guides are above it, sending backward the lowest object above a + clipping path, or any method on the clipping path itself. The one exception is `opacity` or `blendingMode` given the value the object already has, which changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity or blend mode, that value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an object that is hidden or locked itself takes `hidden`, `locked`, `opacity` and `blendingMode` (VectorCraft's own rule). Position, @@ -3271,8 +3276,9 @@ through `$`: `resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path - that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing - changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or + that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard throws + `Cannot edit` with nothing changed, and `pathItems.removeAll()` when any path is on a locked artboard throws + `cannot delete objects on a locked artboard` and deletes nothing. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity` and the gradient stops are not available yet. From 1feb6c7f3884461aa6280c6eb8d54a2a029de396 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 18:18:59 -0800 Subject: [PATCH 15/46] Scripts: duplicate refuses a copy of a clipping path below itself mask.duplicate(mask, ElementPlacement.PLACEAFTER) put the copy directly above the clipping path without an error. A copy now goes through the same refusal as other objects; move of the clipping path below itself still leaves it where it is. --- crates/engine/src/script/dom.rs | 14 ++++++++------ crates/engine/src/tests/script_dom.rs | 8 +++++--- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 04285a3ca5..a041427e46 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2623,8 +2623,9 @@ struct Destination { /// The object a relative object of `move` or `duplicate` names: a page item or a layer of the /// same document as `item`. An object may go directly above or below itself: a copy goes there, as -/// `layer.move` puts copies, and a move there leaves the object where it is. -fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result { +/// `layer.move` puts copies, and a move there leaves the object where it is. A copy (`copy`) of a +/// clipping path cannot go below it. +fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); @@ -2657,9 +2658,10 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: (parent, Some(target)) } }; - // The clipping path stays at the bottom of its clip group or clipping layer. + // The clipping path stays at the bottom of its clip group or clipping layer. Moving the + // clipping path below itself leaves it where it is. if how == Placement::Below - && target != item.id + && (target != item.id || copy) && d.node(parent).is_some_and(crate::doc::Node::clips) && d.position(target).is_some_and(|(_, i, _)| i == 0) { @@ -2719,7 +2721,7 @@ fn item_move(h: &Host, a: &[Data]) -> Answer { if matches!(arg(a, 1), Data::Undefined) { return Err(HostError::Type("move needs a relative object".into())); } - let to = destination(h, item, arg(a, 1), arg(a, 2))?; + let to = destination(h, item, arg(a, 1), arg(a, 2), false)?; if to.beside != Some(item.id) { place(h, item.doc, item.id, &to)?; } @@ -2760,7 +2762,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { } None } - target => Some(destination(h, item, target, arg(a, 2))?), + target => Some(destination(h, item, target, arg(a, 2), true)?), }; let id = atomically(h, |h| { let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index eb5a2ff667..e7b53f8759 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -918,18 +918,20 @@ fn nothing_is_placed_below_a_clipping_path() { let d = rect(&mut s, 300.0, 10.0, 5.0, 5.0); s.execute("select.none", &json!({})).unwrap(); let (before, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); - // From outside the group, from above the clipping path inside it, and a copy. + // From outside the group, from above the clipping path inside it, a copy, and a copy of the + // clipping path below itself. let out = log( &mut s, "var p = app.activeDocument.pageItems, mask = p[4], out = [];\ var tries = [function () { p[0].move(mask, ElementPlacement.PLACEAFTER); },\ function () { p[3].move(mask, ElementPlacement.PLACEAFTER); },\ - function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); }];\ + function () { p[0].duplicate(mask, ElementPlacement.PLACEAFTER); },\ + function () { mask.duplicate(mask, ElementPlacement.PLACEAFTER); }];\ for (var i = 0; i < tries.length; i++) { try { tries[i](); out.push('ran'); } catch (e) { out.push(e.message); } }\ vc.log(out);", ); let messages = out[0].as_array().cloned().unwrap_or_default(); - assert_eq!(messages.len(), 3, "{out:?}"); + assert_eq!(messages.len(), 4, "{out:?}"); for m in &messages { assert!(m.as_str().is_some_and(|m| m.contains("an object cannot go below a clipping mask")), "{out:?}"); } From ab051030b760e0093ec4cda74391eb05f63e0ba5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 18:52:55 -0800 Subject: [PATCH 16/46] Docs: a clipping path moved below itself stays where it is --- docs/mcp.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 45b8f7a119..5be728a873 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3034,7 +3034,9 @@ through `$`: group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws - `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). An object of + `an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception + is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the + document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or From 183c365effb201f9f92e0c84a8e68d4a447e3388 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 20:09:42 -0800 Subject: [PATCH 17/46] Icons: draw every tool icon's outline at the same width The app icon set declared a 1.6-unit stroke, but its own dc-* icons draw 1.5-unit outlines and its Lucide copies draw 2-unit ones. The framework scales each icon's strokes by the drawn width over the declared width, so the dc-* icons drew about 6% thinner than the catalog's icons and the Lucide copies (Pen, Paintbrush, Add and Delete Anchor Point and others) about 25% heavier, which made the tool rail's outlines uneven. - Split the table: the dc-* icons stay in the "vectorcraft" set, now declared at 1.5, and the Lucide copies move to a "vectorcraft-lucide" set declared at 2. icons::register() registers both. - dc-free-distort drew a 2-unit outline; it now draws 1.5 like the rest of its set. - A test checks that every app icon's outline width equals its set's declared width. --- assets/icons/dc-free-distort.svg | 2 +- crates/ui-egui/src/addons/shapes.rs | 4 +- crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/cursors/tests.rs | 2 +- crates/ui-egui/src/icon_data.rs | 53 ++++++++------- crates/ui-egui/src/icons.rs | 78 +++++++++++++++++------ crates/ui-egui/src/panels/layers/tests.rs | 4 +- crates/ui-egui/src/tests/cut.rs | 2 +- 8 files changed, 97 insertions(+), 50 deletions(-) diff --git a/assets/icons/dc-free-distort.svg b/assets/icons/dc-free-distort.svg index 9013cf97ae..3a6ea4451d 100644 --- a/assets/icons/dc-free-distort.svg +++ b/assets/icons/dc-free-distort.svg @@ -1,4 +1,4 @@ - + diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index e5fde5725e..65fed545ca 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -709,7 +709,7 @@ mod cancel_tests { #[cfg(test)] mod tests { use craft::behavior::IconId; - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; use super::icon_for_shape; @@ -717,7 +717,7 @@ mod tests { /// would show the placeholder instead of the toolbar's icon. #[test] fn every_shape_button_shows_its_tools_icon() { - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] { let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool")); assert_eq!(icon_for_shape(id), crate::icons::tool_icon(tool.icon), "{id}"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 34bad16a79..9849b7e02e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -67,7 +67,7 @@ impl VectorcraftApp { /// once, gives Data Recovery the host's store and makes a view for each open document. pub fn new(mut session: Session, mut services: Services) -> Self { // Every entry point (desktop, web, tests) makes the app before its first pass. - craft::ui::primitives::register_app_icons(&super::icons::APP_ICONS); + super::icons::register(); craft::ui::primitives::register_app_icons(&super::cursors::CURSOR_ICONS); // The font menus and the first file opened need the installed fonts: catalog them now. vectorcraft_text::FontDb::global().scan_in_background(); diff --git a/crates/ui-egui/src/cursors/tests.rs b/crates/ui-egui/src/cursors/tests.rs index 183bda8b47..2f6821f8a9 100644 --- a/crates/ui-egui/src/cursors/tests.rs +++ b/crates/ui-egui/src/cursors/tests.rs @@ -17,7 +17,7 @@ fn every_tool_cursors_hotspot_is_on_its_glyph() { use craft::ui::primitives::{painted_image, register_app_icons}; use craft::ui::runtime::env::Env; use craft::ui::style::rgba_color; - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); register_app_icons(&CURSOR_ICONS); let mut missed = Vec::new(); crate::testing::ui_context() diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 96719fa0c9..eb2a544af8 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -4,31 +4,8 @@ /// The Selection and Direct Selection arrows' fill, painted black or white under their outline. pub const DC_ARROW_FILL: &[u8] = include_bytes!("../../../assets/icons/dc-arrow-fill.svg"); +/// VectorCraft's own `dc-*` icons, drawn with 1.5-unit strokes in a 24-unit view box. pub static ICONS: &[(&str, &[u8])] = &[ - ("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")), - ("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")), - ("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")), - ("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")), - ("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")), - ("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")), - ("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")), - ("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")), - ("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")), - ("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")), - ("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")), - ("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")), - ("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")), - ("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")), - ("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")), - ("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")), - ("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")), - ("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")), - ("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")), - ("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")), - // PLAN: circle-off.svg is plugins-w11's file; the row waits for it. - ("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")), - ("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")), - ("combine", include_bytes!("../../../assets/icons/combine.svg")), ("dc-actions", include_bytes!("../../../assets/icons/dc-actions.svg")), ("dc-al-bottom", include_bytes!("../../../assets/icons/dc-al-bottom.svg")), ("dc-al-center", include_bytes!("../../../assets/icons/dc-al-center.svg")), @@ -244,6 +221,34 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-wrinkle", include_bytes!("../../../assets/icons/dc-wrinkle.svg")), ("dc-zoom-large", include_bytes!("../../../assets/icons/dc-zoom-large.svg")), ("dc-zoom-small", include_bytes!("../../../assets/icons/dc-zoom-small.svg")), +]; + +/// Lucide icons the built-in catalog lacks, drawn with Lucide's 2-unit strokes in a 24-unit view box. +pub static LUCIDE_ICONS: &[(&str, &[u8])] = &[ + ("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")), + ("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")), + ("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")), + ("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")), + ("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")), + ("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")), + ("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")), + ("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")), + ("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")), + ("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")), + ("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")), + ("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")), + ("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")), + ("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")), + ("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")), + ("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")), + ("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")), + ("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")), + ("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")), + ("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")), + // PLAN: circle-off.svg is plugins-w11's file; the row waits for it. + ("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")), + ("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")), + ("combine", include_bytes!("../../../assets/icons/combine.svg")), ("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")), ("eye-off", include_bytes!("../../../assets/icons/eye-off.svg")), ("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 30b6edfb49..a544de7e90 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -2,14 +2,24 @@ use craft::ui::primitives::{AppIcons, icon_names}; -use crate::icon_data::{DC_ARROW_FILL, ICONS}; +use crate::icon_data::{DC_ARROW_FILL, ICONS, LUCIDE_ICONS}; /// The fills of the Selection and Direct Selection arrows: black and white whatever the theme, as users /// know them, under an outline in the theme's colour. const FILLS: &[(&str, &[u8], [u8; 4])] = &[("dc-selection", DC_ARROW_FILL, [0, 0, 0, 255]), ("dc-direct", DC_ARROW_FILL, [255, 255, 255, 255])]; -/// The app's icons, for `register_app_icons`. -pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.6), ICONS).with_fills(FILLS); +/// The app's own icons, for `register_app_icons`. The stroke width is the documents' own, so the framework redraws +/// their strokes at the width it draws the catalog's. +pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.5), ICONS).with_fills(FILLS); + +/// The Lucide icons the catalog lacks, with Lucide's own stroke width. +pub static LUCIDE_APP_ICONS: AppIcons = AppIcons::new("vectorcraft-lucide", Some(2.0), LUCIDE_ICONS); + +/// Registers both of the app's icon sets beside the framework's catalog. +pub fn register() { + craft::ui::primitives::register_app_icons(&APP_ICONS); + craft::ui::primitives::register_app_icons(&LUCIDE_APP_ICONS); +} /// Map tool-catalogue icon names to the names of icons that resolve. pub fn tool_icon(name: &str) -> &'static str { @@ -114,23 +124,63 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-print-tiling" => "dc-print-tiling", "tool-zoom" => "zoom_in", // A name that is already an icon maps to itself, as the `'static` name of the set that has it. - other => icon_names().iter().copied().chain(APP_ICONS.icons.iter().map(|(n, _)| *n)).find(|n| *n == other).unwrap_or("rect_dashed"), + other => icon_names() + .iter() + .copied() + .chain(APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons).map(|(n, _)| *n)) + .find(|n| *n == other) + .unwrap_or("rect_dashed"), } } #[cfg(test)] mod tests { - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; // PLAN: assumed the `craft` facade is a dependency of vectorcraft-ui-egui (Cargo.toml is not in this set's files; craft-ui does not re-export IconId) use craft::behavior::IconId; use super::*; fn resolves(name: &'static str) -> bool { - register_app_icons(&APP_ICONS); + register(); has_icon(&IconId::new(name)) } + /// The SVG document of the app icon `name`, from either set. + fn app_svg(name: &str) -> String { + let (_, bytes) = ICONS.iter().chain(LUCIDE_ICONS).find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an app icon")); + String::from_utf8_lossy(bytes).into_owned() + } + + /// The `stroke-width` the document's root `` element sets, the width of every stroke that sets none of its + /// own; `None` for a document drawn with fills. + fn root_stroke_width(svg: &str) -> Option { + let root = svg.split("').next()?; + Some(root.split("stroke-width=\"").nth(1)?.split('"').next()?.parse().unwrap_or(f32::NAN)) + } + + // Regression test: the tool rail's icons drew uneven outlines. The app set declared a 1.6-unit stroke while its own icons drew 1.5 and + // its Lucide copies drew 2, so the framework drew them 6% thinner and 25% heavier than the catalog's icons. + /// The framework scales every stroke in a set by the drawn width over the set's declared width, so an icon's + /// outline matches the catalog's only when its root stroke width equals its set's declared width. Details with + /// a width of their own keep their ratio to the outline. + #[test] + fn every_app_icon_draws_its_outline_at_the_catalog_width() { + let mut off = Vec::new(); + for set in [&APP_ICONS, &LUCIDE_APP_ICONS] { + let declared = set.stroke_width.unwrap_or_else(|| panic!("{} declares its stroke width", set.name)); + for (name, bytes) in set.icons { + let Some(width) = root_stroke_width(&String::from_utf8_lossy(bytes)) else { continue }; + // The outline's drawn width relative to the catalog's. + let relative = width / declared; + if !(0.99..=1.01).contains(&relative) { + off.push(format!("{name} in {}: {width} draws at {relative:.3} of the catalog width", set.name)); + } + } + } + assert!(off.is_empty(), "app icons whose outlines do not draw at the catalog width: {off:#?}"); + } + /// The ways a source line writes an icon id as a literal; a `const` that holds one is read by `const_icon`. const FORMS: [&str; 3] = ["IconId::new(\"", "icon(\"", "icon = \""]; @@ -153,7 +203,7 @@ mod tests { /// app's set. Other ids built in match arms and tuple tables are not scanned. #[test] fn every_icon_id_literal_and_panel_icon_resolves() { - register_app_icons(&APP_ICONS); + register(); let resolves = |id: &str| has_icon(&IconId::from(std::borrow::Cow::Owned(id.to_owned()))); let (mut seen, mut unknown) = (0, Vec::new()); let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")]; @@ -212,10 +262,7 @@ mod tests { // as opaque as the line, so the line vanished where it crossed the bar. #[test] fn the_cap_icons_mark_the_path_end_in_one_place_over_a_lighter_stroke() { - let svg = |name: &str| { - let (_, bytes) = crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an icon")); - String::from_utf8_lossy(bytes).into_owned() - }; + let svg = app_svg; // The end-of-path line is the icon's last shape, a vertical line `M{x} …V…`. let end_line = |icon: &str| -> String { let last = icon.rsplit(">(); let pen = shapes(&svg("tool-pen")); @@ -331,7 +373,7 @@ mod tests { assert!(resolves(name), "{} maps to {name}, which no icon set has", tool.icon); } let catalog = icon_names(); - for (name, _) in APP_ICONS.icons { + for (name, _) in APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons) { assert!(!catalog.contains(name), "{name} is in the catalog: the app's copy is refused"); } } diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 6155d4f6e7..ef54366ba5 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -341,7 +341,7 @@ fn rows_list_by_depth_and_ruler_guide_nodes_get_no_object_row() { /// guide kind's ruler, and both glyphs are in the app's icon set. #[test] fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() { - use craft::ui::primitives::{has_icon, register_app_icons}; + use craft::ui::primitives::has_icon; let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); @@ -355,7 +355,7 @@ fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() { }; let (across, down) = (icon_of(false), icon_of(true)); assert_ne!(across, down, "the two kinds of guide rows look alike"); - register_app_icons(&crate::icons::APP_ICONS); + crate::icons::register(); for icon in [&across, &down] { assert!(has_icon(icon), "{icon:?} is in no icon set, so the row draws nothing"); } diff --git a/crates/ui-egui/src/tests/cut.rs b/crates/ui-egui/src/tests/cut.rs index 4732a6347b..995f87564a 100644 --- a/crates/ui-egui/src/tests/cut.rs +++ b/crates/ui-egui/src/tests/cut.rs @@ -11,7 +11,7 @@ fn the_cut_tools_have_their_own_icons_and_toolbar_slot() { let info = vectorcraft_tools::tool_info(tool).unwrap(); assert_eq!(icons::tool_icon(info.icon), icon); // The app registers its icons at start; a test run alone in its process must too. - craft::ui::primitives::register_app_icons(&icons::APP_ICONS); + icons::register(); assert!(craft::ui::primitives::has_icon(&IconId::new(icon)), "{icon}"); assert!(crate::toolbar::BASIC.iter().flat_map(|(_, slots)| slots.iter()).any(|s| s.contains(&tool) && s.contains(&"knife"))); } From de519fe5659d6ad18a50dedea1350b813f0b581b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 20:46:38 -0800 Subject: [PATCH 18/46] CI: call the gate at craft-common-actions main again craft-common-actions#408 merged, so main's gate.yml has the warm-split input. --- .github/workflows/ci.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e9e00e24d..becfca919b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,9 +23,7 @@ concurrency: jobs: gate: # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. - # Pinned to storytold/craft-common-actions#408 (the gate's warm-split input) until it merges; - # this goes back to @main before this pull request merges. - uses: dotCooCoo/craft-common-actions/.github/workflows/gate.yml@2dccde94f9052f8cd613ab1a35b251a58a1193a2 + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: # Same craft-fonts commit as release.yml. craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From b143f92f3fe4d0f4848c4925ee7a6da02ad32441 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 20:49:40 -0800 Subject: [PATCH 19/46] Vector Halftone: Euclidean and Elliptical dot shapes Object > Vector Halftone and the live Vector Halftone effect get two dot shapes that follow the classic spot functions. Euclidean dots are round in the highlights, meet corner to corner at 50% as a checkerboard and turn into round holes in the shadows. Elliptical dots are long, join into chains along their length at 40% and on every side at 60%, then turn into long holes. Each dot is a vector path whose area is the cell's tone. The existing Ellipse shape is unchanged. --- crates/effects/src/addons/halftone.rs | 215 ++++++++++++++++++++++++- crates/engine/src/cmd/halftone.rs | 6 +- crates/ui-egui/src/dialogs/halftone.rs | 10 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 5 files changed, 229 insertions(+), 7 deletions(-) diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 9b5771e7bd..b031cf4c44 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -19,7 +19,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::color::{BlendMode, Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId}; use vectorcraft_geom::hit::fill_contains; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, BezPath, CubicBez, FillRule, PathData, Point, Rect, shapes}; use vectorcraft_pathops::{self as po, BoolOp}; use crate::catalog::{EffectInfo, Lengths}; @@ -43,7 +43,7 @@ pub(crate) fn catalog() -> Vec { id: HALFTONE, label: "Vector Halftone…", menu: &["Effect", "Color Effects"], - params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", + params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is", defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}), raster: false, lengths: Lengths::default(), @@ -63,6 +63,12 @@ pub enum DotShape { Square, Diamond, Line, + /// Round dots that grow into squares meeting corner to corner at 50% (a checkerboard), then + /// round holes, as the Euclidean spot function draws them. + Euclidean, + /// Elongated dots that join along their long side at 40% into chains, along their short side + /// at 60%, then elongated holes. + Elliptical, } impl DotShape { @@ -73,6 +79,8 @@ impl DotShape { "square" => DotShape::Square, "diamond" => DotShape::Diamond, "line" | "lines" => DotShape::Line, + "euclidean" => DotShape::Euclidean, + "elliptical" => DotShape::Elliptical, _ => return None, }) } @@ -94,10 +102,149 @@ impl DotShape { DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)), // Cells along a row join into a line as thick as the tone. DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))), + DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, 1.0, &EUCLIDEAN)), + DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, elliptical_ratio(), &ELLIPTICAL)), } } } +/// The Elliptical dot's height over its width: the ratio at which a dot exactly as wide as its +/// cell, clipped to the cell's diamond, covers 40% of the cell. +fn elliptical_ratio() -> f64 { + static R: OnceLock = OnceLock::new(); + *R.get_or_init(|| { + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..60 { + let mid = (lo + hi) / 2.0; + if quadrant_area(1.0, mid, 1.0) < 0.4 { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) +} + +/// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5. +const SIZE_STEPS: usize = 512; + +static EUCLIDEAN: OnceLock> = OnceLock::new(); +static ELLIPTICAL: OnceLock> = OnceLock::new(); + +/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the ellipse with height `ratio × a` whose part +/// inside the diamond |x| + |y| ≤ 1 covers that tone of the cell [-1, 1]². +fn dot_sizes(ratio: f64) -> Vec { + (0..=SIZE_STEPS) + .map(|k| { + // A quadrant of the cell has area 1. + let target = k as f64 / SIZE_STEPS as f64 * 0.5; + let (mut lo, mut hi) = (0.0, 1.0 / ratio); + for _ in 0..50 { + let mid = (lo + hi) / 2.0; + if quadrant_area(mid, mid * ratio, 1.0) < target { lo = mid } else { hi = mid } + } + (lo + hi) / 2.0 + }) + .collect() +} + +/// The area of the first quadrant of the ellipse with semi-axes `a`, `b` clipped to x + y ≤ `h`. +fn quadrant_area(a: f64, b: f64, h: f64) -> f64 { + use vectorcraft_geom::kurbo::ParamCurveArea; + quadrant(a, b, h).iter().map(|c| c.signed_area()).sum() +} + +/// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤ +/// `h`, from its point on the x axis to its point on the y axis, as cubic curves. +fn quadrant(a: f64, b: f64, h: f64) -> Vec { + use std::f64::consts::FRAC_PI_2; + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let arc = |out: &mut Vec, t0: f64, t1: f64| { + if t1 <= t0 { + return; + } + let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); + let d = (t1 - t0) / n; + let k = 4.0 / 3.0 * (d / 4.0).tan(); + for i in 0..n as usize { + let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0)); + let (p0, p3) = (at(u0), at(u1)); + let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos()); + let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos()); + out.push(CubicBez::new(p0, c1, c2, p3)); + } + }; + let line = |p: Point, q: Point| CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q); + let mut out = vec![]; + let r = a.hypot(b); + if r <= h { + arc(&mut out, 0.0, FRAC_PI_2); + return out; + } + let (phi, alpha) = (b.atan2(a), (h / r).acos()); + let (ts, te) = (phi - alpha, phi + alpha); + let start = if ts > 0.0 { + arc(&mut out, 0.0, ts); + at(ts) + } else { + Point::new(h, 0.0) + }; + let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) }; + out.push(line(start, end)); + arc(&mut out, te, FRAC_PI_2); + out +} + +/// `curves` reversed, each curve run backwards. +fn reversed(curves: &[CubicBez]) -> Vec { + curves.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect() +} + +/// `curves` with each point mapped by `f`. +fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec { + curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect() +} + +/// The quadrant of the spot for tone `u` (0..0.5) in a cell of half side `h`, its dot `ratio` as +/// tall as wide, its sizes from `table` ([`dot_sizes`]). +fn spot_quadrant(u: f64, h: f64, ratio: f64, table: &OnceLock>) -> Vec { + let sizes = table.get_or_init(|| dot_sizes(ratio)); + let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64; + let i = (x.floor() as usize).min(SIZE_STEPS - 1); + let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); + let a = lo + (hi - lo) * (x - i as f64); + quadrant(a * h, a * ratio * h, h) +} + +/// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to +/// half tone, an ellipse (`ratio` as tall as wide) clipped to the cell's diamond, with the tone's +/// area; past half, the cell with the dot of the opposite tone cut out at each corner, so the dark +/// joins up and the light becomes holes. +fn spot(t: f64, h: f64, ratio: f64, table: &OnceLock>) -> BezPath { + let mut bp = BezPath::new(); + let mut add = |curves: Vec, first: bool| { + for (k, c) in curves.iter().enumerate() { + if k == 0 { + if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) } + } + bp.curve_to(c.p1, c.p2, c.p3); + } + }; + if t <= 0.5 { + let q1 = spot_quadrant(t, h, ratio, table); + add(q1.clone(), true); + add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false); + add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false); + add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false); + } else { + // Round the corners counterclockwise, each one's hole the dot of the opposite tone. + let q1 = spot_quadrant(1.0 - t.min(1.0), h, ratio, table); + add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); + add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); + add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); + add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false); + } + bp.close_path(); + bp +} + /// One screen: its ink and angle, and how to read its tone from a sampled pixel. struct Screen { paint: Color, @@ -399,6 +546,7 @@ pub fn halftone_art(d: &Document, n: &Node) -> Option { mod tests { use super::*; use vectorcraft_doc::Effect; + use vectorcraft_geom::Shape; /// A black square's samples: `side` points of black from (10, 10), white around it. fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) { @@ -464,6 +612,69 @@ mod tests { assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2); } + /// Is `p` (in cells of side 1) inside the dot `shape` draws for tone `t`? + fn covers(shape: DotShape, t: f64, p: (f64, f64)) -> bool { + fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1)) + } + + #[test] + fn spot_dots_cover_the_tone() { + for shape in [DotShape::Euclidean, DotShape::Elliptical] { + for k in 1..100 { + let t = f64::from(k) / 100.0; + let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0; + assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}"); + let b = shape.path(t, 2.0).control_bounds().unwrap(); + assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}"); + } + } + assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical))); + } + + #[test] + fn euclidean_dots_meet_corner_to_corner_at_half() { + let s = DotShape::Euclidean; + // Round dots apart from their neighbors below half. + assert!(!covers(s, 0.45, (0.49, 0.0)) && !covers(s, 0.45, (0.0, 0.49)) && covers(s, 0.45, (0.3, 0.0))); + // At half the dot is the diamond reaching the middle of each side: a checkerboard. + for p in [(0.49, 0.0), (-0.49, 0.0), (0.0, 0.49), (0.0, -0.49)] { + assert!(covers(s, 0.5, p), "{p:?}"); + } + assert!(!covers(s, 0.5, (0.26, 0.26)) && covers(s, 0.5, (0.24, 0.24))); + // Past half the light becomes round holes at the corners. + assert!(covers(s, 0.55, (0.0, 0.499)) && covers(s, 0.55, (0.499, 0.0)) && !covers(s, 0.55, (0.49, 0.49))); + assert!(covers(s, 0.99, (0.3, 0.3))); + } + + #[test] + fn elliptical_dots_join_along_their_length_then_their_width() { + let s = DotShape::Elliptical; + // Below 40% the dots stand apart. + assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45))); + // From 40% they reach their neighbors along x, making chains, but not along y. + assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45))); + // Up to 60% the light still runs along the top edge between the corner holes. + assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3))); + // Past 60% the dark joins across the top edge too, leaving elongated holes. + assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49))); + // The holes are longer along x than along y. + assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {}", elliptical_ratio()); + // Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall. + let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap(); + assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}"); + } + + #[test] + fn spot_shapes_make_dots_through_the_screen() { + for shape in [DotShape::Euclidean, DotShape::Elliptical] { + let h = Halftone::of(&effect(json!({"frequency": 18, "shape": format!("{shape:?}")}))).unwrap(); + assert_eq!(h.shape, shape); + let (s, b) = black_square(60.0, &h); + let (layers, dots) = h.layers(&s, b, None); + assert!(layers.len() == 1 && (150..=320).contains(&dots), "{shape:?}: {dots}"); + } + } + #[test] fn the_caps_refuse_too_many_cells() { let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap(); diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index b54e92932c..9677f23ad6 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] @@ -28,7 +28,9 @@ pub fn specs() -> Vec { fn halftone(s: &mut Session, p: &Value) -> Result { const C: &str = "object.vectorHalftone"; let shape = match text_param(p, "shape", C)? { - Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?, + Some(v) => { + DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))? + } None => DotShape::Circle, }; let frequency = number_or(p, "frequency", 20.0, C)?; diff --git a/crates/ui-egui/src/dialogs/halftone.rs b/crates/ui-egui/src/dialogs/halftone.rs index 98a8515c16..ebc54223f6 100644 --- a/crates/ui-egui/src/dialogs/halftone.rs +++ b/crates/ui-egui/src/dialogs/halftone.rs @@ -47,7 +47,15 @@ pub(super) fn options>(list: &[(I, &str)]) -> Vec<(String, Label)> /// Vector Halftone adds Keep Original. The Color row depends on two values, so the rows are built /// from `fields`. pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec { - let shapes = [("circle", "Circle"), ("ellipse", "Ellipse"), ("square", "Square"), ("diamond", "Diamond"), ("line", "Line")]; + let shapes = [ + ("circle", "Circle"), + ("ellipse", "Ellipse"), + ("square", "Square"), + ("diamond", "Diamond"), + ("line", "Line"), + ("euclidean", "Euclidean"), + ("elliptical", "Elliptical"), + ]; let mut rows = vec![ Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into()))), Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch), diff --git a/docs/mcp.md b/docs/mcp.md index 55886fae8f..8ffe40b45c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -15588,7 +15588,7 @@ effects keep their colours. ## Vector halftone `object.vectorHalftone` turns the selection into vector dots, lines or shapes sized by its -tone (mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the +tone (the `shape` values are those of the live effect below, Euclidean and Elliptical dots included; mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the art that can't be decoded is sampled as blank (no dots, or full dots with `invert`), and the result carries the `warning` that Flatten Transparency gives: @@ -17619,7 +17619,7 @@ Object › Vector Halftone without Keep Original, and the Appearance panel reope | Parameter | Values (default) | Does | |---|---|---| -| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line` (`circle`) | The dot shape; lines join along a row | +| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line`, `euclidean`, `elliptical` (`circle`) | The dot shape; lines join along a row; `euclidean` dots are round, meet corner to corner at 50% and turn into round holes past it; `elliptical` dots are long, join into chains along their length at 40% and on every side at 60%, then turn into long holes | | `frequency` | lines per inch 1…300 (20) | Cells per inch of the screen | | `angle` | degrees (45) | The screen angle; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it | | `mode` | `mono`, `cmyk` (`mono`) | One screen following lightness, or four ink screens following the art's ink amounts, multiplied over each other | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index db42c0d72c..8e956a2c75 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1460,6 +1460,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). + - Vector Halftone (Object › Vector Halftone and the live effect) has Euclidean and Elliptical dot shapes: Euclidean dots meet corner to corner at 50% and become round holes past it; Elliptical dots join into chains at 40% and on every side at 60%, then become long holes. Each dot covers its cell's tone. - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). - Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column. - The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown. From 7a46d5ec564fec016045cf956ef86817c8275559 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:19:58 -0800 Subject: [PATCH 20/46] Shape Builder: stop building regions of paths that cross too often Paths that cross each other many times are cut by the sweep into far more pieces than they have segments, and building the regions and edges of those pieces took minutes and gigabytes of memory. 400 circles stacked nearly on top of each other (1,600 segments) were cut into about 320,000 pieces, and their map took 60 s and 4.2 GB, enough to make the whole computer unresponsive. The Shape Builder now stops after the sweep when it cuts the paths into more than SHAPE_BUILDER_MAX_MAP_EDGES pieces (twice SHAPE_BUILDER_MAX_SEGMENTS, what open paths that cross nothing make at that cap) and finds no regions. The filled-area regions it falls back to are capped the same way. --- crates/pathops/README.md | 2 +- crates/pathops/src/lib.rs | 5 ++- crates/pathops/src/pathfinder.rs | 10 +++++ crates/pathops/src/planar.rs | 4 +- crates/pathops/src/planar/map.rs | 18 +++++++-- crates/pathops/src/planar/shape_builder.rs | 19 ++++++++-- crates/pathops/src/planar/tests.rs | 43 ++++++++++++++++++++++ 7 files changed, 89 insertions(+), 12 deletions(-) diff --git a/crates/pathops/README.md b/crates/pathops/README.md index 2397045a84..54b39b1dc5 100644 --- a/crates/pathops/README.md +++ b/crates/pathops/README.md @@ -59,7 +59,7 @@ pub fn interior_point(path: &PathData) -> Option; Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` treats every path as an edge, open paths included. Three crossing lines enclose a triangle, a line across a rectangle splits it in two, and an area enclosed by paths becomes a face even when nothing fills it. Each face lists the inputs whose fill covers it; the list is empty for an area that is only enclosed by paths. Each edge is a piece of a path, split wherever another path meets it, and keeps the key of the front-most input it lies on. -`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. +`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. When the paths cross each other so often that the sweep cuts them into more than `SHAPE_BUILDER_MAX_MAP_EDGES` pieces, it returns no regions. ```rust pub struct Adjacency { pub faces: Vec, pub edges: Vec, pub slivers: Vec, pub outlines: Vec } diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d02e5a8a93..61d03ecbc1 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -33,8 +33,9 @@ pub use pathfinder::{ FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within, }; pub use planar::{ - Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, - encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, + Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, + adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, + shape_builder_with_gap, }; pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 102d7e7138..3caddb4bc0 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -561,6 +561,16 @@ pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec { arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default() } +/// [`regions_with`], or `None` when the sweep cuts the shapes into more than `max_edges` pieces +/// (the faces are then not built). +pub(crate) fn regions_capped(shapes: &[Shape], precision: f64, max_edges: usize) -> Option> { + let Some(a) = arrangement(shapes, precision) else { return Some(Vec::new()) }; + if a.top.segment_indices().nth(max_edges).is_some() { + return None; + } + Some(regions_of(&a)) +} + /// [`regions`] when there are at most `limit` of them; `None` when there are more, found as soon /// as the face past `limit` is built (the faces after it are not built). pub fn regions_within(shapes: &[Shape], limit: usize) -> Option> { diff --git a/crates/pathops/src/planar.rs b/crates/pathops/src/planar.rs index f702f993ed..ca473dd839 100644 --- a/crates/pathops/src/planar.rs +++ b/crates/pathops/src/planar.rs @@ -41,8 +41,8 @@ pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps}; pub use map::interior_point; pub(crate) use map::{Map, Rest, map}; pub use shape_builder::{ - BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, run_around, shape_builder, - shape_builder_with_gap, + BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, + run_around, shape_builder, shape_builder_with_gap, }; pub(crate) use shape_builder::{builder, gap_inputs}; diff --git a/crates/pathops/src/planar/map.rs b/crates/pathops/src/planar/map.rs index f2c4b200d3..051a341e1a 100644 --- a/crates/pathops/src/planar/map.rs +++ b/crates/pathops/src/planar/map.rs @@ -42,6 +42,11 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option { /// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped. pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option { + map_within(shapes, cover, precision, usize::MAX) +} + +/// [`map_with`], or `None` when the sweep cuts the paths into more than `max_edges` pieces. +pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Option { let mut inputs: Vec<(BezPath, usize)> = Vec::new(); for (i, s) in shapes.iter().enumerate() { let mut bp = BezPath::new(); @@ -69,7 +74,7 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option< return None; } let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0)); - let (points, edges) = sweep_graph(&inputs, eps, precision)?; + let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges)?; let nv = points.len(); // Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is @@ -188,11 +193,17 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option< Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap }) } -fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option<(Vec, Vec)> { +fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize) -> Option<(Vec, Vec)> { // The sweep can panic on rare near-degenerate input; that must never take the app down. let sweep = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps))); let top = sweep.ok()?.ok()?; + // What is built from here on takes time and memory in proportion to the pieces the sweep cut + // the paths into, and paths that cross many times are cut into far more pieces than they have + // segments. + if top.segment_indices().nth(max_edges).is_some() { + return None; + } // The planar graph: vertices are the sweep's points, edges its segments. Points closer than // the sweep's tolerance are one vertex (it can put a corner that lies on another path's edge // a rounding error away from where it cuts that edge). @@ -426,8 +437,9 @@ impl Map { /// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath) /// that lie under another path in front of them, whose edges are that path's: under a closed /// path's outline, or along an open path in front. +/// `None` when the sweep cuts the paths into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec, Vec, Vec)> { - let m = map_with(shapes, false, precision)?; + let m = map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?; let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m; let snap = *snap; let fills: Vec = shapes.iter().map(Fill::new).collect(); diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index fcfb6cea95..b1f8520c23 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -9,6 +9,14 @@ use super::*; /// can take on art far past what a drawing holds. pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536; +/// Most pieces the sweep may cut the Shape Builder's paths into, where they cross each other and +/// where an open path is traced there and back: twice [`SHAPE_BUILDER_MAX_SEGMENTS`], what open +/// paths that cross nothing make at that cap. Paths that cross many times make far more pieces +/// than they have segments (400 circles stacked nearly on top of each other, 1,600 segments, make +/// about 320,000), and the regions and edges built from them took minutes and gigabytes of memory. +/// Past this the Shape Builder finds no regions. +pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS; + /// The Shape Builder's arrangement: see [`shape_builder`]. #[derive(Clone, Debug, Default, PartialEq)] pub struct BuilderArrangement { @@ -40,7 +48,8 @@ pub fn has_open_path(shapes: &[Shape]) -> bool { /// nothing fills, and each path with no closed subpath comes back cut wherever another path meets /// it, as pieces keyed by its index in `shapes`. Outlines are cut the same way. With more than /// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or a map that can't be built, only the filled areas -/// count and there are no pieces. +/// count and there are no pieces. When the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, there are no regions either. pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement { shape_builder_with_gap(shapes, edges, 0.0) } @@ -97,7 +106,7 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - faces } else { // The filled areas from their arrangement, whose faces merge exactly, then the gaps. - let mut regions = crate::pathfinder::regions_with(shapes, precision); + let mut regions = crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default(); regions.extend(faces.into_iter().filter(|f| f.sources.is_empty())); regions }; @@ -112,14 +121,16 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) - /// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no /// area, such as cutting lines) is left out, so a flood of them cannot push the arrangement past its /// size budget and take the filled shapes down with it; the regions keep the original indices. +/// There are none when the sweep cuts the filled shapes into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces. fn filled_regions(shapes: &[Shape], precision: f64) -> Vec { let fills = |s: &Shape| s.path.subpaths.iter().any(|sp| sp.closed || encloses_area(sp)); let keep: Vec = (0..shapes.len()).filter(|&i| shapes.get(i).is_some_and(fills)).collect(); if keep.len() == shapes.len() { - return crate::pathfinder::regions_with(shapes, precision); + return crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default(); } let kept: Vec = keep.iter().filter_map(|&i| shapes.get(i).cloned()).collect(); - crate::pathfinder::regions_with(&kept, precision) + crate::pathfinder::regions_capped(&kept, precision, SHAPE_BUILDER_MAX_MAP_EDGES) + .unwrap_or_default() .into_iter() .map(|mut r| { r.sources = r.sources.iter().filter_map(|&s| keep.get(s).copied()).collect(); diff --git a/crates/pathops/src/planar/tests.rs b/crates/pathops/src/planar/tests.rs index ad888448a7..130d381bfa 100644 --- a/crates/pathops/src/planar/tests.rs +++ b/crates/pathops/src/planar/tests.rs @@ -603,6 +603,49 @@ fn shape_builder_offers_the_gaps_closed_shapes_enclose() { assert!(shape_builder(&s, false).regions.iter().all(|r| !r.sources.is_empty())); } +/// `n` horizontal and `n` vertical lines across one square, every one crossing every other. +fn line_grid(n: usize) -> Vec { + let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64; + let across = (0..n).map(|k| line((0.0, at(k)), (1000.0, at(k)), k as u64)); + let down = (0..n).map(|k| line((at(k), 0.0), (at(k), 1000.0), (n + k) as u64)); + across.chain(down).collect() +} + +/// `n` horizontal and `n` vertical bars across one square, every one crossing every other. +fn bar_grid(n: usize) -> Vec { + let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64; + let across = (0..n).map(|k| rect(0.0, at(k), 1000.0, at(k) + 1.0, k as u64)); + let down = (0..n).map(|k| rect(at(k), 0.0, at(k) + 1.0, 1000.0, (n + k) as u64)); + across.chain(down).collect() +} + +#[test] +fn a_map_past_its_edge_cap_is_not_built() { + // 20 lines each way: each line is cut into 21 pieces, 840 in all. + let s = line_grid(20); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_some()); + assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_none()); + let bars = bar_grid(20); + assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 100_000).is_some_and(|r| r.len() > 400)); + assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 1000).is_none()); +} + +#[test] +fn shape_builder_builds_no_regions_past_its_edge_cap() { + // 300 lines each way cross 90,000 times with 600 segments: the sweep cuts them into about + // 180,000 pieces, past the cap, and nothing is built from them. + let s = line_grid(300); + let started = work_done(); + let BuilderArrangement { regions, lines, edges, lines_under } = shape_builder(&s, true); + assert!(regions.is_empty() && lines.is_empty() && edges.is_empty() && lines_under.is_empty(), "{} regions", regions.len()); + assert_eq!(work_done() - started, 0, "no face or edge was looked up"); + // Bars, closed paths only, each edge crossing 300 others: their filled areas are not built + // either. + assert!(shape_builder(&bar_grid(150), true).regions.is_empty()); + // Under the cap, the same grid is built. + assert_eq!(shape_builder(&line_grid(20), false).regions.len(), 19 * 19); +} + #[test] fn shape_builder_stays_quick_up_to_its_cap() { // A wavy ring of nearly the most segments the map takes, crossed by a few lines. From 0a4fcb67aeeee4eca164d4843cc665f69a3da0e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:27:14 -0800 Subject: [PATCH 21/46] Vector Halftone: Elliptical dots bridge along their length from 40% Below 50% the Elliptical dot was an ellipse clipped to the cell's diamond, so from 40% horizontal neighbors met at a single point and at 50% the dot reached the vertical neighbors too. The dot is now an ellipse as wide as its cell at 40%; past that it is clipped to the cell's side, which makes a bridge to the next dot, and to a middle-tone cut line through the quadrant's center, which keeps the short side apart until 60%. Areas still match the tone. --- crates/effects/src/addons/halftone.rs | 168 ++++++++++++++++++++------ 1 file changed, 133 insertions(+), 35 deletions(-) diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index b031cf4c44..252945c768 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -102,25 +102,21 @@ impl DotShape { DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)), // Cells along a row join into a line as thick as the tone. DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))), - DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, 1.0, &EUCLIDEAN)), - DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, elliptical_ratio(), &ELLIPTICAL)), + DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)), + DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Elliptical)), } } } -/// The Elliptical dot's height over its width: the ratio at which a dot exactly as wide as its -/// cell, clipped to the cell's diamond, covers 40% of the cell. -fn elliptical_ratio() -> f64 { - static R: OnceLock = OnceLock::new(); - *R.get_or_init(|| { - let (mut lo, mut hi) = (0.0, 1.0); - for _ in 0..60 { - let mid = (lo + hi) / 2.0; - if quadrant_area(1.0, mid, 1.0) < 0.4 { lo = mid } else { hi = mid } - } - (lo + hi) / 2.0 - }) -} +/// The Elliptical dot's height over its width: a dot as wide as its cell covers 40% of it +/// (π × ratio / 4 = 0.4 of a quadrant). +const ELLIPTICAL_RATIO: f64 = 1.6 / std::f64::consts::PI; + +/// The Elliptical dot's middle-tone cut in a quadrant of half side 1, the line +/// `ELLIPTICAL_CUT.0 × x + y = ELLIPTICAL_CUT.1`. It meets the side x = 1 at y = 0.25 and the y +/// axis at 0.75 and runs through the quadrant's center, so the dot it cuts at 50% is its own +/// complement: the dark bridges across the x side from 40%, and the y side stays light until 60%. +const ELLIPTICAL_CUT: (f64, f64) = (0.5, 0.75); /// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5. const SIZE_STEPS: usize = 512; @@ -128,27 +124,124 @@ const SIZE_STEPS: usize = 512; static EUCLIDEAN: OnceLock> = OnceLock::new(); static ELLIPTICAL: OnceLock> = OnceLock::new(); -/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the ellipse with height `ratio × a` whose part -/// inside the diamond |x| + |y| ≤ 1 covers that tone of the cell [-1, 1]². -fn dot_sizes(ratio: f64) -> Vec { +/// The two spot-function dots. +#[derive(Clone, Copy)] +enum SpotKind { + Euclidean, + Elliptical, +} + +impl SpotKind { + /// The first quadrant of the dot of width `a` in a quadrant of half side 1. + fn quadrant(self, a: f64) -> Vec { + match self { + SpotKind::Euclidean => quadrant(a, a, 1.0), + SpotKind::Elliptical => elliptical_quadrant(a), + } + } + + /// The width at which the dot covers half the cell. + fn max_size(self) -> f64 { + match self { + SpotKind::Euclidean => 1.0, + SpotKind::Elliptical => ELLIPTICAL_CUT.1 / ELLIPTICAL_RATIO, + } + } + + fn table(self) -> &'static OnceLock> { + match self { + SpotKind::Euclidean => &EUCLIDEAN, + SpotKind::Elliptical => &ELLIPTICAL, + } + } +} + +/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the dot of `kind` that covers that tone of the +/// cell [-1, 1]². +fn dot_sizes(kind: SpotKind) -> Vec { (0..=SIZE_STEPS) .map(|k| { // A quadrant of the cell has area 1. let target = k as f64 / SIZE_STEPS as f64 * 0.5; - let (mut lo, mut hi) = (0.0, 1.0 / ratio); + let (mut lo, mut hi) = (0.0, kind.max_size()); for _ in 0..50 { let mid = (lo + hi) / 2.0; - if quadrant_area(mid, mid * ratio, 1.0) < target { lo = mid } else { hi = mid } + if curves_area(&kind.quadrant(mid)) < target { lo = mid } else { hi = mid } } (lo + hi) / 2.0 }) .collect() } -/// The area of the first quadrant of the ellipse with semi-axes `a`, `b` clipped to x + y ≤ `h`. -fn quadrant_area(a: f64, b: f64, h: f64) -> f64 { +/// The area between the origin and `curves`, which run from the x axis to the y axis. +fn curves_area(curves: &[CubicBez]) -> f64 { use vectorcraft_geom::kurbo::ParamCurveArea; - quadrant(a, b, h).iter().map(|c| c.signed_area()).sum() + curves.iter().map(|c| c.signed_area()).sum() +} + +/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`. +fn ellipse_arc(out: &mut Vec, a: f64, b: f64, t0: f64, t1: f64) { + if t1 <= t0 { + return; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); + let d = (t1 - t0) / n; + let k = 4.0 / 3.0 * (d / 4.0).tan(); + for i in 0..n as usize { + let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0)); + let (p0, p3) = (at(u0), at(u1)); + let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos()); + let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos()); + out.push(CubicBez::new(p0, c1, c2, p3)); + } +} + +/// The straight segment from `p` to `q` as a cubic curve. +fn segment(p: Point, q: Point) -> CubicBez { + CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q) +} + +/// The first quadrant of the Elliptical dot of width `a` (height `ELLIPTICAL_RATIO × a`) in a +/// quadrant of half side 1, from the x axis to the y axis. Up to width 1 (40%) it is the whole +/// ellipse. Wider, the ellipse is clipped to the side x = 1, which makes a bridge to the next dot +/// along x, and to the cut line [`ELLIPTICAL_CUT`], which keeps it off the y side. +fn elliptical_quadrant(a: f64) -> Vec { + use std::f64::consts::FRAC_PI_2; + let b = a * ELLIPTICAL_RATIO; + let mut out = vec![]; + if a <= 1.0 { + ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2); + return out; + } + let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); + let (m, c) = ELLIPTICAL_CUT; + // The ellipse crosses the side x = 1 at angle t0. + let t0 = (1.0 / a).acos(); + // Between angles ts and te the ellipse lies beyond the cut line. + let r = (m * a).hypot(b); + let (ts, te) = if r > c { + let (phi, alpha) = (b.atan2(m * a), (c / r).acos()); + (phi - alpha, phi + alpha) + } else { + (FRAC_PI_2, FRAC_PI_2) + }; + let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, c) }; + out.push(segment(Point::new(1.0, 0.0), if t0 < ts || t0 >= te { at(t0) } else { Point::new(1.0, c - m) })); + if t0 >= te { + ellipse_arc(&mut out, a, b, t0, FRAC_PI_2); + return out; + } + if t0 < ts { + ellipse_arc(&mut out, a, b, t0, ts.min(FRAC_PI_2)); + if ts >= FRAC_PI_2 { + return out; + } + } + let from = out.last().map_or(Point::new(1.0, 0.0), |q| q.p3); + out.push(segment(from, end)); + ellipse_arc(&mut out, a, b, te, FRAC_PI_2); + out } /// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤ @@ -202,22 +295,23 @@ fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec { curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect() } -/// The quadrant of the spot for tone `u` (0..0.5) in a cell of half side `h`, its dot `ratio` as -/// tall as wide, its sizes from `table` ([`dot_sizes`]). -fn spot_quadrant(u: f64, h: f64, ratio: f64, table: &OnceLock>) -> Vec { - let sizes = table.get_or_init(|| dot_sizes(ratio)); +/// The quadrant of the `kind` spot for tone `u` (0..0.5) in a cell of half side `h`, its size from +/// the kind's table ([`dot_sizes`]). +fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec { + let sizes = kind.table().get_or_init(|| dot_sizes(kind)); let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64; let i = (x.floor() as usize).min(SIZE_STEPS - 1); let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0)); let a = lo + (hi - lo) * (x - i as f64); - quadrant(a * h, a * ratio * h, h) + mapped(&kind.quadrant(a), |p| Point::new(p.x * h, p.y * h)) } /// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to -/// half tone, an ellipse (`ratio` as tall as wide) clipped to the cell's diamond, with the tone's -/// area; past half, the cell with the dot of the opposite tone cut out at each corner, so the dark -/// joins up and the light becomes holes. -fn spot(t: f64, h: f64, ratio: f64, table: &OnceLock>) -> BezPath { +/// half tone, the `kind` dot with the tone's area (Euclidean: a circle clipped to the cell's +/// diamond; Elliptical: an ellipse clipped to the cell's sides and its middle-tone cut); past half, +/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the +/// light becomes holes. +fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath { let mut bp = BezPath::new(); let mut add = |curves: Vec, first: bool| { for (k, c) in curves.iter().enumerate() { @@ -228,14 +322,14 @@ fn spot(t: f64, h: f64, ratio: f64, table: &OnceLock>) -> BezPath { } }; if t <= 0.5 { - let q1 = spot_quadrant(t, h, ratio, table); + let q1 = spot_quadrant(t, h, kind); add(q1.clone(), true); add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false); add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false); add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false); } else { // Round the corners counterclockwise, each one's hole the dot of the opposite tone. - let q1 = spot_quadrant(1.0 - t.min(1.0), h, ratio, table); + let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind); add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true); add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false); add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false); @@ -653,12 +747,16 @@ mod tests { assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45))); // From 40% they reach their neighbors along x, making chains, but not along y. assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45))); + // The chains are bridges as tall as the tone allows across the shared side, not single + // points: off the axis on the side x = 0.5, and on the cell's other side by symmetry. + assert!(covers(s, 0.46, (0.499, 0.03)) && covers(s, 0.46, (-0.499, -0.03)) && !covers(s, 0.46, (0.499, 0.2))); + assert!(covers(s, 0.5, (0.499, 0.12)) && !covers(s, 0.5, (0.499, 0.13)) && !covers(s, 0.5, (0.0, 0.49))); // Up to 60% the light still runs along the top edge between the corner holes. assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3))); // Past 60% the dark joins across the top edge too, leaving elongated holes. assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49))); // The holes are longer along x than along y. - assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {}", elliptical_ratio()); + assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {ELLIPTICAL_RATIO}"); // Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall. let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap(); assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}"); From 1b59873456b35fa79675541f3bdbcc8552aff439 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:30:33 -0800 Subject: [PATCH 22/46] Shape Builder: say the filled areas keep their own cap past the map's When the sweep cuts the paths into more than SHAPE_BUILDER_MAX_MAP_EDGES pieces, the Shape Builder falls back to the regions of the filled areas, which are capped separately. The docs said it then finds no regions. --- crates/pathops/README.md | 2 +- crates/pathops/src/planar/shape_builder.rs | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/pathops/README.md b/crates/pathops/README.md index 54b39b1dc5..f41873333c 100644 --- a/crates/pathops/README.md +++ b/crates/pathops/README.md @@ -59,7 +59,7 @@ pub fn interior_point(path: &PathData) -> Option; Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` treats every path as an edge, open paths included. Three crossing lines enclose a triangle, a line across a rectangle splits it in two, and an area enclosed by paths becomes a face even when nothing fills it. Each face lists the inputs whose fill covers it; the list is empty for an area that is only enclosed by paths. Each edge is a piece of a path, split wherever another path meets it, and keeps the key of the front-most input it lies on. -`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. When the paths cross each other so often that the sweep cuts them into more than `SHAPE_BUILDER_MAX_MAP_EDGES` pieces, it returns no regions. +`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. When the paths cross each other so often that the sweep cuts them into more than `SHAPE_BUILDER_MAX_MAP_EDGES` pieces, it skips the full map and returns only the regions of the filled areas, which are capped on their own: a filled shape apart from open paths that cross too often still has its region. ```rust pub struct Adjacency { pub faces: Vec, pub edges: Vec, pub slivers: Vec, pub outlines: Vec } diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index b1f8520c23..8dca6f752d 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -14,7 +14,9 @@ pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536; /// paths that cross nothing make at that cap. Paths that cross many times make far more pieces /// than they have segments (400 circles stacked nearly on top of each other, 1,600 segments, make /// about 320,000), and the regions and edges built from them took minutes and gigabytes of memory. -/// Past this the Shape Builder finds no regions. +/// Past this the Shape Builder skips the full map and keeps only the regions of the filled areas, +/// which are capped on their own: when the open paths alone cross too often, a filled shape apart +/// from them still has its region. pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS; /// The Shape Builder's arrangement: see [`shape_builder`]. @@ -48,8 +50,9 @@ pub fn has_open_path(shapes: &[Shape]) -> bool { /// nothing fills, and each path with no closed subpath comes back cut wherever another path meets /// it, as pieces keyed by its index in `shapes`. Outlines are cut the same way. With more than /// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or a map that can't be built, only the filled areas -/// count and there are no pieces. When the sweep cuts the paths into more than -/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces, there are no regions either. +/// count and there are no pieces. The same happens when the sweep cuts the paths into more than +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces; the filled areas are then capped on their own, so they +/// have no regions only when they alone are cut into more pieces than that. pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement { shape_builder_with_gap(shapes, edges, 0.0) } From 9b65da9150c9c05f0094a8bc8296edf3dec5cd32 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:36:06 -0800 Subject: [PATCH 23/46] Tests: check representative raster effects in the catalog test listed_applied_edited_and_undone checks five representative catalog entries and an unknown effect id instead of every raster effect, and applies out-of-range parameters to Radial Blur and Unsharp Mask. Every effect is still drawn by each_effect_changes_the_canvas_and_draws_the_same_twice. --- crates/engine/src/tests/rasterfilters.rs | 38 +++++++++--------------- 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/tests/rasterfilters.rs b/crates/engine/src/tests/rasterfilters.rs index b46cd1e572..8ac581993e 100644 --- a/crates/engine/src/tests/rasterfilters.rs +++ b/crates/engine/src/tests/rasterfilters.rs @@ -119,33 +119,23 @@ fn mean_diff(a: &Rendered, b: &Rendered) -> f64 { fn listed_applied_edited_and_undone() { let (mut s, g) = striped(); let list = s.execute("effect.list", &json!({})).unwrap(); - for (id, _) in EFFECTS { - let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed")); - assert_eq!(e["raster"], json!(true), "{id}"); - assert!(e["params"].as_str().unwrap().contains("radius") || id == "blur.radial", "{id}"); - } - let menus: Vec = - EFFECTS.iter().map(|(id, _)| list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap()["menu"].clone()).collect(); - assert_eq!(menus, [json!(["Effect", "Blur"]), json!(["Effect", "Blur"]), json!(["Effect", "Sharpen"])]); - for (group, menu) in [ - (ARTISTIC.as_slice(), "Artistic"), - (BRUSH_STROKES.as_slice(), "Brush Strokes"), - (DISTORT.as_slice(), "Distort"), - (PIXELATE.as_slice(), "Pixelate"), - (SKETCH.as_slice(), "Sketch"), - (TEXTURE.as_slice(), "Texture"), - (VIDEO.as_slice(), "Video"), - ([("video.ntscColors", "{}")].as_slice(), "Video"), + // A few representative entries, one per kind of submenu, are listed as raster effects. + for (id, menu) in [ + ("blur.radial", "Blur"), + ("sharpen.unsharpMask", "Sharpen"), + ("artistic.cutout", "Artistic"), + ("sketch.chrome", "Sketch"), + ("video.ntscColors", "Video"), ] { - for (id, _) in group { - let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == *id).unwrap_or_else(|| panic!("{id} listed")); - assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}"); - } + let e = list["catalog"].as_array().unwrap().iter().find(|e| e["id"] == id).unwrap_or_else(|| panic!("{id} listed")); + assert_eq!((&e["raster"], &e["menu"]), (&json!(true), &json!(["Effect", menu])), "{id}"); } + assert!(list["catalog"].as_array().unwrap().iter().all(|e| e["id"] != "blur.notAnEffect")); + assert!(s.execute("effect.apply", &json!({"effect": "blur.notAnEffect", "ids": [g]})).is_err()); // Numbers far out of range are stored as given and read clamped; the canvas still draws. // Radial Blur's Blur Center is refused outside 0 to 1 instead. let center = |id: &str, k: &str| id == "blur.radial" && matches!(k, "centerX" | "centerY"); - for (id, _) in EFFECTS { + for id in ["blur.radial", "sharpen.unsharpMask"] { let defaults = vectorcraft_render::effects::default_params(id).unwrap(); let junk: serde_json::Map = defaults .as_object() @@ -161,11 +151,11 @@ fn listed_applied_edited_and_undone() { assert!(s.execute("effect.apply", &json!({"effect": "blur.radial", "ids": [g], "params": {"centerX": 1e308}})).is_err()); let _ = render(&s); let n = s.doc().unwrap().doc.node(NodeId(g)).unwrap().clone(); - assert_eq!(n.appearance.effects.len(), 3); + assert_eq!(n.appearance.effects.len(), 2); assert_eq!(n.appearance.effects[0].params["method"], json!("spin"), "defaults fill the rest"); s.execute("effect.setParams", &json!({"index": 0, "ids": [g], "params": {"method": "zoom"}})).unwrap(); assert_eq!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects[0].params["method"], json!("zoom")); - for _ in 0..4 { + for _ in 0..3 { s.execute("edit.undo", &json!({})).unwrap(); } assert!(s.doc().unwrap().doc.node(NodeId(g)).unwrap().appearance.effects.is_empty()); From bb80cc827ccb68cfea387eb31aaa931e8faf839e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 21:45:20 -0800 Subject: [PATCH 24/46] Shape Builder: name sliver drops in the over-cap region note --- crates/pathops/src/planar/shape_builder.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/pathops/src/planar/shape_builder.rs b/crates/pathops/src/planar/shape_builder.rs index 8dca6f752d..4ddd10495a 100644 --- a/crates/pathops/src/planar/shape_builder.rs +++ b/crates/pathops/src/planar/shape_builder.rs @@ -51,8 +51,9 @@ pub fn has_open_path(shapes: &[Shape]) -> bool { /// it, as pieces keyed by its index in `shapes`. Outlines are cut the same way. With more than /// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or a map that can't be built, only the filled areas /// count and there are no pieces. The same happens when the sweep cuts the paths into more than -/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces; the filled areas are then capped on their own, so they -/// have no regions only when they alone are cut into more pieces than that. +/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces; the filled areas are then capped on their own. They +/// then have no regions when they alone are cut into more pieces than that, and a filled area +/// thinner than the precision is dropped as a sliver, as in [`regions`](crate::regions). pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement { shape_builder_with_gap(shapes, edges, 0.0) } From 69ff74a63b6df602ad6f2c65082383d342aa7cfa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:21:53 -0800 Subject: [PATCH 25/46] Render: thin strokes keep smooth curves round where their lines turn sharply Since #9972 a thin stroke along a curve is drawn as lines, and where two of those lines met at a sharp angle the stroke's own join was drawn there. Along smooth anchors that sit close together after a bend, or a curve that bends tightly, the lines turn sharply, so a miter join drew a spike past the stroke and the smooth curve showed sharp corners on the canvas. The document's anchors are unchanged; only the drawing was wrong. The stroke's join is now drawn only at the path's own corners, where two segments meet with tangents that are not in line. Where the lines a curve is drawn with turn sharply they meet with a round join, as the stroke along the curve itself is round there. Tests: a bend followed by smooth anchors 0.1 and 1 apart keeps every outline point within the stroke's width of the curve and covers it; with long handles the outline matches the curve's own outline away from its edge; 200 random cubics with a miter join keep their outline within the stroke's width of the curve. --- crates/render/src/stroke.rs | 59 ++++++++++-- crates/render/src/tests/thincoverage.rs | 121 ++++++++++++++++++++++++ 2 files changed, 172 insertions(+), 8 deletions(-) diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index cd5cacac97..eaf22f0809 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -19,7 +19,7 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) -> } // Closed endpoint rounding must not consume a substantial part of a subpixel band. let fine = (tol / 8.0).min(width / 32.0).max(1e-4); - if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) { + if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, &corners(line), st, width, fine)) { return band; } let outline = effects::stroke::line_outline(line, st, width, fine); @@ -49,14 +49,53 @@ fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option { lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines) } +/// The points where `line` has a corner: where two of its segments meet with tangents that are not +/// in line ([`SMOOTH`]), or where a segment has no direction there. Sorted by [`point_order`]. +/// [`draw_sub`] leaves these points where they are, so the lines a curve is drawn with have each +/// corner at the same point. +fn corners(line: &BezPath) -> Vec { + let tangents = |seg: PathSeg| { + let c = match seg { + PathSeg::Line(l) => CubicBez::new(l.p0, l.p0, l.p1, l.p1), + other => cubic(other)?, + }; + Some((start_tangent(&c)?, end_tangent(&c)?)) + }; + let mut out = Vec::new(); + // A span of `f64::INFINITY` gives every segment no steps: only the segments are wanted. + for sub in subpaths(line.elements(), f64::INFINITY, 1.0).unwrap_or_default() { + let n = sub.segs.len(); + let first = if sub.closed { 0 } else { 1 }; + for i in first..n { + let before = if i == 0 { n - 1 } else { i - 1 }; + let (Some((a, _)), Some((b, _))) = (sub.segs.get(before), sub.segs.get(i)) else { continue }; + let smooth = match (tangents(*a).map(|t| t.1), tangents(*b).map(|t| t.0)) { + (Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(), + _ => false, + }; + if !smooth { + out.push(b.start()); + } + } + } + out.sort_by(point_order); + out +} + +/// Points in order of `x`, then `y` ([`corners`]). +fn point_order(a: &Point, b: &Point) -> std::cmp::Ordering { + a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)) +} + /// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill /// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet -/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the -/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as +/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross. Elsewhere the +/// stroke's join is drawn at the path's `corners` ([`corners`]) and a round join where the lines a +/// curve is drawn with meet. An open subpath ends in the stroke's caps, with round parts drawn as /// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a /// point that isn't finite, or is closed and no wider or taller than the stroke: those take /// [`effects::stroke::line_outline`]. -fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option { +fn thin_band(lines: &BezPath, corners: &[Point], st: &StrokeLayer, width: f64, fine: f64) -> Option { let h = width / 2.0; // The angle between two points of an arc of radius `h` drawn as lines within `fine` of it. let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3); @@ -80,7 +119,7 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option return None; } } - band_sub(out, pts, closed, st, h, step); + band_sub(out, pts, corners, closed, st, h, step); pts.clear(); Some(()) }; @@ -108,8 +147,9 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option /// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side, /// the end cap, its right side backward and the start cap; for a closed one its left side and its /// right side backward, as two contours. `h` is half the width and `step` the angle between the -/// points of a round join or cap. -fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { +/// points of a round join or cap. A sharp turn takes the stroke's join at one of the path's +/// `corners` (sorted by [`point_order`]) and a round join elsewhere. +fn band_sub(out: &mut BezPath, pts: &[Point], corners: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { use vectorcraft_doc::{LineCap, LineJoin}; let n = pts.len(); let chords = if closed { n } else { n - 1 }; @@ -143,7 +183,10 @@ fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: inner.push(p); inner.push(p - nb * sign); outer.push(p + na * sign); - match st.join { + // Only the path's corners take the stroke's join; where the lines of a curve turn sharply + // the stroke along the curve is round. + let kind = if corners.binary_search_by(|c| point_order(c, &p)).is_ok() { st.join } else { LineJoin::Round }; + match kind { LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign), LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)), LineJoin::Miter | LineJoin::Bevel => {} diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs index 4017448fd9..62197d4ec0 100644 --- a/crates/render/src/tests/thincoverage.rs +++ b/crates/render/src/tests/thincoverage.rs @@ -133,6 +133,127 @@ fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() { assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}"); } +/// A path with a bend at (10, 0) and then six smooth anchors `gap` apart, each with handles +/// `handle` and 1.7 times `handle` long, scaled by `zoom`, and its points flattened within 0.001. +fn close_smooth_anchors(gap: f64, handle: f64, zoom: f64) -> (BezPath, Vec) { + let path = close_smooth_path(gap, handle, zoom); + let mut line = Vec::new(); + vectorcraft_geom::flatten(path.iter(), 1e-3, |el| { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el { + line.push(p); + } + }); + (path, line) +} + +/// How far `q` is from the nearest point of `path`. +fn from_curve(path: &BezPath, q: kurbo::Point) -> f64 { + use kurbo::ParamCurveNearest; + path.segments().map(|s| s.nearest(q, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min) +} + +/// The path of [`close_smooth_anchors`]. +fn close_smooth_path(gap: f64, handle: f64, zoom: f64) -> BezPath { + use vectorcraft_geom::path::{Anchor, AnchorKind, PathData, SubPath}; + let dir = kurbo::Vec2::new(0.8, 0.6); + let mut anchors = vec![ + Anchor::corner(kurbo::Point::new(0.0, 0.0)), + Anchor::with_handles(kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 5.0)), + ]; + let mut x = 10.0; + for i in 0..6 { + x += gap; + let p = kurbo::Point::new(x, 1.0 + if i % 2 == 0 { 0.3 } else { -0.2 } * gap); + anchors.push(Anchor { p, h_in: p - dir * handle, h_out: p + dir * handle * 1.7, kind: AnchorKind::Smooth }); + } + anchors.push(Anchor::smooth(kurbo::Point::new(x + 20.0, 0.0), kurbo::Point::new(x + 25.0, -4.0))); + kurbo::Affine::scale(zoom) * PathData::single(SubPath::new(anchors, false)).to_bezpath() +} + +/// A thin stroke along smooth anchors that sit close together after a bend follows the curve: its +/// outline has no point farther than a stroke's width from the curve, and covers the curve. The +/// lines such a curve is drawn with are short beside the stroke and turn sharply, so offsetting +/// them drew the stroke's miter joins as spikes. +#[test] +fn thin_strokes_follow_smooth_anchors_close_together() { + for gap in [0.1, 1.0] { + let (path, line) = close_smooth_anchors(gap, 1.0, 1.0); + for w in [0.6, 0.9] { + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, 0.25); + for el in o.elements() { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el { + let d = from_curve(&path, p); + assert!(d <= w, "gap {gap}, width {w}: outline point {p:?} is {d} from the curve"); + } + } + for p in line.iter().step_by(7) { + assert!(o.winding(*p) != 0, "gap {gap}, width {w}: the curve at {p:?} is not covered"); + } + } + } +} + +/// A thin stroke's outline stays within the stroke's width of its curve where the lines the curve is +/// drawn with turn sharply, as near a cusp: they meet with a round join, not the stroke's miter. +/// 200 cubic curves, each about 100 device pixels across. +#[test] +fn thin_strokes_meet_round_where_a_curves_lines_turn_sharply() { + let mut seed: u64 = 7; + let mut r = |lo: f64, hi: f64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64) + }; + let w = 0.5; + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.join = LineJoin::Miter; + st.miter_limit = 10.0; + for _ in 0..200 { + let (x, y) = (r(20.0, 980.0), r(20.0, 980.0)); + let mut q = [kurbo::Point::ZERO; 3]; + for p in &mut q { + *p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71); + } + let mut path = BezPath::new(); + path.move_to((x * 1.71, y * 1.71)); + path.curve_to(q[0], q[1], q[2]); + let o = raster_stroke_outline(&path, &st, w, 0.25); + for el in o.elements() { + if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el { + let d = from_curve(&path, p); + assert!(d <= w, "outline point {p:?} is {d} from the curve {path:?}"); + } + } + } +} + +/// A thin stroke along smooth anchors close together, with handles long beside the gaps between +/// them, covers what the curve's own outline covers: at every point of a grid more than 0.25 pixels +/// nearer or farther than half the stroke's width from the curve, both outlines agree. The miter +/// joins drawn where the curve's lines turned sharply covered points well outside the stroke. +#[test] +fn thin_strokes_along_long_handles_cover_the_curve_outline() { + let tol = 0.25; + for (gap, w) in [(1.0, 0.6), (1.0, 0.9), (0.1, 0.6)] { + let path = close_smooth_path(gap, 10.0, 4.0); + let st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + let o = raster_stroke_outline(&path, &st, w, tol); + let fine = (tol / 8.0).min(w / 32.0); + let mut want = BezPath::new(); + vectorcraft_geom::flatten(crate::effects::stroke::line_outline(&path, &st, w, fine).iter(), fine, |el| want.push(el)); + let bb = want.bounding_box().inflate(w, w); + for i in 0..90 { + for j in 0..90 { + let q = kurbo::Point::new(bb.x0 + bb.width() * f64::from(i) / 90.0, bb.y0 + bb.height() * f64::from(j) / 90.0); + let d = from_curve(&path, q); + if (d - w / 2.0).abs() > 0.25 { + assert_eq!(o.winding(q) != 0, want.winding(q) != 0, "gap {gap}, width {w}: at {q:?}, {d} from the curve"); + } + } + } + } +} + /// Independently integrate coverage in radial/angle bins of an original notched ring. Checking /// only the outline geometry misses raster flattening that cancels its two nearby contours. #[test] From 12cb63642e36a9771e24509451e893392397936f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:27:55 -0800 Subject: [PATCH 26/46] Shortcuts: a lone Alt over the canvas no longer gives the menu bar the keys Alt is a tool modifier, and pressing and releasing it without a click moved the keys to the menu bar on Windows and Linux. The next tool letter then opened the menu with that access key (V opened View, W Window, T Type) instead of choosing the tool. While the canvas has the keys, the canvas now takes the lone Alt tap. F10 and Alt with a letter still open the menus, and a lone Alt in a field or on the bar is unchanged. --- crates/ui-egui/src/canvas/tool_adapter.rs | 9 ++++++++- crates/ui-egui/tests/menu_access_keys.rs | 16 ++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/tool_adapter.rs b/crates/ui-egui/src/canvas/tool_adapter.rs index 2e33ef9cf8..8b2b35db16 100644 --- a/crates/ui-egui/src/canvas/tool_adapter.rs +++ b/crates/ui-egui/src/canvas/tool_adapter.rs @@ -463,7 +463,14 @@ impl CanvasTool for SessionTool<'_> { if claim(&mut app, EngineKey::Left) { claims = claims.nudges(); } - if claim(&mut app, EngineKey::AltTap) { + // A lone Alt while the canvas has the keys is the tools' modifier let go without a click: the canvas takes it, + // so it does not give the menu bar the keys and the next tool letter still chooses its tool. F10 and Alt with + // a letter still reach the bar, and a lone Alt in a field or the bar keeps the framework's rule. + let canvas_has_keys = app + .ui_ctx + .as_ref() + .is_some_and(|ctx| !ctx.egui_wants_keyboard_input() && !craft::ui::menu::bar::is_focused(ctx) && !craft::ui::menu::bar::is_open(ctx)); + if canvas_has_keys || claim(&mut app, EngineKey::AltTap) { claims = claims.alt_tap(); } claims diff --git a/crates/ui-egui/tests/menu_access_keys.rs b/crates/ui-egui/tests/menu_access_keys.rs index c837734c99..f2a04cd75a 100644 --- a/crates/ui-egui/tests/menu_access_keys.rs +++ b/crates/ui-egui/tests/menu_access_keys.rs @@ -164,10 +164,22 @@ fn menu_access_custom_shortcut_typing_tool_altgr_and_cancel_ownership() { assert_eq!(s.app.session.tool_id(), "pen", "after the dismissal the letter selects its tool"); s.app.select_tool("selection"); - // While the bar holds the keys after a lone Alt, the letter does not reach the tool either. + // A lone Alt over the canvas is a tool modifier let go: the bar does not take the keys, and the next tool + // letters choose their tools instead of opening View or Window. s.bare_alt(); s.settle(); - assert!(is_focused(&s.ctx), "a lone Alt gives the bar the keys"); + assert!(!is_focused(&s.ctx) && !is_open(&s.ctx), "a lone Alt over the canvas leaves the bar alone"); + s.letter(Key::V, "v", Modifiers::NONE); + assert!(!is_open(&s.ctx), "V after a lone Alt opens no menu"); + s.letter(Key::P, "p", Modifiers::NONE); + assert_eq!(s.app.session.tool_id(), "pen", "P after a lone Alt chooses the Pen"); + s.app.select_tool("selection"); + + // While the bar holds the keys after F10, the letter does not reach the tool. + s.frame(vec![key(Key::F10, true, Modifiers::NONE)]); + s.frame(vec![key(Key::F10, false, Modifiers::NONE)]); + s.settle(); + assert!(is_focused(&s.ctx), "F10 gives the bar the keys"); s.letter(Key::P, "p", Modifiers::NONE); assert_eq!(s.app.session.tool_id(), "selection", "a focused bar takes the letter"); s.click(outside); From 85ad10feb5b013454ccdc656223d7b427ec2359a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:32:07 -0800 Subject: [PATCH 27/46] Vector Halftone: Euclidean quadrant uses the shared arc and segment helpers quadrant() had local closures that repeated ellipse_arc() and segment(). It now calls those helpers, as elliptical_quadrant() does. The geometry is unchanged. --- crates/effects/src/addons/halftone.rs | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/crates/effects/src/addons/halftone.rs b/crates/effects/src/addons/halftone.rs index 252945c768..371f664781 100644 --- a/crates/effects/src/addons/halftone.rs +++ b/crates/effects/src/addons/halftone.rs @@ -249,39 +249,23 @@ fn elliptical_quadrant(a: f64) -> Vec { fn quadrant(a: f64, b: f64, h: f64) -> Vec { use std::f64::consts::FRAC_PI_2; let at = |th: f64| Point::new(a * th.cos(), b * th.sin()); - let arc = |out: &mut Vec, t0: f64, t1: f64| { - if t1 <= t0 { - return; - } - let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0); - let d = (t1 - t0) / n; - let k = 4.0 / 3.0 * (d / 4.0).tan(); - for i in 0..n as usize { - let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0)); - let (p0, p3) = (at(u0), at(u1)); - let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos()); - let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos()); - out.push(CubicBez::new(p0, c1, c2, p3)); - } - }; - let line = |p: Point, q: Point| CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q); let mut out = vec![]; let r = a.hypot(b); if r <= h { - arc(&mut out, 0.0, FRAC_PI_2); + ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2); return out; } let (phi, alpha) = (b.atan2(a), (h / r).acos()); let (ts, te) = (phi - alpha, phi + alpha); let start = if ts > 0.0 { - arc(&mut out, 0.0, ts); + ellipse_arc(&mut out, a, b, 0.0, ts); at(ts) } else { Point::new(h, 0.0) }; let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) }; - out.push(line(start, end)); - arc(&mut out, te, FRAC_PI_2); + out.push(segment(start, end)); + ellipse_arc(&mut out, a, b, te, FRAC_PI_2); out } From c47fdb89746fc6b85859bc75e6eb903194eaa1f5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 22:58:06 -0800 Subject: [PATCH 28/46] Tests: check the PDF key and Math.random seeds by behavior The PDF encryption and Math.random seed tests read their source files and searched for names. They now build the seed from given OS bytes: equal bytes give an equal stream, other bytes give another stream, and a failed OS read is an error for the PDF key. Mixing any other source into either seed fails the tests. The PDF seed is split into Entropy::seeded, which takes the OS bytes and the time, and the module doc now names the OS random source. --- crates/js/src/builtins_tests.rs | 13 ++++++++----- crates/js/src/realm.rs | 9 +++++++++ crates/pdf/src/encrypt.rs | 17 ++++++++++++----- crates/pdf/src/tests/encrypt.rs | 17 +++++++++++++---- 4 files changed, 42 insertions(+), 14 deletions(-) diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 6a6867b270..c262216c1c 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -624,11 +624,14 @@ fn math_functions_follow_the_special_cases() { fn math_random_is_seeded_from_the_os_random_source() { // On wasm32-unknown-unknown `RandomState`'s keys come from memory addresses, which are the // same on every page load: the seed must come from the OS (the browser's crypto) instead. - let src = include_str!("interp.rs"); - let Some(start) = src.find("fn random_seed()") else { panic!("interp.rs has no random_seed") }; - let body = &src[start..]; - let body = &body[..body.find("\n}").unwrap_or(body.len())]; - assert!(body.contains("random_seed_from(getrandom::u64())"), "Math.random isn't seeded from the OS random source"); + // The OS value is the generator's only state: realms given the same value draw the same + // numbers, and a different value draws different ones. + let draws = |os: u64| match Realm::with_os_random(Ok(os)).run("[Math.random(), Math.random(), Math.random()].join()") { + Ok(JsValue::String(s)) => s, + other => panic!("{other:?}"), + }; + assert_eq!(draws(0x1234_5678_9abc_def0), draws(0x1234_5678_9abc_def0)); + assert_ne!(draws(0x1234_5678_9abc_def0), draws(0x0fed_cba9_8765_4321)); // The OS value is the seed, made odd so it's never zero; a failed read still gives a seed. assert_eq!(crate::interp::random_seed_from(Ok(0x40)), 0x41); assert_eq!(crate::interp::random_seed_from(Ok(0)), 1); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d673c92d26..1032b01a17 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -209,6 +209,15 @@ impl Realm { Self::with_options(Options::default(), Limits::default()) } + /// A realm whose `Math.random` starts from the seed made of `os`, as if the OS random source + /// had returned it. + #[cfg(test)] + pub(crate) fn with_os_random(os: Result) -> Self { + let mut realm = Self::new(); + realm.interp.random = crate::interp::random_seed_from(os); + realm + } + /// A realm whose scripts (and the source given to `eval` and `Function`) are read with /// `options`; [`Options::max_source_units`] caps the source parsed in one run, all of it /// counted together. diff --git a/crates/pdf/src/encrypt.rs b/crates/pdf/src/encrypt.rs index 6ee43ef05d..4807763598 100644 --- a/crates/pdf/src/encrypt.rs +++ b/crates/pdf/src/encrypt.rs @@ -6,7 +6,7 @@ //! algorithm follows the compatibility ([`Encryption`]): 40-bit RC4 for PDF 1.3 (revision 2), //! 128-bit RC4 for PDF 1.4 (revision 3) and 1.5 (revision 4), 128-bit AES for 1.6 (revision 4) and //! 256-bit AES for 1.7 and 2.0 (revision 6). The random file key, salts and initialisation vectors -//! come from a SHA-256 stream seeded with the process's random hash keys, the time and the file +//! come from a SHA-256 stream seeded with the OS random source, the time and the file //! itself. A linearised file is encrypted between its two steps ([`protect_keeping`]): what //! encrypted it then encrypts the hint stream written last ([`Cipher`]). //! @@ -163,7 +163,7 @@ fn hash6(password: &[u8], salt: &[u8], udata: &[u8]) -> Result<[u8; 32], PdfErro } /// Unpredictable bytes: SHA-256 of a seed and a counter. -struct Entropy { +pub(crate) struct Entropy { seed: [u8; 32], counter: u64, } @@ -172,10 +172,17 @@ impl Entropy { /// Seeded from the OS random source, with the time and `material` mixed in. fn new(material: &[&[u8]]) -> Result { let mut os = [0u8; 32]; - getrandom::fill(&mut os).map_err(|e| failed(&format!("no random numbers ({e})")))?; + let os = getrandom::fill(&mut os).map(|()| os); + Self::seeded(os, vectorcraft_doc::metadata::now_unix().unwrap_or_default(), material) + } + + /// [`Entropy::new`] from what the OS random source returned and the time. Nothing else goes + /// into the seed, and a failed OS read is an error. + pub(crate) fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result { + let os = os.map_err(|e| failed(&format!("no random numbers ({e})")))?; let mut h = Sha256::new(); h.update(os); - h.update(vectorcraft_doc::metadata::now_unix().unwrap_or_default().to_le_bytes()); + h.update(now.to_le_bytes()); for m in material { h.update((m.len() as u64).to_le_bytes()); h.update(m); @@ -183,7 +190,7 @@ impl Entropy { Ok(Self { seed: h.finalize().into(), counter: 0 }) } - fn bytes(&mut self) -> [u8; N] { + pub(crate) fn bytes(&mut self) -> [u8; N] { let mut out = [0u8; N]; for chunk in out.chunks_mut(32) { self.counter += 1; diff --git a/crates/pdf/src/tests/encrypt.rs b/crates/pdf/src/tests/encrypt.rs index c6b8772ff3..89c2542266 100644 --- a/crates/pdf/src/tests/encrypt.rs +++ b/crates/pdf/src/tests/encrypt.rs @@ -193,8 +193,17 @@ fn the_same_file_and_passwords_get_fresh_keys_each_time() { #[test] fn the_file_key_is_seeded_from_the_os_random_source() { - // `RandomState` is no CSPRNG and its keys are fixed on the web: the seed must come from the OS. - let src = include_str!("../encrypt.rs"); - assert!(!src.contains("RandomState"), "encrypt.rs seeds its keys from RandomState"); - assert!(src.contains("getrandom::fill"), "encrypt.rs doesn't seed its keys from the OS random source"); + // The OS bytes, the time and the file are the whole seed: equal inputs give equal streams, so + // no other source (such as `RandomState`, whose keys are fixed on the web) is mixed in, and + // other OS bytes alone give another stream. + use crate::encrypt::Entropy; + let file: &[&[u8]] = &[b"%PDF-2.0 same file"]; + let stream = |os: [u8; 32]| match Entropy::seeded(Ok(os), 1_700_000_000, file) { + Ok(mut e) => e.bytes::<48>(), + Err(e) => panic!("{e:?}"), + }; + assert_eq!(stream([7; 32]), stream([7; 32])); + assert_ne!(stream([7; 32]), stream([8; 32])); + // A failed OS read is an error, not a weaker seed. + assert!(Entropy::seeded(Err(getrandom::Error::UNSUPPORTED), 1_700_000_000, file).is_err()); } From f1ef1a4e39359ec3489df9bfbbf77ace3f42703a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 23:02:15 -0800 Subject: [PATCH 29/46] Render: a thin stroke takes the corners of its own subpath A corner in one subpath gave the stroke's join to the lines of a curve in another subpath that met at the same point, so a miter could be drawn there instead of a round join. The corners are now kept per subpath and each subpath of the outline reads only its own. Test: a curve's outline is the same with and without a second subpath that has a corner at the curve's start. --- crates/render/src/stroke.rs | 32 +++++++++++++++---------- crates/render/src/tests/thincoverage.rs | 21 ++++++++++++++++ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index eaf22f0809..93fe88a1ed 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -50,10 +50,10 @@ fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option { } /// The points where `line` has a corner: where two of its segments meet with tangents that are not -/// in line ([`SMOOTH`]), or where a segment has no direction there. Sorted by [`point_order`]. -/// [`draw_sub`] leaves these points where they are, so the lines a curve is drawn with have each -/// corner at the same point. -fn corners(line: &BezPath) -> Vec { +/// in line ([`SMOOTH`]), or where a segment has no direction there. One list for each subpath, in +/// order, each sorted by [`point_order`]. [`draw_sub`] leaves these points where they are, so the +/// lines a curve is drawn with have each corner at the same point, and draws one subpath for each. +fn corners(line: &BezPath) -> Vec> { let tangents = |seg: PathSeg| { let c = match seg { PathSeg::Line(l) => CubicBez::new(l.p0, l.p0, l.p1, l.p1), @@ -64,6 +64,7 @@ fn corners(line: &BezPath) -> Vec { let mut out = Vec::new(); // A span of `f64::INFINITY` gives every segment no steps: only the segments are wanted. for sub in subpaths(line.elements(), f64::INFINITY, 1.0).unwrap_or_default() { + let mut here = Vec::new(); let n = sub.segs.len(); let first = if sub.closed { 0 } else { 1 }; for i in first..n { @@ -74,11 +75,12 @@ fn corners(line: &BezPath) -> Vec { _ => false, }; if !smooth { - out.push(b.start()); + here.push(b.start()); } } + here.sort_by(point_order); + out.push(here); } - out.sort_by(point_order); out } @@ -90,19 +92,22 @@ fn point_order(a: &Point, b: &Point) -> std::cmp::Ordering { /// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill /// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet /// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross. Elsewhere the -/// stroke's join is drawn at the path's `corners` ([`corners`]) and a round join where the lines a +/// stroke's join is drawn at the corners of the same subpath of the path (`corners`, one list for +/// each subpath of `lines`, [`corners`]) and a round join where the lines a /// curve is drawn with meet. An open subpath ends in the stroke's caps, with round parts drawn as /// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a /// point that isn't finite, or is closed and no wider or taller than the stroke: those take /// [`effects::stroke::line_outline`]. -fn thin_band(lines: &BezPath, corners: &[Point], st: &StrokeLayer, width: f64, fine: f64) -> Option { +fn thin_band(lines: &BezPath, corners: &[Vec], st: &StrokeLayer, width: f64, fine: f64) -> Option { let h = width / 2.0; // The angle between two points of an arc of radius `h` drawn as lines within `fine` of it. let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3); let mut out = BezPath::new(); let mut pts: Vec = Vec::new(); let mut closed = false; - let flush = |pts: &mut Vec, closed: bool, out: &mut BezPath| -> Option<()> { + // The subpath being read; `None` before the first move. + let mut sub: Option = None; + let flush = |pts: &mut Vec, closed: bool, sub: Option, out: &mut BezPath| -> Option<()> { if pts.is_empty() { return Some(()); } @@ -119,14 +124,15 @@ fn thin_band(lines: &BezPath, corners: &[Point], st: &StrokeLayer, width: f64, f return None; } } - band_sub(out, pts, corners, closed, st, h, step); + band_sub(out, pts, corners.get(sub?)?, closed, st, h, step); pts.clear(); Some(()) }; for el in lines.elements() { match *el { PathEl::MoveTo(p) => { - flush(&mut pts, closed, &mut out)?; + flush(&mut pts, closed, sub, &mut out)?; + sub = Some(sub.map_or(0, |s| s + 1)); closed = false; pts.push(p); } @@ -139,7 +145,7 @@ fn thin_band(lines: &BezPath, corners: &[Point], st: &StrokeLayer, width: f64, f PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None, } } - flush(&mut pts, closed, &mut out)?; + flush(&mut pts, closed, sub, &mut out)?; Some(out) } @@ -147,7 +153,7 @@ fn thin_band(lines: &BezPath, corners: &[Point], st: &StrokeLayer, width: f64, f /// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side, /// the end cap, its right side backward and the start cap; for a closed one its left side and its /// right side backward, as two contours. `h` is half the width and `step` the angle between the -/// points of a round join or cap. A sharp turn takes the stroke's join at one of the path's +/// points of a round join or cap. A sharp turn takes the stroke's join at one of this subpath's /// `corners` (sorted by [`point_order`]) and a round join elsewhere. fn band_sub(out: &mut BezPath, pts: &[Point], corners: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) { use vectorcraft_doc::{LineCap, LineJoin}; diff --git a/crates/render/src/tests/thincoverage.rs b/crates/render/src/tests/thincoverage.rs index 62197d4ec0..ab31619111 100644 --- a/crates/render/src/tests/thincoverage.rs +++ b/crates/render/src/tests/thincoverage.rs @@ -254,6 +254,27 @@ fn thin_strokes_along_long_handles_cover_the_curve_outline() { } } +/// A corner of one subpath does not change the join where the lines of another subpath's curve +/// meet at the same point: the first subpath's outline is the same with or without the second. +#[test] +fn thin_strokes_take_corners_from_their_own_subpath() { + let w = 0.5; + let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w); + st.join = LineJoin::Miter; + st.miter_limit = 10.0; + let mut alone = BezPath::new(); + alone.move_to((-1.0, 0.0)); + alone.line_to((0.0, 0.0)); + alone.curve_to((0.000001, 0.0), (-1.0, 0.5), (-2.0, 1.0)); + let mut both = alone.clone(); + both.move_to((-10.0, -10.0)); + both.line_to((0.0, 0.0)); + both.line_to((-10.0, 10.0)); + let one = raster_stroke_outline(&alone, &st, w, 0.25); + let two = raster_stroke_outline(&both, &st, w, 0.25); + assert_eq!(two.elements().get(..one.elements().len()), Some(one.elements()), "the second subpath changed the first one's outline"); +} + /// Independently integrate coverage in radial/angle bins of an original notched ring. Checking /// only the outline geometry misses raster flattening that cancels its two nearby contours. #[test] From 3f21a06bed9c7fe47255676aab78ceedbc8e6707 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 23:01:09 -0800 Subject: [PATCH 30/46] Tests: cover broken hex strings in the stream scan and restricted file fonts A hex string broken by a byte that is neither a hex digit nor white space is no string: the hostile-input scan goes on from the next byte, so a cross-reference stream after it is still read. A font a PDF carries with restricted license flags (OS/2 fsType 0x0002) keeps drawing its type, and a PDF saved from the document draws that type as outlines with the license warning instead of embedding the font again. --- crates/pdf/src/streams.rs | 13 +++++++++++++ crates/pdf/src/tests/file_fonts.rs | 28 +++++++++++++++++++++++++++- crates/pdf/src/tests/live_text.rs | 2 +- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index e29d828f48..7314e930ae 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -1034,6 +1034,19 @@ mod tests { assert!(unread.is_empty(), "{unread:#?}"); } + #[test] + fn a_hex_string_broken_by_a_non_hex_byte_hides_no_stream_after_it() { + // A `<` followed by hex digits and then a byte that is neither a hex digit nor white space + // is no hex string: the scan goes on from the next byte instead of skipping to a `>`. + let bad = b"<< /Type /XRef /DecodeParms 9 0 R >> stream\nx\nendstream"; + for lead in [&b"<4G "[..], b"<41 4z ", b"<\x00 "] { + let pdf = [lead, &bad[..]].concat(); + assert!(unsafe_file_streams(&pdf), "{}", String::from_utf8_lossy(&pdf)); + } + // A hex string that ends is skipped, and the stream after it is still read. + assert!(unsafe_file_streams(&[&b"<41 42> "[..], &bad[..]].concat())); + } + #[test] fn a_run_of_lt_in_an_image_a_string_or_a_comment_opens() { // #3924 review: every `<<` in a run of `<` (an image's flat area of grey 60) was read as a diff --git a/crates/pdf/src/tests/file_fonts.rs b/crates/pdf/src/tests/file_fonts.rs index d0d1b949ab..b27dac4f0d 100644 --- a/crates/pdf/src/tests/file_fonts.rs +++ b/crates/pdf/src/tests/file_fonts.rs @@ -10,7 +10,7 @@ use kurbo::{Point, Rect, Shape}; use vectorcraft_doc::{Document, FILE_FONT_MIME, TextObject}; use vectorcraft_text::{FontDb, FontMatch}; -use crate::tests::live_text::{SOURCE_SERIF, outlines, texts, uninstalled_serif}; +use crate::tests::live_text::{SOURCE_SERIF, outlines, renamed, texts, uninstalled_serif}; use crate::*; /// Lines of (x, y from the top, size, text): kerned pairs, a long line, two sizes. @@ -274,3 +274,29 @@ fn two_glyphs_for_one_character_both_survive_import() { }; close(&glyph_ink(db, &imported), "imported"); } + +/// The license flags (OS/2 `fsType`) of the font a PDF carries go with the font the document keeps: +/// a restricted font (0x0002) still draws its type, and a PDF saved from the document draws that +/// type as outlines with the license warning instead of embedding the font again. +#[test] +fn a_restricted_font_the_file_carries_is_not_embedded_again() { + let mut font = renamed(SOURCE_SERIF, &[("SourceSerif4", "SourceSerif7"), ("Source Serif 4", "Source Serif 7")]); + let tables = usize::from(u16::from_be_bytes([font[4], font[5]])); + let os2 = (0..tables).map(|i| 12 + 16 * i).find(|r| &font[*r..*r + 4] == b"OS/2").unwrap(); + let at = u32::from_be_bytes(font[os2 + 8..os2 + 12].try_into().unwrap()) as usize; + font[at + 8..at + 10].copy_from_slice(&0x0002u16.to_be_bytes()); + + let carried = import(&page_pdf(font)); + let t = texts(&carried.document); + assert!(t.iter().any(|t| t.file_fonts.is_some()), "the file's font draws its type"); + + let saved = export_with_report(&carried.document, &PdfOptions::default()).unwrap(); + assert!(saved.warnings.iter().any(|w| w.contains("Source Serif 7") && w.contains("doesn't allow embedding")), "{:?}", saved.warnings); + let back = import(&saved.bytes); + assert!( + texts(&back.document).is_empty(), + "no type in the saved file: {:?}", + texts(&back.document).iter().map(TextObject::plain_text).collect::>() + ); + assert!(!back.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "no font in the saved file"); +} diff --git a/crates/pdf/src/tests/live_text.rs b/crates/pdf/src/tests/live_text.rs index 90341ca28b..f6a2e8229b 100644 --- a/crates/pdf/src/tests/live_text.rs +++ b/crates/pdf/src/tests/live_text.rs @@ -271,7 +271,7 @@ fn invisible_text_is_type_whatever_its_glyphs_look_like() { } /// `font` with each of `names` (`from`, `to`, the same length) replaced, in ASCII and UTF-16. -fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec { +pub(crate) fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec { let mut bytes = font.to_vec(); let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); for &(from, to) in names { From f08d12949c8c79b5d72fcda342a6830d8526f3a1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 23:03:43 -0800 Subject: [PATCH 31/46] Tests: run the attached recolor import test on a synthetic document The recolor adjustment test read test.af from the repository root and returned early when the file was absent, so it never ran in CI. It now builds a magenta rectangle with an attached Recolor adjustment in the test and checks that lightness 1 imports as a white fill, that lightness 0.5 at hue 0 draws pure red, and that a hidden adjustment leaves the fill unchanged. --- crates/engine/tests/it/affinity_features.rs | 51 +++++++++++++++------ 1 file changed, 36 insertions(+), 15 deletions(-) diff --git a/crates/engine/tests/it/affinity_features.rs b/crates/engine/tests/it/affinity_features.rs index 98fdbe6b23..a5bc28f24b 100644 --- a/crates/engine/tests/it/affinity_features.rs +++ b/crates/engine/tests/it/affinity_features.rs @@ -744,20 +744,41 @@ fn objects_beyond_the_document_range_are_left_out() { assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings); } +/// A magenta rectangle with a Recolor adjustment (`RcRA`) attached, at `lightness`. +fn recolored(visible: bool, lightness: f64) -> F { + let mut node = rectangle(10, (0.0, 0.0), (50.0, 50.0)); + let recolor = F::Def( + 20, + vec![tag(b"RcRA")], + vec![ + (tag(b"Visi"), F::Bool(visible)), + (tag(b"AdjP"), F::Obj(tag(b"RecP"), vec![(tag(b"RecH"), F::F64(0.0)), (tag(b"RecS"), F::F64(1.0)), (tag(b"RecL"), F::F64(lightness))])), + ], + ); + if let F::Def(_, _, fields) = &mut node { + fields.push((tag(b"AdCh"), F::Shared(vec![recolor]))); + } + node +} + +fn first_fill(n: &Node) -> Paint { + let Some(AppearanceItem::Fill(fill)) = n.appearance.items.first() else { panic!("no fill: {:?}", n.appearance) }; + fill.paint.clone() +} + #[test] -fn test_af_g_symbol_fill_is_white() { - let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af"); - let Ok(bytes) = std::fs::read(&path) else { - return; - }; - let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap(); - assert!(!loaded.preview_only, "{:?}", loaded.warnings); - let d = &loaded.doc; - // The visible "g41" group holds the "g" symbol (path43). - let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present"); - let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present"); - let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else { - panic!("path43 has no fill: {:?}", path43.appearance); - }; - assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint); +fn attached_recolor_adjustments_recolor_the_shape() { + // Lightness 1 recolors to white. + let loaded = open("recolor.af", &canvas_with(vec![recolored(true, 1.0)], None)); + assert!(!loaded.warnings.iter().any(|w| w.contains("attached to other layers")), "{:?}", loaded.warnings); + let rect = named(&loaded.doc, "Magenta box"); + assert!(rect.appearance.effects.is_empty()); + assert_eq!(first_fill(rect), Paint::solid(Color::rgb(1.0, 1.0, 1.0))); + // Lightness 0.5 at hue 0 and full saturation is pure red. + let d = open("red.af", &canvas_with(vec![recolored(true, 0.5)], None)).doc; + let [r, g, b, a] = pixel(&d, 25, 25); + assert!(r > 250 && g < 5 && b < 5 && a == 255, "{:?}", [r, g, b, a]); + // A hidden adjustment leaves the shape as it is. + let d = open("hidden.af", &canvas_with(vec![recolored(false, 1.0)], None)).doc; + assert_eq!(first_fill(named(&d, "Magenta box")), Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0))); } From 68dbba0b9203d8af64027f2fcef9cabd059fb9a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 23:05:46 -0800 Subject: [PATCH 32/46] PDF: count test reads of a buffer from a mark, not over its address's whole history reads_of counts reads by buffer address and never forgets them, so a buffer allocated where another test's freed buffer was read starts with that count. linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box asserted reads_of(&blob) == 0 and failed once that way under 16 test threads. Each read now gets a sequence number. read_mark returns the next one and reads_of_since counts only the reads at or after a mark. The linked-pages test takes a mark before opening the file. --- crates/engine/src/tests/placed_document.rs | 4 +- crates/pdf/src/lib.rs | 4 +- crates/pdf/src/pages.rs | 44 +++++++++++++++++++--- 3 files changed, 44 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tests/placed_document.rs b/crates/engine/src/tests/placed_document.rs index 00f976ab3f..3dd4959489 100644 --- a/crates/engine/src/tests/placed_document.rs +++ b/crates/engine/src/tests/placed_document.rs @@ -739,6 +739,8 @@ fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() { let art = || PdfPage::new(100.0, 50.0, "1 0 0 rg 10 10 20 20 re f"); write(&src, &pdf(&[art(), PdfPage::new(80.0, 40.0, ""), art()], None)); let mut s = Session::new(); + // A freed buffer that had the blob's address may have been read before, in another test. + let mark = vectorcraft_pdf::read_mark(); s.execute("document.open", &json!({"path": src, "linkPages": true, "cropTo": "bounding"})).unwrap(); let d = &s.doc().unwrap().doc; let boards: Vec = d.artboards.iter().map(|a| a.rect).collect(); @@ -748,7 +750,7 @@ fn linked_pages_read_the_file_once_and_a_blank_page_keeps_its_crop_box() { // The pages are read from the one copy every page's blob keeps: a page that read the file // again would count here. let blob = d.images.values().next().map(|b| b.bytes.clone()).unwrap(); - assert_eq!(vectorcraft_pdf::reads_of(&blob), 0, "the pages are read from the file read once"); + assert_eq!(vectorcraft_pdf::reads_of_since(&blob, mark), 0, "the pages are read from the file read once"); } #[test] diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 7c97651d1d..2dc6f1ec0a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -90,12 +90,12 @@ pub use import_shading::function_evaluation_limit; pub use marks::{leaves_out_bleed, page_bleed, printer_marks}; pub use output::ActiveProfiles; pub use page_widths::{FontWidths, PageWidths}; -#[cfg(any(test, feature = "read-count"))] -pub use pages::reads_of; pub use pages::{ IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, is_postscript, open_pdf, read_illustrator_data_without_pdf_part, read_illustrator_data_without_pdf_part_with, }; +#[cfg(any(test, feature = "read-count"))] +pub use pages::{read_mark, reads_of, reads_of_since}; pub use piece_info::{PRIVATE_CHUNK, PrivateData}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; pub use print::*; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index a742070d20..7455c6d0f5 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -368,14 +368,33 @@ pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: & }) } -/// How many times each buffer has been read as a PDF, by its address (tests). +/// The number the next read as a PDF gets, and every read of a buffer by the buffer's address with +/// its number (tests). A freed buffer's reads stay under its address, so a later buffer at the same +/// address starts with them: count from a [`read_mark`] taken before that buffer exists. #[cfg(any(test, feature = "read-count"))] -static READS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); +type Reads = (u64, std::collections::BTreeMap>); + +#[cfg(any(test, feature = "read-count"))] +static READS: std::sync::Mutex = std::sync::Mutex::new((0, std::collections::BTreeMap::new())); /// How many times `bytes`, at its address, has been read as a PDF on any thread (tests). #[cfg(any(test, feature = "read-count"))] pub fn reads_of(bytes: &[u8]) -> usize { - READS.lock().ok().and_then(|r| r.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) + READS.lock().ok().and_then(|r| r.1.get(&(bytes.as_ptr() as usize)).map(Vec::len)).unwrap_or(0) +} + +/// The number the next read as a PDF gets, for [`reads_of_since`] (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn read_mark() -> u64 { + READS.lock().map(|r| r.0).unwrap_or(0) +} + +/// How many times `bytes`, at its address, has been read as a PDF on any thread since `mark` was +/// taken with [`read_mark`] (tests). Reads made before `mark`, such as reads of a freed buffer +/// that had the same address, are not counted. +#[cfg(any(test, feature = "read-count"))] +pub fn reads_of_since(bytes: &[u8], mark: u64) -> usize { + READS.lock().ok().and_then(|r| r.1.get(&(bytes.as_ptr() as usize)).map(|reads| reads.iter().filter(|&&n| n >= mark).count())).unwrap_or(0) } /// [`open_with_options`] without looking at the file's objects ([`hostile`]): the reader builds its @@ -384,8 +403,9 @@ pub fn reads_of(bytes: &[u8]) -> usize { fn open_structural_with_options(bytes: &[u8], password: Option<&str>, options: &craft::pdf::OpenOptions) -> Result { #[cfg(any(test, feature = "read-count"))] if let Ok(mut reads) = READS.lock() { - let n = reads.entry(bytes.as_ptr() as usize).or_default(); - *n = n.saturating_add(1); + let n = reads.0; + reads.0 = n.saturating_add(1); + reads.1.entry(bytes.as_ptr() as usize).or_default().push(n); } if is_postscript(bytes) { return Err(PdfError::PostScript); @@ -763,4 +783,18 @@ mod tests { assert_eq!(super::decoded_size(1 << 30), "1 GB"); assert_eq!(super::decoded_size((1 << 30) + (1 << 20)), "1025 MB"); } + + /// Reads made before a mark, as of a freed buffer whose address a new one takes, are not + /// counted from that mark; reads after it are. + #[test] + fn reads_since_a_mark_leave_out_earlier_reads_at_the_same_address() { + let bytes = b"not a pdf".to_vec(); + let start = super::read_mark(); + let _ = super::open_structural_with_options(&bytes, None, &super::open_options()); + let mark = super::read_mark(); + assert_eq!(super::reads_of_since(&bytes, start), 1, "the read from the start"); + assert_eq!(super::reads_of_since(&bytes, mark), 0, "the read before the mark"); + let _ = super::open_structural_with_options(&bytes, None, &super::open_options()); + assert_eq!(super::reads_of_since(&bytes, mark), 1, "the read after the mark"); + } } From c9d9b75f761027bbef7a1fa32e90859fc9a46636 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:30:45 -0800 Subject: [PATCH 33/46] Tests: the held font scan test no longer hangs when its pipe is released early the_menu_family_list_now_does_not_wait_for_the_scan holds the font scan at a named pipe and released it with one blocking open for writing. That open waits for any reader and lets go only the readers already waiting. When the scan reached the pipe after the release, or ran on the test's own thread because its background thread did not start, nothing opened the pipe again and the test waited until the job timed out (a gate shard on pull request 10368 ran for over two hours). The release thread now opens the pipe for reading and writing, which does not wait for a reader, and repeats that until the scan has ended. The thread is joined after the list that waits for the scan. --- crates/text/src/tests/sysfonts.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 261cc1c54c..246f589518 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -536,21 +536,28 @@ fn the_menu_family_list_now_does_not_wait_for_the_scan() { db.scan_in_background(); // The scan can't end until the pipe is opened for writing, so a list that waited for it would // hold the installed fonts. This thread lets the scan go on once the calls return, or after 10 s - // if they are still waiting, so that such a test fails instead of hanging. + // if they are still waiting, so that such a test fails instead of hanging. It opens the pipe + // for reading and writing, which doesn't wait for a reader, and repeats that until the scan has + // ended: a single open for writing waits for any reader and lets only the readers already + // waiting go, so the test hung when the scan reached the pipe later, or ran on this thread + // because its own thread didn't start. let (returned, waiting) = std::sync::mpsc::channel::<()>(); let release = pipe.clone(); let guard = std::thread::spawn(move || { let _ = waiting.recv_timeout(std::time::Duration::from_secs(10)); - // The pipe is opened and closed with nothing written. - drop(std::fs::OpenOptions::new().write(true).open(&release).unwrap()); + while !db.installed_fonts_ready() { + // The pipe is opened and closed with nothing written. + drop(std::fs::OpenOptions::new().read(true).write(true).open(&release).unwrap()); + std::thread::yield_now(); + } }); let ready = db.installed_fonts_ready(); let listed = db.menu_family_list_now(); drop(returned); - guard.join().unwrap(); assert!(!ready && !has(&listed, FAMILY), "before the scan ends, only the fonts already loaded"); // Waits for the scan. assert!(has(&db.menu_family_list(), FAMILY)); + guard.join().unwrap(); assert!(db.installed_fonts_ready()); assert_ne!(db.generation(), generation, "a menu built from the short list is built again"); assert!(has(&db.menu_family_list_now(), FAMILY)); From c175089a206dfb53e544a99307022f890419a38f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 01:32:39 -0800 Subject: [PATCH 34/46] Tests: seed the Math.random test realm through Interp::new Realm::with_os_random made a realm and then replaced its seed, so the test still passed if Interp::new stopped seeding from the OS random source. The OS read now goes through os_random(), which a test can set for the realms made on its thread, and with_os_random builds its realm with Realm::new. The test fails when Interp::new uses a fixed seed. --- crates/js/src/interp.rs | 20 +++++++++++++++++++- crates/js/src/realm.rs | 8 +++++--- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 517caa9c06..05e704b08e 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -544,7 +544,25 @@ fn index_names_bytes(len: usize, per_entry: usize) -> usize { /// random source (the browser's crypto on the web), or the standard library's randomly keyed /// hasher when that fails; never zero. fn random_seed() -> u64 { - random_seed_from(getrandom::u64()) + random_seed_from(os_random()) +} + +/// The OS random source. +#[cfg(not(test))] +fn os_random() -> Result { + getrandom::u64() +} + +#[cfg(test)] +thread_local! { + /// What the OS random source returns to realms made on this thread, when set. + pub(crate) static TEST_OS_RANDOM: std::cell::Cell>> = const { std::cell::Cell::new(None) }; +} + +/// The OS random source, or what a test set in [`TEST_OS_RANDOM`]. +#[cfg(test)] +fn os_random() -> Result { + TEST_OS_RANDOM.with(std::cell::Cell::get).unwrap_or_else(getrandom::u64) } /// [`random_seed`] from what the OS random source returned. diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 1032b01a17..822477780f 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -210,11 +210,13 @@ impl Realm { } /// A realm whose `Math.random` starts from the seed made of `os`, as if the OS random source - /// had returned it. + /// had returned it. The realm is made by [`Realm::new`], so its seed comes through the same + /// path as any other realm's. #[cfg(test)] pub(crate) fn with_os_random(os: Result) -> Self { - let mut realm = Self::new(); - realm.interp.random = crate::interp::random_seed_from(os); + crate::interp::TEST_OS_RANDOM.with(|c| c.set(Some(os))); + let realm = Self::new(); + crate::interp::TEST_OS_RANDOM.with(|c| c.set(None)); realm } From 45fd2a5347ee8c3c68550a371da05d0152353450 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:59:09 -0800 Subject: [PATCH 35/46] Troubleshooting: report the active graphics driver (#10348) --- apps/vectorcraft/src/hang_watch.rs | 31 +++++++++++++++++++++--- apps/vectorcraft/src/hang_watch/tests.rs | 19 +++++++++++++++ apps/vectorcraft/src/main.rs | 22 +++++++++++------ 3 files changed, 61 insertions(+), 11 deletions(-) diff --git a/apps/vectorcraft/src/hang_watch.rs b/apps/vectorcraft/src/hang_watch.rs index 5714b8c548..5039c89bd1 100644 --- a/apps/vectorcraft/src/hang_watch.rs +++ b/apps/vectorcraft/src/hang_watch.rs @@ -3,8 +3,8 @@ //! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the //! log (`logs/vectorcraft.log`) and to `logs/hang-report-.txt`: the stage, a clipboard //! call in progress, the last commands, the last frames' times, the platform, the window system, the -//! graphics processor and the present mode the app asked for, and how long the session has run with -//! how many documents open. The process holds a lock on the file until the interface thread answers +//! graphics processor, its driver when known, and the present mode the app asked for, and how long +//! the session has run with how many documents open. The process holds a lock on the file until the interface thread answers //! again; then the log says after how long and the file is removed. A file nobody holds at a later //! launch was left by a session that was closed while it did not answer, and a locked one belongs to //! another instance that is stalled now and is left alone. That launch writes the report to the log, @@ -113,6 +113,8 @@ pub struct Facts { pub flatpak: bool, /// The graphics processor the window draws with. pub graphics: Option, + /// The active graphics driver's identity, when the backend reports it. + graphics_driver: Option, /// The present mode and frame queue the app asked the window surface for. pub surface: String, } @@ -128,14 +130,29 @@ impl Facts { session_type: value("XDG_SESSION_TYPE"), flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()), graphics, + graphics_driver: None, surface, } } + #[cfg(any(feature = "wgpu", test))] + pub fn with_graphics_driver(mut self, driver: &str, info: &str) -> Facts { + // D3D12 reports 0.0.0.0 when the driver version could not be read. + let mut fields = [driver, info].map(clean).into_iter().filter(|value| !value.is_empty() && value != "0.0.0.0"); + self.graphics_driver = fields.next().map(|mut detail| { + if let Some(info) = fields.next().filter(|info| info != &detail) { + detail.push_str(" / "); + detail.push_str(&info); + } + detail + }); + self + } + /// The facts as report lines. pub fn lines(&self) -> String { let or_unknown = |v: &Option| v.clone().unwrap_or_else(|| "unknown".to_string()); - format!( + let mut lines = format!( "VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n", vectorcraft_ui_egui::os_window::version(), std::env::consts::OS, @@ -146,7 +163,13 @@ impl Facts { if self.flatpak { "yes" } else { "no" }, or_unknown(&self.graphics), self.surface, - ) + ); + if let Some(driver) = &self.graphics_driver { + lines.push_str("Graphics driver: "); + lines.push_str(driver); + lines.push('\n'); + } + lines } } diff --git a/apps/vectorcraft/src/hang_watch/tests.rs b/apps/vectorcraft/src/hang_watch/tests.rs index 7452d41502..608d6e9b78 100644 --- a/apps/vectorcraft/src/hang_watch/tests.rs +++ b/apps/vectorcraft/src/hang_watch/tests.rs @@ -279,3 +279,22 @@ fn troubleshooting_info_holds_both_sessions_reports() { assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n")); assert!(text.contains("Recent commands, oldest first: none")); } + +#[test] +fn troubleshooting_info_distinguishes_drivers_on_the_same_adapter() { + let mut shared = shared(None); + let beacon = Beacon::new(); + for (driver, info, expected) in [ + (" 32.0.16.1088 ", "", Some("32.0.16.1088")), + ("32.0.16.2124", "", Some("32.0.16.2124")), + ("Mesa\nRADV", "Mesa 25.2", Some("MesaRADV / Mesa 25.2")), + ("Mesa", "Mesa", Some("Mesa")), + ("0.0.0.0", "", None), + ("", "", None), + ] { + shared.facts = facts().with_graphics_driver(driver, info); + let text = troubleshooting(&shared, &beacon, UNIX_EPOCH); + assert!(text.contains("Graphics: Test GPU"), "the adapter description is still in the report"); + assert_eq!(text.lines().find_map(|line| line.strip_prefix("Graphics driver: ")), expected); + } +} diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index b603ed7960..dc6e7fd7d6 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -981,14 +981,22 @@ fn main() -> std::process::ExitCode { .map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency)); #[cfg(not(feature = "wgpu"))] let surface = None; + let facts = hang_watch::Facts::new( + |name| std::env::var(name).ok(), + std::path::Path::new("/.flatpak-info").exists(), + hang_watch::window_system(winit_window.as_deref()), + app.graphics_adapter.clone(), + hang_watch::surface(surface), + ); + #[cfg(feature = "wgpu")] + let facts = if let Some(rs) = &cc.wgpu_render_state { + let info = rs.adapter.get_info(); + facts.with_graphics_driver(&info.driver, &info.driver_info) + } else { + facts + }; let hang = std::sync::Arc::new(hang_watch::Shared { - facts: hang_watch::Facts::new( - |name| std::env::var(name).ok(), - std::path::Path::new("/.flatpak-info").exists(), - hang_watch::window_system(winit_window.as_deref()), - app.graphics_adapter.clone(), - hang_watch::surface(surface), - ), + facts, started: std::time::Instant::now(), last: std::sync::Mutex::new(None), previous: previous_hang.clone(), From e5bdd539d0e208888a36f12b3867a98d03e8f9a3 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:01:10 -0800 Subject: [PATCH 36/46] Keep file progress windows visible between frames (#10343) * Keep the file progress window visible between frames * Apply completed jobs while showing progress --- crates/ui-egui/src/export_progress.rs | 13 ++++++++---- crates/ui-egui/src/lib.rs | 17 +++++++++++---- crates/ui-egui/src/opening.rs | 2 +- crates/ui-egui/src/opening/tests.rs | 30 +++++++++++++++++++++++---- crates/ui-egui/src/placing.rs | 2 +- crates/ui-egui/src/placing/tests.rs | 5 ++++- crates/ui-egui/src/plugin_runs.rs | 2 +- crates/ui-egui/src/retype_runs.rs | 2 +- crates/ui-egui/src/trace_runs.rs | 2 +- 9 files changed, 57 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/export_progress.rs b/crates/ui-egui/src/export_progress.rs index 81bf88811c..1f1245000d 100644 --- a/crates/ui-egui/src/export_progress.rs +++ b/crates/ui-egui/src/export_progress.rs @@ -67,7 +67,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { ui.ctx().request_repaint_after(Duration::from_secs_f64(DELAY - age)); return; } - if app.any_dialog_open() { + // Progress is modal for input, but the window must not block itself on its next pass. + if app.asking_dialog_open() { return; } let Shown { title, step, fraction, counts, queued, cancel, hide, .. } = shown; @@ -208,17 +209,21 @@ mod tests { assert_eq!(r["background"], true, "{r}"); } let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); assert!(!frame(&mut app, &ctx).contains("Saving a.vectorcraft"), "not before the delay"); age(&mut app); frame(&mut app, &ctx); - let shown = frame(&mut app, &ctx); - assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("waiting"), "{shown}"); - assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}"); + let visible: Vec<_> = (0..6).map(|_| (frame(&mut app, &ctx), app.any_dialog_open())).collect(); assert_eq!(app.run("file.saveInBackground", json!({})).unwrap()["hidden"], 2); assert!(!frame(&mut app, &ctx).contains("Saving"), "hidden saves aren't shown"); assert!(crate::menus::enabled(&app, "file.cancelSave"), "they can still be canceled"); go.store(true, std::sync::atomic::Ordering::SeqCst); background::wait_all(&mut app); + for (shown, modal) in visible { + assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("waiting"), "{shown}"); + assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}"); + assert!(modal, "progress remains modal for input"); + } assert!(app.background.jobs.is_empty()); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/docs/b.vectorcraft")); app.session.execute("prefs.set", &json!({"values": {"backgroundSave": false}})).unwrap(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3cd948fce0..8a931c60b3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -372,13 +372,22 @@ pub struct VectorcraftApp { impl VectorcraftApp { /// Whether a layer that takes the keys (a modal dialog, a popup) showed in the last pass, or a - /// modal dialog opened since: a command or a canvas gesture waits while one does. A modeless - /// dialog blocks nothing, and the job progress window does not count (its layer has the - /// progress role). False before the app has a context. + /// modal dialog opened since: a command or a canvas gesture waits while one does. This includes + /// job progress, which is a modal layer. pub(crate) fn any_dialog_open(&self) -> bool { + self.dialog_open(OpenFilter::Modal) + } + + /// Whether a question or popup is open. Applying a job's result can close its progress window. + pub(crate) fn asking_dialog_open(&self) -> bool { + self.dialog_open(OpenFilter::Asks) + } + + /// Whether a layer matching the filter, a popup or a pending app modal is open. + fn dialog_open(&self, filter: OpenFilter) -> bool { // A modeless layer with a focus scope (the canvas's task bar) takes keys too, and blocks nothing. let popup = |ctx: &egui::Context| overlay::top(ctx).and_then(|id| overlay::entry(ctx, id)).is_some_and(|e| e.rank == overlay::Rank::Popup); - self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, OpenFilter::Modal) || popup(ctx)) + self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, filter) || popup(ctx)) || self.dialogs().is_some_and(|d| d.with(|h| h.shows_modal())) } diff --git a/crates/ui-egui/src/opening.rs b/crates/ui-egui/src/opening.rs index 5e72952fe2..541b033cff 100644 --- a/crates/ui-egui/src/opening.rs +++ b/crates/ui-egui/src/opening.rs @@ -148,7 +148,7 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver bool { - if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) { + if app.asking_dialog_open() || crate::dialogs::missing_fonts::waiting(app) { return false; } let s = &app.session; diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index cdb55375db..0dd4c4c3b7 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -545,16 +545,20 @@ fn a_file_that_takes_a_while_to_open_shows_a_progress_window() { // The app's clock stands still: a read is only old enough for its window after `age`. app.now_override = Some(0.0); let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); assert_eq!(progress(&mut app, &ctx), "", "nothing opening"); start(&mut app, "/art/Big.vectorcraft", bytes("Big")); assert_eq!(progress(&mut app, &ctx), "", "not at once"); age(&mut app); progress(&mut app, &ctx); // a new window measures itself unseen first - let texts = progress(&mut app, &ctx); - for want in ["Opening Big.vectorcraft…", "Reading the file…", "Cancel", "Continue in Background"] { - assert!(texts.contains(want), "{want} in {texts}"); + for _ in 0..6 { + let texts = progress(&mut app, &ctx); + for want in ["Opening Big.vectorcraft…", "Reading the file…", "Cancel", "Continue in Background"] { + assert!(texts.contains(want), "{want} in {texts}"); + } + assert!(!texts.contains("waiting"), "{texts}"); + assert!(app.any_dialog_open(), "progress remains modal for input"); } - assert!(!texts.contains("waiting"), "{texts}"); start(&mut app, "/art/Next.vectorcraft", bytes("Next")); let texts = progress(&mut app, &ctx); assert!(texts.contains("Opening Big.vectorcraft…") && texts.contains("waiting"), "{texts}"); @@ -569,6 +573,24 @@ fn a_file_that_takes_a_while_to_open_shows_a_progress_window() { assert_eq!(app.session.documents().len(), before + 2); } +#[test] +fn a_file_ready_while_progress_is_visible_opens_without_hiding_progress() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.now_override = Some(0.0); + let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); + start(&mut app, "/art/Big.vectorcraft", bytes("Big")); + age(&mut app); + progress(&mut app, &ctx); + assert!(progress(&mut app, &ctx).contains("Opening Big.vectorcraft")); + assert!(app.any_dialog_open()); + + open_ready(&mut app); + assert!(app.opening.pending.is_empty()); + assert_eq!(app.session.doc().unwrap().path.as_deref(), Some("/art/Big.vectorcraft")); + assert_eq!(progress(&mut app, &ctx), "", "completion closes progress"); +} + /// #5930: the progress window's Cancel (`file.cancelOpen`): the file doesn't open, even once it /// has been read, and the status bar no longer says it is opening. #[test] diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index 972e907fea..9d1cc5be02 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -445,7 +445,7 @@ fn spawn_labeled( /// the file is placed unless the tool has a preview open (the Flare tool after its center drag). pub fn poll(app: &mut VectorcraftApp) { settle_swatch_paste(app); - while !app.any_dialog_open() + while !app.asking_dialog_open() && !app.session.in_interaction() && !(app.session.tool_busy() && app.session.pointer_held()) && let Some(p) = app.placing.pending.first() diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index fb75d86663..dc6a19e0fc 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -1980,6 +1980,7 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let ctx = crate::testing::ui_context(); + app.adopt_context(&ctx); assert_eq!(progress(&mut app, &ctx), "", "nothing placing"); let slow_path = saved("progress", "slow.png", &picture(Png, 100, 100)); @@ -2002,10 +2003,12 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() { start(&mut app, &json!({"path": next_path, "at": [200, 150]}), false).unwrap(); let texts = progress(&mut app, &ctx); assert!(texts.contains("Placing slow.png…") && texts.contains("waiting"), "{texts}"); + assert!(app.any_dialog_open()); - // Release and finish + // Releasing the read applies both files without dismissing the progress window first. drop(go); placed(&mut app); + assert_eq!(progress(&mut app, &ctx), "", "completion closes progress"); } /// #5930: cancelling a place aborts the operation, drops the parsed asset, leaves the document diff --git a/crates/ui-egui/src/plugin_runs.rs b/crates/ui-egui/src/plugin_runs.rs index 067302ddcb..a5be54af01 100644 --- a/crates/ui-egui/src/plugin_runs.rs +++ b/crates/ui-egui/src/plugin_runs.rs @@ -458,7 +458,7 @@ pub fn poll(app: &mut VectorcraftApp) { poll_checks(app); let mut i = 0; while let Some(r) = app.plugin_runs.running.get(i) { - let dialog = app.any_dialog_open() || app.session.script_running(); + let dialog = app.asking_dialog_open() || app.session.script_running(); let ended = match &r.backend { Backend::Thread(_) if dialog => None, Backend::Worker(..) if dialog => watch_worker(app, i), diff --git a/crates/ui-egui/src/retype_runs.rs b/crates/ui-egui/src/retype_runs.rs index 81f774d5d3..c51c5a6a8f 100644 --- a/crates/ui-egui/src/retype_runs.rs +++ b/crates/ui-egui/src/retype_runs.rs @@ -130,7 +130,7 @@ fn stop(app: &mut VectorcraftApp) { /// Runs the command of the search that is done (each frame). Not while a dialog is open, nor while /// an interaction is open or a tool drags with the pointer button held, as [`crate::trace_runs::poll`]. pub fn poll(app: &mut VectorcraftApp) { - if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { + if app.asking_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { return; } let Some(r) = &app.retype_runs.running else { return }; diff --git a/crates/ui-egui/src/trace_runs.rs b/crates/ui-egui/src/trace_runs.rs index 341c0c4113..c554b21add 100644 --- a/crates/ui-egui/src/trace_runs.rs +++ b/crates/ui-egui/src/trace_runs.rs @@ -140,7 +140,7 @@ pub fn start(app: &mut VectorcraftApp, command: &str, p: Value, from_panel: bool /// dialog is open (its OK acts on the active document, which a trace's result changes), nor while /// an interaction is open or a tool drags with the pointer button held, as [`crate::placing::poll`]. pub fn poll(app: &mut VectorcraftApp) { - if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { + if app.asking_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) { return; } let mut i = 0; From d0cf7f09ecb670f9edc30b9cda3b17e5155b6ab0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:05:29 -0800 Subject: [PATCH 37/46] Tests: format tests check exact values instead of wide tolerances The PDF, EPS, SVG mesh, metafile hatch and distorted-image tests now assert the values the input gives: the Letter page a page without area falls back to, the H glyph's box from its font metrics, the middle gray of each mesh piece, the 8 of 64 hatch pixels, and the bounds of the placement taken at the image's center. --- crates/doc/src/image_quad.rs | 2 +- crates/eps/src/import/tests_composite.rs | 14 ++++++++++---- crates/metafile/src/tests/import.rs | 6 ++++-- crates/pdf/src/tests/import_options.rs | 3 ++- crates/svg/tests/it/mesh_export.rs | 5 +++++ 5 files changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs index 8f514a3b71..f5b087125d 100644 --- a/crates/doc/src/image_quad.rs +++ b/crates/doc/src/image_quad.rs @@ -457,7 +457,7 @@ mod tests { n.transform(Affine::scale_non_uniform(1.0, 0.25), false); assert!(n.extras().image_quad.is_none()); let b = n.geometric_bounds().unwrap(); - assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}"); + assert!(b.height() < 1e-6 && (b.x0 + 200.0 / 9.0).abs() < 1e-6 && (b.x1 - 1400.0 / 9.0).abs() < 1e-6, "{b:?}"); } /// A file's corners that the image cannot take are dropped as it is read, so a later scale diff --git a/crates/eps/src/import/tests_composite.rs b/crates/eps/src/import/tests_composite.rs index ff3b3382d3..6e3a63373d 100644 --- a/crates/eps/src/import/tests_composite.rs +++ b/crates/eps/src/import/tests_composite.rs @@ -64,8 +64,10 @@ fn type42_descendants_draw_their_own_glyphs() { } // The H, then the I one H's width along; both stand on the baseline, a cap height tall. let (bh, bi) = (bounds(paths[0]), bounds(paths[1])); - assert!((bh.x0 - 10.0).abs() < 8.0 && bh.width() > 20.0 && bh.width() < 50.0 * wh, "{bh:?}"); - assert!((bh.height() - bi.height()).abs() < 0.5 && bh.height() > 25.0 && bh.height() < 40.0, "{bh:?} {bi:?}"); + // The bundled font's H spans (90, 0)–(562, 656) of its 1000-unit em: at 50 pt from x = 10 that + // is 14.5 to 38.1, 32.8 tall. + assert!((bh.x0 - 14.5).abs() < 0.01 && (bh.width() - 23.6).abs() < 0.01 && (bh.height() - 32.8).abs() < 0.01, "{bh:?}"); + assert!((bh.height() - bi.height()).abs() < 0.5, "{bh:?} {bi:?}"); assert!(bi.x0 > 10.0 + 50.0 * wh - 1.0 && bi.x1 < 10.0 + 50.0 * (wh + wi), "{bi:?}"); } @@ -78,8 +80,12 @@ fn type42_descendants_measure_space_and_outline_their_glyphs() { check(format!("(\\000\\001\\000\\002) stringwidth pop {} sub abs 0.01 lt", 50.0 * (wh + wi))); // xyshow places each character where its numbers say. check("gsave nulldevice 10 20 moveto (\\000\\001\\000\\002) [30 0 7 0] xyshow currentpoint grestore pop 47 sub abs 0.01 lt".into()); - // charpath outlines them. - check("newpath 10 20 moveto (\\000\\001) true charpath pathbbox exch pop sub abs 25 gt exch 10 sub abs 8 lt and".into()); + // charpath outlines them: the H's box is (14.5, 20)–(38.1, 52.8). + check( + "newpath 10 20 moveto (\\000\\001) true charpath pathbbox 52.8 sub abs 0.01 lt exch 38.1 sub abs 0.01 lt and \ + exch 20 sub abs 0.01 lt and exch 14.5 sub abs 0.01 lt and" + .into(), + ); } /// A descendant that is a font by name only (its program isn't run) sets its characters as type, diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 15eca240a9..42a66bc8d5 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -731,7 +731,8 @@ fn hatched_brushes_fill_with_their_average_color() { let p = paths(&back.document); assert_eq!(p.len(), 1); let [r, g, b] = fill_rgb(&p[0]).unwrap(); - assert!(b == 255 && r == g && r > 0 && r < 255, "{:?}", [r, g, b]); + // The horizontal hatch covers one row in eight of its 8 × 8 tile: 8 blue and 56 white pixels. + assert_eq!([r, g, b], [223, 223, 255]); // With a transparent background (SETBKMODE 1) the hatch is blue with gaps: a translucent fill. let mut records = records; records.insert(0, (18, le(&[1]))); @@ -739,7 +740,8 @@ fn hatched_brushes_fill_with_their_average_color() { let p = paths(&back.document); assert_eq!(fill_rgb(&p[0]), Some([0, 0, 255])); let AppearanceItem::Fill(f) = &p[0].appearance.items[0] else { panic!("a fill") }; - assert!(f.opacity > 0.0 && f.opacity < 1.0, "{}", f.opacity); + // One eighth of 255, truncated to 31. + assert!((f.opacity - 31.0 / 255.0).abs() < 1e-6, "{}", f.opacity); } #[test] diff --git a/crates/pdf/src/tests/import_options.rs b/crates/pdf/src/tests/import_options.rs index a419d64137..2205ae2a7f 100644 --- a/crates/pdf/src/tests/import_options.rs +++ b/crates/pdf/src/tests/import_options.rs @@ -272,7 +272,8 @@ fn a_page_without_area_gets_the_size_viewers_give_it() { let bytes = pdf(&[PdfPage { media: [0.0, 0.0, 0.0, 0.0], ..PdfPage::new(0.0, 0.0, "") }], None); let i = info(&bytes, None).unwrap(); let (w, h) = (i.pages[0].width, i.pages[0].height); - assert!(w > 0.0 && h > 0.0); + // US Letter, 8.5 × 11 in. + assert_eq!((w, h), (612.0, 792.0)); for crop in [CropTo::Crop, CropTo::Media, CropTo::Art] { let ab = open(&bytes, ImportOptions { crop, ..Default::default() }).artboards[0].rect; assert_eq!((ab.width(), ab.height()), (w, h), "{crop:?}"); diff --git a/crates/svg/tests/it/mesh_export.rs b/crates/svg/tests/it/mesh_export.rs index 78f30f50c9..c46b943734 100644 --- a/crates/svg/tests/it/mesh_export.rs +++ b/crates/svg/tests/it/mesh_export.rs @@ -84,6 +84,11 @@ fn a_patch_is_cut_no_finer_than_its_colour_changes() { let d = doc(2, 2, |_, c| Color::rgb8(100 + c as u8, 100 + c as u8, 100 + c as u8)); let svg = export(&d, &ExportOptions::default()); assert!(pieces(&svg) <= 4, "{} pieces", pieces(&svg)); + // Each piece takes its patch's middle color: 100.5 and 101.5 round to 101 and 102. + let mut fills: Vec<&str> = svg.split("fill=\"").skip(1).filter_map(|s| s.split('"').next()).filter(|f| f.starts_with('#')).collect(); + fills.sort_unstable(); + fills.dedup(); + assert_eq!(fills, ["#656565", "#666666"], "{svg}"); assert_looks_alike(&d, &svg, in_square, 2, 0.0); } From 78eb2f4afb6adc0bb844c07ad59ccbce1522322d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:09:48 -0800 Subject: [PATCH 38/46] Arrange Tools: list Group by Row among the dialogs ui.menuDialog opens ui.menuDialog opens the Group by Row dialog, so its params text and the MCP UI catalog name addon.arrange.groupRows with the other Arrange Tools dialogs. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..ca3e348b7c 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..67dabfc392 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.arrange.groupRows|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 540d0fad700b7ff90dfdc6a5d04166e4b1e10a73 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:11:16 -0800 Subject: [PATCH 39/46] Plug-ins: list Mark Bounds of Each in ui.menuDialog's params text ui.menuDialog opens the Mark Bounds of Each dialog, so its command list and the generated MCP catalog now name addon.arrange.markBounds. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 2c8f54eb6e..d3d44c9f15 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5681df62bf..f497b0dd08 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.menuDialog", "Menu Dialog", "", - "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", + "{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.arrange.markBounds|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)", ), ( "ui.widthPointEdit", From 93286c8deb03a465a6bb7a37934358a3025b9b6e Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:14:03 -0800 Subject: [PATCH 40/46] Dock panels inside the window on native Wayland (#10341) --- apps/vectorcraft/src/main.rs | 10 ++++++++-- apps/vectorcraft/src/tests.rs | 13 +++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index dc6e7fd7d6..4b1c77e0f1 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -432,6 +432,12 @@ fn opens_through_xwayland(pref: Option<&str>) -> bool { true } +/// The docking runtime needs the backend the desktop window is opened on. +fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo { + let backend = if forced_to_x11 { Backend::X11 } else { detected }; + ShellInfo::current().backend(backend) +} + /// The nightly channel this build is, as a string for the log. fn channel_name() -> &'static str { match build_flavor::COMPILED { @@ -718,10 +724,10 @@ fn main() -> std::process::ExitCode { // A window forced onto XWayland runs on X11, whose window manager draws the frame: the // framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and // Preferences › User Interface › System Title Bar. - let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() }; + let shell_info = desktop_shell_info(Backend::from_env(), forced_to_x11); // On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted // beside it (#2450, #5311). - let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland; + let wayland = shell_info.backend == Backend::Wayland; let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing); let shell_info = shell_info.caps(caps); let titlebar_pref = diff --git a/apps/vectorcraft/src/tests.rs b/apps/vectorcraft/src/tests.rs index 838d96845a..c28fb19c13 100644 --- a/apps/vectorcraft/src/tests.rs +++ b/apps/vectorcraft/src/tests.rs @@ -1,5 +1,18 @@ use super::*; +#[test] +fn desktop_shell_reports_the_backend_selected_for_docking() { + let wayland = desktop_shell_info(Backend::Wayland, false); + assert_eq!(wayland.backend, Backend::Wayland); + assert!(!wayland.window_positions(), "native Wayland keeps palettes inside the window"); + + for (detected, force_x11) in [(Backend::Wayland, true), (Backend::X11, false)] { + let x11 = desktop_shell_info(detected, force_x11); + assert_eq!(x11.backend, Backend::X11); + assert!(x11.window_positions(), "X11 and XWayland can place native palettes"); + } +} + /// The saved UI state of an old `ui.json`, as the legacy import reads it. fn legacy_ui(bytes: &[u8]) -> Option { vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui) From 9730c888fba05ee9d477e0bd49017ea55ff0355f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:01:10 -0800 Subject: [PATCH 41/46] Tests: seed the PDF file key test through protect The test called Entropy::seeded directly, so it still passed if export stopped reading the OS random source. Entropy::new now reads the OS bytes and the time through seed_sources(), which a test can set for its thread, and the test runs protect with fixed OS bytes, other OS bytes and a failed OS read. The OS read in vectorcraft-js's os_random() is now one function for tests and builds alike. --- crates/js/src/interp.rs | 22 ++++++++++-------- crates/pdf/src/encrypt.rs | 40 ++++++++++++++++++++++++++++----- crates/pdf/src/tests/encrypt.rs | 25 ++++++++++++++------- 3 files changed, 64 insertions(+), 23 deletions(-) diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 05e704b08e..dac4a0c729 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -547,22 +547,26 @@ fn random_seed() -> u64 { random_seed_from(os_random()) } -/// The OS random source. -#[cfg(not(test))] -fn os_random() -> Result { - getrandom::u64() -} - #[cfg(test)] thread_local! { /// What the OS random source returns to realms made on this thread, when set. pub(crate) static TEST_OS_RANDOM: std::cell::Cell>> = const { std::cell::Cell::new(None) }; } -/// The OS random source, or what a test set in [`TEST_OS_RANDOM`]. -#[cfg(test)] +/// The OS random source (in tests, what `TEST_OS_RANDOM` holds when set). fn os_random() -> Result { - TEST_OS_RANDOM.with(std::cell::Cell::get).unwrap_or_else(getrandom::u64) + test_os_random().unwrap_or_else(getrandom::u64) +} + +/// What a test set in `TEST_OS_RANDOM`. +#[cfg(test)] +fn test_os_random() -> Option> { + TEST_OS_RANDOM.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn test_os_random() -> Option> { + None } /// [`random_seed`] from what the OS random source returned. diff --git a/crates/pdf/src/encrypt.rs b/crates/pdf/src/encrypt.rs index 4807763598..e9d845756c 100644 --- a/crates/pdf/src/encrypt.rs +++ b/crates/pdf/src/encrypt.rs @@ -163,22 +163,50 @@ fn hash6(password: &[u8], salt: &[u8], udata: &[u8]) -> Result<[u8; 32], PdfErro } /// Unpredictable bytes: SHA-256 of a seed and a counter. -pub(crate) struct Entropy { +struct Entropy { seed: [u8; 32], counter: u64, } +/// What the OS random source returned, and the time. +type SeedSources = (Result<[u8; 32], getrandom::Error>, i64); + +#[cfg(test)] +thread_local! { + /// What the OS random source and the clock return to [`Entropy::new`] on this thread, when set. + pub(crate) static TEST_SEED_SOURCES: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// 32 bytes from the OS random source, and the time. +fn seed_sources() -> SeedSources { + test_seed_sources().unwrap_or_else(|| { + let mut os = [0u8; 32]; + let os = getrandom::fill(&mut os).map(|()| os); + (os, vectorcraft_doc::metadata::now_unix().unwrap_or_default()) + }) +} + +/// What a test set in `TEST_SEED_SOURCES`. +#[cfg(test)] +fn test_seed_sources() -> Option { + TEST_SEED_SOURCES.with(std::cell::Cell::get) +} + +#[cfg(not(test))] +fn test_seed_sources() -> Option { + None +} + impl Entropy { /// Seeded from the OS random source, with the time and `material` mixed in. fn new(material: &[&[u8]]) -> Result { - let mut os = [0u8; 32]; - let os = getrandom::fill(&mut os).map(|()| os); - Self::seeded(os, vectorcraft_doc::metadata::now_unix().unwrap_or_default(), material) + let (os, now) = seed_sources(); + Self::seeded(os, now, material) } /// [`Entropy::new`] from what the OS random source returned and the time. Nothing else goes /// into the seed, and a failed OS read is an error. - pub(crate) fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result { + fn seeded(os: Result<[u8; 32], getrandom::Error>, now: i64, material: &[&[u8]]) -> Result { let os = os.map_err(|e| failed(&format!("no random numbers ({e})")))?; let mut h = Sha256::new(); h.update(os); @@ -190,7 +218,7 @@ impl Entropy { Ok(Self { seed: h.finalize().into(), counter: 0 }) } - pub(crate) fn bytes(&mut self) -> [u8; N] { + fn bytes(&mut self) -> [u8; N] { let mut out = [0u8; N]; for chunk in out.chunks_mut(32) { self.counter += 1; diff --git a/crates/pdf/src/tests/encrypt.rs b/crates/pdf/src/tests/encrypt.rs index 89c2542266..5e586bec6f 100644 --- a/crates/pdf/src/tests/encrypt.rs +++ b/crates/pdf/src/tests/encrypt.rs @@ -195,15 +195,24 @@ fn the_same_file_and_passwords_get_fresh_keys_each_time() { fn the_file_key_is_seeded_from_the_os_random_source() { // The OS bytes, the time and the file are the whole seed: equal inputs give equal streams, so // no other source (such as `RandomState`, whose keys are fixed on the web) is mixed in, and - // other OS bytes alone give another stream. - use crate::encrypt::Entropy; - let file: &[&[u8]] = &[b"%PDF-2.0 same file"]; - let stream = |os: [u8; 32]| match Entropy::seeded(Ok(os), 1_700_000_000, file) { - Ok(mut e) => e.bytes::<48>(), + // other OS bytes alone give another stream. The exports set what the OS and the clock return. + use crate::encrypt::TEST_SEED_SOURCES; + let mut opts = PdfOptions::default(); + opts.settings.compatibility = Compatibility::Pdf20; + let plain = export(&doc(), &opts).unwrap(); + opts.settings.security = security("pw", "own"); + let protect_with = |os: Result<[u8; 32], getrandom::Error>| { + TEST_SEED_SOURCES.with(|c| c.set(Some((os, 1_700_000_000)))); + let out = protect(plain.clone(), &opts.settings); + TEST_SEED_SOURCES.with(|c| c.set(None)); + out + }; + let dict = |os: [u8; 32]| match protect_with(Ok(os)) { + Ok(bytes) => encrypt_dict(&bytes), Err(e) => panic!("{e:?}"), }; - assert_eq!(stream([7; 32]), stream([7; 32])); - assert_ne!(stream([7; 32]), stream([8; 32])); + assert_eq!(dict([7; 32]), dict([7; 32])); + assert_ne!(dict([7; 32]), dict([8; 32])); // A failed OS read is an error, not a weaker seed. - assert!(Entropy::seeded(Err(getrandom::Error::UNSUPPORTED), 1_700_000_000, file).is_err()); + assert!(protect_with(Err(getrandom::Error::UNSUPPORTED)).is_err()); } From a0bdd86acc42e02c92b25386e945b8729c747de1 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:17:48 -0800 Subject: [PATCH 42/46] Reuse document resources when rendering PDF effects (#10342) --- crates/engine/src/cmd/rasterfx.rs | 21 +++++++++++++++++---- crates/engine/src/tests/pdfraster.rs | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index d5f90d2411..f035ff55f5 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -149,17 +149,30 @@ pub(crate) fn clip_group(d: &mut Document, path: PathData, rule: FillRule, art: } /// Render `nodes` alone over transparency: (premultiplied pixels, width, height). -fn render(doc: &Document, nodes: Vec, region: Rect, scale: f64, anti_alias: AntiAlias) -> vectorcraft_render::Rendered { - let mut tmp = doc.clone(); +fn render(doc: &mut Document, nodes: Vec, region: Rect, scale: f64, anti_alias: AntiAlias) -> vectorcraft_render::Rendered { + struct RestoreLayers<'a> { + doc: &'a mut Document, + original: Vec>, + } + + impl Drop for RestoreLayers<'_> { + fn drop(&mut self) { + std::mem::swap(&mut self.doc.layers, &mut self.original); + } + } + let mut layer = Node::layer(NodeId(u64::MAX), "raster", vectorcraft_doc::LayerColor::Preset(0)); if let Some(ch) = layer.children_mut() { *ch = nodes.into_iter().map(Arc::new).collect(); } - tmp.layers = vec![Arc::new(layer)]; + // Keep the same resource tables, including images made by earlier effects, without + // copying them for each render. Restore the original layers even if rendering unwinds. + let original = std::mem::replace(&mut doc.layers, vec![Arc::new(layer)]); + let scoped = RestoreLayers { doc, original }; let mut r = vectorcraft_render::Renderer::new(); r.threads = 0; // Art Optimized is supersampled, as in exports: shapes meeting edge to edge leave no seam. - r.render_region_with(&tmp, region, scale, &RenderOptions { skip_templates: true, anti_alias, supersample: true, ..Default::default() }) + r.render_region_with(scoped.doc, region, scale, &RenderOptions { skip_templates: true, anti_alias, supersample: true, ..Default::default() }) } /// The note for pixels drawn since [`vectorcraft_render::decode_failures`] stood at `failed`, when diff --git a/crates/engine/src/tests/pdfraster.rs b/crates/engine/src/tests/pdfraster.rs index 957a6c3c2c..226bff66f1 100644 --- a/crates/engine/src/tests/pdfraster.rs +++ b/crates/engine/src/tests/pdfraster.rs @@ -104,6 +104,27 @@ fn assert_written(what: &str, d: &Document) { assert!(diff < 0.02 && diff < without / 4.0, "{what}: read back {:.2}% off ({:.2}% without the effects)", diff * 100.0, without * 100.0); } +#[test] +fn raster_pass_keeps_layers_and_a_previously_generated_image() { + use crate::cmd::rasterfx::effect_image; + + let mut d = Document::new(200.0, 200.0); + let art = rect(&mut d, Rect::new(40.0, 40.0, 80.0, 80.0), Color::rgb(1.0, 0.0, 0.0)); + let original_layer = Arc::clone(&d.layers[0]); + let first = effect_image(&mut d, &art, None, 1.0).unwrap(); + let second = effect_image(&mut d, &first, None, 1.0).unwrap(); + + assert_eq!(d.layers.len(), 1); + assert!(Arc::ptr_eq(&d.layers[0], &original_layer)); + assert_eq!(d.images.len(), 2); + + add(&mut d, second); + let rendered = render(&d); + let at = (60 * rendered.width as usize + 60) * 4; + let pixel = &rendered.pixels[at..at + 4]; + assert!(pixel[0] > 240 && pixel[1] < 15 && pixel[2] < 15, "the second pass still reads the first pass's image: {pixel:?}"); +} + #[test] fn groups_layers_type_images_and_symbols_keep_their_raster_effects() { // A group's shadow (one shadow of both members). From cdc355d4367dd431a738f33e80822e25d3502b1d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:27:45 -0800 Subject: [PATCH 43/46] Tests: check the drawn H's vertical position and each mesh column's color The composite import test now checks the H's top and bottom as well as its width and height, so a shift of the drawn glyph fails it. The mesh export test samples each patch's center, so swapped column fills fail it. --- crates/eps/src/import/tests_composite.rs | 2 ++ crates/svg/tests/it/mesh_export.rs | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/crates/eps/src/import/tests_composite.rs b/crates/eps/src/import/tests_composite.rs index 6e3a63373d..4caf968271 100644 --- a/crates/eps/src/import/tests_composite.rs +++ b/crates/eps/src/import/tests_composite.rs @@ -67,6 +67,8 @@ fn type42_descendants_draw_their_own_glyphs() { // The bundled font's H spans (90, 0)–(562, 656) of its 1000-unit em: at 50 pt from x = 10 that // is 14.5 to 38.1, 32.8 tall. assert!((bh.x0 - 14.5).abs() < 0.01 && (bh.width() - 23.6).abs() < 0.01 && (bh.height() - 32.8).abs() < 0.01, "{bh:?}"); + // In the y-down document the baseline at y = 20 lands at 80, and the cap height 32.8 above it at 47.2. + assert!((bh.y0 - 47.2).abs() < 0.01 && (bh.y1 - 80.0).abs() < 0.01, "{bh:?}"); assert!((bh.height() - bi.height()).abs() < 0.5, "{bh:?} {bi:?}"); assert!(bi.x0 > 10.0 + 50.0 * wh - 1.0 && bi.x1 < 10.0 + 50.0 * (wh + wi), "{bi:?}"); } diff --git a/crates/svg/tests/it/mesh_export.rs b/crates/svg/tests/it/mesh_export.rs index c46b943734..281d3b1571 100644 --- a/crates/svg/tests/it/mesh_export.rs +++ b/crates/svg/tests/it/mesh_export.rs @@ -89,6 +89,11 @@ fn a_patch_is_cut_no_finer_than_its_colour_changes() { fills.sort_unstable(); fills.dedup(); assert_eq!(fills, ["#656565", "#666666"], "{svg}"); + // The left column's pieces take 101 and the right column's 102, in both rows. + let img = resvg_render(&svg); + for (x, y, want) in [(60, 60, 101), (60, 140, 101), (140, 60, 102), (140, 140, 102)] { + assert_eq!(&img.pixel(x, y)[..3], &[want; 3], "({x}, {y}) {svg}"); + } assert_looks_alike(&d, &svg, in_square, 2, 0.0); } From dd1f4d2936443ab039af39c639b82688f80e2410 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:34:49 -0800 Subject: [PATCH 44/46] Tools: add search beside Edit Toolbar (#8770) * Tools: add search beside Edit Toolbar Open the existing tool-aware command palette from the Tools footer, preserving the customization button and fitting both column layouts. Closes #8758. * Format the toolbar Search interaction regressions * Format the native Search tooltip expectation * Use the current stroke paint API in Properties * Scope app-bar test lookups to the title bar --------- Co-authored-by: FredApps Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/ui-egui/src/chrome/tests.rs | 20 +-- crates/ui-egui/src/toolbar.rs | 54 ++++++-- crates/ui-egui/src/toolbar/tests.rs | 189 ++++++++++++++++++++++++++++ docs/gaps.md | 3 + docs/roadmap.md | 4 +- docs/target-app-parity.md | 5 +- docs/ui-parity.md | 4 + 7 files changed, 262 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 0a9e079f68..837c3d5e9a 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -110,12 +110,18 @@ impl Shown { self.find(label).unwrap_or_else(|| panic!("no {label:?} in {:?}", self.names())) } - /// The first node of the latest frame whose name starts with `prefix`, a control before a label. - fn starting(&self, prefix: &str) -> Option { + /// The named control in the window's title bar. The Tools panel can have a control with the same name. + fn app_bar_control(&self, prefix: &str) -> Option { let tree = self.fixture.tree(); - let named: Vec<_> = tree.keys().into_iter().filter(|key| tree.name_of(*key).is_some_and(|name| name.starts_with(prefix))).collect(); - let first = named.iter().find(|key| tree.role_of(**key) != Some(Role::LABEL)).or(named.first()); - first.and_then(|key| self.fixture.target(*key)) + let ctx = self.fixture.ctx(); + let window = ctx.content_rect(); + let title_height = craft::ui::runtime::env::Env::of_root(ctx).tokens.size.bar.title; + let title_bar = egui::Rect::from_min_size(window.min, egui::vec2(window.width(), title_height)); + tree.keys() + .into_iter() + .filter(|key| tree.role_of(*key) != Some(Role::LABEL) && tree.name_of(*key).is_some_and(|name| name.starts_with(prefix))) + .filter_map(|key| self.fixture.target(key)) + .find(|target| title_bar.contains(target.rect.center())) } /// The names the latest frame gives screen readers. @@ -452,7 +458,7 @@ fn the_app_bar_gives_up_its_right_hand_controls_in_order() { for width in (30..=160).rev().map(|w| w as f32 * 10.0) { bar.room(egui::vec2(width, 600.0)); bar.frame(Vec::new()).frame(Vec::new()); - let shown: Vec> = controls.iter().map(|c| bar.starting(c)).collect(); + let shown: Vec> = controls.iter().map(|c| bar.app_bar_control(c)).collect(); for (control, target) in controls.iter().zip(&shown) { if let Some(t) = target { assert!(t.rect.left() >= 0.0 && t.rect.right() <= width, "{width}: {control} at {:?} lies inside the window", t.rect); @@ -541,7 +547,7 @@ fn the_app_bar_keeps_its_right_hand_controls_an_item_gap_apart() { bar.frame(Vec::new()).frame(Vec::new()); assert!(gap.get() > 0.0, "the item gap is read from the theme"); let controls = ["Discord", "Search commands", "Choose a workspace"]; - let rects: Vec = controls.iter().map(|c| bar.starting(c).unwrap_or_else(|| panic!("{c} shows")).rect).collect(); + let rects: Vec = controls.iter().map(|c| bar.app_bar_control(c).unwrap_or_else(|| panic!("{c} shows")).rect).collect(); for pair in rects.windows(2) { let between = pair[1].left() - pair[0].right(); assert!(between >= gap.get() - 0.5, "neighboring controls {pair:?} are {between} apart, under the item gap {}", gap.get()); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index e80ed26a77..34a7829ba9 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -2,8 +2,8 @@ //! Draw, Modify, Type, Navigate, Color). Window → Toolbars → Advanced shows every tool group; the //! double arrow at the top (or Window → Toolbars → Double Column, `window.toolbarColumns`) lays the //! tools out in one or two columns. -//! Bottom: fill/stroke proxy, colour/gradient/none, drawing modes, screen mode; the rail's own Edit -//! Toolbar button opens the All Tools drawer (`edit_toolbar`). +//! Bottom: fill/stroke proxy, colour/gradient/none, drawing modes, screen mode, Search and Edit +//! Toolbar. Edit opens the native All Tools drawer (`edit_toolbar`). //! //! The dock draws the rail ([`rail_view`]) for the Tools panel, for each toolbar made with New //! Toolbar and for each group torn off either of them (a `strip:` panel). @@ -21,7 +21,7 @@ use craft::ui::contract::{Bind, BodyCx, Entry, Gap, Props as _, Show as _, ShowC use craft::ui::display::Divider; use craft::ui::docking::{DockGrid, GroupAt}; use craft::ui::form::Field; -use craft::ui::layout_components::Row; +use craft::ui::layout_components::{Row, Stack}; use craft::ui::pickers::{Anchor9, ReferencePointLook, Select}; use craft::ui::rails::{LastUsed, RailDensity, RailFooter, RailTool, SlotId, ToolRail, ToolSlot}; use craft::ui::runtime::commands::{self, CommandRef}; @@ -263,12 +263,13 @@ fn strip_tools(app: &VectorcraftApp, parent: &Owner, first: &str) -> Vec<&'stati groups_of(app, parent).into_iter().find(|g| g.first().is_some_and(|f| *f == first)).unwrap_or_default() } -/// The dock grid of the rail panel `owner`: a cell for each of its slots and its Edit Toolbar button. Its rail draws at -/// the chrome's density, so the dock resolves the grid's steps in its own. +/// The dock grid of the rail panel `owner`: a cell for each tool slot and a custom toolbar's Edit Toolbar button. +/// The Tools panel keeps its actions in the host footer. The rail draws at the chrome's density. pub(crate) fn dock_grid(app: &VectorcraftApp, owner: &Owner) -> DockGrid { let cells = match owner { Owner::Strip(parent, first) => strip_tools(app, parent, first).len(), - _ => groups_of(app, owner).len() + 1, + Owner::Tools => groups_of(app, owner).len(), + Owner::Toolbar(_) => groups_of(app, owner).len() + 1, }; DockGrid::rail(cells).density(rail_density(app, owner)) } @@ -461,7 +462,10 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m rail = rail.footer_scrolls(); } if own_bar { - rail = rail.tear_off().edit_toolbar(tl!("Edit Toolbar")); + rail = rail.tear_off(); + if !tools_panel { + rail = rail.edit_toolbar(tl!("Edit Toolbar")); + } } if editing(app, &owner) { rail = rail.editing(); @@ -471,9 +475,11 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m _ => None, }; let measured = matches!(at, GroupAt::Measure(_)); + let mut tools_edit = None; let footer = |ui: &mut Ui, footer: RailFooter| { if tools_panel { bottom_controls(app, ui, footer); + tools_edit = search_and_edit_buttons(app, ui, footer); } else if let Some(id) = bar { crate::custom_toolbars::add_menu(app, ui, id, footer, measured); } @@ -482,7 +488,11 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m GroupAt::Measure(width) => return rail.measure_rail(ui, width, footer).y, GroupAt::Show(rect) => rect, }; - let out = rail.show_rail(ui, footer); + let mut out = rail.show_rail(ui, footer); + if tools_panel { + // The native footer opener follows the same drawer, focus and customization path. + out.edit_toolbar = tools_edit; + } if let Some(tool) = out.select.as_deref().filter(|tool| *tool != app.session.tool_id()) { // Not an error to report: a tool the command refuses stays unselected. app.run("tool.select", json!({ "tool": tool })).ok(); @@ -883,5 +893,33 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui) { } pub(crate) mod card; +/// Search and Edit Toolbar share a row in a wide rail; a narrow rail keeps Edit Toolbar last. +fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter) -> Option { + let enabled = !crate::panel_docking::modal_window_up(app); + let mut edit = None; + let buttons = |ui: &mut Ui, _: &mut BodyCx<'_>| { + IconButton::command(IconId::new("search"), "help.commandPalette") + .label(tl!("Search commands")) + .tooltip(tl!("Search commands, tools, panels and effects")) + .selected(app.ui.palette_open) + .enabled(enabled) + .show(ui); + edit = Some( + IconButton::new(IconId::new("more")) + .label(tl!("Edit Toolbar")) + .selected(editing(app, &Owner::Tools)) + .enabled(crate::menus::enabled(app, "window.editToolbar")) + .show(ui) + .response, + ); + }; + if footer.columns > 1 { + Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); + } else { + Stack::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons); + } + edit +} + #[cfg(test)] pub(crate) mod tests; diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 9d8040e68f..34447647d9 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -579,6 +579,195 @@ fn the_rail_builds_its_slots_only_when_its_tool_groups_change() { assert_eq!(kept, Some(advanced), "the rail shows the Advanced toolbar's slots"); } +/// The real Tools dock column; distinguishes its footer Search from the app bar's Search. +fn review_8758_panel(app: &VectorcraftApp, ctx: &egui::Context) -> egui::Rect { + let report = crate::panel_docking::inspect(app, ctx); + let columns = report["columns"].as_array().expect("dock columns"); + let r = &columns.iter().find(|column| column["panel"] == "tools").expect("the Tools column")["rect"]; + egui::Rect::from_min_size( + egui::pos2(r[0].as_f64().unwrap() as f32, r[1].as_f64().unwrap() as f32), + egui::vec2(r[2].as_f64().unwrap() as f32, r[3].as_f64().unwrap() as f32), + ) +} + +fn review_8758_button<'a>(app: &VectorcraftApp, ctx: &egui::Context, nodes: &'a [Node], label: &str) -> &'a Node { + let panel = review_8758_panel(app, ctx); + nodes + .iter() + .find(|n| n.role() == Role::Button && n.label() == Some(label) && bounds(n).is_some_and(|r| panel.contains_rect(r))) + .unwrap_or_else(|| panic!("Tools footer button {label:?} is drawn")) +} + +fn review_8758_query(nodes: &[Node]) -> &str { + nodes + .iter() + .find(|n| n.role() == Role::TextInput && n.label() == Some("Search commands")) + .and_then(Node::value) + .expect("the native palette's query field") +} + +fn review_8758_unchanged_content(app: &VectorcraftApp) -> Value { + let st = app.session.active().unwrap(); + json!({"document": &*st.doc, "selection": format!("{:?}", st.selection), + "undo": st.history.undo.len(), "redo": st.history.redo.len(), "slots": slots(app)}) +} + +/// Paint the native tooltip over whole app frames, keeping the same window and dock measurements. +fn review_8758_hovered_texts(app: &mut VectorcraftApp, ctx: &egui::Context, t0: f64, at: Pos2) -> Vec { + fn texts(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(text) => out.push(text.galley.text().to_string()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), + _ => {} + } + } + let mut shown = vec![]; + for i in 0..20 { + let events = match i { + 0 => vec![Event::PointerGone], + 1 => vec![Event::PointerMoved(at)], + _ => vec![], + }; + let out = crate::testing::app_frame( + app, + ctx, + egui::RawInput { + time: Some(t0 + f64::from(i) * 0.1), + events, + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, 1400.0))), + ..Default::default() + }, + ); + out.shapes.iter().for_each(|shape| texts(&shape.shape, &mut shown)); + } + shown +} + +fn review_8758_edit_control(app: &mut VectorcraftApp, ctx: &egui::Context, nodes: &[Node]) { + let edit = bounds(review_8758_button(app, ctx, nodes, "Edit Toolbar")).unwrap(); + let panel = review_8758_panel(app, ctx); + let before = slots(app); + let nodes = click(app, ctx, 1.0, edit.center(), 1400.0); + assert!(app.ui.tools_drawer && app.ui.drawer_toolbar.is_none(), "Edit opens the Tools customization drawer"); + let drawer = nodes + .iter() + .find(|n| n.role() == Role::Dialog && n.label() == Some("Edit Toolbar")) + .and_then(bounds) + .expect("the native customization drawer is drawn"); + // Main anchors its native drawer to the rail's canvas side; the footer button remains its focus opener. + assert!( + drawer.left() >= panel.right() - 1.0 && drawer.top() < panel.bottom() && drawer.bottom() > panel.top(), + "the customization drawer remains beside its Tools rail: {drawer:?}, {panel:?}" + ); + assert!(nodes.iter().any(|n| n.label() == Some("All Tools")), "the customization list is present"); + assert_eq!(slots(app), before, "opening customization does not change tool membership"); + assert!(before.iter().any(|(_, tools)| tools.contains(&"rectangle"))); + app.run("toolbar.removeTool", json!({"tool": "rectangle"})).unwrap(); + assert!(!slots(app).iter().any(|(_, tools)| tools.contains(&"rectangle")), "customization still edits the toolbar"); + // Use the native close control, which returns focus to this footer's Edit button. + let close = named_rect(&nodes, "Close"); + click(app, ctx, 2.0, close.center(), 1400.0); + assert!(!app.ui.tools_drawer); + let key = |pressed| Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(app, ctx, 2.2, vec![key(true), key(false)], 1400.0); + settled(app, ctx, 2.3, 1400.0); + assert!(app.ui.tools_drawer, "focus returns to Edit: Enter reopens its customization drawer"); + app.run("window.editToolbar", json!({})).unwrap(); + settled(app, ctx, 2.6, 1400.0); +} + +fn review_8758_layout(double: bool) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(300, 300); + app.run("window.toolbarColumns", json!({"double": double})).unwrap(); + let ctx = reader(); + let nodes = settled(&mut app, &ctx, 0.0, 1400.0); + review_8758_edit_control(&mut app, &ctx, &nodes); + let nodes = settled(&mut app, &ctx, 3.0, 1400.0); + let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); + let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap(); + let panel = review_8758_panel(&app, &ctx); + assert!(panel.contains_rect(search) && panel.contains_rect(edit), "both controls fit the actual Tools panel"); + assert!(search.bottom() <= 1400.0 && edit.bottom() <= 1400.0, "both controls fit the window"); + if double { + assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row"); + } else { + assert!( + search.bottom() <= edit.top() && (search.center().x - edit.center().x).abs() < 0.01, + "one column keeps both controls in a fitted stack" + ); + } + let chord = crate::menus::shortcut_of(&app, "help.commandPalette").expect("the native Search command has its current shortcut"); + let expected = craft::ui::contract::tooltip::with_chord("Search commands, tools, panels and effects", &chord, crate::keymap::platform()); + let tips = review_8758_hovered_texts(&mut app, &ctx, 4.0, search.center()); + assert!(tips.iter().any(|tip| tip == &expected), "the native Search tooltip includes its command shortcut: {tips:?}"); + let before = review_8758_unchanged_content(&app); + let tool = app.session.tool_id().to_string(); + click(&mut app, &ctx, 8.0, search.center(), 1400.0); + let nodes = frame(&mut app, &ctx, 9.0, vec![Event::Text("old query".into())], 1400.0); + assert_eq!(review_8758_query(&nodes), "old query", "the opened native search has keyboard focus"); + app.run("help.commandPalette", json!({})).unwrap(); + settled(&mut app, &ctx, 10.0, 1400.0); + let nodes = click(&mut app, &ctx, 11.0, search.center(), 1400.0); + assert!(app.ui.palette_open, "the actual footer button opens the existing command palette"); + assert!(review_8758_query(&nodes).is_empty(), "the native palette opens with a fresh query"); + let nodes = frame(&mut app, &ctx, 12.0, vec![Event::Text("focused".into())], 1400.0); + assert_eq!(review_8758_query(&nodes), "focused", "reopening gives the search field keyboard focus"); + assert!(!app.ui.tools_drawer, "Search is distinct from Edit Toolbar"); + assert_eq!(review_8758_unchanged_content(&app), before, "Search changes no document, history, selection or toolbar membership"); + assert_eq!(app.session.tool_id(), tool); +} + +#[test] +fn review_8758_toolbar_search_fits_beside_edit_and_opens_the_existing_palette() { + for double in [true, false] { + review_8758_layout(double); + } +} + +#[test] +fn review_8758_toolbar_search_accepts_a_tool_query_and_is_disabled_over_a_dialog() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(300, 300); + let ctx = reader(); + let nodes = settled(&mut app, &ctx, 0.0, 1400.0); + let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap(); + let before = review_8758_unchanged_content(&app); + click(&mut app, &ctx, 0.2, search.center(), 1400.0); + assert!(app.ui.palette_open); + let nodes = frame(&mut app, &ctx, 0.4, vec![Event::Text("Scissors".into())], 1400.0); + assert_eq!(review_8758_query(&nodes), "Scissors", "the actual focused query field receives typing"); + let nodes = settled(&mut app, &ctx, 0.5, 1400.0); + let tool = nodes + .iter() + .find(|n| n.role() == Role::ListBoxOption && n.label().is_some_and(|label| label.starts_with("Scissors"))) + .expect("the native palette lists the matching Scissors tool"); + assert!(!tool.is_disabled()); + click(&mut app, &ctx, 0.7, bounds(tool).unwrap().center(), 1400.0); + assert_eq!(app.session.tool_id(), "scissors", "activating the real result chooses the tool"); + assert!(!app.ui.palette_open, "a pick closes the palette"); + assert_eq!(app.ui.recent_commands.first().map(|command| command.key_text().into_owned()), Some("tool:scissors".to_string())); + assert_eq!(review_8758_unchanged_content(&app), before, "choosing a tool changes no artwork/history or toolbar membership"); + + // Current main owns query state inside CommandPalette and resets it on opening. A blocked footer press must not + // open that component at all, invoke a command, steal focus or change the existing real dialog's fields. + open_options(&mut app, "lineSegment").unwrap(); + let nodes = settled(&mut app, &ctx, 1.0, 1400.0); + let dialog = tool_dialog(&app).expect("the real Tool Options dialog"); + let focus = craft::ui::runtime::focus::focused_rec(&ctx); + let runs = app.run_count; + let recent = app.ui.recent_commands.clone(); + let search = review_8758_button(&app, &ctx, &nodes, "Search commands"); + assert!(search.is_disabled(), "screen readers find Search disabled while a modal window is open"); + click(&mut app, &ctx, 1.2, bounds(search).unwrap().center(), 1400.0); + assert!(!app.ui.palette_open, "the disabled footer cannot open Search over a dialog"); + assert_eq!(app.run_count, runs, "the disabled footer does not invoke the palette command"); + assert_eq!(craft::ui::runtime::focus::focused_rec(&ctx), focus, "the existing modal keeps focus"); + assert_eq!(app.ui.recent_commands, recent); + assert_eq!(tool_dialog(&app), Some(dialog)); + assert_eq!(review_8758_unchanged_content(&app), before); +} + /// A window too short for the tools shows the rail's scroll bar with the pointer away from the rail: a narrow bar, /// several times taller than wide, inside the rail's end edge. A window tall enough for every tool shows none. #[test] diff --git a/docs/gaps.md b/docs/gaps.md index 205b6161be..a98c869e44 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -27,6 +27,8 @@ History panel row context menus (2026-11-20, G12): Right-clicking any state offe OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. + - **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. @@ -1052,6 +1054,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | | 2026-11-20 | minor | G12: Appearance panel: right-click item context menus for rows (Duplicate Stroke/Fill, Delete Stroke/Fill, Hide/Show Stroke/Fill, Edit Effect…, Duplicate Effect, Delete Effect, Hide/Show Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling; headless tests in `crates/ui-egui/src/panels/tests_appearance.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. | +| 2026-11-19 | minor | Tools toolbar: Search sits left of Edit Toolbar in two columns, stacks in one column, and opens the existing command palette to find and activate tools; disabled over a dialog. Edit Toolbar and customization are retained (#8758). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 57b8cd1108..f669559fd2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -33,6 +33,7 @@ ## Feature submission evidence Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. @@ -209,7 +210,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames, and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | -| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | +| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -265,6 +266,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | | 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. | +| 2026-11-19 | minor | Tools toolbar: Search sits left of Edit Toolbar in two columns, stacks in one column, and opens the existing command palette to find and activate tools; disabled over a dialog. Edit Toolbar and customization are retained (#8758). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688). Scores and estimates unchanged. | | 2026-11-19 | minor | M14/G12: Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides); regression tests in crates/ui-egui/src/panels/text_styles/tests.rs; scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8e956a2c75..74789b33ba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -75,6 +75,8 @@ Script appearance and geometry setters reject objects on locked artboards. Assig **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. + Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged. Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. @@ -368,7 +370,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 87% | TIFF choices and settings are implemented; anti-aliasing ghost borders are fixed (#983) | 2–4 | estimated; depth not measured | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 80% | script DOM classes for layers, artboards and gradient stops, `#engine` (#1183), Batch option depth (scripting, #9019, Batch, #1938, and image and graph variables are done) | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show (`panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`); Properties Quick Actions offer Ungroup for any selected group, Isolate Group only for one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path (`panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`); Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged; the Artboards panel's list fills the panel, so it resizes with the window (#6085), score and hours unchanged; Layers appearance marker uses a hollow diamond and tooltip separate from targeting and selected art (#8710), based on Hassan1305's #8757; focused Layers coverage, runtime validation pending; scores and hours unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Document Info Selection Only (`ui.docInfo.selectionOnly`) counts the selection through `document.info`, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show (`panels::doc_info::tests::test_doc_info_counts_entire_document`, `test_doc_info_selection_only_toggles_and_filters_counts`, `test_doc_info_selection_only_keeps_selected_artboard`, `test_doc_info_panel_menu_toggles_state`); Properties Quick Actions offer Ungroup for any selected group, Isolate Group only for one group, and Unite only for selections of at least two objects, each a non-guide path or a compound path (`panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`); Asset Export item context menus implemented (G12); Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the remaining panels that have none (History rows implemented, #8845), accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; Character Styles and Paragraph Styles item context menus have focused regressions (panels::text_styles::tests::right_click_context_menu_*); scores and estimates unchanged; History row context menus have snapshot, pending-edit, typing and clear-history headless regressions (panels::history::tests, #8845); swatches dropped on New Swatch or Delete Swatch carry the selected swatches the find field or kind filter hides (#8620); scores and estimates unchanged; the Artboards panel's list fills the panel, so it resizes with the window (#6085), score and hours unchanged; Layers appearance marker uses a hollow diamond and tooltip separate from targeting and selected art (#8710), based on Hassan1305's #8757; focused Layers coverage, runtime validation pending; scores and hours unchanged; Tools toolbar Search entry and retained customization covered in `crates/ui-egui/src/toolbar/tests.rs` (#8758), scores and hours unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~79%** | | **~250–420** | | @@ -3410,6 +3412,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. | +| 2026-11-19 | minor | Tools toolbar: Search sits left of Edit Toolbar in two columns, stacks in one column, and opens the existing command palette to find and activate tools; disabled over a dialog. Edit Toolbar and customization are retained (#8758). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | Performance: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688). Evidence added; scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d699d6d282..8bb6c7b87a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -27,6 +27,8 @@ **Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged. +**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged. + **Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. @@ -486,6 +488,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | | Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | | Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | +| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and stacked in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | | Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | | Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | | Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | @@ -678,6 +681,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-19 | minor | Layers: hollow-diamond own-appearance marker and explanatory tooltip distinguish appearance from targeting and selected art (#8710), retaining targeting/drag/Alt-copy behavior and Hassan1305's #8757 ring-visibility fix/four-state coverage. Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible, with a smaller appearance dot inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Targeting items for appearance attributes) do. Before, the dot covered the ring and a targeted item with an appearance looked untargeted, #8711. Scores and estimates unchanged. | | 2026-11-19 | minor | View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid until it is off; the choices come back as they were and the rulers stay, though dragging or double-clicking them makes no guide meanwhile (#8363). Scores and estimates unchanged. | +| 2026-11-19 | minor | Tools toolbar: Search sits left of Edit Toolbar in two columns, stacks in one column, and opens the existing command palette to find and activate tools; disabled over a dialog. Edit Toolbar and customization are retained (#8758). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-20 | minor | Properties panel per context (G12): Quick Actions for text selection (Create Outlines, Retype, Find and Replace…); Retype reveals panel without toggling off if already open; headless tests in panels::properties::tests. Scores and estimates unchanged. | From 1241f076f58b45ffda2f715bc71abf2ce06da94b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:14:16 -0800 Subject: [PATCH 45/46] Main: the Home size test uses the renamed app bar helper #8770 renamed the chrome test helper Shown::starting to app_bar_control, which looks only in the window's title bar because the Tools panel can hold a control with the same name. The test the_app_bar_home_is_small_and_menu_titles_pad_their_text came in with 2030c7b2d2f while #8770 was open and still called starting, so vectorcraft-ui-egui's tests no longer compile on main (E0599 at chrome/tests.rs:573). The test now calls app_bar_control("Home"). --- crates/ui-egui/src/chrome/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 837c3d5e9a..79d4371f47 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -570,7 +570,7 @@ fn the_app_bar_home_is_small_and_menu_titles_pad_their_text() { bar.frame(Vec::new()).frame(Vec::new()); let (small, pad) = read.get(); assert!(small > 0.0 && pad > 0.0, "the sizes are read from the theme"); - let home = bar.starting("Home").unwrap_or_else(|| panic!("Home shows in {:?}", bar.names())).rect; + let home = bar.app_bar_control("Home").unwrap_or_else(|| panic!("Home shows in {:?}", bar.names())).rect; assert!(home.height() <= small + 0.5, "Home is {} high, over the small control height {small}", home.height()); let texts = bar.texts(); for title in ["File", "Edit", "Object"] { From e28faa0a9437537d290ebf6d6b52b0a6b29f14b7 Mon Sep 17 00:00:00 2001 From: yoriswind <164435053+yoriswind@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:17:04 -0800 Subject: [PATCH 46/46] Color Halftone: draw dark dots on light tones (#10316) * fix(effects): draw dark dots in RGB Color Halftone (cherry picked from commit 2dbe91af9ff27d238e0c31ba129864678fe57dfa) * Cover dark-on-light RGB halftone polarity Updated halftone tests to clarify behavior regarding pixel brightness and dot sizes. (cherry picked from commit babd60e3325031984dc55d501c8898ac594d554c) * effects: bound Color Halftone dots at full coverage (cherry picked from commit 8fb0bf55607762df6e3acc2ed7ed37a643fea022) * effects: describe Color Halftone ink coverage (cherry picked from commit 0dbf12514095b6e12cb4414055d8ac47ee1fbcdc) * Document the change to saved RGB halftones * Test the bounded edge overlap of full halftone dots --------- Co-authored-by: Mex <44814932+MMexicann@users.noreply.github.com> Co-authored-by: dotCooCoo --- crates/effects/src/catalog.rs | 2 +- crates/effects/src/pixel/pixelate.rs | 7 +++--- crates/effects/src/pixel/tests.rs | 33 +++++++++++++++++++++++++++- crates/render/src/tests/memory.rs | 10 ++++----- docs/mcp.md | 4 ++++ docs/target-app-parity.md | 2 +- 6 files changed, 47 insertions(+), 11 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 5c31278493..474a6c0a0c 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -744,7 +744,7 @@ pub fn effect_catalog() -> Vec { "pixelate.colorHalftone", "Color Halftone…", PIXELATE, - "{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} screens each colour channel (red, green, blue: channels 1 to 3; in CMYK documents cyan, magenta, yellow, black: 1 to 4) at its angle into dots whose area follows the channel's mean over their cell", + "{maxRadius: px 4..127 (8; the radius of a dot at full strength, which fills its square cell, in pixels of the Document Raster Effects resolution), channel1: screen angle deg -360..360 (108), channel2: deg (162), channel3: deg (90), channel4: deg (45)} The effect screens cyan, magenta and yellow ink (channels 1 to 3; CMYK mode adds black as channel 4) at their angles into dots whose area follows the cell's mean ink coverage.", json!({"maxRadius": 8.0, "channel1": 108.0, "channel2": 162.0, "channel3": 90.0, "channel4": 45.0}), ), r( diff --git a/crates/effects/src/pixel/pixelate.rs b/crates/effects/src/pixel/pixelate.rs index 0318eb5f45..e7fcf05e08 100644 --- a/crates/effects/src/pixel/pixelate.rs +++ b/crates/effects/src/pixel/pixelate.rs @@ -437,7 +437,7 @@ impl Screen { /// Color Halftone: each channel screened at its angle in square cells sized so that a dot of /// `max_radius` (pixels of the document's raster grid, `space.line` each) fills one; each cell's -/// dot covers the share of it that is the channel's mean there (white stays white, black black). +/// dot covers the mean ink coverage of that cell (white stays white, black black). /// Coverage stays as it is. pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, max_radius: f64, angles: [f64; 4]) { let Some(place) = Place::new(space, w, h) else { return }; @@ -446,7 +446,8 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix if !(side.is_finite() && side / place.px >= 3.0) { return; } - let channels = space.channels; + // Screen RGB as dark ink against white, like the CMY channel previews. + let channels = if space.channels == Channels::Rgb { Channels::CmyPlane } else { space.channels }; let n = split([0; 4], channels).1; let limit = w.saturating_mul(h).saturating_add(4096); let mut screens = Vec::with_capacity(n); @@ -478,7 +479,7 @@ pub(super) fn color_halftone(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pix let mean = if sum[1] > 1e-6 { f64::from(sum[0] / sum[1]) } else { 0.0 }; // Full strength fills the cell, corners too; none leaves no speck. let radius = match mean { - m if m >= 254.5 / 255.0 => f64::INFINITY, + m if m >= 254.5 / 255.0 => side / std::f64::consts::SQRT_2 + 0.5 * place.px, m if m <= 0.5 / 255.0 => 0.0, m => dot_radius(m) * side, }; diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index 6dd7942e5e..89b2e7dc16 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -1070,13 +1070,44 @@ fn color_halftone_screens_midtones_into_dots_and_keeps_white_and_black() { let mut half = image(w, h, |x, _| if x < 32 { grey(160) } else { [0; 4] }); halftone.apply(&mut half, w, h, &space(w, h)); assert!((0..h).all(|y| (32..w).all(|x| at(&half, w, x, y) == [0; 4]))); - // Dots are bigger where the image is brighter. + // Brighter areas have fewer dark pixels. let mut ramp = image(w, h, |x, _| grey((x * 4) as u8)); halftone.apply(&mut ramp, w, h, &space(w, h)); let lit = |x0: usize| (0..h).flat_map(|y| (x0..x0 + 16).map(move |x| (x, y))).filter(|(x, y)| at(&ramp, w, *x, *y)[0] > 127).count(); assert!(lit(8) < lit(40), "{} < {}", lit(8), lit(40)); } +#[test] +fn color_halftone_draws_dark_dots_on_light_rgb() { + let (w, h) = (64, 64); + let halftone = fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0})); + let mut d = image(w, h, |_, _| grey(192)); + halftone.apply(&mut d, w, h, &space(w, h)); + assert_eq!(at(&d, w, 37, 37), grey(0)); + assert_eq!(at(&d, w, 32, 32), grey(255)); +} + +#[test] +fn color_halftone_full_coverage_only_overlaps_the_edge_of_an_empty_neighbor() { + let (w, h) = (96, 64); + let source = image(w, h, |x, _| grey(if x < w / 2 { 0 } else { 255 })); + let mut screened = source.clone(); + fx("pixelate.colorHalftone", json!({"maxRadius": 8, "channel1": 0, "channel2": 0, "channel3": 0})).apply(&mut screened, w, h, &space(w, h)); + let half_cell = (8.0 * std::f64::consts::SQRT_2 / 2.0) as usize; + let (edge, y) = (w / 2, h / 2 + half_cell); + assert_eq!(at(&screened, w, edge - half_cell, y), grey(0), "the full cell keeps its center"); + assert_eq!(at(&screened, w, edge, y), grey(0), "the round dot crosses the straight cell edge"); + let fringe = at(&screened, w, edge + 2, y)[0]; + assert!(fringe > 0 && fringe < 255, "the last overlapping column is antialiased: {fringe}"); + // With an 8 px radius and the grid aligned to this edge, the circle and its antialiasing + // can reach only the first three columns of white. Check every row, including cell corners. + for y in 0..h { + for x in edge + 3..w { + assert_eq!(at(&screened, w, x, y), grey(255), "unexpected ink at ({x}, {y})"); + } + } +} + #[test] fn color_halftone_sizes_its_dots_in_pixels_of_the_raster_effects_resolution() { // Max Radius counts the document's raster grid pixels (#3260): 16 px at 144 ppi (lines half a diff --git a/crates/render/src/tests/memory.rs b/crates/render/src/tests/memory.rs index 7b68bc74d4..d5009c2072 100644 --- a/crates/render/src/tests/memory.rs +++ b/crates/render/src/tests/memory.rs @@ -2455,8 +2455,8 @@ fn proof_previews_draw_changes_as_a_new_renderer_does() { } /// A thumbnail of an object under a filter that treats color channels apart (Color Halftone) is -/// made again when the document's color mode changes: CMYK documents screen ink channels, RGB -/// documents light ones. +/// made again when the document's color mode changes. RGB documents screen three ink planes. +/// CMYK documents screen four ink planes. #[test] fn filtered_thumbnails_follow_the_color_mode() { let _fonts = fonts_steady(); @@ -2464,9 +2464,9 @@ fn filtered_thumbnails_follow_the_color_mode() { let mut d = Document::new(200.0, 100.0); d.color_mode = vectorcraft_doc::ColorMode::Cmyk; let halftone = effect("pixelate.colorHalftone", serde_json::json!({"maxRadius": 4})); - let orange = filled(&mut d, rectangle(Rect::new(20.0, 20.0, 180.0, 80.0)), Paint::solid(Color::rgb(1.0, 0.5, 0.0)), vec![halftone]); - let id = orange.id; - let mut d = with_art(d, vec![orange]); + let gray = filled(&mut d, rectangle(Rect::new(20.0, 20.0, 180.0, 80.0)), Paint::solid(Color::rgb(0.5, 0.5, 0.5)), vec![halftone]); + let id = gray.id; + let mut d = with_art(d, vec![gray]); let mut r = Renderer::new(); let before = r.render_thumbnail(&d, id, 128).unwrap().pixels; d.color_mode = vectorcraft_doc::ColorMode::Rgb; diff --git a/docs/mcp.md b/docs/mcp.md index 83755a1937..9604e3da61 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11438,6 +11438,10 @@ image `object.rasterize` makes with the same options. {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"rasterize","params":{"useDocumentResolution":false,"resolution":150,"background":"white"}}}} ``` +Color Halftone (`pixelate.colorHalftone`) screens cyan, magenta and yellow ink in RGB mode and also black ink in CMYK +mode. Dot area follows each cell's mean ink coverage. A full-strength dot has a finite radius that fills the cell, +including its corners. + ## Glass textures Glass (`distort.glass`) takes an image file as its surface in `params.textureImage`, as `{path}` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 74789b33ba..5f5f9644d5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2790,7 +2790,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Rough Pastels' Load Texture:** Effect › Artistic › Rough Pastels… has the same Load Texture… button, and its Texture and Light Direction controls are menus. The loaded image's gray levels are the paper surface (Loaded Texture in the Texture menu, `textureImage` stored with the effect), and Scaling, Relief, Light Direction and Invert act on it as on Brick, Burlap, Canvas and Sandstone (`pixel::tests::rough_pastels_draws_a_loaded_texture_as_its_surface`, `rough_pastels_loads_a_texture_saves_it_and_draws_it`). - **Bounded effect length inputs (#4638):** Effect dialog fields with defined length ranges (such as Crystallize Cell Size 3..300 pt) clamp immediately on commit and reject invalid inputs visibly with an accent highlight without reverting to sub-minimum values. -- **Color Halftone in raster pixels (#3260):** Max Radius is 4–127 px of the Document Raster Effects resolution, as public documentation gives it, shown in px whatever the document units; documents from before open with their radii in points converted (document version 3), and a file saved for an older app version holds them in points again. +- **Color Halftone in raster pixels (#3260):** Max Radius is 4–127 px of the Document Raster Effects resolution, as public documentation gives it, shown in px whatever the document units; documents from before open with their radii in points converted (document version 3), and a file saved for an older app version holds them in points again. Saved RGB Color Halftone artwork can render differently when reopened: light tones now produce dark dots on a light background, and the first three angle controls now set the cyan, magenta and yellow ink screens. CMYK mode also screens black ink. A full-strength dot reaches its cell corners and can overlap the edge of an adjacent cell. The overlap is bounded by the circle and its antialiased edge. - **Raster effects after document and view changes:** a cached drop shadow, outer glow or filtered content is made again when something its content reads from outside the object changes: a pattern's art or tiling, a symbol shown inside another symbol, a brush definition, an image's pixels, the raster resolution (De-Interlace, Color Halftone), Page Knockout Group, the substitution highlights (Highlight Substituted Fonts and Highlight Alternate Glyphs in Preferences › Type, Highlight Substituted Glyphs in Document Setup), a layer's Dim Images, the color settings, the fonts, Pixel Preview, Anti-aliased Artwork, Overprint Preview and isolation mode. A thumbnail under Color Halftone or Mezzotint is made again when the document's color mode changes. Raster effects (blur, shadow, glow, grain) drawn after a pattern, radial or freeform gradient fill export at their place and size (#1541, fixes #1536). - **Drop Shadow's Darkness:** Effect › Stylize › Drop Shadow… has Color and Darkness as radio buttons, each with its field, and the Appearance panel's inline editor has the two radio buttons in its Shade row (`shade`: `color` or `darkness`; `darkness`: 0 to 100%, 100 by default). Color is the default, and a shadow saved without these keys draws as before. With Darkness, the stored source-color model determines the adjustment before document/profile conversion and blur: subtract Darkness/100 from each RGB channel, clamped at zero, or add it to CMYK black K and Gray black, clamped at one, preserving CMYK C/M/Y. At the near-100% endpoint the shadow source becomes gray black before conversion. Shadow opacity stays separate. Original gradient stops follow the same application rule before interpolation; exact resource-level gradient parity remains open. Application SVG export keeps a live filter for simple uniform sRGB sources and uses rendered shadow images for other working RGB profiles, source models and gradients. Low-level SVG filter output warns when this preparation is needed; proportional intermediate SVG filters are not misread as additive Darkness. Exact spot/custom-color and composite-source parity remain open, and resulting CMYK ink values follow the application color pipeline. CSS export leaves the shadow out and marks the object unsupported. When a `.ai`, EPS or PDF opens from its editing data, a Drop Shadow with Darkness in an object's art style is read as one with Color is, with the shadow's Darkness percentage (100% when the style gives none). Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 428 (PDF page 434).