Merge main into rfc52-headless-column

This commit is contained in:
FredApps committed 2026-11-28 12:25:53 +07:00
commit 60e1a5fa94
97 files changed
+3657 -606

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
name: Cache prune
# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while
# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run
# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does
# not run again. The entry it replaced would stay until the next main run, and with it the cache
# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once
# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune).
on:
workflow_run:
workflows: [CI]
types: [completed]
branches: [main]
permissions:
contents: read
jobs:
cache-prune:
name: cache prune
# A fork's pull request from a branch named main also matches `branches`.
if: github.event.workflow_run.event != 'pull_request'
timeout-minutes: 10
runs-on: ubuntu-24.04
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
# A failed pass warns; the next run's prune deletes what it missed.
- name: Prune replaced cache entries
uses: storytold/craft-common-actions/actions/cache-prune@main
continue-on-error: true
+70 -2
View File
@@ -1,10 +1,14 @@
name: CI
# Quality gates for every push to main and every pull request (`cargo xtask ci`), through the
# suite's shared gate workflow in craft-common-actions.
# suite's shared gate workflow in craft-common-actions. Every night the gate runs a cold build:
# the safety net for the workspace crates it keeps between runs (`cache-workspace-crates`), and a
# fresh start for that cache entry.
on:
push:
branches: [main]
schedule:
- cron: "37 3 * * *"
pull_request:
workflow_dispatch:
@@ -23,7 +27,10 @@ jobs:
with:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
timeout-minutes: 90
# A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change)
# took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with
# those steps and the save it needs about two hours.
timeout-minutes: 150
# The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0,
# CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line
# tables ran the hosted runner out of resources, and it stopped mid-link with "received a
@@ -39,7 +46,68 @@ jobs:
test-shards: 5
shard-command: cargo xtask ci shard
warm-command: cargo xtask ci warm
# 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
# `cache-prune` below deletes the one it replaced. The nightly run restores nothing and
# builds everything from source.
cache-workspace-crates: true
cold-build: ${{ github.event_name == 'schedule' }}
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
libgl1-mesa-dev
# 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.
cache-prune:
name: cache prune
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
timeout-minutes: 170
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- name: Prune replaced cache entries
uses: storytold/craft-common-actions/actions/cache-prune@main
continue-on-error: true
with:
watch: true
watch-minutes: 160
saving-jobs: |
^gate( / cache warm \(.*\))?$
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
# while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the
# 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
# When the leg fails or is canceled it saves nothing, and this job fails too, so "Re-run failed
# jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg
# starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves
# 40 minutes for that.
cold-cache-clear:
name: cold cache clear
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
timeout-minutes: 200
permissions:
actions: write
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Delete the old rolling entries before the save
env:
GH_TOKEN: ${{ github.token }}
run: python3 scripts/ci-clear-rolling-cache.py
+6 -3
View File
@@ -3,13 +3,14 @@ name: Nightly check
# The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive,
# plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing
# PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle
# is built and verified by nightly-macos.yml behind the `full-ci` label.
# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the
# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls.
on:
push:
branches: [main, release]
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
pull_request:
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"]
paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"]
workflow_dispatch:
permissions:
@@ -34,6 +35,8 @@ jobs:
persist-credentials: false
- name: Run the synthetic suites
run: python3 packaging/nightly-tests.py
- name: Run the cold cache clear suite
run: python3 scripts/ci-clear-rolling-cache-tests.py
- name: Parse every nightly shell script
run: |
set -euo pipefail
Generated
+8 -8
View File
@@ -9175,9 +9175,9 @@ dependencies = [
[[package]]
name = "wasmi"
version = "2.0.0"
version = "2.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78693fcdd618e0fc34af59c6b8efa9ac5d58c68df940beff4bedddb6acfe7c27"
checksum = "36dcb6cbd722c1575daf8c3063dd7ba1883fcd35b51fcbd377ae4f3371ac4dba"
dependencies = [
"spin",
"wasmi_collections",
@@ -9188,27 +9188,27 @@ dependencies = [
[[package]]
name = "wasmi_collections"
version = "2.0.0"
version = "2.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a8be2aa467cf2d29e96ff759472c36eeb44a3c81c67fc9cb76c9a24c519c557"
checksum = "b62dc4c1a17f3294aa2b23ac39979e3b38f3ee6afe5673eea76b76902d11103b"
dependencies = [
"string-interner",
]
[[package]]
name = "wasmi_core"
version = "2.0.0"
version = "2.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69372d5fda3ea3d1e0aa6603c7888110e0187e88ea17cd8fc2e2df0a0e1f37fa"
checksum = "c19f6f7fcf32b9e12cebc8fec606fefac71af3d386bae1472e35d620b5471754"
dependencies = [
"libm",
]
[[package]]
name = "wasmi_ir"
version = "2.0.0"
version = "2.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f17b774caa13c618c7244f1ee51fe23c5e7b8538a471fa46d9949779758aed6"
checksum = "14f9c115dfd2397700880a64d14161db3a4da0a11059fac39c6a7935eb8f6b36"
dependencies = [
"wasmi_core",
]
+221 -137
View File
@@ -612,9 +612,46 @@ mod loads {
/// The longest a read waits for the clipboard's owner to send its data.
pub(super) const LOAD_WAIT: Duration = Duration::from_secs(2);
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
/// text read included. Text, file lists and the UI thread's bitmap check wait [`LOAD_WAIT`].
pub(super) const IMAGE_WAIT: Duration = Duration::from_secs(10);
/// What a read says once its worker has stopped.
pub(super) const GONE: &str = "the clipboard's reader stopped";
/// How long the reads of a [`Loads`] wait for the clipboard's owner.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Waits {
/// A text or file-list read, the UI thread's bitmap check, and dropping an idle `Loads`.
pub(super) load: Duration,
/// A paste's bitmap read off the UI thread, and a paste's wait for a read that got no
/// answer in its wait.
pub(super) image: Duration,
}
impl Waits {
/// [`LOAD_WAIT`] and [`IMAGE_WAIT`].
pub(super) const APP: Self = Self { load: LOAD_WAIT, image: IMAGE_WAIT };
/// No limit: each wait ends when its answer comes or its worker stops.
#[cfg(test)]
pub(super) const UNTIL_ANSWERED: Self = Self { load: Duration::MAX, image: Duration::MAX };
}
/// What is left at `now` of `limit` from `sent`; [`Duration::MAX`] (no limit) when the end is
/// past the clock's range.
pub(super) fn left(sent: Instant, limit: Duration, now: Instant) -> Duration {
sent.checked_add(limit).map_or(Duration::MAX, |end| end.saturating_duration_since(now))
}
/// What comes on `rx` within `wait`; a wait whose end is past the clock's range has no limit.
fn recv_within<T>(rx: &mpsc::Receiver<T>, wait: Duration) -> Result<T, mpsc::RecvTimeoutError> {
match Instant::now().checked_add(wait) {
Some(_) => rx.recv_timeout(wait),
None => rx.recv().map_err(mpsc::RecvTimeoutError::from),
}
}
/// Requests of type `R` answered with `A` on a worker thread.
pub(super) struct Loads<R, A> {
/// The worker's requests; the worker stops once this is dropped.
@@ -623,6 +660,8 @@ mod loads {
done: mpsc::Receiver<()>,
/// How long after it was sent dropping `Loads` waits for an unanswered read to end.
finish: Duration,
/// How long its reads wait.
waits: Waits,
}
/// Where requests go to a [`Loads`] worker.
@@ -685,18 +724,18 @@ mod loads {
}
}
/// When dropping `Loads` stops waiting for its worker: `finish` after the unanswered read
/// `pending` was sent (at once if that time has passed), and with no read unanswered
/// [`LOAD_WAIT`] from `now` at most (an idle worker ends at once).
fn stop_by(pending: Option<Instant>, now: Instant, finish: Duration) -> Instant {
pending.map_or(now + LOAD_WAIT, |sent| sent + finish)
/// How long, from `now`, dropping `Loads` waits for its worker: until `finish` after the
/// unanswered read `pending` was sent (not at all if that time has passed), and with no read
/// unanswered `idle` at most (an idle worker ends at once).
fn stop_wait(pending: Option<Instant>, now: Instant, finish: Duration, idle: Duration) -> Duration {
pending.map_or(idle, |sent| left(sent, finish, now))
}
impl<R: Send + 'static, A: Send + 'static> Loads<R, A> {
/// A worker thread named `name` that answers each request with `load`; dropping the result
/// waits up to `finish` after an unanswered read was sent for that read to end. None when the
/// worker can't start.
pub(super) fn spawn(name: &str, finish: Duration, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
/// A worker thread named `name` that answers each request with `load`, whose reads wait as
/// `waits` says; dropping the result waits up to `finish` after an unanswered read was sent
/// for that read to end. None when the worker can't start.
pub(super) fn spawn(name: &str, finish: Duration, waits: Waits, mut load: impl FnMut(R) -> A + Send + 'static) -> Option<Self> {
let (requests, asked) = mpsc::channel::<(R, mpsc::Sender<A>)>();
let (alive, done) = mpsc::channel::<()>();
let open = Arc::new(AtomicUsize::new(0));
@@ -714,7 +753,12 @@ mod loads {
drop(alive);
};
std::thread::Builder::new().name(name.into()).spawn(work).ok()?;
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish })
Some(Self { line: Arc::new(Line { requests, open, sent: Mutex::default() }), done, finish, waits })
}
/// How long its reads wait.
pub(super) fn waits(&self) -> Waits {
self.waits
}
/// `request` sent to the worker; its answer comes on the channel returned, for
@@ -741,9 +785,10 @@ mod loads {
}
}
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most.
/// The answer that comes on `answer` ([`Loads::ask`]), or why there is none, after `wait` at most
/// ([`Duration::MAX`]: no limit).
pub(super) fn wait_for_answer<A>(answer: &mpsc::Receiver<A>, wait: Duration) -> Result<A, String> {
match answer.recv_timeout(wait) {
match recv_within(answer, wait) {
Ok(answer) => Ok(answer),
Err(mpsc::RecvTimeoutError::Timeout) => Err(format!("the clipboard's owner didn't send its data within {wait:?}")),
Err(mpsc::RecvTimeoutError::Disconnected) => Err(GONE.into()),
@@ -751,16 +796,16 @@ mod loads {
}
impl<R, A> Drop for Loads<R, A> {
/// Stops the worker and waits until it has let go of what its `load` holds, until
/// [`stop_by`] at most: on X11 the last arboard handle dropped hands what the app copied to
/// the clipboard manager, and the app's own handle must be that one.
/// Stops the worker and waits until it has let go of what its `load` holds, as long as
/// [`stop_wait`] says at most: on X11 the last arboard handle dropped hands what the app
/// copied to the clipboard manager, and the app's own handle must be that one.
fn drop(&mut self) {
// No `Asker` sends after this, and one that holds the line lets go once it has sent.
let pending = self.line.close();
drop(std::mem::replace(&mut self.line, Line::dead()));
let end = stop_by(pending, Instant::now(), self.finish);
// Nothing is sent on `done`: this ends when the worker drops `alive`, or at `end`.
let _ = self.done.recv_timeout(end.saturating_duration_since(Instant::now()));
let wait = stop_wait(pending, Instant::now(), self.finish, self.waits.load);
// Nothing is sent on `done`: this ends when the worker drops `alive`, or after `wait`.
let _ = recv_within(&self.done, wait);
}
}
@@ -770,18 +815,38 @@ mod loads {
use super::*;
/// No limit: a wait ends when its answer comes.
const UNTIL_ANSWERED: Duration = Duration::MAX;
#[test]
fn a_read_that_answers_in_time_gives_the_text() {
let mut loads = Loads::spawn("test", Duration::ZERO, |()| "<svg/>".to_string()).unwrap();
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
assert_eq!(loads.get((), Duration::from_secs(5)), Ok("<svg/>".to_string()));
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| "<svg/>".to_string()).unwrap();
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok("<svg/>".to_string()));
}
#[test]
fn a_wait_with_no_limit_ends_when_its_answer_comes() {
let (reply, answer) = mpsc::channel();
let late = std::thread::spawn(move || reply.send(7));
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Ok(7));
assert_eq!(late.join().ok(), Some(Ok(())));
// A worker that stops without answering ends the wait too.
let (reply, answer) = mpsc::channel::<u8>();
drop(reply);
assert_eq!(wait_for_answer(&answer, UNTIL_ANSWERED), Err(GONE.to_string()));
// Limits from a read's send: what is left, none once it is over, no limit past the clock.
let now = Instant::now();
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(3)), Duration::from_secs(7));
assert_eq!(left(now, Duration::from_secs(10), now + Duration::from_secs(20)), Duration::ZERO);
assert_eq!(left(now, Duration::MAX, now), Duration::MAX);
}
#[test]
fn an_owner_that_never_answers_holds_the_worker_not_the_caller() {
let (release, gate) = mpsc::channel::<()>();
let mut calls = 0;
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| {
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| {
calls += 1;
if calls == 1 {
// The first owner sends nothing until released.
@@ -793,11 +858,11 @@ mod loads {
.unwrap();
assert!(loads.get((), Duration::ZERO).is_err(), "the first read times out");
// While it is unanswered, a read doesn't queue behind it or wait at all.
assert!(loads.get((), Duration::from_secs(600)).is_err());
assert!(loads.get((), UNTIL_ANSWERED).is_err());
release.send(()).unwrap();
// Once the late answer is in, it is dropped and a new read is made.
let text = loop {
match loads.get((), Duration::from_secs(600)) {
match loads.get((), UNTIL_ANSWERED) {
Ok(text) => break text,
Err(why) => {
// The late answer isn't in yet.
@@ -811,17 +876,17 @@ mod loads {
#[test]
fn a_read_after_the_worker_stops_says_so() {
let mut loads = Loads::spawn("test", Duration::ZERO, |()| String::new()).unwrap();
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| String::new()).unwrap();
// The worker ends when its requests stop: cut them off by hand.
drop(std::mem::replace(&mut loads.line, Line::dead()));
assert_eq!(loads.get((), Duration::from_millis(50)), Err(GONE.to_string()));
assert_eq!(loads.get((), UNTIL_ANSWERED), Err(GONE.to_string()));
}
#[test]
fn another_threads_reads_stop_with_the_reads() {
let loads = Loads::spawn("test", Duration::ZERO, |()| 1).unwrap();
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |()| 1).unwrap();
let asker = loads.asker();
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, Duration::from_secs(600))), Ok(1));
assert_eq!(asker.ask(()).and_then(|a| wait_for_answer(&a, UNTIL_ANSWERED)), Ok(1));
drop(loads);
assert_eq!(asker.ask(()).err(), Some(GONE.to_string()));
// Closed while an asker still holds the line: nothing more is sent.
@@ -833,7 +898,7 @@ mod loads {
#[test]
fn an_answer_waited_for_on_another_thread_holds_back_the_next_read() {
let (release, gate) = mpsc::channel::<()>();
let mut loads = Loads::spawn("test", Duration::ZERO, move |n: u32| {
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |n: u32| {
if n == 1 {
let _ = gate.recv();
}
@@ -842,20 +907,21 @@ mod loads {
.unwrap();
let answer = loads.ask(1).unwrap();
// The caller doesn't wait: the answer is waited for wherever the channel goes.
let waiter = std::thread::spawn(move || wait_for_answer(&answer, Duration::from_secs(600)));
let waiter = std::thread::spawn(move || wait_for_answer(&answer, UNTIL_ANSWERED));
// Until it comes, a read fails at once instead of queuing behind it.
assert!(loads.get(2, Duration::from_secs(600)).is_err());
assert!(loads.get(2, UNTIL_ANSWERED).is_err());
release.send(()).unwrap();
assert_eq!(waiter.join().ok(), Some(Ok(1)));
assert_eq!(loads.get(3, Duration::from_secs(600)), Ok(3));
assert_eq!(loads.get(3, UNTIL_ANSWERED), Ok(3));
}
#[test]
fn dropping_the_reads_waits_until_the_worker_lets_go_of_its_clipboard() {
let clipboard = Arc::new(());
let held = clipboard.clone();
let mut loads = Loads::spawn("test", Duration::ZERO, move |()| Arc::strong_count(&held)).unwrap();
assert_eq!(loads.get((), Duration::from_secs(600)), Ok(2));
// With no limit on the idle wait, the drop ends only once the worker has let go.
let mut loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |()| Arc::strong_count(&held)).unwrap();
assert_eq!(loads.get((), UNTIL_ANSWERED), Ok(2));
drop(loads);
assert_eq!(Arc::strong_count(&clipboard), 1, "the worker's handle is gone before the app's");
}
@@ -865,12 +931,12 @@ mod loads {
let now = Instant::now();
let limit = Duration::from_secs(25);
// No read unanswered: the idle worker ends at once, LOAD_WAIT is only the bound.
assert_eq!(stop_by(None, now, limit), now + LOAD_WAIT);
assert_eq!(stop_wait(None, now, limit, LOAD_WAIT), LOAD_WAIT);
// A read sent 2 s ago that timed out: wait for it until 25 s after it was sent.
assert_eq!(stop_by(Some(now - Duration::from_secs(2)), now, limit), now + Duration::from_secs(23));
assert_eq!(stop_wait(Some(now - Duration::from_secs(2)), now, limit, LOAD_WAIT), Duration::from_secs(23));
// Its limit already over, or no limit (data-control, the core protocol): no wait.
assert!(stop_by(Some(now - Duration::from_secs(30)), now, limit) <= now);
assert_eq!(stop_by(Some(now), now, Duration::ZERO), now);
assert_eq!(stop_wait(Some(now - Duration::from_secs(30)), now, limit, LOAD_WAIT), Duration::ZERO);
assert_eq!(stop_wait(Some(now), now, Duration::ZERO, LOAD_WAIT), Duration::ZERO);
}
}
}
@@ -885,6 +951,8 @@ mod portable {
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
use super::loads::Waits;
use super::{
BITMAP, ClipboardBackend, ClipboardError, ClipboardImage, ClipboardRead, Flavor, Flavour, LaterFlavor, PNG, TEXT, copied_file, decode_png,
engine_mimes, png_flavour, read_flavor, read_image_flavor, read_later_flavor, takes_files,
@@ -991,28 +1059,21 @@ mod portable {
reads.get(request, wait).unwrap_or_else(|why| Answer::failed(request, why))
}
/// The longest a paste's bitmap read of arboard's waits for the app that copied, off the UI
/// thread: the bitmap's transfer and its PNG decoding happen within the read. A paste waits as
/// long, from when it was sent, for a read that got no answer in its wait, the core protocol's
/// text read included. Text, file lists and the UI thread's bitmap check wait
/// [`LOAD_WAIT`](super::loads::LOAD_WAIT).
/// How long a read of `request` waits for the app that copied: `waits.image` for a bitmap,
/// `waits.load` otherwise.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
const IMAGE_WAIT: Duration = Duration::from_secs(10);
/// How long a read of `request` waits for the app that copied.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn wait_for(request: Request) -> Duration {
fn wait_for(waits: Waits, request: Request) -> Duration {
match request {
Request::Image => IMAGE_WAIT,
Request::Text | Request::Files => super::loads::LOAD_WAIT,
Request::Image => waits.image,
Request::Text | Request::Files => waits.load,
}
}
/// How long a paste's read of `request` after a late answer waits at `now`: as long as any read
/// of `request`, or until [`IMAGE_WAIT`] after the unanswered read was `sent` when that is later.
/// of `request`, or until `waits.image` after the unanswered read was `sent` when that is later.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn follow_up_wait(request: Request, sent: Instant, now: Instant) -> Duration {
wait_for(request).max((sent + IMAGE_WAIT).saturating_duration_since(now))
fn follow_up_wait(waits: Waits, request: Request, sent: Instant, now: Instant) -> Duration {
wait_for(waits, request).max(super::loads::left(sent, waits.image, now))
}
/// The longest an X11 read of arboard's lasts while the owner sends nothing: a text read tries
@@ -1063,6 +1124,8 @@ mod portable {
sent: Instant,
/// The worker, for the paste's other reads.
reads: super::loads::Asker<Request, Answer>,
/// How long the worker's reads wait.
waits: Waits,
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
@@ -1078,7 +1141,8 @@ mod portable {
}
/// What a paste of one of `mimes` takes, once this read's answer comes, waiting for it until
/// [`IMAGE_WAIT`] after it was sent, as long as a paste's bitmap read waits. Once it comes,
/// `waits.image` ([`IMAGE_WAIT`](super::loads::IMAGE_WAIT)) after it was sent, as long as a
/// paste's bitmap read waits. Once it comes,
/// the same read is made again, since the clipboard may have changed hands meanwhile.
/// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the
/// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as
@@ -1088,12 +1152,12 @@ mod portable {
/// names a picture (`adopt_system_clipboard_or_defer` in `vectorcraft-ui-egui`). Those reads
/// wait as [`follow_up_wait`] says.
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
let wait = (self.sent + IMAGE_WAIT).saturating_duration_since(Instant::now());
let wait = super::loads::left(self.sent, self.waits.image, Instant::now());
super::loads::wait_for_answer(&self.answer, wait).ok()?;
let fresh = |request: Request| {
self.reads
.ask(request)
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(request, self.sent, Instant::now())))
.and_then(|a| super::loads::wait_for_answer(&a, follow_up_wait(self.waits, request, self.sent, Instant::now())))
.unwrap_or_else(|why| Answer::failed(request, why))
};
// The late answer may come from an app that lost the clipboard while it was awaited.
@@ -1139,14 +1203,15 @@ mod portable {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
impl Late {
/// What a paste of one of `mimes` takes once the answer comes ([`Unanswered::paste`]). The
/// core protocol's answer is waited for as long, until [`IMAGE_WAIT`] after its read was
/// sent; then the clipboard is read again and pasted as at once, unless it holds the Copy
/// made here ([`super::wayland::Unanswered::paste`]).
/// core protocol's answer is waited for as long, until
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) after its read was sent; then the clipboard is
/// read again and pasted as at once, unless it holds the Copy made here
/// ([`super::wayland::Unanswered::paste`]).
fn paste(self, ours: Option<&Ours>, mimes: &[&'static str]) -> Option<Flavour> {
match self {
Self::Arboard(unanswered) => unanswered.paste(ours, mimes),
#[cfg(target_os = "linux")]
Self::Wayland(unanswered) => unanswered.paste(mimes, IMAGE_WAIT),
Self::Wayland(unanswered) => unanswered.paste(mimes),
}
}
}
@@ -1163,8 +1228,9 @@ mod portable {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
{
let mut reader = arboard::Clipboard::new().map_err(|e| e.to_string())?;
let reads = super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), move |request| answer(&mut reader, request))
.ok_or("the clipboard's reader didn't start")?;
let reads =
super::loads::Loads::spawn("clipboard-read", finish(on_data_control()), Waits::APP, move |request| answer(&mut reader, request))
.ok_or("the clipboard's reader didn't start")?;
Ok(Self { reads, unanswered: None, cb })
}
#[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd")))]
@@ -1181,13 +1247,13 @@ mod portable {
impl<C> Arboard<C> {
/// Reads on the worker; the write handle `C` is not used.
fn read(&mut self, request: Request) -> Answer {
self.read_waiting(request, wait_for(request))
self.read_waiting(request, wait_for(self.reads.waits(), request))
}
/// A bitmap read on the worker that waits [`LOAD_WAIT`](super::loads::LOAD_WAIT) at most, for
/// a check on the UI thread.
fn image_now(&mut self) -> Result<arboard::ImageData<'static>, String> {
self.read_waiting(Request::Image, super::loads::LOAD_WAIT).image()
self.read_waiting(Request::Image, self.reads.waits().load).image()
}
/// `request` read on the worker, waiting `wait` at most. A read that gets no answer in that
@@ -1202,7 +1268,7 @@ mod portable {
Ok(answer) => answer,
Err(why) => {
if why != super::loads::GONE {
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker() });
self.unanswered = Some(Unanswered { request, answer, sent, reads: self.reads.asker(), waits: self.reads.waits() });
}
Answer::failed(request, why)
}
@@ -1217,11 +1283,13 @@ mod portable {
Ok(answer)
}
/// A bitmap read sent to the worker now; the work returned waits [`IMAGE_WAIT`] at most for
/// it, so the caller can wait off the UI thread. Err when the read can't be sent.
/// A bitmap read sent to the worker now; the work returned waits
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most for it, so the caller can wait off the UI
/// thread. Err when the read can't be sent.
fn image_later(&mut self) -> Result<ImageWork, String> {
let wait = self.reads.waits().image;
let answer = self.ask(Request::Image)?;
Ok(Box::new(move || super::loads::wait_for_answer(&answer, IMAGE_WAIT).and_then(Answer::image)))
Ok(Box::new(move || super::loads::wait_for_answer(&answer, wait).and_then(Answer::image)))
}
/// The read that got no answer in its wait, while its answer has still not come and a paste
@@ -1503,12 +1571,12 @@ mod portable {
/// Text and copied files are read here, and work that reads arboard's image comes back. On
/// the Wayland core protocol the copied files, else the first of `mimes` the clipboard
/// offers, is read: text here, file lists, SVG and PNG by the work that comes back, which
/// waits [`IMAGE_WAIT`] at most.
/// waits [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
fn read_now_or_later(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
let cb = self.cb(Asker::User).ok()?;
#[cfg(target_os = "linux")]
if let Backend::Wayland(cb) = cb {
return cb.read(mimes, IMAGE_WAIT);
return cb.read(mimes);
}
if let Some(f) = copied_file(cb.file_list(), mimes) {
return Some(ClipboardRead::Now(f));
@@ -1654,9 +1722,12 @@ mod portable {
mod tests {
use std::cell::Cell;
use super::super::loads::Loads;
use super::super::loads::{Loads, Waits};
use super::*;
/// No limit: a wait ends when its answer comes.
const UNTIL_ANSWERED: Duration = Duration::MAX;
/// A clock that starts now and moves only when told.
struct Clock(Cell<Instant>);
@@ -1780,27 +1851,27 @@ mod portable {
fn reads_return_while_the_clipboard_owner_sends_nothing() {
let (release, gate) = std::sync::mpsc::channel::<()>();
// The app that copied never sends its data until released.
let mut reads = Loads::spawn("test", Duration::ZERO, move |request| {
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
let _ = gate.recv();
Answer::failed(request, "late".into())
})
.unwrap();
// Copy's look at the text, Paste's file list and its bitmap: none waits for the owner.
assert!(read_within(&mut reads, Request::Text, Duration::ZERO).text().is_err());
assert!(read_within(&mut reads, Request::Files, Duration::from_secs(600)).files().is_empty());
assert!(read_within(&mut reads, Request::Image, Duration::from_secs(600)).image().is_err());
assert!(read_within(&mut reads, Request::Files, UNTIL_ANSWERED).files().is_empty());
assert!(read_within(&mut reads, Request::Image, UNTIL_ANSWERED).image().is_err());
drop(release);
}
#[test]
fn each_read_takes_its_own_answer() {
let mut reads = Loads::spawn("test", Duration::ZERO, |request| match request {
let mut reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
Request::Text => Answer::Text(Ok("<svg/>".into())),
Request::Image => Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) })),
Request::Files => Answer::Files(vec![PathBuf::from("art.svg")]),
})
.unwrap();
let wait = Duration::from_secs(600);
let wait = UNTIL_ANSWERED;
assert_eq!(read_within(&mut reads, Request::Text, wait).text(), Ok("<svg/>".to_string()));
assert_eq!(read_within(&mut reads, Request::Image, wait).image().map(|i| (i.width, i.height)), Ok((2, 1)));
assert_eq!(read_within(&mut reads, Request::Files, wait).files(), [PathBuf::from("art.svg")]);
@@ -1847,7 +1918,8 @@ mod portable {
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn arboards_reads_run_on_its_reader_and_wait_by_kind() {
let reads = Loads::spawn("test", Duration::ZERO, |request| match request {
// The reads wait for their answer however long it takes, so the answer decides the result.
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |request| match request {
Request::Text => Answer::Text(Ok("read on the worker".into())),
_ => Answer::failed(request, "not asked".into()),
})
@@ -1855,15 +1927,18 @@ mod portable {
// `()` for writes: a read made through the write handle wouldn't build.
let mut cb = Arboard { reads, unanswered: None, cb: () };
assert_eq!(cb.read(Request::Text).text(), Ok("read on the worker".to_string()));
assert_eq!(wait_for(Request::Text), super::super::loads::LOAD_WAIT);
assert_eq!(wait_for(Request::Files), super::super::loads::LOAD_WAIT);
assert_eq!(wait_for(Request::Image), Duration::from_secs(10));
let app = Waits::APP;
assert_eq!(wait_for(app, Request::Text), super::super::loads::LOAD_WAIT);
assert_eq!(wait_for(app, Request::Files), super::super::loads::LOAD_WAIT);
assert_eq!(wait_for(app, Request::Image), Duration::from_secs(10));
// A paste's reads after a late answer wait until 10 s after the unanswered read was
// sent, and never less than any read of their kind.
let sent = Instant::now();
assert_eq!(follow_up_wait(Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
assert_eq!(follow_up_wait(Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
assert_eq!(follow_up_wait(Request::Image, sent, sent + Duration::from_secs(20)), IMAGE_WAIT);
assert_eq!(follow_up_wait(app, Request::Text, sent, sent + Duration::from_secs(3)), Duration::from_secs(7));
assert_eq!(follow_up_wait(app, Request::Files, sent, sent + Duration::from_secs(9)), super::super::loads::LOAD_WAIT);
assert_eq!(follow_up_wait(app, Request::Image, sent, sent + Duration::from_secs(20)), super::super::loads::IMAGE_WAIT);
// With no limit, the follow-up reads have none either.
assert_eq!(follow_up_wait(Waits::UNTIL_ANSWERED, Request::Text, sent, sent + Duration::from_secs(20)), Duration::MAX);
// X11 waits for an unanswered read when the clipboard closes; data-control doesn't.
assert_eq!(finish(false), X11_READ_LIMIT);
assert_eq!(finish(true), Duration::ZERO);
@@ -1884,7 +1959,7 @@ mod portable {
fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() {
let (release, gate) = std::sync::mpsc::channel::<()>();
// The app that copied sends its bitmap only when released.
let reads = Loads::spawn("test", Duration::ZERO, move |request| match request {
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| match request {
Request::Image => {
let _ = gate.recv();
Answer::Image(Ok(arboard::ImageData { width: 2, height: 1, bytes: Cow::Owned(vec![0; 8]) }))
@@ -1903,11 +1978,12 @@ mod portable {
}
/// An arboard clipboard whose owner answers each read with `answer` only once the sender
/// returned is used or dropped.
/// returned is used or dropped. Its reads wait for their answers with no limit: the
/// release decides when a paste gets its answer.
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
fn slow_owner(answer: impl Fn(Request) -> Answer + Send + 'static) -> (Arboard<()>, std::sync::mpsc::Sender<()>) {
let (release, gate) = std::sync::mpsc::channel::<()>();
let reads = Loads::spawn("test", Duration::ZERO, move |request| {
let reads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |request| {
let _ = gate.recv();
answer(request)
})
@@ -2028,10 +2104,10 @@ mod portable {
/// Core protocol reads of a clipboard offering `types`, whose owner answers each read
/// of a text type with `text` and of `image/png` with `png`, only once the sender
/// returned is used or dropped.
/// returned is used or dropped. The reads wait for their answers with no limit.
fn slow_owner(types: &[&str], text: &'static str, png: &'static [u8]) -> (Reads, Arc<Mutex<Seen>>, std::sync::mpsc::Sender<()>) {
let (release, gate) = std::sync::mpsc::channel::<()>();
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
let _ = gate.recv();
Ok(if wire == PNG { png.to_vec() } else { text.as_bytes().to_vec() })
})
@@ -2047,7 +2123,7 @@ mod portable {
// in its wait (2 s on the UI thread, none here).
assert!(reads.text(Duration::ZERO).is_err());
// The paste's own read fails at once while the owner hasn't answered.
assert!(reads.text(Duration::from_secs(600)).is_err());
assert!(reads.text(UNTIL_ANSWERED).is_err());
// A paste of a bitmap alone can't take text: the read stays kept.
assert!(reads.unanswered(&[BITMAP]).is_none());
let late = Late::Wayland(reads.unanswered(&PASTE_ORDER).expect("the check's read is kept for the paste"));
@@ -2083,7 +2159,7 @@ mod portable {
// again and takes the new owner's text.
let (release, gate) = std::sync::mpsc::channel::<()>();
let mut texts_read = 0;
let loads = Loads::spawn("test", Duration::ZERO, move |_: String| {
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |_: String| {
let _ = gate.recv();
texts_read += 1;
Ok(if texts_read == 1 { "old owner" } else { "new owner" }.as_bytes().to_vec())
@@ -2149,7 +2225,7 @@ mod wayland {
use wayland_client::protocol::wl_seat::{self, WlSeat};
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, WEnum};
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, wait_for_answer};
use super::loads::{Asker, GONE, LOAD_WAIT, Loads, Waits, left, wait_for_answer};
use super::{BITMAP, Flavour, MAX_BYTES, PNG, PathBuf, SVG, TEXT, copied_file, gnome_copied_paths, takes_files, uri_list_paths};
/// The types text is offered under and read from, best first: `text/plain;charset=utf-8` (GTK
@@ -2445,16 +2521,18 @@ mod wayland {
/// The worker, for the reads made once the answer comes.
reads: Asker<String, Got>,
seen: Arc<Mutex<Seen>>,
/// How long the worker's reads wait.
waits: Waits,
}
impl Unanswered {
/// What a paste of one of `mimes` takes once this read's answer comes, waiting for it until
/// `limit` after the read was sent: the clipboard read again as [`pick_pasted`] reads it,
/// each read waiting as long, [`LOAD_WAIT`] at least, since the app that answers late may
/// have lost the clipboard meanwhile. None when the answer doesn't come or the clipboard holds this
/// connection's Copy.
pub(super) fn paste(self, mimes: &[&'static str], limit: Duration) -> Option<Flavour> {
let left = |now: Instant| (self.sent + limit).saturating_duration_since(now);
/// `waits.image` after the read was sent: the clipboard read again as [`pick_pasted`] reads
/// it, each read waiting as long, `waits.load` ([`LOAD_WAIT`]) at least, since the app that
/// answers late may have lost the clipboard meanwhile. None when the answer doesn't come or
/// the clipboard holds this connection's Copy.
pub(super) fn paste(self, mimes: &[&'static str]) -> Option<Flavour> {
let left = |now: Instant| left(self.sent, self.waits.image, now);
let _late = wait_for_answer(&self.answer, left(Instant::now())).ok()?;
let offered = {
let seen = lock(&self.seen);
@@ -2464,7 +2542,7 @@ mod wayland {
seen.offered.clone()
};
pick_pasted(&offered, mimes, |wire| {
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, LOAD_WAIT.max(left(Instant::now()))).ok()?.ok()
wait_for_answer(&self.reads.ask(wire.to_string()).ok()?, self.waits.load.max(left(Instant::now()))).ok()?.ok()
})
}
}
@@ -2491,7 +2569,8 @@ mod wayland {
Ok(got) => Ok(flavour(TEXT, got?).map(|f| String::from_utf8_lossy(&f.data).into_owned()).unwrap_or_default()),
Err(why) => {
if why != GONE {
self.unanswered = Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone() });
self.unanswered =
Some(Unanswered { answer, sent, reads: self.loads.asker(), seen: self.seen.clone(), waits: self.loads.waits() });
}
Err(why)
}
@@ -2501,12 +2580,13 @@ mod wayland {
/// What a paste of one of `mimes` reads: the files a file manager copied, else the first of
/// `mimes` the clipboard offers. A file list is asked for here and read, with the files,
/// by the work that comes back, which pastes the first file that is art ([`copied`]) and
/// else reads `mimes` as [`pick`] does. Text is read here, [`LOAD_WAIT`] at most, and
/// pasted unless it is empty; SVG and PNG are asked for here and waited for, `wait` at most,
/// by the work that comes back. When that read fails or is empty, the work reads the rest
/// of `mimes` as [`pick`] does. Each read the work makes after the first waits until `wait`
/// after the first was sent, [`LOAD_WAIT`] at least.
pub(super) fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
/// else reads `mimes` as [`pick`] does. Text is read here, `waits.load` ([`LOAD_WAIT`]) at
/// most, and pasted unless it is empty; SVG and PNG are asked for here and waited for,
/// `waits.image` at most, by the work that comes back. When that read fails or is empty,
/// the work reads the rest of `mimes` as [`pick`] does. Each read the work makes after the
/// first waits until `waits.image` after the first was sent, `waits.load` at least.
pub(super) fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
let Waits { load, image: wait } = self.loads.waits();
if takes_files(mimes) {
let offered = lock(&self.seen).offered.clone();
if let Some(list) = file_list_type(&offered).map(str::to_string) {
@@ -2515,7 +2595,7 @@ mod wayland {
self.unanswered = None;
let (reads, mimes) = (self.loads.asker(), mimes.to_vec());
return Some(ClipboardRead::Later(Box::new(move || {
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
let left = || load.max(left(sent, wait, Instant::now()));
// The list asked for here is read from its answer, every other type anew.
let mut first = Some((list, answer));
pick_pasted(&offered, &mimes, |wire| {
@@ -2531,7 +2611,7 @@ mod wayland {
mimes.iter().enumerate().find_map(|(i, &mime)| {
let wire = self.wire(mime)?;
if mime == TEXT {
let text = self.text(LOAD_WAIT).ok().filter(|t| !t.is_empty())?;
let text = self.text(load).ok().filter(|t| !t.is_empty())?;
return Some(ClipboardRead::Now(Flavour { mime: TEXT, data: text.into_bytes() }));
}
let sent = Instant::now();
@@ -2543,7 +2623,7 @@ mod wayland {
return Some(f);
}
let offered = lock(&seen).offered.clone();
let left = || LOAD_WAIT.max((sent + wait).saturating_duration_since(Instant::now()));
let left = || load.max(left(sent, wait, Instant::now()));
pick(&offered, &rest, |wire| wait_for_answer(&reads.ask(wire.to_string()).ok()?, left()).ok()?.ok())
})))
})
@@ -2809,7 +2889,7 @@ mod wayland {
let receiver = Receiver { conn: conn.clone(), objects: objects.clone(), _window: window.clone() };
// Dropping doesn't wait for an unanswered read: only arboard's X11 handles hand what the
// app copied on when the last one goes.
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, move |wire| receiver.receive(wire))?;
let loads = Loads::spawn("wayland-clipboard-read", Duration::ZERO, Waits::APP, move |wire| receiver.receive(wire))?;
let stop = Arc::new(AtomicBool::new(false));
let (stopped, held) = (stop.clone(), window.clone());
let work = move || {
@@ -2846,14 +2926,16 @@ mod wayland {
self.conn.flush().map_err(|e| format!("couldn't reach the compositor: {e}"))
}
/// The text, waiting [`LOAD_WAIT`] at most ([`Reads::text`]).
pub fn text(&mut self) -> Result<String, String> {
self.reads.text(LOAD_WAIT)
let wait = self.reads.loads.waits().load;
self.reads.text(wait)
}
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for `wait` at
/// most.
pub fn read(&mut self, mimes: &[&'static str], wait: Duration) -> Option<ClipboardRead> {
self.reads.read(mimes, wait)
/// What a paste of one of `mimes` reads ([`Reads::read`]), SVG and PNG waited for
/// [`IMAGE_WAIT`](super::loads::IMAGE_WAIT) at most.
pub fn read(&mut self, mimes: &[&'static str]) -> Option<ClipboardRead> {
self.reads.read(mimes)
}
pub fn has(&self, mimes: &[&'static str]) -> bool {
@@ -3022,8 +3104,8 @@ mod wayland {
assert_eq!(keyboard_serial(&modifiers(9), None), None);
}
/// A wait no test reaches: the other end of each pipe below either moves data or closes.
const LONG: Duration = Duration::from_secs(600);
/// No limit ([`idle_until`]): the other end of each pipe below either moves data or closes.
const LONG: Duration = Duration::MAX;
/// A pipe holding `data`, its write end closed when `close`.
fn pipe_with(data: &[u8], close: bool) -> (std::io::PipeReader, Option<std::io::PipeWriter>) {
@@ -3041,7 +3123,7 @@ mod wayland {
assert_eq!(read_capped(pipe_with(&[0u8; 9], true).0, 8, Duration::ZERO), Err("the clipboard's data is larger than 0 MiB".to_string()));
// More than a pipe holds, from an app that is still sending.
let (from, to) = std::io::pipe().unwrap();
assert!(Sends::default().start(to, vec![0u8; (2 << 20) + 1].into()));
assert!(Sends { idle: LONG, ..Sends::default() }.start(to, vec![0u8; (2 << 20) + 1].into()));
assert_eq!(read_capped(from, 2 << 20, LONG), Err("the clipboard's data is larger than 2 MiB".to_string()));
// A pipe that can't be read: the write end.
let (_, to) = std::io::pipe().unwrap();
@@ -3095,8 +3177,8 @@ mod wayland {
#[test]
fn a_copys_data_is_sent_through_the_pipe_and_closed() {
let sends = Sends::default();
assert_eq!(sends.idle, IDLE_WAIT);
assert_eq!(Sends::default().idle, IDLE_WAIT);
let sends = Sends { idle: LONG, ..Sends::default() };
let (from, to) = std::io::pipe().unwrap();
let data: Arc<[u8]> = vec![7u8; 300_000].into();
assert!(sends.start(to, data.clone()));
@@ -3146,9 +3228,10 @@ mod wayland {
const NOTHING: Held = &[];
const UNKNOWN: Held = &[("application/x-other", b"x")];
/// Reads of a clipboard holding `data`, answered at once.
/// Reads of a clipboard holding `data`, answered at once; each read waits for its answer
/// with no limit.
fn reads_of(data: Held) -> Reads {
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.to_vec()).ok_or_else(|| "not offered".to_string())
})
.unwrap();
@@ -3159,27 +3242,26 @@ mod wayland {
#[test]
fn a_picture_or_svg_alone_can_be_pasted_and_is() {
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
let wait = Duration::from_secs(600);
for (data, mime) in [(PNG_ONLY, PNG), (SVG_ONLY, SVG)] {
let mut reads = reads_of(data);
// The paste check enables Paste from the types alone.
assert!(reads.has(&PASTE_ORDER));
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("{mime} is read off the UI thread") };
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("{mime} is read off the UI thread") };
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, data[0].1.to_vec())));
}
let mut reads = reads_of(TEXT_ONLY);
assert!(reads.has(&[TEXT]) && !reads.has(&[BITMAP, SVG]));
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER, wait) else { panic!("text is read at once") };
let Some(ClipboardRead::Now(f)) = reads.read(&PASTE_ORDER) else { panic!("text is read at once") };
assert_eq!((f.mime, f.data), (TEXT, b"words".to_vec()));
// An empty clipboard, or one with no type a paste reads, enables nothing and pastes nothing.
for data in [NOTHING, UNKNOWN] {
let mut reads = reads_of(data);
assert!(!reads.has(&PASTE_ORDER));
assert!(reads.read(&PASTE_ORDER, wait).is_none());
assert_eq!(reads.text(wait), Ok(String::new()));
assert!(reads.read(&PASTE_ORDER).is_none());
assert_eq!(reads.text(Duration::MAX), Ok(String::new()));
}
// Empty text is not pasted.
assert!(reads_of(EMPTY_TEXT).read(&[TEXT], wait).is_none());
assert!(reads_of(EMPTY_TEXT).read(&[TEXT]).is_none());
}
#[test]
@@ -3188,36 +3270,38 @@ mod wayland {
const EMPTY_SVG_TEXT: Held = &[(SVG, b""), ("text/plain", b"words"), (PNG, b"\x89PNG")];
const EMPTY_SVG_PNG: Held = &[(SVG, b""), (PNG, b"\x89PNG")];
const EMPTY_SVG_URL: Held = &[(SVG, b""), ("text/plain", b"https://example.com/art.png"), (PNG, b"\x89PNG")];
let wait = Duration::from_secs(600);
const EMPTY_PNG: Held = &[(PNG, b"")];
for (data, mime, bytes) in
[(EMPTY_SVG_TEXT, TEXT, &b"words"[..]), (EMPTY_SVG_PNG, PNG, &b"\x89PNG"[..]), (EMPTY_SVG_URL, PNG, &b"\x89PNG"[..])]
{
// Held while the work runs, as the clipboard is.
let mut reads = reads_of(data);
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the SVG is asked for") };
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the SVG is asked for") };
assert_eq!(work().map(|f| (f.mime, f.data)), Some((mime, bytes.to_vec())));
}
// A failed PNG read, last of all, pastes nothing.
let mut reads = reads_of(EMPTY_PNG);
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER, wait) else { panic!("the PNG is asked for") };
let Some(ClipboardRead::Later(work)) = reads.read(&PASTE_ORDER) else { panic!("the PNG is asked for") };
assert!(work().is_none());
}
#[test]
fn a_read_that_fails_pastes_nothing() {
let loads = Loads::spawn("test", Duration::ZERO, |_: String| Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string()))
.unwrap();
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, |_: String| {
Err::<Vec<u8>, _>("the clipboard's data is larger than 64 MiB".to_string())
})
.unwrap();
let mut reads = Reads::new(loads, Arc::new(Mutex::new(Seen::offering(&[PNG, "text/plain"]))));
assert_eq!(reads.text(Duration::from_secs(600)), Err("the clipboard's data is larger than 64 MiB".to_string()));
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP], Duration::from_secs(600)) else { panic!("the PNG is asked for") };
assert_eq!(reads.text(Duration::MAX), Err("the clipboard's data is larger than 64 MiB".to_string()));
let Some(ClipboardRead::Later(work)) = reads.read(&[BITMAP]) else { panic!("the PNG is asked for") };
assert!(work().is_none());
}
/// Reads of a clipboard holding `data` by type, answered at once.
/// Reads of a clipboard holding `data` by type, answered at once; each read waits for its
/// answer with no limit.
fn reads_holding(data: Vec<(String, Vec<u8>)>) -> Reads {
let types: Vec<String> = data.iter().map(|(t, _)| t.clone()).collect();
let loads = Loads::spawn("test", Duration::ZERO, move |wire: String| {
let loads = Loads::spawn("test", Duration::ZERO, Waits::UNTIL_ANSWERED, move |wire: String| {
data.iter().find(|(t, _)| *t == wire).map(|(_, d)| d.clone()).ok_or_else(|| "not offered".to_string())
})
.unwrap();
@@ -3232,7 +3316,7 @@ mod wayland {
/// What a paste of `mimes` takes from `reads`.
fn paste(reads: &mut Reads, mimes: &[&'static str]) -> Option<(&'static str, Vec<u8>)> {
match reads.read(mimes, Duration::from_secs(600))? {
match reads.read(mimes)? {
ClipboardRead::Now(f) => Some((f.mime, f.data)),
ClipboardRead::Later(work) => work().map(|f| (f.mime, f.data)),
}
+5
View File
@@ -1596,6 +1596,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
for xf in placements {
for (k, n) in clip.nodes.iter().enumerate() {
let mut c = d.reid(n);
// A pasted object never goes in as a clip group's clipping path, so a copied clipping
// path comes back as an ordinary path that the path commands work on (#9227).
if let NodeKind::Path { clipping, .. } = &mut c.kind {
*clipping = false;
}
// A pasted symbol set packs from the density recorded for it at Copy.
d.carry_set_densities(n, &c, &clip.set_densities);
imported.apply(&mut c, d);
+7
View File
@@ -411,6 +411,13 @@ impl Session {
pub fn has_selected_blend(&self) -> bool {
super::common::any_selected_of(self, is_blend, |_| true)
}
/// The blends Blend Options edits, in ID order regardless of their selection order.
pub fn selected_blend_ids(&self) -> Vec<NodeId> {
let mut ids = selected_of(self, is_blend);
ids.sort_unstable();
ids
}
}
/// The first selected blend: its id, spec and key ids.
+3
View File
@@ -675,6 +675,9 @@ fn transform_each_as(s: &mut Session, p: &Value, label: &str) -> Result<Value> {
// Five draws whatever the scales are, so a seed gives the moves and the rotation
// the same values whether a side is scaled or not.
let [r_sh, r_sv, r_mh, r_mv, r_rot] = [rng.next(), rng.next(), rng.next(), rng.next(), rng.next()];
// The same horizontal and vertical scale take one share, so the object scales
// evenly (#9320).
let r_sv = if sh == sv { r_sh } else { r_sv };
k_sh = k_sh.map(|v| 1.0 + (v - 1.0) * r_sh);
k_sv = k_sv.map(|v| 1.0 + (v - 1.0) * r_sv);
k_mh = mh * (r_mh * 2.0 - 1.0);
+15 -2
View File
@@ -194,13 +194,19 @@ pub(super) fn clip_make(s: &mut Session, _: &Value) -> Result<Value> {
pub(super) fn clip_release(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_roots(s)?;
// With no clip group selected, the document and its undo history stay as they are.
// With no clip group and no stray clipping path selected, the document and its undo history
// stay as they are.
let d = &s.doc()?.doc;
if !ids.iter().any(|id| d.node(*id).is_some_and(Node::clips)) {
if !ids.iter().any(|id| d.node(*id).is_some_and(Node::clips) || stray_clipping_path(d, *id)) {
return ok();
}
s.edit("Release Clipping Mask", |d, _| {
for id in &ids {
if stray_clipping_path(d, *id)
&& let Some(NodeKind::Path { clipping, .. }) = d.node_mut(*id).map(|n| &mut n.kind)
{
*clipping = false;
}
release_clip(d, *id);
}
Ok(())
@@ -208,6 +214,13 @@ pub(super) fn clip_release(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
/// Whether `id` is a path marked as a clipping path that clips nothing: not the bottom child of a
/// clip group or clipping layer. A paste made one before #9227; the path commands skip it.
fn stray_clipping_path(d: &Document, id: NodeId) -> bool {
let marked = d.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. }));
marked && !d.position(id).is_some_and(|(parent, i, _)| i == 0 && parent.and_then(|p| d.node(p)).is_some_and(Node::clips))
}
/// Selects the clipping path (`mask`) or the clipped contents of every selected clip group (or of the
/// clip group containing a selected object), like Illustrator's Edit Contents / Edit Clipping Path toggle.
pub(super) fn clip_edit(s: &mut Session, mask: bool) -> Result<Value> {
+14 -2
View File
@@ -295,6 +295,18 @@ impl Session {
self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
/// Have listings of the Scripts and Startup Scripts folders measure their time with `clock`
/// instead of the real time ([`script::folder::Clock::Wall`], the default).
pub fn set_script_listing_clock(&mut self, clock: script::folder::Clock) {
self.script_listing_clock = clock;
}
/// How listings of the Scripts and Startup Scripts folders measure their time
/// ([`Session::set_script_listing_clock`]).
pub fn script_listing_clock(&self) -> script::folder::Clock {
self.script_listing_clock
}
/// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders.
pub fn scripts_dir(&self) -> Option<&std::path::Path> {
self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
@@ -581,7 +593,7 @@ fn startup_run(s: &mut Session, p: &Value) -> Result<Value> {
let folder = root.to_string_lossy().into_owned();
// The folder is the app's: a refusal names it as the request may see it.
crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?;
let listing = script::startup::list(&root);
let listing = script::startup::list(&root, s.script_listing_clock);
let name_of = |path: &std::path::Path| path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let (disabled, scripts): (Vec<_>, Vec<_>) =
listing.scripts.into_iter().partition(|path| vectorcraft_plugins::safe_mode::skipped(&startup_item(path)));
@@ -647,7 +659,7 @@ fn list_installed(s: &mut Session, _: &Value) -> Result<Value> {
let folder = root.to_string_lossy();
// The Scripts folder is the app's: a refusal names it as the request may see it.
crate::file_access::check_read(&folder).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), &folder))?;
let listing = script::folder::list(root);
let listing = script::folder::list(root, s.script_listing_clock);
let scripts: Vec<Value> = listing
.scripts()
.into_iter()
+5
View File
@@ -189,6 +189,11 @@ pub fn specs() -> Vec<CommandSpec> {
}
impl Session {
/// The selected slices, including selected objects that are object slices.
pub fn selected_slice_ids(&self) -> Vec<NodeId> {
self.active().map_or_else(Vec::new, |st| selected_slices(&st.doc, &st.selection))
}
/// View → Hide Slices.
pub fn slices_hidden(&self) -> bool {
self.menu.slices_hidden
+3
View File
@@ -222,6 +222,9 @@ pub struct Session {
/// The Startup Scripts folder, whose scripts `script.startup.run` runs; `None`: no folder
/// ([`Session::attach_startup_scripts_dir`]).
startup_scripts_dir: Option<std::path::PathBuf>,
/// How listings of the Scripts and Startup Scripts folders measure their time
/// ([`Session::set_script_listing_clock`]).
script_listing_clock: script::folder::Clock,
/// The folder of File Info's metadata templates; `None`: no folder
/// ([`Session::attach_metadata_templates_dir`]).
metadata_templates_dir: Option<std::path::PathBuf>,
+28 -5
View File
@@ -50,6 +50,30 @@ impl Default for Limits {
}
}
/// How a listing measures the time it has taken, which [`Limits::time`] bounds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Clock {
/// The real time since the listing started.
#[default]
Wall,
/// The same time at every check, whatever the real time: the listing reaches the time limit
/// only when this time is past it.
Fixed(Duration),
}
impl Clock {
/// Calls `f` with this clock's time since `f` was called.
pub fn time<T>(self, f: impl FnOnce(&mut dyn FnMut() -> Duration) -> T) -> T {
match self {
Clock::Wall => {
let start = std::time::Instant::now();
f(&mut || start.elapsed())
}
Clock::Fixed(elapsed) => f(&mut || elapsed),
}
}
}
/// One row of a listing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Entry {
@@ -93,11 +117,10 @@ impl Listing {
}
}
/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives
/// an empty listing.
pub fn list(root: &Path) -> Listing {
let start = std::time::Instant::now();
list_with(root, &Limits::default(), &mut || start.elapsed())
/// What the folder `root` holds, within the default [`Limits`], with the time measured by `clock`.
/// A folder that does not exist gives an empty listing.
pub fn list(root: &Path, clock: Clock) -> Listing {
clock.time(|elapsed| list_with(root, &Limits::default(), elapsed))
}
/// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken.
+4 -5
View File
@@ -37,11 +37,10 @@ pub fn takes(name: &str) -> bool {
&& Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx"))
}
/// The startup scripts in `root`, within the Scripts folder's limits. A folder that does not exist
/// gives an empty listing.
pub fn list(root: &Path) -> Listing {
let start = std::time::Instant::now();
list_with(root, &folder::Limits::default(), &mut || start.elapsed())
/// The startup scripts in `root`, within the Scripts folder's limits, with the time measured by
/// `clock`. A folder that does not exist gives an empty listing.
pub fn list(root: &Path, clock: folder::Clock) -> Listing {
clock.time(|elapsed| list_with(root, &folder::Limits::default(), elapsed))
}
/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones);
+1
View File
@@ -112,6 +112,7 @@ impl Session {
plugin_loads_in_background: false,
scripts_dir: None,
startup_scripts_dir: None,
script_listing_clock: Default::default(),
metadata_templates_dir: None,
new_doc_profile_dir: None,
proof_setup_dir: None,
+16 -30
View File
@@ -2,6 +2,7 @@
//! and Refresh Font List (`text.rescanFonts`).
use serde_json::{Value, json};
use vectorcraft_text::test_fonts::steady_fonts;
use vectorcraft_text::{FontDb, system_font_dirs};
use crate::*;
@@ -13,12 +14,12 @@ fn names(v: &Value) -> Vec<String> {
#[test]
fn the_font_list_names_every_available_family_with_its_styles() {
let mut s = Session::new();
let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]);
// Other tests running at the same time add and remove composite fonts, which the lists show
// first; the installed families are compared.
let db = FontDb::global();
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
assert_eq!(installed_only(&fams), installed_only(&db.menu_family_list()));
// Tests running alongside add fonts and composite fonts to the process-wide database; their
// changes wait until this test ends, so both lists are read from the same fonts.
let _steady = steady_fonts(db);
let fams = names(&s.execute("text.fontList", &json!({})).unwrap()["families"]);
assert_eq!(fams, db.menu_family_list().to_vec());
for f in ["Source Sans 3", "Source Serif 4", "Inter", "JetBrains Mono"] {
assert!(fams.iter().any(|x| x == f), "{f}");
}
@@ -40,6 +41,9 @@ fn the_font_list_names_every_available_family_with_its_styles() {
fn similar_fonts_lists_every_family_by_likeness() {
let mut s = Session::new();
let db = FontDb::global();
// Tests running alongside add fonts and composite fonts to the process-wide database; their
// changes wait until this test ends, so every answer is made from the same fonts.
let _steady = steady_fonts(db);
let r = s.execute("text.similarFonts", &json!({"family": "source sans 3"})).unwrap();
assert_eq!(r["family"], "Source Sans 3");
let order = names(&r["families"]);
@@ -48,31 +52,10 @@ fn similar_fonts_lists_every_family_by_likeness() {
sorted.sort();
let mut listed = db.menu_family_list().to_vec();
listed.sort();
// Other tests running at the same time add and remove composite fonts; the installed families are compared.
let installed_only = |list: &[String]| list.iter().filter(|f| db.has_installed_family(f)).cloned().collect::<Vec<_>>();
assert_eq!(installed_only(&sorted), installed_only(&listed), "every family once");
// The two answers are compared whole when the available fonts did not change while both were
// made (the same `FontDb::generation`), and by their installed families when they changed
// during every try.
let mut answers = (vec![], vec![], false);
for _ in 0..20 {
let generation = db.generation();
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
let unchanged = db.generation() == generation;
answers = (all, two, unchanged);
if unchanged {
break;
}
}
let (all, two, unchanged) = answers;
assert_eq!(two.len(), 2);
if unchanged {
assert_eq!(two, all[..2], "the first families, in order");
} else {
let (two, all) = (installed_only(&two), installed_only(&all));
assert_eq!(two[..], all[..two.len()], "the first installed families, in order");
}
assert_eq!(sorted, listed, "every family once");
let all = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3"})).unwrap()["families"]);
let two = names(&s.execute("text.similarFonts", &json!({"family": "Source Sans 3", "limit": 2})).unwrap()["families"]);
assert_eq!(two, all[..2], "the first families, in order");
for (params, error) in [
(json!({}), "`family` is required"),
(json!({"family": " "}), "`family` is required"),
@@ -94,6 +77,9 @@ fn refreshing_the_font_list_redraws_type_without_editing_the_document() {
s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Type", "font": "No Such Font"})).unwrap();
s.doc_mut().unwrap().mark_saved();
let revision = s.doc().unwrap().revision;
// Fonts that tests running alongside add wait until this test ends, so the count is of the
// fonts the rescan left.
let _steady = steady_fonts(FontDb::global());
let r = s.execute("text.rescanFonts", &json!({})).unwrap();
assert_eq!(r["families"], json!(FontDb::global().menu_family_list().len()));
assert!(r["faces"].is_u64());
+22
View File
@@ -1153,6 +1153,28 @@ fn transform_each_random_is_deterministic_with_seed() {
assert!(x.x0.abs() <= 50.0 && x.width() == 100.0);
}
/// Random with the same horizontal and vertical scale scales each object evenly, Relative and
/// Absolute alike: one random share takes both sides toward the value, so squares stay square, each
/// by its own share (#9320).
#[test]
fn transform_each_random_with_equal_scales_keeps_proportions() {
for p in [
json!({"scaleH": 40, "scaleV": 40, "random": true, "seed": 7}),
json!({"scaleH": 40, "scaleV": 40, "relative": false, "random": true, "seed": 7}),
] {
let mut s = session();
let ids: Vec<NodeId> = (0..8).map(|i| rect(&mut s, f64::from(i) * 150.0, 0.0, 100.0, 100.0)).collect();
sel(&mut s, &ids);
s.execute("object.transformEach", &p).unwrap();
let sizes: Vec<(f64, f64)> = ids.iter().map(|id| bounds(&s, *id)).map(|b| (b.width(), b.height())).collect();
for (w, h) in &sizes {
assert!(close(*w, *h), "{p}: a square came out {w} × {h}");
assert!(*w < 100.0, "{p}: a square didn't shrink: {w}");
}
assert!(sizes.iter().any(|(w, _)| !close(*w, sizes[0].0)), "{p}: every square took the same share: {sizes:?}");
}
}
/// A `reference` or `seed` that is not a whole number (a fraction, a negative number or a string) is an error naming
/// the key, and the object stays as it was; a `reference` of 0.0 is the top-left point.
#[test]
+27 -9
View File
@@ -61,7 +61,7 @@ fn scripts_and_subfolders_are_listed_by_name_without_the_extension() {
touch(&root, name);
}
std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap();
let listing = folder::list(&root);
let listing = list(&root, Limits::default());
assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]");
assert!(!listing.truncated && !listing.unreadable);
// Each script keeps the path the folder gave, whatever its label.
@@ -81,7 +81,7 @@ fn a_script_whose_label_another_row_has_shows_its_whole_file_name() {
touch(&root, name);
}
// `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name.
assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx");
assert_eq!(rows(&list(&root, Limits::default()).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx");
let _ = std::fs::remove_dir_all(dir);
}
@@ -93,7 +93,7 @@ fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut()
touch(&root, "a\u{202E}sj.js");
let long = "n".repeat(200);
touch(&root, &format!("{long}.jsx"));
let listing = folder::list(&root);
let listing = list(&root, Limits::default());
let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect();
assert_eq!(labels[0], "a\\u{202E}sj");
assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1)));
@@ -119,7 +119,7 @@ fn hidden_names_and_links_are_left_out() {
let marked = touch(&root, "marked.js");
assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success());
}
let listing = folder::list(&root);
let listing = list(&root, Limits::default());
assert_eq!(rows(&listing.entries), "shown");
assert!(!listing.truncated && !listing.unreadable);
// Nor is a file behind a link read as a listed script.
@@ -146,12 +146,12 @@ fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreada
let dir = folder("root");
let root = dir.join("Scripts");
touch(&root, "a.js");
assert_eq!(folder::list(&dir.join("None")), Listing::default());
assert_eq!(list(&dir.join("None"), Limits::default()), Listing::default());
let file = touch(&dir, "file");
assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() });
assert_eq!(list(&file, Limits::default()), Listing { unreadable: true, ..Listing::default() });
let link = dir.join("Link");
link_folder(&root, &link);
assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() });
assert_eq!(list(&link, Limits::default()), Listing { unreadable: true, ..Listing::default() });
assert!(folder::read(&link, &link.join("a.js"), 10).is_none());
let _ = std::fs::remove_dir_all(&link);
let _ = std::fs::remove_dir_all(dir);
@@ -187,7 +187,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() {
let root = dir.join("Scripts");
touch(&root, "1/2/3/4/kept.js");
touch(&root, "1/2/3/4/5/deeper.js");
let listing = folder::list(&root);
let listing = list(&root, Limits::default());
assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]");
assert!(listing.truncated);
assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js")));
@@ -199,7 +199,7 @@ fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() {
let listing = list(&root, Limits { folders: 1, ..Limits::default() });
assert_eq!(rows(&listing.entries), "a/[x]");
assert!(listing.truncated);
assert!(!folder::list(&root).truncated);
assert!(!list(&root, Limits::default()).truncated);
let _ = std::fs::remove_dir_all(dir);
let _ = std::fs::remove_dir_all(two);
}
@@ -249,6 +249,7 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() {
touch(&root, "Tidy Layers.jsx");
touch(&root, "Export/All Artboards.js");
let mut s = Session::new();
s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO));
assert_eq!(
s.execute("script.listInstalled", &json!({})).unwrap(),
json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false})
@@ -276,6 +277,22 @@ fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() {
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn list_installed_stops_when_the_sessions_clock_is_past_the_time_limit() {
let dir = folder("command-clock");
let root = dir.join("Scripts");
touch(&root, "a.jsx");
let mut s = Session::new();
s.attach_scripts_dir(root);
s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1)));
let late = s.execute("script.listInstalled", &json!({})).unwrap();
assert_eq!((&late["scripts"], &late["truncated"]), (&json!([]), &json!(true)));
s.set_script_listing_clock(folder::Clock::Fixed(folder::MAX_SCAN));
let on_time = s.execute("script.listInstalled", &json!({})).unwrap();
assert_eq!((on_time["scripts"].as_array().map(Vec::len), &on_time["truncated"]), (Some(1), &json!(false)));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn an_installed_script_is_read_as_script_run_reads_a_file() {
let dir = folder("installed");
@@ -374,6 +391,7 @@ fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() {
std::fs::create_dir_all(&work).unwrap();
let mut s = Session::new();
s.attach_scripts_dir(root.clone());
s.set_script_listing_clock(folder::Clock::Fixed(Duration::ZERO));
let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap();
let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err();
// The Scripts folder is the app's: the error keeps the root and names the folder by its name.
+1
View File
@@ -26,6 +26,7 @@ mod lossy_overwrite;
mod model_based;
mod param_keys;
mod paste_many;
mod pasted_clipping_path;
mod pen_click_after_smooth;
mod pen_endpoint_picking;
mod pen_rubber_band;
@@ -0,0 +1,66 @@
//! A copy of a clip group's clipping path pasted outside it is an ordinary path (#9227).
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_engine::Session;
fn run(s: &mut Session, command: &str, params: Value) -> Value {
s.execute(command, &params).unwrap()
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(run(s, "shape.rectangle", json!({"x": x, "y": y, "width": w, "height": h}))["id"].as_u64().unwrap())
}
fn clipping(s: &Session, id: NodeId) -> bool {
matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { clipping: true, .. })
}
/// A rectangle clipped by a smaller one, and the clipping path's id.
fn clip_group(s: &mut Session) -> NodeId {
run(s, "file.new", json!({"width": 400, "height": 400}));
let art = rect(s, 20.0, 20.0, 200.0, 200.0);
let mask = rect(s, 60.0, 60.0, 100.0, 100.0);
run(s, "select.set", json!({"ids": [art.0, mask.0]}));
run(s, "object.clippingMask.make", json!({}));
assert!(clipping(s, mask));
mask
}
#[test]
fn offset_path_offsets_a_pasted_copy_of_a_clipping_path() {
let mut s = Session::new();
let mask = clip_group(&mut s);
run(&mut s, "select.set", json!({"ids": [mask.0]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "select.none", json!({}));
let pasted = run(&mut s, "edit.pasteInPlace", json!({}));
let copy = NodeId(pasted["ids"][0].as_u64().unwrap());
assert!(!clipping(&s, copy), "the pasted copy clips nothing, so it is not a clipping path");
assert!(clipping(&s, mask), "the original still clips its group");
run(&mut s, "select.set", json!({"ids": [copy.0]}));
let out = s.execute("object.path.offsetPath", &json!({"offset": 5}));
assert!(out.is_ok(), "Offset Path refuses the pasted copy: {out:?}");
}
#[test]
fn release_makes_a_lone_clipping_path_an_ordinary_path() {
let mut s = Session::new();
run(&mut s, "file.new", json!({"width": 400, "height": 400}));
let lone = rect(&mut s, 60.0, 60.0, 100.0, 100.0);
// As a paste made one before #9227, in a document saved then: flagged, outside any clip group.
let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
if let NodeKind::Path { clipping, .. } = &mut d.node_mut(lone).unwrap().kind {
*clipping = true;
}
run(&mut s, "select.set", json!({"ids": [lone.0]}));
assert!(s.execute("object.path.offsetPath", &json!({"offset": 5})).is_err(), "the flagged path is skipped");
run(&mut s, "object.clippingMask.release", json!({}));
assert!(!clipping(&s, lone));
let out = s.execute("object.path.offsetPath", &json!({"offset": 5}));
assert!(out.is_ok(), "Offset Path refuses the released path: {out:?}");
}
+19 -1
View File
@@ -9,9 +9,11 @@
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::Duration;
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_engine::script::folder::{self, Clock};
use vectorcraft_plugins::safe_mode;
use vectorcraft_testkit::TempDir;
@@ -56,9 +58,11 @@ fn write(dir: &Path, name: &str, text: &str) -> PathBuf {
path
}
/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on.
/// A session with the Startup Scripts folder `dir` and Run Startup Scripts on, whose listings take
/// no time.
fn session(dir: &Path) -> Session {
let mut s = Session::new();
s.set_script_listing_clock(Clock::Fixed(Duration::ZERO));
s.attach_startup_scripts_dir(dir.to_path_buf());
s.execute("prefs.set", &json!({"key": "runStartupScripts", "value": true})).unwrap();
s
@@ -115,6 +119,20 @@ fn the_folders_jsx_files_run_in_name_order_at_launch_and_before_a_chosen_script(
assert_eq!(started(&s), ["a.jsx", "b.jsx", "C.JSX", "a.jsx", "b.jsx", "C.JSX", "chosen"], "the startup scripts run first");
}
#[test]
fn a_listing_stops_when_the_sessions_clock_is_past_the_time_limit() {
let _f = fresh();
let dir = tmp_dir("clock");
write(&dir, "a.jsx", "vc.log(1);");
let mut s = session(&dir);
s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN + Duration::from_millis(1)));
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!((names(&r["ran"]), &r["truncated"]), (vec![], &json!(true)));
s.set_script_listing_clock(Clock::Fixed(folder::MAX_SCAN));
let r = s.execute("script.startup.run", &json!({"reason": "launch"})).unwrap();
assert_eq!((names(&r["ran"]), &r["truncated"]), (vec!["a.jsx"], &json!(false)));
}
#[test]
fn a_missing_folder_runs_nothing_and_a_session_without_one_skips() {
let _f = fresh();
+2 -1
View File
@@ -306,7 +306,8 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
// Artboards that don't fit on the canvas are written on a large canvas, at 1/scale.
let scale = canvas_scale(doc);
// The objects that may keep their effects in an art style, as they are before baking (not on
// a large canvas, whose scale the styles' strokes and effects would need).
// a large canvas, whose scale the styles' strokes and effects would need; there only the styles
// that link type's colors to their swatches are written, which hold no lengths).
let styled = writer::styled_objects(doc);
let (symbol_styled, pattern_styled) = writer::styled_definitions(doc);
let own_styles = doc.graphic_styles != Document::new(1.0, 1.0).graphic_styles;
+115 -4
View File
@@ -5088,6 +5088,89 @@ fn kinsoku_settings_come_back_on_each_paragraph() {
assert_eq!(export_ai_editing(&lossy, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]);
}
/// Type in spot inks (CMYK, RGB and Lab) and a global process color, as its fill and as its
/// stroke, at full strength and at a tint: each color reads back linked to its swatch at its tint, with no warning, as key 5
/// of the run's paint names an art style of one paint that holds the link. A link to a process
/// swatch that isn't global still warns: the editing data can't hold it.
#[test]
fn type_in_spot_and_global_colors_reads_back_linked_at_its_tint() {
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
use vectorcraft_geom::Point;
let white = Color::cmyk(0.0, 0.0, 0.0, 0.0);
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
let mut doc = Document::new(300.0, 200.0);
doc.swatches = vec![
Swatch { name: "[None]".into(), paint: Paint::None, global: false, spot: false },
Swatch { name: "White Ink".into(), paint: solid(white), global: true, spot: true },
Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true },
Swatch { name: "Sky".into(), paint: solid(SKY), global: true, spot: true },
Swatch { name: "Mint".into(), paint: solid(MINT), global: true, spot: true },
Swatch { name: "Brand".into(), paint: solid(BRAND), global: true, spot: false },
Swatch { name: "Ink".into(), paint: solid(GOLD), global: false, spot: false },
]
.into();
doc.swatch_groups = vec![].into();
let layer = doc.layers[0].id;
let stroked = |fill: Paint, stroke: Paint| CharStyle { size: 24.0, fill, stroke, stroke_width: 1.0, ..CharStyle::default() };
let mut t = TextObject::point(Point::new(20.0, 60.0), "", style(24.0, Color::BLACK));
t.runs = vec![
TextRun::new("WHITE ", stroked(linked("White Ink", white, 1.0), Paint::None)),
TextRun::new("RED ", stroked(linked("Red Ink", red, 0.4), linked("Brand", BRAND, 0.6))),
TextRun::new("SKY ", stroked(linked("Sky", SKY, 0.75), linked("Red Ink", red, 1.0))),
TextRun::new("MINT ", stroked(linked("Mint", MINT, 0.3), Paint::None)),
TextRun::new("BRAND", stroked(linked("Brand", BRAND, 1.0), linked("White Ink", white, 0.5))),
];
let n = text_node(&mut doc, t);
doc.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let runs = |d: &Document| {
let mut all = vec![];
paths(&d.layers, &mut all);
all.iter()
.filter_map(|n| match &n.kind {
NodeKind::Text(t) => Some(t.runs.iter().map(|r| (r.text.clone(), paint(&r.style.fill), paint(&r.style.stroke))).collect::<Vec<_>>()),
_ => None,
})
.collect::<Vec<_>>()
};
assert_eq!(runs(&read_back(&doc)), runs(&doc));
let mut process = doc.clone();
let id = process.layers[0].children().unwrap()[0].id;
if let Some(NodeKind::Text(t)) = process.node_mut(id).map(|n| &mut n.kind) {
t.runs[0].style.fill = linked("Ink", GOLD, 1.0);
}
assert_eq!(export_ai_editing(&process, &opts()).unwrap().warnings, [writer::TYPE_ATTRIBUTES]);
}
/// Type whose story isn't written (a thread the text document can't hold, written as outlines)
/// leaves no art style for its colors behind.
#[test]
fn type_written_as_outlines_leaves_no_style_for_its_colors() {
use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun};
use vectorcraft_geom::Point;
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
let mut doc = Document::new(300.0, 200.0);
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
swatches.push(Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true });
doc.swatches = swatches.into();
let inked = CharStyle { size: 12.0, fill: linked("Red Ink", red, 1.0), ..CharStyle::default() };
let mut first = TextObject::point(Point::ZERO, "A story in a spot ink that runs on.", inked.clone());
first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 120.0, 60.0)) };
first.xf = Affine::IDENTITY;
// Point type can't be a frame of a thread: the text document doesn't hold the thread.
let mut second = TextObject::point(Point::new(20.0, 120.0), "", inked.clone());
second.runs = vec![TextRun::new("", inked)];
let (first, second) = (text_node(&mut doc, first), text_node(&mut doc, second));
doc.text_threads.push(vec![first.id, second.id]);
let layer = doc.layers[0].id;
doc.insert(Some(layer), usize::MAX, first).unwrap();
doc.insert(Some(layer), usize::MAX, second).unwrap();
let text = program(&doc);
assert!(!text.contains("%AI11_BeginTextDocument"), "the thread was written as type");
assert!(!text.contains("/SimpleStyle"), "{text}");
}
#[test]
fn type_is_written_again_as_the_same_bytes() {
let doc = typed();
@@ -8122,11 +8205,12 @@ fn a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws() {
assert!(apart <= 4, "{apart} pixels differ");
}
/// On a large canvas no art style is written (the reader scales the styles of a large canvas):
/// objects with effects are written as their vector art with their geometry effects applied, with a
/// warning.
/// On a large canvas no art style of an object is written (the reader scales the styles of a large
/// canvas): objects with effects are written as their vector art with their geometry effects
/// applied, with a warning. Type's colors keep their swatch links there: their styles hold no
/// lengths.
#[test]
fn a_large_canvas_writes_no_art_styles() {
fn a_large_canvas_writes_only_the_art_styles_of_type_colors() {
let mut doc = Document::new(20000.0, 100.0);
let n = styled_rect(
&mut doc,
@@ -8141,6 +8225,33 @@ fn a_large_canvas_writes_no_art_styles() {
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::LARGE_CANVAS_STYLES), "{:?}", out.warnings);
assert!(!String::from_utf8(out.program).unwrap().contains("ArtStyle"));
let mut typed = Document::new(20000.0, 100.0);
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
let mut swatches: Vec<Swatch> = typed.swatches.iter().cloned().collect();
swatches.push(Swatch { name: "Red Ink".into(), paint: solid(red), global: true, spot: true });
typed.swatches = swatches.into();
let fill = linked("Red Ink", red, 0.4);
let t = vectorcraft_doc::TextObject::point(
vectorcraft_geom::Point::new(20.0, 60.0),
"FAR",
vectorcraft_doc::CharStyle { size: 24.0, fill: fill.clone(), ..vectorcraft_doc::CharStyle::default() },
);
let n = text_node(&mut typed, t);
let layer = typed.layers[0].id;
typed.insert(Some(layer), usize::MAX, n).unwrap();
let out = export_ai_editing(&typed, &opts()).unwrap();
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
let mut all = vec![];
paths(&read_back(&typed).layers, &mut all);
let fills: Vec<String> = all
.iter()
.filter_map(|n| match &n.kind {
NodeKind::Text(t) => Some(paint(&t.runs[0].style.fill)),
_ => None,
})
.collect();
assert_eq!(fills, [paint(&fill)]);
}
#[test]
+12
View File
@@ -1623,6 +1623,18 @@ impl<'a> Writer<'a> {
if !self.take_objects(stub) {
return;
}
// The art styles that hold the swatch links of its colors, its thread's too.
let members: Vec<&vectorcraft_doc::TextObject> = match thread {
Some(thread) => thread
.iter()
.filter_map(|id| match &doc.node(*id)?.kind {
NodeKind::Text(t) => Some(t.as_ref()),
_ => None,
})
.collect(),
None => vec![t],
};
self.link_type_colors(&members);
let placed = if let Some(thread) = thread {
// A thread is checked for what it loses, in every frame, when its story is written.
let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held);
+38 -3
View File
@@ -20,7 +20,7 @@ use super::{Writer, Xy, blend_code, compound_path, hide};
use crate::ai_ops;
use crate::ps;
pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no art styles or graphic styles are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps";
pub(in crate::ai_editing) const LARGE_CANVAS_STYLES: &str = "on a large canvas, no graphic styles and no art styles of objects are written: objects with live effects are written with their geometry effects applied to the artwork, where they can no longer be edited, and their other effects are left out of the editing data for other apps";
pub(in crate::ai_editing) const PANEL_STYLES: &str = "graphic styles with gradient or pattern fills, with fills, strokes or effects the editing data can't hold as a graphic style, with a name another style has, with names over 1,024 bytes, or past 4,096 styles, are left out of the editing data for other apps";
pub(in crate::ai_editing) const PANEL_EMPTY: &str =
"a Graphic Styles panel with no style written opens from the editing data with a new document's styles";
@@ -173,6 +173,9 @@ pub(in crate::ai_editing) struct Styles {
next_anon: u64,
/// How many objects were written with the graphic style they are linked to.
pub(super) links_written: usize,
/// The styles that only link type's colors to their swatches ([`Writer::type_color_style`]):
/// written only when the text document names them.
type_colors: HashSet<String>,
/// The style texts checked so far, as the reader parses them.
pub(super) parsed: Parsed,
}
@@ -335,6 +338,33 @@ impl Writer<'_> {
std::mem::replace(&mut self.body, saved)
}
/// Look at the swatch links of the colors of type `texts` ([`super::texts::TextDoc::set_link`]):
/// each is held by an art style of one paint, its color with its swatch at its tint, which key 5
/// of a run's paint names ([`Self::type_color_style`]), or by none.
pub(super) fn link_type_colors(&mut self, texts: &[&vectorcraft_doc::TextObject]) {
for p in self.texts.unlooked_links(texts) {
let style = self.type_color_style(p);
self.texts.set_link(p, style);
}
}
/// The name of the art style that holds the swatch link of type colored `p`: a style of one
/// paint, its fill alone on (`0 1 Xd`), whose paint is `p` as a path's fill writes it (a spot or
/// global process color by its name and tint, Registration). The reader gives type whose paint
/// names that style the style's color at its tint, linked to its swatch
/// ([`crate::import::parsed_type_color`]); `None`, and no style, when it wouldn't give the same
/// swatch and tint (a swatch that is neither spot nor global, for one).
fn type_color_style(&mut self, p: &Paint) -> Option<String> {
let Paint::Solid { swatch: Some(name), tint, .. } = p else { return None };
let ops = self.color_ops(p, false);
let text = format!("/SimpleStyle :\n0 O\n{ops}0 1 0 0 0 Xy\n{NO_LINE}0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n");
let back = self.styles.parsed.get(&text).and_then(crate::import::parsed_type_color);
let same = matches!(back, Some(Paint::Solid { swatch: Some(n), tint: t, .. }) if n == name && (t - tint).abs() <= 1e-4);
let name = same.then(|| self.styles.object_style(text))?;
self.styles.type_colors.insert(name.clone());
Some(name)
}
/// A fill style holding a color, as an effect's entry `key` or a fill's own.
fn fill_style(&mut self, s: &mut String, color: vectorcraft_color::Color, key: &str) {
let ops = self.color_ops(&Paint::solid(color), false);
@@ -929,12 +959,17 @@ impl Writer<'_> {
/// The art styles written, in a non-printing block: `%AI9_BeginArtStyles`, each style,
/// `%AI9_EndArtStyles`.
/// A style that only links type's colors is written when the text document names it: type
/// whose story isn't written (written as its outlines instead) leaves none behind.
pub(in crate::ai_editing) fn art_styles(&self, s: &mut String) {
if self.styles.known.is_empty() {
let named = self.texts.named_styles();
let written: Vec<&(String, String)> =
self.styles.known.iter().filter(|(name, _)| !self.styles.type_colors.contains(name) || named.contains(name.as_str())).collect();
if written.is_empty() {
return;
}
s.push_str("%AI5_Begin_NonPrinting\nNp\n%AI9_BeginArtStyles\n");
for (name, text) in &self.styles.known {
for (name, text) in written {
s.push_str(&known_style(name, text));
}
s.push_str("%AI9_EndArtStyles\n%AI5_End_NonPrinting--\n");
+85 -14
View File
@@ -31,7 +31,7 @@ use vectorcraft_geom::{Affine, PathData, Point};
use crate::{ai_ops, ps};
/// What the text document holds of type, and what it leaves out.
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
pub(in crate::ai_editing) const TYPE_ATTRIBUTES: &str = "attributes of type other than its font, size, leading, tracking, baseline shift, horizontal and vertical scale, solid fill, solid stroke and its weight, cap, join and miter limit, capitals, small capitals at the document's size, Tate-chu-yoko, Standard Vertical Roman Alignment, Insert Aki, paragraph alignment, indents, space before and after, hyphenation on or off, right-to-left direction, Kinsoku set, Kinsoku Shori Type, Burasagari and Bunri-Kinshi (for example underline, kerning, OpenType features, swatch links of its colors other than to spot colors, global process colors and Registration, character and paragraph styles, tabs, lists, optical margin alignment, area type's inset spacing, vertical alignment and flow, a minimum first baseline with the Ascent first baseline, and type on a path's effect, alignment and spacing and an end bracket at the very end of an open path) are left out of the editing data for other apps";
/// The version of the text document's form (`/98 << /0 n >>`), as the newest files users sent have it.
const STREAM_VERSION: u32 = 14;
@@ -177,15 +177,32 @@ fn set(resources: Vec<V>, display: bool) -> V {
/// A paint: kind 0 gray (`[alpha, lightness]`), 1 RGB, 2 CMYK, as the reader's `paint` reads them.
/// RGB values are an RGB color's own (in the working RGB space) and a Lab color's converted into
/// the working RGB space ([`ai_ops::rgb_values`]).
fn paint(c: &Color) -> V {
/// the working RGB space ([`ai_ops::rgb_values`]). With `style`, the art style that links the color
/// to its swatch (key 5, [`TextDoc::link`]): the reader takes the style's color, at its tint, in
/// place of these values.
fn paint(c: &Color, style: Option<&str>) -> V {
let (kind, values) = match *c {
Color::Gray { k } => (0, vec![1.0 - f64::from(k.clamp(0.0, 1.0))]),
Color::Cmyk { c, m, y, k } => (2, [c, m, y, k].iter().map(|v| f64::from(v.clamp(0.0, 1.0))).collect()),
Color::Rgb { .. } | Color::Lab { .. } => (1, ai_ops::rgb_values(*c).iter().map(|v| f64::from(*v)).collect()),
};
let values: Vec<f64> = std::iter::once(1.0).chain(values).collect();
dict(vec![(99, V::Name("SimplePaint")), (0, dict(vec![(0, V::Int(kind)), (1, reals(&values))]))])
let color = dict(vec![(0, V::Int(kind)), (1, reals(&values))]);
match style {
Some(name) => dict(vec![(99, V::Name("CAITextPaint")), (5, V::Str(name.to_owned())), (0, color)]),
None => dict(vec![(99, V::Name("SimplePaint")), (0, color)]),
}
}
/// A color linked to a swatch, by the swatch's name and its tint ([`TextDoc::links`]).
pub(in crate::ai_editing) type LinkKey = (String, u32);
/// The swatch and tint paint `p` is linked to, if it is.
pub(in crate::ai_editing) fn link_key(p: &Paint) -> Option<LinkKey> {
match p {
Paint::Solid { swatch: Some(name), tint, .. } => Some((name.clone(), tint.to_bits())),
_ => None,
}
}
/// The color of paint `p` when the text document can hold it (a solid color or none).
@@ -447,14 +464,16 @@ fn held_aki(v: f64) -> f64 {
/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? `fonts` holds the
/// fonts already resolved.
fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool {
fn loses(t: &TextObject, fonts: &mut ResolvedFonts, links: &HashMap<LinkKey, Option<String>>) -> bool {
// Small capitals are read back at Document Setup's default size.
let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size;
// Is paint `p` held with its swatch link, by an art style ([`TextDoc::link`])?
let linked = |p: &Paint| link_key(p).is_some_and(|k| matches!(links.get(&k), Some(Some(_))));
// A run's style as the text document holds it: every other attribute at its default. A color
// is held without its swatch link.
// is held without its swatch link, unless an art style holds the link.
let held_char = |s: &CharStyle| {
let unlinked = |p: &Paint| match p {
Paint::Solid { color, .. } => Paint::solid(*color),
Paint::Solid { color, .. } if !linked(p) => Paint::solid(*color),
other => other.clone(),
};
let stroked = !s.stroke.is_none();
@@ -500,8 +519,8 @@ fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool {
..s.clone()
}
};
// A Lab color is written as RGB.
let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. });
// A Lab color is written as RGB, unless an art style holds it with its link.
let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }) && !linked(p);
s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !fonts.kept(&s)
};
// A paragraph's style as the text document holds it, and its text: aligned to the start of
@@ -842,6 +861,10 @@ pub(in crate::ai_editing) struct TextDoc {
doc_values: usize,
/// The fonts of the styles written so far, as they resolve.
resolved: ResolvedFonts,
/// The swatch links of type's colors looked at so far, by swatch and tint: the art style that
/// holds each (a style of one paint, the color with its swatch, which key 5 of a run's paint
/// names), `None` when the editing data can't hold it ([`super::Writer::link_type_colors`]).
links: HashMap<LinkKey, Option<String>>,
}
impl TextDoc {
@@ -851,7 +874,53 @@ impl TextDoc {
/// Has type `t` attributes the text document leaves out ([`loses`])?
pub(in crate::ai_editing) fn loses(&mut self, t: &TextObject) -> bool {
loses(t, &mut self.resolved)
loses(t, &mut self.resolved, &self.links)
}
/// The colors of type whose swatch links are still to be looked at: the fills and strokes of
/// `texts`' runs that are linked to a swatch and not in [`Self::links`] yet, each once.
pub(in crate::ai_editing) fn unlooked_links<'t>(&self, texts: &[&'t TextObject]) -> Vec<&'t Paint> {
let mut seen = HashSet::new();
texts
.iter()
.flat_map(|t| t.runs.iter().flat_map(|r| [&r.style.fill, &r.style.stroke]))
.filter(|p| link_key(p).is_some_and(|k| !self.links.contains_key(&k) && seen.insert(k)))
.collect()
}
/// Record the art style `style` that holds the swatch link of colors linked as `p` is, or
/// `None` when none does ([`Self::links`]).
pub(in crate::ai_editing) fn set_link(&mut self, p: &Paint, style: Option<String>) {
if let Some(k) = link_key(p) {
self.links.insert(k, style);
}
}
/// The art styles the stories written name for their runs' colors (key 5 of a paint).
pub(in crate::ai_editing) fn named_styles(&self) -> HashSet<&str> {
fn walk<'v>(v: &'v V, out: &mut HashSet<&'v str>) {
match v {
V::Dict(d) => {
if d.iter().any(|(k, v)| *k == 99 && matches!(v, V::Name("CAITextPaint"))) {
out.extend(d.iter().filter_map(|(k, v)| match (k, v) {
(5, V::Str(s)) => Some(s.as_str()),
_ => None,
}));
}
d.iter().for_each(|(_, v)| walk(v, out));
}
V::List(l) => l.iter().for_each(|v| walk(v, out)),
_ => {}
}
}
let mut out = HashSet::new();
self.stories.iter().for_each(|v| walk(v, &mut out));
out
}
/// The art style that holds the swatch link of `p`, if one does.
fn link(&self, p: &Paint) -> Option<&str> {
self.links.get(&link_key(p)?)?.as_deref()
}
/// The index of the font of `st` in the font set.
@@ -909,11 +978,13 @@ impl TextDoc {
let fill = solid(&st.fill).flatten();
// A stroke of no width keeps its paint.
let stroke = solid(&st.stroke).flatten();
// A color linked to a swatch names the art style that holds the link, the fill's for a
// stroke too (the reader's `Texts::with_paints`).
if let Some(c) = &fill {
d.push((53, paint(c)));
d.push((53, paint(c, self.link(&st.fill))));
}
if let Some(c) = &stroke {
d.push((54, paint(c)));
d.push((54, paint(c, self.link(&st.stroke))));
}
d.extend([(56, V::Bool(fill.is_some())), (57, V::Bool(stroke.is_some()))]);
if stroke.is_some() {
@@ -1243,7 +1314,7 @@ impl TextDoc {
if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) {
return None;
}
let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved));
let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved, &self.links));
let frames: Vec<usize> = texts.iter().map(|t| self.frame(t, canvas, scale)).collect();
let story = self.story(&whole, &frames, scale);
if !self.fits(mark) {
@@ -1357,7 +1428,7 @@ impl TextDoc {
(12, V::Int(0)),
// Every run writes its own key 35, so this only sets where new type starts: Standard (1).
(35, V::Int(1)),
(53, paint(&Color::gray(1.0))),
(53, paint(&Color::gray(1.0), None)),
(56, V::Bool(true)),
(57, V::Bool(false)),
(63, real(1.0)),
+1 -1
View File
@@ -98,7 +98,7 @@ pub(crate) use ai::{
BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS,
MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, ParsedStyle,
blend_reads, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, parse_art_style, parsed_moves_with,
read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number,
parsed_type_color, read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number,
};
pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version};
pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from};
+2 -2
View File
@@ -60,8 +60,8 @@ pub use read::read;
#[cfg(test)]
pub(crate) use read::with_image_limits;
pub(crate) use read::{
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, read_over_page,
read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color,
read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
};
pub use read::{
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
+6 -5
View File
@@ -155,7 +155,7 @@ pub use document::{
};
pub(crate) use document::{slot_frame, slot_of};
use graph::Graph;
pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, read_parsed_style, read_style_list};
pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_type_color, read_parsed_style, read_style_list};
#[cfg(test)]
pub(crate) use raster::with_image_limits;
pub(crate) use types::BLEND_BUDGET;
@@ -219,10 +219,11 @@ pub struct Structure {
pub warped_type: super::envelope::WarpedType,
/// The document's graphic styles are those of the file's style list, in place of the defaults.
pub styles_read: bool,
/// The patterns that paint the text document's characters, placed in the document, by the
/// name of the art style that gives each: the styles that are one paint, a pattern this read
/// (see `ate::Texts::with_patterns`).
pub text_patterns: HashMap<String, Paint>,
/// The paints the text document's characters take in place of their own colors, by the name
/// of the art style that gives each: the styles that are one paint, a pattern this read,
/// placed in the document, or a color linked to its swatch at its tint (see
/// `ate::Texts::with_paints`).
pub text_paints: HashMap<String, Paint>,
/// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not.
pub canvas_scale: f64,
/// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its
+28 -6
View File
@@ -1065,7 +1065,7 @@ impl<'a> Reader<'a> {
/// whose name another swatch has, take the first free "Name 2", "Name 3"…
/// ([`Document::free_swatch_name`]) once the other colors and the patterns have their swatches;
/// a pattern a swatch already paints with gets no other.
fn file_swatches(&self, doc: &mut Document, own_palette: bool) -> HashMap<String, String> {
fn file_swatches(&self, doc: &mut Document, own_palette: bool, type_colors: &[super::Named]) -> HashMap<String, String> {
let mut defined = std::collections::HashSet::new();
let mut clashes = vec![];
// The swatch names there are, looked up rather than scanned for each name a file defines
@@ -1075,7 +1075,8 @@ impl<'a> Reader<'a> {
// The names a swatch of another kind than a gradient or pattern has.
let mut solid: std::collections::HashSet<String> =
doc.swatches_iter().filter(|s| !matches!(s.paint, Paint::Gradient(_) | Paint::Pattern { .. })).map(|s| s.name.clone()).collect();
let colors = self.spots.iter().chain(&self.stop_spots).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true)));
let colors =
self.spots.iter().chain(&self.stop_spots).chain(type_colors).map(|n| (n, n.spot)).chain(self.custom_colors.iter().map(|n| (n, true)));
for (n, spot) in colors {
let first = defined.insert(n.name.clone());
let swatch = Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot };
@@ -1327,7 +1328,26 @@ impl<'a> Reader<'a> {
}
None => false,
};
let renamed = self.file_swatches(&mut doc, own_palette);
// The swatch colors of the styles that are one paint, which the text document's characters
// name for their fills and strokes, in the order of the styles' names.
let mut type_colors: Vec<(&String, &(Paint, Option<super::Named>))> =
self.styles.iter().filter_map(|(style, st)| Some((style, st.simple_color.as_ref()?))).collect();
type_colors.sort_by_key(|(style, _)| *style);
let type_named: Vec<super::Named> = type_colors.iter().filter_map(|(_, (_, named))| named.clone()).collect();
let renamed = self.file_swatches(&mut doc, own_palette, &type_named);
let type_colors: Vec<(String, Paint)> = type_colors
.into_iter()
.map(|(style, (paint, _))| {
let mut paint = paint.clone();
// A color that took a free name is linked by that name.
if let Paint::Solid { swatch: Some(link), .. } = &mut paint
&& let Some(new) = renamed.get(link.as_str())
{
link.clone_from(new);
}
(style.clone(), paint)
})
.collect();
if let Some(author) = self.author.take() {
doc.metadata.author = author;
}
@@ -1394,8 +1414,9 @@ impl<'a> Reader<'a> {
}
warnings.extend(self.names.notes());
// The patterns of the styles that are one paint, which the text document's characters
// name for their fills and strokes: those that place in the document.
let text_patterns = self
// name for their fills and strokes: those that place in the document. With them, those
// styles' swatch colors.
let text_paints = self
.styles
.iter()
.filter_map(|(style, st)| {
@@ -1403,6 +1424,7 @@ impl<'a> Reader<'a> {
let paint = super::ops::style_pattern(name, *matrix, controls, &self.pattern_tiles, &self.v7_patterns, &self.global_names, to_doc)?;
Some((style.clone(), paint))
})
.chain(type_colors)
.collect();
Ok(Structure {
doc,
@@ -1430,7 +1452,7 @@ impl<'a> Reader<'a> {
type_clips: self.type_clips,
},
styles_read,
text_patterns,
text_paints,
canvas_scale: self.canvas_scale,
symbols_own_size: self.symbols_own_size,
xml_ids: self.xml_ids,
+8
View File
@@ -1763,6 +1763,14 @@ pub(crate) fn parse_art_style(section: &[u8], name: &str) -> Option<ParsedStyle>
crate::import::ai::style::art_styles(section).remove(name).map(|style| ParsedStyle { style })
}
/// The color type takes from art style `parsed` when a character's fill or stroke names it (key 5
/// of its paint, `ate`): a style of one paint whose paint is a color with a swatch, at its tint and
/// linked to that swatch ([`crate::import::ai::style::ArtStyle::simple_color`]). `None` for any
/// other style.
pub(crate) fn parsed_type_color(parsed: &ParsedStyle) -> Option<&Paint> {
parsed.style.simple_color.as_ref().map(|(paint, _)| paint)
}
/// Art style `parsed` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], with a
/// style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads it on
/// objects other than type. A stroke that names a brush is read with that brush's name, as [`styled`]
+49 -17
View File
@@ -215,6 +215,13 @@ pub(super) struct ArtStyle {
/// paint is a pattern: its [`StyleItem::Pattern`]. A text document's characters name such
/// styles for their fills and strokes (`ate`). `None` for any other paint or style.
pub simple_pattern: Option<StyleItem>,
/// A style that is one paint, when that paint is a colour with a swatch (a spot ink or a
/// global process colour, `x`, `Xx`, `Xk`; Registration): the paint at its tint, linked to the
/// swatch, with the named colour that makes the swatch (none for Registration). Only when the
/// style's fill alone is on (`0 1 Xd`) and it sets no stroke colour or pattern, before or after. A text
/// document's characters name such styles for their fills and strokes (`ate`), and keep only
/// the colour's process values themselves. `None` for any other paint or style.
pub simple_color: Option<(Paint, Option<paint::Named>)>,
/// A style that is one paint: its fill and stroke, bottom first, each there when its
/// `stroke fill Xd` turns it on (none when neither is on). `Err` when it turns on a fill or
/// stroke whose paint isn't read here (a gradient that names no swatch or isn't in a gradient
@@ -477,16 +484,20 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap<String, A
let mut open: Vec<usize> = vec![];
let mut pending: Option<bool> = None;
let mut in_basic = false;
// A style that is one paint being read, and its pattern so far.
let mut simple: Option<Option<StyleItem>> = None;
// A style that is one paint being read, and its pattern or swatch colour so far.
let mut simple: Option<SimplePaint> = None;
// The same style's paint operators so far.
let mut one_paint: Option<OnePaint> = None;
let mut finish = |name: Option<String>, filters: &mut Vec<Filter>, simple_pattern: Option<StyleItem>, one_paint: Option<OnePaint>| {
let mut finish = |name: Option<String>, filters: &mut Vec<Filter>, simple: SimplePaint, one_paint: Option<OnePaint>| {
if let Some(name) = name {
// Only a style that is one paint holds a pattern for type: one with filters as well
// paints with more than that.
let simple_pattern = simple_pattern.filter(|_| filters.is_empty());
let mut st = ArtStyle { simple_pattern, ..style(filters) };
// Only a style that is one paint holds a pattern or a swatch colour for type: one with
// filters as well paints with more than that.
let SimplePaint { pattern, color, stroke_painted } = if filters.is_empty() { simple } else { SimplePaint::default() };
// The colour is the style's one paint: only its fill is on (`0 1 Xd`) and nothing sets a
// stroke's colour or pattern.
let filled = one_paint.as_ref().is_some_and(|one| one.xd && one.paint.paints == (false, true));
let color = color.filter(|_| filled && !stroke_painted);
let mut st = ArtStyle { simple_pattern: pattern, simple_color: color, ..style(filters) };
if let Some(one) = one_paint.filter(|_| filters.is_empty()) {
if let Some((mode, opacity)) = one.paint.xy {
let (isolate, knockout) = one.paint.xy_group.unwrap_or((false, Knockout::Off));
@@ -531,12 +542,12 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap<String, A
}
Tok::Name(n) => match n {
b"KnownStyle" => {
finish(name.take(), &mut filters, simple.take().flatten(), one_paint.take());
finish(name.take(), &mut filters, simple.take().unwrap_or_default(), one_paint.take());
operands.clear();
open.clear();
(pending, in_basic, style_entry, other_entry) = (None, false, None, None);
}
b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(None), Some(OnePaint::default())),
b"SimpleStyle" if filters.is_empty() => (simple, one_paint) = (Some(SimplePaint::default()), Some(OnePaint::default())),
b"FillStyle" => style_entry = Some(Kind::Fill),
b"StrokeStyle" | b"BlendStyle" => style_entry = Some(Kind::Other),
b"Name" if name.is_none() && filters.is_empty() => name = operands.iter().rev().find_map(|v| names.text(v)),
@@ -653,7 +664,7 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap<String, A
operands.clear();
}
}
finish(name, &mut filters, simple.take().flatten(), one_paint.take());
finish(name, &mut filters, simple.take().unwrap_or_default(), one_paint.take());
styles
}
@@ -814,7 +825,7 @@ fn pattern_operands(vals: &[V], names: &mut Names) -> Option<(String, Option<[f6
/// that is one paint (`simple` and `one_paint`, while one is read).
fn style_paint_op(
filters: &mut [Filter],
simple: &mut Option<Option<StyleItem>>,
simple: &mut Option<SimplePaint>,
one_paint: &mut Option<OnePaint>,
op: &str,
vals: &[V],
@@ -937,14 +948,35 @@ impl OnePaint {
}
}
/// What type takes from a style that is one paint ([`ArtStyle::simple_pattern`],
/// [`ArtStyle::simple_color`]): one of them at most.
#[derive(Default)]
struct SimplePaint {
pattern: Option<StyleItem>,
color: Option<(Paint, Option<paint::Named>)>,
/// A stroke's colour or pattern was set, before or after the fill's: the style isn't one
/// colour, so it holds none for type (its pattern is kept as before).
stroke_painted: bool,
}
/// A paint operator of a style that is one paint: a pattern (`p`) is kept as its
/// [`StyleItem::Pattern`], and any other paint after it (a colour, a stroke's pattern or a
/// gradient) leaves the style without one.
fn simple_paint_op(paint: &mut Option<StyleItem>, op: &str, vals: &[V], names: &mut Names) {
/// [`StyleItem::Pattern`] and a fill colour that has a swatch as its paint and named colour. Any
/// other paint after one of them (a colour, a stroke's colour or pattern, a gradient) leaves the
/// style without it, and a stroke's colour or pattern anywhere is remembered
/// ([`SimplePaint::stroke_painted`]).
fn simple_paint_op(simple: &mut SimplePaint, op: &str, vals: &[V], names: &mut Names) {
let stroke_painted = simple.stroke_painted;
match op {
"p" => *paint = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls }),
"Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "xa" | "xx" | "xk" | "xs"
| "xz" | "P" | "Bg" => *paint = None,
"p" => {
let pattern = pattern_operands(vals, names).map(|(name, matrix, controls)| StyleItem::Pattern { name, matrix, controls });
*simple = SimplePaint { pattern, color: None, stroke_painted };
}
"Xa" | "k" | "g" | "x" | "Xx" | "Xk" | "Xs" | "Xz" | "xa" | "xx" | "xk" | "xs" | "xz" => {
let color = paint::color_op_in(op, vals, names).filter(|(p, _)| matches!(p, Paint::Solid { swatch: Some(_), .. }));
*simple = SimplePaint { pattern: None, color, stroke_painted };
}
"XA" | "K" | "G" | "X" | "XX" | "XK" | "XS" | "XZ" | "P" => *simple = SimplePaint { stroke_painted: true, ..SimplePaint::default() },
"Bg" => *simple = SimplePaint { stroke_painted, ..SimplePaint::default() },
_ => {}
}
}
+48
View File
@@ -1548,6 +1548,54 @@ fn only_a_style_of_one_pattern_paint_holds_a_pattern_for_type() {
}
}
/// A style that is one paint holds a swatch colour for type when its paint is a fill colour with a
/// swatch: the paint at its tint and the named colour that makes the swatch. A process colour,
/// another paint after the colour, a stroke's colour before it, a fill that is off, or filters
/// beside it give none.
#[test]
fn only_a_style_of_one_swatch_colour_holds_it_for_type() {
let painted = |paint: &str, xd: &str| format!("/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n{xd}/Paint ;\n");
let simple = |paint: &str| painted(paint, "0 1 Xd\n");
let active = "/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n1 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\
/FillStyle : 0 O\n1 0 0 0 k\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n;\n";
let color = |body: &str| {
let styles = art_styles_in(format!("/KnownStyle :\n(S) /Name ,\n{body} /Def ;\n").as_bytes(), &mut Names::default());
styles.get("S").and_then(|s| s.simple_color.clone())
};
let red = Color::cmyk(0.0, 1.0, 1.0, 0.0);
let ink = "0 1 1 0 (Red Ink) 0.25 x";
let linked = Paint::Solid { color: red.tinted(0.75), swatch: Some("Red Ink".into()), tint: 0.75 };
let named = |spot: bool| paint::Named { name: "Red Ink".into(), color: red, tint: 0.75, spot };
assert_eq!(color(&simple(ink)), Some((linked.clone(), Some(named(true)))));
// A global process colour is no ink of its own.
assert_eq!(color(&simple("0 1 1 0 (Red Ink) 0.25 0 Xk")), Some((linked, Some(named(false)))));
// Registration has the built-in swatch.
let registration = color(&simple("1 1 1 1 ([Registration]) 0 Xs"));
assert!(matches!(&registration, Some((p, None)) if p.is_registration()), "{registration:?}");
let dots = "(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p";
for body in [
simple("0 1 1 0 k"),
simple(&format!("{ink}\n{dots}")),
simple(&format!("{ink}\n0 0 0 1 K")),
simple(&format!("{ink}\n0 1 1 0 k")),
// The order of the paints doesn't matter: a stroke's colour before the fill's.
simple(&format!("0 0 0 1 K\n{ink}")),
simple(&format!("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] P\n{ink}")),
// The fill is off, both are off, the stroke is on too, or nothing says which is on.
painted(ink, "1 0 Xd\n"),
painted(ink, "0 0 Xd\n"),
painted(ink, "1 1 Xd\n"),
painted(ink, ""),
format!("{}{active}", simple(ink)),
format!("{active}{}", simple(ink)),
] {
assert_eq!(color(&body), None, "{body}");
}
// The last fill colour is the style's.
assert!(color(&simple(&format!("{dots}\n{ink}"))).is_some());
}
/// A style that is one paint reads as the fill and stroke its `Xd` turns on, in the paint's colors
/// and the stroke's style; one that turns on a paint not read here, or has no `Xd`, isn't read.
#[test]
+77 -50
View File
@@ -527,11 +527,11 @@ struct Style {
v_scale: f64,
fill: Option<Color>,
stroke: Option<Color>,
/// The pattern that paints the fill or the stroke in place of its colour: the one the art
/// style named by key 5 of its paint gives ([`Texts::with_patterns`]), placed in the document.
/// `None` for any other paint, which keeps its colour.
fill_pattern: Option<Paint>,
stroke_pattern: Option<Paint>,
/// The paint of the fill or the stroke in place of its colour: the one the art style named by
/// key 5 of its paint gives ([`Texts::with_paints`]), a pattern placed in the document or a
/// colour linked to its swatch. `None` for any other paint, which keeps its colour.
fill_paint: Option<Paint>,
stroke_paint: Option<Paint>,
stroke_width: f64,
/// Key 61, the stroke's cap: 0 butt, 1 round, 2 projecting (square).
stroke_cap: LineCap,
@@ -613,24 +613,30 @@ pub(super) struct Texts {
/// attributes (key 5) and the paragraph style it is based on (key 6, an index into these).
para_sheets: Vec<Val>,
frames: Vec<Val>,
/// The patterns that paint characters, by the name of the art style that gives each
/// ([`Self::with_patterns`]).
patterns: HashMap<String, Paint>,
/// The paints characters take in place of their colours, by the name of the art style that
/// gives each ([`Self::with_paints`]).
paints: HashMap<String, Paint>,
/// The document's Kinsoku sets (key 4 of its resources), in order, each by its name (key 0):
/// Hard or Soft, `None` for any other set.
kinsoku_sets: Vec<Option<Kinsoku>>,
}
impl Texts {
/// The text document with its characters painted by `patterns`: the patterns of the editing
/// data's art styles that paint with one, each placed in the document, by the style's name.
/// A run's fill or stroke (key 53 or 54) is a paint whose key 0 is a colour and whose key 5
/// names the art style that paints it. In users' files (used locally, never committed), such a
/// style is one paint: a colour, which key 0 already has, or a pattern, whose key 0 is black
/// (`/0 0 /1 [ 1 0 ]`). The pattern's matrix is in art space, as a path's pattern fill has it:
/// the files' own pages tile the type with the matrix a path's fill would get there.
pub(super) fn with_patterns(self, patterns: HashMap<String, Paint>) -> Texts {
Texts { patterns, ..self }
/// The text document with its characters painted by `paints`: the paints of the editing data's
/// art styles that are one paint, a pattern placed in the document or a colour linked to its
/// swatch, by the style's name. A run's fill or stroke (key 53 or 54) is a paint whose key 0
/// is a colour (grey, RGB or CMYK) and whose key 5 names the art style that paints it. In
/// users' files (used locally, never committed), such a style is one paint, always its fill's,
/// for a run's stroke too:
/// - a process colour, which key 0 already has;
/// - a spot ink or a global process colour at a tint (`c m y k (name) tint x`, `Xx`, `Xk`),
/// whose process values at that tint are all key 0 keeps: the name and the tint are only in
/// the style, so the type keeps its ink only when it takes the style's paint;
/// - a pattern, whose key 0 is black (`/0 0 /1 [ 1 0 ]`). Its matrix is in art space, as a
/// path's pattern fill has it: the files' own pages tile the type with the matrix a path's
/// fill would get there.
pub(super) fn with_paints(self, paints: HashMap<String, Paint>) -> Texts {
Texts { paints, ..self }
}
/// The text document in the editing copy `data`, if it has one that can be read.
@@ -699,7 +705,7 @@ impl Texts {
char_sheets,
para_sheets,
frames: doc.take("0")?.take("8")?.take("0")?.into_list(),
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets,
})
}
@@ -939,8 +945,8 @@ impl Texts {
let on = |k: &str| !matches!(pick(k), Some(Val::Bool(false)));
let font = num("0").and_then(|i| self.fonts.get(i as usize)).filter(|f| !f.name.is_empty());
let size = num("1").filter(|v| *v > 0.0 && *v < 1e5).unwrap_or(12.0);
// Key 5 of a paint names the art style that paints it ([`Self::with_patterns`]).
let pattern = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.patterns.get(name)).cloned();
// Key 5 of a paint names the art style that paints it ([`Self::with_paints`]).
let styled = |k: &str| pick(k).and_then(|p| p.get("5")).and_then(Val::str).and_then(|name| self.paints.get(name)).cloned();
Style {
font: font.map(|f| f.font().clone()),
size,
@@ -951,8 +957,8 @@ impl Texts {
v_scale: num("7").filter(|v| *v > 0.0 && *v < 100.0).unwrap_or(1.0),
fill: if on("56") { Some(pick("53").and_then(paint).unwrap_or(Color::BLACK)) } else { None },
stroke: if matches!(pick("57"), Some(Val::Bool(true))) { pick("54").and_then(paint) } else { None },
fill_pattern: pattern("53"),
stroke_pattern: pattern("54"),
fill_paint: styled("53"),
stroke_paint: styled("54"),
stroke_width: num("63").filter(|v| *v >= 0.0 && *v < 1e4).unwrap_or(1.0),
// Numbered as PostScript's `setlinecap` and `setlinejoin` operators number them
// (PostScript Language Reference, 3rd ed.): in users' files the page strokes type with
@@ -1588,16 +1594,18 @@ fn para_style(p: &Para, scale: f64) -> ParaStyle {
/// The character style of character attributes `s`: its font from the fonts the app has (the
/// installed copy its font record names, [`DocFont::font`]), its lengths (size, leading, baseline
/// shift, stroke width) scaled by `scale`, and its patterns placed in the type's text space by
/// `to_text` (the document → its text space), where they stay as the document has them.
/// shift, stroke width) scaled by `scale`, its patterns placed in the type's text space by
/// `to_text` (the document → its text space), where they stay as the document has them, and its
/// swatch colours linked to their swatches.
fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle {
let (family, style, version) = s.font.clone().unwrap_or_else(|| (CharStyle::default().font_family, "Regular".to_string(), None));
// A fill or stroke that is on takes its pattern in place of its colour.
let paint = |color: Option<Color>, pattern: &Option<Paint>| match (color, pattern) {
// A fill or stroke that is on takes its style's paint in place of its colour.
let paint = |color: Option<Color>, styled: &Option<Paint>| match (color, styled) {
// A pattern that can't be placed (the type's text space out of range) keeps the colour.
(Some(_), Some(Paint::Pattern { pattern, xf })) if (to_text * *xf).is_finite() => {
Paint::Pattern { pattern: pattern.clone(), xf: to_text * *xf }
}
(Some(_), Some(linked @ Paint::Solid { swatch: Some(_), .. })) => linked.clone(),
(color, _) => color.map_or(Paint::None, Paint::solid),
};
// Type without a stroke keeps the stroke's defaults, as its weight is 0.
@@ -1616,8 +1624,8 @@ fn char_style(s: &Style, scale: f64, to_text: Affine) -> CharStyle {
baseline_shift: s.baseline_shift * scale,
h_scale: s.h_scale * 100.0,
v_scale: s.v_scale * 100.0,
fill: paint(s.fill, &s.fill_pattern),
stroke: paint(s.stroke, &s.stroke_pattern),
fill: paint(s.fill, &s.fill_paint),
stroke: paint(s.stroke, &s.stroke_paint),
stroke_width: if s.stroke.is_some() { s.stroke_width * scale } else { 0.0 },
stroke_cap,
stroke_join,
@@ -1655,7 +1663,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let justify = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justify;
@@ -1680,7 +1688,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let auto = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).justification.auto_leading;
@@ -1704,7 +1712,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let options = |own: &[u8], scale: f64| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), scale).hyphenation;
@@ -1723,7 +1731,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let own = |own: &[u8]| para_style(&bare.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).hyphenation;
@@ -1765,7 +1773,7 @@ mod tests {
// [Normal Paragraph Style] has the Soft set; the second style has Force burasagari.
para_sheets: vec![read(b"/5 << /27 1 >>").unwrap(), read(b"/5 << /24 2 /23 true >>").unwrap()],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![Some(Kinsoku::Hard), Some(Kinsoku::Soft), None],
};
let para = |run: &[u8]| texts.para(Some(&read(run).unwrap()));
@@ -1824,7 +1832,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let tabs = |own: &[u8], scale: f64| {
@@ -1892,7 +1900,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
}
.para(None);
@@ -1941,7 +1949,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: cases.iter().map(|c| frame(c)).collect(),
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let vertical: Vec<bool> = (0..cases.len() + 1).map(|i| texts.frame_vertical(i)).collect();
@@ -1960,7 +1968,7 @@ mod tests {
char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Block) /6 << /35 3 >>").unwrap()],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let tcy = |run: &[u8]| texts.style(Some(&read(run).unwrap())).tate_chu_yoko;
@@ -1985,7 +1993,7 @@ mod tests {
char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rotated) /6 << /35 2 >>").unwrap()],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let roman = |defaults: &[u8], run: &[u8]| texts(defaults).style(Some(&read(run).unwrap())).standard_vertical_roman;
@@ -2021,7 +2029,7 @@ mod tests {
],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let aki = |defaults: &[u8], normal: &[u8], run: &[u8]| {
@@ -2059,7 +2067,7 @@ mod tests {
char_sheets: vec![read(b"/0 ([Normal Character Style]) /6 << >>").unwrap(), read(b"/0 (Rounded) /6 << /61 1 /62 1 >>").unwrap()],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let stroke = |run: &[u8]| {
@@ -2102,10 +2110,10 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
}
.with_patterns(patterns)
.with_paints(patterns)
}
/// Key 5 of a run's fill or stroke names the art style that paints it: one that paints with a
@@ -2142,6 +2150,25 @@ mod tests {
}
}
/// A run whose art style paints with a colour linked to a swatch takes that paint, the swatch
/// and its tint, in place of the process values key 0 keeps for it; a fill or stroke that is
/// off stays off.
#[test]
fn a_run_painted_by_a_swatch_colours_art_style_takes_the_swatch() {
// GUARDS: type in a spot ink came in as the process colour key 0 keeps for it.
let ink = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0).tinted(0.5), swatch: Some("Red Ink".into()), tint: 0.5 };
let texts = patterned_texts().with_paints(HashMap::from([("Anon 1".to_string(), ink.clone())]));
let paints = |run: &str| {
let s = char_style(&texts.style(Some(&read(run.as_bytes()).unwrap())), 1.0, Affine::IDENTITY);
(s.fill, s.stroke)
};
let red = |style: &str| format!("<< /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 .5 .5 0.0 ] >> {style} >>");
let process = Paint::solid(Color::cmyk(0.0, 0.5, 0.5, 0.0));
assert_eq!(paints(&format!("/6 << /53 {} >>", red("/5 (Anon 1)"))), (ink.clone(), Paint::None));
assert_eq!(paints(&format!("/6 << /53 {} /57 true /54 {} >>", red(""), red("/5 (Anon 1)"))), (process, ink));
assert_eq!(paints(&format!("/6 << /56 false /53 {} /54 {} >>", red("/5 (Anon 1)"), red("/5 (Anon 1)"))), (Paint::None, Paint::None));
}
/// A run's pattern stays where the document has it whatever the type's own text space: turned
/// and moved point type, and area type, whose text space is the document's.
#[test]
@@ -2154,9 +2181,9 @@ mod tests {
] {
let mut st = story("type", &[0.0], &Para::default());
st.frames = vec![frame.clone()];
st.runs[0].1.fill_pattern = Some(dots_at((10.0, 20.0)));
st.runs[0].1.fill_paint = Some(dots_at((10.0, 20.0)));
st.runs[0].1.stroke = Some(Color::BLACK);
st.runs[0].1.stroke_pattern = Some(dots_at((-3.0, 8.0)));
st.runs[0].1.stroke_paint = Some(dots_at((-3.0, 8.0)));
let node = st.node(NodeId(1), 0, (0.0, 0.0), to_doc).unwrap();
let NodeKind::Text(t) = node.kind else { panic!("not type") };
for (paint, at) in [(&t.runs[0].style.fill, Point::new(10.0, 20.0)), (&t.runs[0].style.stroke, Point::new(-3.0, 8.0))] {
@@ -2186,7 +2213,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![read(b"/0 << /0 [ 0 0 ] /2 << /0 0 >> >>").unwrap()],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let text = |kerns: &[u8]| -> TextObject {
@@ -2254,7 +2281,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
let direction = |own: &[u8]| para_style(&texts.para(Some(&read(&[b"/5 << ", own, b" >>"].concat()).unwrap())), 1.0).direction;
@@ -2303,7 +2330,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![read(doc.as_bytes()).unwrap()],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
texts.frame(0)
@@ -2511,8 +2538,8 @@ mod tests {
v_scale: 1.0,
fill: Some(Color::BLACK),
stroke: None,
fill_pattern: None,
stroke_pattern: None,
fill_paint: None,
stroke_paint: None,
stroke_width: 1.0,
stroke_cap: LineCap::Butt,
stroke_join: LineJoin::Miter,
@@ -2964,7 +2991,7 @@ mod tests {
char_sheets: vec![],
para_sheets: vec![],
frames: vec![read(doc.as_bytes()).unwrap()],
patterns: HashMap::new(),
paints: HashMap::new(),
kinsoku_sets: vec![],
};
texts.frame(0).unwrap()
+5 -5
View File
@@ -184,10 +184,10 @@ impl ReadText {
self.texts.get_or_insert_with(|| Texts::read(data)).as_ref()
}
/// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]).
fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
/// [`Self::texts`] with its characters painted by `paints` ([`Texts::with_paints`]).
fn texts_with(&mut self, data: &[u8], paints: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
self.forget_in_tests();
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns));
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_paints(paints));
self.texts.insert(texts).as_ref()
}
}
@@ -336,7 +336,7 @@ pub(super) fn build_weighing(
placed_pages,
envelopes_drawn,
styles_read,
text_patterns,
text_paints,
canvas_scale,
symbols_own_size,
xml_ids,
@@ -497,7 +497,7 @@ pub(super) fn build_weighing(
// The page's type that needs no text object of the layers: the layers' own legacy text, or
// placed files that show it.
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
let texts = text.texts_with(data, text_patterns);
let texts = text.texts_with(data, text_paints);
// Each story is read once, however many text objects name it.
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
let stories: Vec<Option<Arc<Story>>> = infos
+79
View File
@@ -3755,6 +3755,85 @@ fn type_painted_with_a_pattern_takes_it_from_the_art_style_its_paint_names() {
assert_eq!(r.document.pattern("Dots").map(|p| p.tile.height()), Some(4.0));
}
#[test]
fn type_set_in_a_spot_ink_takes_it_from_the_art_style_its_paint_names() {
// GUARDS: type set in a spot ink or a global process colour came in as a process colour, so it
// printed on the process plates (and white type on none): the text document keeps only the
// colour's process values at its tint, and the ink's name and tint are in the art style that
// key 5 of the paint names, a style of one paint (`/SimpleStyle`), its fill's for a stroke too.
use vectorcraft_color::{Color, Paint};
let simple = |name: &str, paint: &str| {
format!(
"/KnownStyle :\n({name}) /Name ,\n/SimpleStyle :\n0 O\n{paint}\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Paint ;\n /Def ;\n"
)
};
let styles = [
simple("Anon 1", "0 0 0 0 (White Ink) 0 x"),
simple("Anon 2", "0 1 1 0 (Red Ink) 0.4 x"),
simple("Anon 3", "0 0 0 0 1 1 1 (Chalk) 0 1 Xx"),
simple("Anon 4", "0 0.5 1 0 (Brand Orange) 0 0 Xk"),
// Styles that give no swatch colour: a process colour, a stroke's colour after the fill's.
simple("Anon 5", "0 1 1 0 k"),
simple("Anon 6", "0 0 0 0 (Stray Ink) 0 x\n0 0 0 1 K"),
]
.concat();
let styles = format!("%AI9_BeginArtStyles\n{styles}%AI9_EndArtStyles\n");
let doc = text_document(&[("abcdefghijklmn\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let one = "<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 /53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> >> >> >> /1 15 >>";
assert!(doc.contains(one));
// Each paint keeps the process values of its colour at its tint, as the files do.
let cmyk = |v: &str, style: &str| format!("<< /99 /CAITextPaint /5 ({style}) /0 << /0 2 /1 [ 1.0 {v} ] >> >>");
let rgb = |v: &str, style: &str| format!("<< /99 /CAITextPaint /5 ({style}) /0 << /0 1 /1 [ 1.0 {v} ] >> >>");
let run = |own: &str| format!("<< /0 << /0 << /0 () /5 0 /6 << /0 0 /1 14.0 {own} >> >> >> /1 2 >>");
let white = cmyk("0.0 0.0 0.0 0.0", "Anon 1");
let runs = [
run(&format!("/53 {white}")),
run(&format!("/53 {}", cmyk("0.0 .6 .6 0.0", "Anon 2"))),
run(&format!("/53 {}", rgb("1.0 1.0 1.0", "Anon 3"))),
run(&format!("/53 {}", cmyk("0.0 .5 1.0 0.0", "Anon 4"))),
run(&format!("/53 {} /57 true /54 {white} /63 2.0", cmyk("0.0 1.0 1.0 0.0", "Anon 5"))),
run(&format!("/53 {}", cmyk("0.0 0.0 0.0 0.0", "Anon 6"))),
// A style the file doesn't have, over "m", "n" and the story's end.
run(&format!("/53 {}", cmyk("0.0 0.0 0.0 1.0", "Anon 7"))).replace("/1 2 >>", "/1 3 >>"),
];
let doc = doc.replacen(one, &runs.join(" "), 1);
// The art beside the type paints with one of the inks too: the type's is the same swatch.
let spare = format!("0 1 1 0 (Red Ink) 0 x\n{}\n{}", square_path(30, 30), text_object(0));
let art = native_with_text(&format!("{styles}{}{}", layer("Back", true, &square(10, 10)), layer("Spare", false, &spare)), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
let texts = text_of(&r.document.layers[1]);
assert_eq!(texts.len(), 1, "{:?}", r.warnings);
// Each character's fill and stroke: the swatch it is linked to at its tint, else "process".
let paint = |p: &Paint| match p {
Paint::Solid { swatch: Some(name), tint, .. } => format!("{name} at {:.0} %", tint * 100.0),
Paint::Solid { swatch: None, .. } => "process".into(),
Paint::None => "none".into(),
other => format!("{other:?}"),
};
let chars: Vec<(char, String, String)> =
texts[0].runs.iter().flat_map(|r| r.text.chars().map(|c| (c, paint(&r.style.fill), paint(&r.style.stroke))).collect::<Vec<_>>()).collect();
let want = |c: char, fill: &str, stroke: &str| (c, fill.to_string(), stroke.to_string());
let mut expected = vec![];
expected.extend(['a', 'b'].map(|c| want(c, "White Ink at 100 %", "none")));
expected.extend(['c', 'd'].map(|c| want(c, "Red Ink at 60 %", "none")));
expected.extend(['e', 'f'].map(|c| want(c, "Chalk at 100 %", "none")));
expected.extend(['g', 'h'].map(|c| want(c, "Brand Orange at 100 %", "none")));
expected.extend(['i', 'j'].map(|c| want(c, "process", "White Ink at 100 %")));
expected.extend("klmn".chars().map(|c| want(c, "process", "none")));
assert_eq!(chars, expected);
// The tinted ink draws as its tint, the colour the text document keeps for it.
let red = texts[0].runs.iter().find(|r| r.text.starts_with('c')).and_then(|r| r.style.fill.color());
assert_eq!(red, Some(Color::cmyk(0.0, 1.0, 1.0, 0.0).tinted(0.6)));
// The inks are the document's spot swatches, each once, and the global colour a process one.
let swatch = |name: &str| r.document.swatches_iter().filter(|s| s.name == name).map(|s| (s.spot, s.global)).collect::<Vec<_>>();
for ink in ["White Ink", "Red Ink", "Chalk"] {
assert_eq!(swatch(ink), [(true, true)], "{ink}");
}
assert_eq!(swatch("Brand Orange"), [(false, true)]);
assert_eq!(r.document.swatch("White Ink").and_then(|s| s.paint.color()), Some(Color::cmyk(0.0, 0.0, 0.0, 0.0)));
assert_eq!(r.document.swatch("Chalk").and_then(|s| s.paint.color()), Some(Color::rgb(1.0, 1.0, 1.0)));
}
#[test]
fn type_keeps_its_manual_kerning() {
// GUARDS: the text document's manual kerning (key 8 of a story's text: runs of characters, each
+98 -22
View File
@@ -470,6 +470,36 @@ fn property_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsRe
if matches!(v, Value::Undefined) { Ok(Value::str("")) } else { Ok(Value::String(i.to_str(&v)?)) }
}
fn property_parts(value: &xmp::Value, item: Option<usize>) -> Option<(Option<&str>, u32, &str)> {
match item {
None => Some((value.text(), value.options(), "")),
Some(index) => match value {
xmp::Value::Array { items, .. } => {
items.get(index).map(|item| (Some(item.text.as_str()), item.options(), item.lang.as_deref().unwrap_or("")))
}
_ => None,
},
}
}
fn property_at(i: &mut Interp, o: ObjId, at: usize, item: Option<usize>, ns: &str, path: &str) -> JsResult<Value> {
let scan_bytes = match (&meta_of(i, o)?.props[at].value, item) {
(xmp::Value::Array { form: Form::Alt, items }, None) => items.len().saturating_mul(std::mem::size_of::<Item>()).saturating_mul(2),
_ => 0,
};
if scan_bytes != 0 {
spend(i, scan_bytes)?;
}
let bytes = {
let Some((text, _, locale)) = property_parts(&meta_of(i, o)?.props[at].value, item) else { return Ok(Value::Undefined) };
text.map_or(0, str::len).saturating_add(locale.len())
};
spend(i, bytes.saturating_mul(4))?;
let Some((text, options, locale)) = property_parts(&meta_of(i, o)?.props[at].value, item) else { return Ok(Value::Undefined) };
let (text, locale) = (text.map(str::to_owned), locale.to_owned());
property(i, ns, path, text.as_deref(), options, &locale)
}
fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let what = "XMPMeta.getProperty";
let o = this_meta(i, &this, what)?;
@@ -480,22 +510,20 @@ fn get_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul
}
let found = {
let m = meta_of(i, o)?;
match m.find(&ns, &name).map(|at| &m.props[at].value) {
match m.find(&ns, &name) {
None => Ok(None),
Some(value) => match step {
Step::Whole => Ok(Some((value.text().map(str::to_string), value.options(), String::new()))),
Step::Item(index) => match value {
xmp::Value::Array { items, .. } => Ok(position(index, items.len())
.and_then(|p| items.get(p))
.map(|item| (Some(item.text.clone()), item.options(), item.lang.clone().unwrap_or_default()))),
Some(at) => match step {
Step::Whole => Ok(Some((at, None))),
Step::Item(index) => match &m.props[at].value {
xmp::Value::Array { items, .. } => Ok(position(index, items.len()).map(|p| (at, Some(p)))),
_ => Err(()),
},
},
}
};
let found = found.map_err(|()| not_array(i, what, &name))?;
let Some((text, options, locale)) = found else { return Ok(Value::Undefined) };
property(i, &ns, &path, text.as_deref(), options, &locale)
let Some((at, item)) = found else { return Ok(Value::Undefined) };
property_at(i, o, at, item, &ns, &path)
}
fn set_property(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
@@ -629,13 +657,8 @@ fn get_array_item(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes
let index = item_index(i, &arg(args, 2), what)?;
let Some((at, _, len)) = array_items(i, o, &ns, &name, what)? else { return Ok(Value::Undefined) };
let Some(p) = position(index, len) else { return Ok(Value::Undefined) };
let item = match &meta_of(i, o)?.props[at].value {
xmp::Value::Array { items, .. } => items.get(p).cloned(),
_ => None,
};
let Some(item) = item else { return Ok(Value::Undefined) };
let path = format!("{path}[{}]", p + 1);
property(i, &ns, &path, Some(&item.text), item.options(), item.lang.as_deref().unwrap_or(""))
property_at(i, o, at, Some(p), &ns, &path)
}
fn does_array_item_exist(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
@@ -803,13 +826,13 @@ fn generic_lang(lang: Option<&str>, generic: &str) -> bool {
/// The item of `items` for `specific`, else one whose language starts with `generic`, else the
/// `x-default` item, else the first.
fn pick_lang<'a>(items: &'a [Item], generic: &str, specific: &str) -> Option<&'a Item> {
fn pick_lang(items: &[Item], generic: &str, specific: &str) -> Option<usize> {
items
.iter()
.find(|i| same_lang(i.lang.as_deref(), specific))
.or_else(|| items.iter().find(|i| generic_lang(i.lang.as_deref(), generic)))
.or_else(|| items.iter().find(|i| same_lang(i.lang.as_deref(), "x-default")))
.or_else(|| items.first())
.position(|i| same_lang(i.lang.as_deref(), specific))
.or_else(|| items.iter().position(|i| generic_lang(i.lang.as_deref(), generic)))
.or_else(|| items.iter().position(|i| same_lang(i.lang.as_deref(), "x-default")))
.or_else(|| (!items.is_empty()).then_some(0))
}
/// A language argument: `null` and `undefined` are empty.
@@ -843,11 +866,11 @@ fn get_localized_text(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J
return Err(not_alt_text(i, what, &name));
}
let found = match &meta_of(i, o)?.props[at].value {
xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific).cloned(),
xmp::Value::Array { items, .. } => pick_lang(items, &generic, &specific),
_ => None,
};
match found {
Some(item) => property(i, "", "", Some(&item.text), item.options(), item.lang.as_deref().unwrap_or("")),
Some(item) => property_at(i, o, at, Some(item), "", ""),
None => Ok(Value::Undefined),
}
}
@@ -1477,6 +1500,55 @@ mod namespace_heap_tests {
}
}
#[test]
fn selected_property_values_charge_for_copying_their_text() {
let mut interp = Interp::new(crate::Options::default(), crate::Limits::default());
install(&mut interp).unwrap();
let text = "x".repeat(1024 * 1024);
let value = new_meta(
&mut interp,
Meta {
props: vec![
xmp::Prop { ns: xmp::DC.into(), name: "value".into(), value: xmp::Value::Simple { text: text.clone(), uri: false } },
xmp::Prop {
ns: xmp::DC.into(),
name: "items".into(),
value: xmp::Value::Array { form: Form::Alt, items: vec![Item { text, lang: Some("en-US".into()) }] },
},
],
..Meta::default()
},
)
.unwrap();
interp
.rooted(std::slice::from_ref(&value), |interp| {
let mut limited = Vec::new();
for fuel in [1_000, 100_000] {
for getter in 0..3 {
interp.fuel = fuel;
let result = match getter {
0 => get_property(interp, value.clone(), &[Value::str(xmp::DC), Value::str("value")], false),
1 => get_array_item(interp, value.clone(), &[Value::str(xmp::DC), Value::str("items"), Value::Number(1.0)], false),
_ => get_localized_text(
interp,
value.clone(),
&[Value::str(xmp::DC), Value::str("items"), Value::str("fr"), Value::str("fr-FR")],
false,
),
};
if fuel == 1_000 {
limited.push(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))));
} else {
assert!(result.is_ok(), "getter {getter} failed with sufficient fuel");
}
}
}
assert_eq!(limited, [true; 3]);
Ok(())
})
.unwrap();
}
#[test]
fn localized_text_lookup_charges_for_language_scans() {
let mut interp = Interp::new(crate::Options::default(), crate::Limits::default());
@@ -1499,8 +1571,12 @@ mod namespace_heap_tests {
interp.fuel = 1_000;
let result = get_localized_text(interp, value.clone(), &args, false);
assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "{result:?}");
interp.fuel = 1_000;
let result = get_property(interp, value.clone(), &args[..2], false);
assert!(matches!(result, Err(Abrupt::Limit(crate::LimitKind::Fuel))), "whole-array options did not charge for their scan");
interp.fuel = 1_000_000;
assert!(get_localized_text(interp, value.clone(), &args, false).is_ok());
assert!(get_property(interp, value.clone(), &args[..2], false).is_ok());
Ok(())
})
.unwrap();
+7 -1
View File
@@ -63,7 +63,8 @@ impl Exporter<'_> {
/// missing or left out, its pixels can't be decoded, or its color channel exceeds
/// [`vectorcraft_doc::MAX_RASTER_ALLOC`]; cached by key and paint (and size when images are
/// resampled), image rejections too.
/// With `interpolate` (and the export's own setting), viewers may smooth it. With `overprint`
/// With `interpolate` (and the export's own setting), viewers may smooth it, unless every
/// pixel is covered or not ([`crate::images::bilevel_coverage`]). With `overprint`
/// a gray or CMYK color is written as a DeviceN space of the process inks it holds, so the plates it
/// leaves at zero keep the inks below: the nonzero overprint mode does not apply to an image's
/// samples (ISO 32000-1 §8.6.7).
@@ -94,6 +95,11 @@ impl Exporter<'_> {
self.images.insert(cache, None);
return None;
};
// A mask that only covers or doesn't, a 1-bit image mask as both importers open one, is
// never smoothed: a RIP that smooths it greys its edges, so where the same mask is drawn
// over itself in another ink the ink below shows at the edges. krilla has no 1-bit soft
// mask or /ImageMask, so it stays an 8-bit mask that isn't smoothed.
let interpolate = interpolate && !crate::images::bilevel_coverage(&alpha);
let n = alpha.len();
let registration = swatch.as_deref() == Some(vectorcraft_color::swatch::REGISTRATION);
let inks: Vec<(String, [f32; 4])> = if registration {
+7 -1
View File
@@ -700,11 +700,17 @@ pub(crate) fn recode(
Recoded { image, warning: rule.instead, note, unconverted }
}
/// Whether coverage `cover` (one byte a pixel) only covers or doesn't, as a 1-bit image mask's
/// does: what the Monochrome settings resample, and kept so.
pub(crate) fn bilevel_coverage(cover: &[u8]) -> bool {
cover.iter().all(|v| *v == 0 || *v == 255)
}
/// A colorized image's coverage (one sample a pixel, `w` × `h`, see
/// [`ImageBlob::coverage`]) placed `size` points wide and high, resampled as the Compression
/// settings `c` ask for monochrome images (when every sample is 0 or 255) or grayscale ones.
pub(crate) fn coverage_sized(w: u32, h: u32, cover: Vec<u8>, size: (f64, f64), c: &CompressionSettings) -> Option<(u32, u32, Vec<u8>)> {
let mono = cover.iter().all(|v| *v == 0 || *v == 255);
let mono = bilevel_coverage(&cover);
let rule = rule(c, if mono { Kind::Mono } else { Kind::Gray });
let to = sized(&rule, (w, h), size);
if to == (w, h) {
+36 -1
View File
@@ -535,12 +535,47 @@ fn a_colorized_missing_link_placeholder_is_written_in_its_own_colors() {
}
}
/// A `w` × `h` gray PNG of `px`.
fn gray_png(w: u32, h: u32, px: Vec<u8>) -> Vec<u8> {
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, px).unwrap();
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
}
/// Whether each image XObject of `pdf`, soft masks too, has /Interpolate true.
fn interpolated(pdf: &[u8]) -> Vec<bool> {
let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap();
file.objects()
.into_iter()
.filter_map(|o| match o {
Object::Stream(s) if s.dict().get::<Name<'_>>(b"Subtype").is_some_and(|n| n.as_ref() == b"Image") => {
Some(s.dict().get::<bool>(b"Interpolate") == Some(true))
}
_ => None,
})
.collect()
}
/// A colorized image whose pixels are black or white (a 1-bit image mask, as both importers open
/// one) is written without /Interpolate, its soft mask too: a RIP that smooths the mask greys its
/// edges, and the same mask drawn below in another ink shows there. A grayscale image keeps it.
#[test]
fn a_black_and_white_colorized_image_asks_viewers_not_to_smooth_it() {
let red = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 };
for (pixels, smooth) in [(vec![0, 255], false), (vec![0, 128], true)] {
let mut d = doc(ColorMode::Cmyk, Some(red.clone()));
d.images.insert("pic".into(), ImageBlob::png(gray_png(2, 1, pixels.clone())));
let found = interpolated(&pdf(&d));
assert_eq!(found, [smooth, smooth], "{pixels:?}: the image and its soft mask");
}
}
/// A pixelated colorized image (an envelope's with Anti-Alias off) is written without
/// /Interpolate, as an uncolorized one is.
/// /Interpolate, as an uncolorized one is. (Its pixels are gray: a black-and-white one never is.)
#[test]
fn a_pixelated_colorized_image_asks_viewers_not_to_smooth_it() {
for pixelated in [false, true] {
let mut d = doc(ColorMode::Cmyk, Some(Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0))));
d.images.insert("pic".into(), ImageBlob::png(gray_png(2, 1, vec![0, 128])));
let id = d.layers[0].children().unwrap()[0].id;
d.node_mut(id).unwrap().extras_mut().pixelated = pixelated;
let out = pdf(&d);
+76 -44
View File
@@ -1,14 +1,14 @@
//! The plug-in ABI end to end: the example Desaturate plug-in, and hostile modules (infinite
//! loops, memory bombs, out-of-bounds access, bad manifests and outputs…), which must all fail
//! with an error, quickly.
//! with an error, within their instruction budget.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_plugins::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES};
use vectorcraft_plugins::storage::{Meter, Storage, StorageError};
use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl};
use vectorcraft_plugins::{
Error, FUEL_SLICE, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl,
};
/// The example Desaturate plug-in, built from `crates/plugins/example`.
const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm");
@@ -30,11 +30,16 @@ fn ok_module(run: &str) -> Vec<u8> {
const INPUT: &str = r#"{"objects":[]}"#;
/// Runs `bytes` on an empty input; returns the error and how long it took.
fn run_err(bytes: &[u8], limits: Limits) -> (Error, Duration) {
let t = Instant::now();
/// Runs `bytes` on an empty input → the error.
fn run_err(bytes: &[u8], limits: Limits) -> Error {
let r = Plugin::load(bytes, limits).and_then(|p| p.run(INPUT.as_bytes(), b"{}"));
(r.expect_err("hostile module must fail"), t.elapsed())
r.expect_err("hostile module must fail")
}
/// Two slices of instructions and nothing per input byte: a run that is not stopped between the
/// first and the second slice ends with the instruction budget.
fn two_slices() -> Limits {
Limits { fuel_base: 2 * FUEL_SLICE, fuel_per_byte: 0, ..Limits::default() }
}
#[test]
@@ -86,37 +91,49 @@ fn input_and_params_reach_the_plugin_and_output_comes_back() {
assert_eq!(fixed.run(input, b"{}").unwrap(), br#"{"objects":[]}"#);
}
/// Each hostile module fails with the error for what it did. The ones that never end stop at
/// their instruction budget, not at the time budget, so how long they run depends on the
/// instructions they are given and not on the machine's speed.
#[test]
fn hostile_modules_fail_quickly() {
let quick = Duration::from_secs(5);
let cases: Vec<(&str, Vec<u8>)> = vec![
("infinite loop", ok_module("(loop $l (br $l)) (i64.const 0)")),
("memory.grow bomb, then trap", ok_module("(loop $l (br_if $l (i32.ne (memory.grow (i32.const 512)) (i32.const -1)))) unreachable")),
("memory.grow forever", ok_module("(loop $l (drop (memory.grow (i32.const 1))) (br $l)) (i64.const 0)")),
("out-of-bounds write", ok_module("(i32.store (i32.const -4) (i32.const 0)) (i64.const 0)")),
("trap", ok_module("unreachable")),
("division by zero", ok_module("(drop (i32.div_u (i32.const 1) (i32.const 0))) (i64.const 0)")),
("deep recursion", module(MANIFEST, "(call $r) (i64.const 0)", "(func $r (call $r))")),
("error code", ok_module("(i64.const -7)")),
("output outside memory", ok_module("(i64.const 0x00000100fffffff0)")),
("huge output", ok_module("(i64.const 0x7fffffff00000000)")),
fn hostile_modules_fail_within_their_budget() {
let budget = "plug-in exceeded its instruction budget";
let cases: Vec<(&str, Vec<u8>, &str)> = vec![
("infinite loop", ok_module("(loop $l (br $l)) (i64.const 0)"), budget),
(
"memory.grow bomb, then trap",
ok_module("(loop $l (br_if $l (i32.ne (memory.grow (i32.const 512)) (i32.const -1)))) unreachable"),
"plug-in trapped: wasm `unreachable`",
),
("memory.grow forever", ok_module("(loop $l (drop (memory.grow (i32.const 1))) (br $l)) (i64.const 0)"), budget),
("out-of-bounds write", ok_module("(i32.store (i32.const -4) (i32.const 0)) (i64.const 0)"), "plug-in trapped: out of bounds memory access"),
("trap", ok_module("unreachable"), "plug-in trapped: wasm `unreachable`"),
("division by zero", ok_module("(drop (i32.div_u (i32.const 1) (i32.const 0))) (i64.const 0)"), "plug-in trapped: integer divide by zero"),
("deep recursion", module(MANIFEST, "(call $r) (i64.const 0)", "(func $r (call $r))"), "plug-in trapped: call stack exhausted"),
("error code", ok_module("(i64.const -7)"), "plug-in failed: vc_run returned error code -7"),
("output outside memory", ok_module("(i64.const 0x00000100fffffff0)"), "plug-in ABI: the output points outside memory"),
("huge output", ok_module("(i64.const 0x7fffffff00000000)"), "plug-in exceeded its output size"),
(
"wrong ABI version",
build(&tpl::module(MANIFEST, "(i64.const 0)", "", 1).replace("(result i32) (i32.const 1))", "(result i32) (i32.const 2))")),
"plug-in ABI: vc_abi_version returned 2",
),
("bad manifest", module("not json", "(i64.const 0)", "")),
("manifest with a bad id", module(r#"{"id":"a b","name":"x","kind":"filter"}"#, "(i64.const 0)", "")),
("manifest of the wrong kind", module(r#"{"id":"a","name":"x","kind":"panel"}"#, "(i64.const 0)", "")),
("start function loops", module(MANIFEST, "(i64.const 0)", "(func $spin (loop $l (br $l))) (start $spin)")),
("bad manifest", module("not json", "(i64.const 0)", ""), "plug-in manifest: "),
("manifest with a bad id", module(r#"{"id":"a b","name":"x","kind":"filter"}"#, "(i64.const 0)", ""), "plug-in manifest: invalid id \"a b\""),
(
"manifest of the wrong kind",
module(r#"{"id":"a","name":"x","kind":"panel"}"#, "(i64.const 0)", ""),
"plug-in manifest: manifest: unknown variant `panel`",
),
("start function loops", module(MANIFEST, "(i64.const 0)", "(func $spin (loop $l (br $l))) (start $spin)"), budget),
(
"WASI import",
module(MANIFEST, "(i64.const 0)", r#"(import "wasi_snapshot_preview1" "fd_write" (func (param i32 i32 i32 i32) (result i32)))"#),
"plug-in ABI: the module imports `wasi_snapshot_preview1.fd_write`",
),
];
for (name, bytes) in cases {
let (e, t) = run_err(&bytes, Limits::default());
assert!(t < quick, "{name} took {t:?}");
eprintln!("{name}: {e} ({t:?})");
for (name, bytes, want) in cases {
let e = run_err(&bytes, Limits::default()).to_string();
assert!(e.starts_with(want), "{name}: {e}");
}
}
@@ -146,7 +163,7 @@ fn malformed_and_oversized_modules_are_refused() {
"(func (export \"vc_alloc\") (param $n i32) (result i32) (local $old i32)",
"(func (export \"vc_alloc\") (param $n i32) (result i32) (local $old i32) (return (i32.const -16))",
));
let (e, _) = run_err(&bogus_alloc, Limits::default());
let e = run_err(&bogus_alloc, Limits::default());
assert!(matches!(e, Error::Abi(_)), "{e}");
}
@@ -198,6 +215,22 @@ fn a_plugin_may_use_the_listed_webassembly_proposals_and_no_others() {
}
}
/// A multi-value `br_table` whose targets all take the same values, with another operand under
/// those values, gives every target the values it was branched with: the run traps unless each
/// branch index returns both of them.
#[test]
fn a_multi_value_branch_table_gives_every_target_its_values() {
let fields = "(func $pick (param $i i32) (result i64 i64)
(block (result i64 i64) (i32.const 7) (i64.const 0x1111) (i64.const 0x2222) (br_table 0 1 0 (local.get $i))))
(func $check (param $i i32) (local $a i64) (local $b i64)
(call $pick (local.get $i)) (local.set $b) (local.set $a)
(if (i64.ne (local.get $a) (i64.const 0x1111)) (then unreachable))
(if (i64.ne (local.get $b) (i64.const 0x2222)) (then unreachable)))";
let run = format!("(call $check (i32.const 0)) (call $check (i32.const 1)) (call $check (i32.const 2)) {}", tpl::ECHO);
let p = Plugin::load(&module(MANIFEST, &run, fields), Limits::default()).unwrap();
assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes());
}
/// A function type with more than 32 parameters or results is refused before any function body is
/// validated: the module's extra function has an invalid body, and the error names the limit. A
/// type with 32 of each loads.
@@ -218,7 +251,7 @@ fn a_function_type_past_32_values_is_refused_before_any_function_body_is_validat
#[test]
fn budgets_stop_runaway_plugins() {
let spin = ok_module("(loop $l (br $l)) (i64.const 0)");
let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, fuel_per_byte: 10, ..Limits::default() });
let e = run_err(&spin, Limits { fuel_base: 1_000_000, fuel_per_byte: 10, ..Limits::default() });
assert_eq!(e, Error::Limit("instruction budget".into()));
}
@@ -261,31 +294,30 @@ fn a_bulk_memory_instruction_at_the_end_of_a_slice_keeps_the_run_s_fuel() {
}
}
/// The time budget stops a runaway plug-in where the first slice of its instruction budget ends:
/// with a time budget of 0 the deadline has passed on the monotonic clock before the run starts,
/// and an endless loop given two slices ends with the time budget. With the default time budget
/// the same loop runs through both slices and ends with the instruction budget.
#[test]
fn wall_clock_budget_stops_runaway_plugins() {
let spin = ok_module("(loop $l (br $l)) (i64.const 0)");
// Wall-clock budget, with an effectively unlimited instruction budget.
let (e, t) = run_err(&spin, Limits { fuel_base: u64::MAX / 4, wall_time_ms: 300, ..Limits::default() });
assert_eq!(e, Error::Limit("time budget".into()));
assert!(t < Duration::from_secs(3), "{t:?}");
assert_eq!(run_err(&spin, Limits { wall_time_ms: 0, ..two_slices() }), Error::Limit("time budget".into()));
assert_eq!(run_err(&spin, two_slices()), Error::Limit("instruction budget".into()));
}
/// Cancelling stops a run where one slice of its budget ends: an endless loop given all but
/// unlimited instructions comes back `Cancelled` within seconds, where outside a cancelled scope the
/// same module runs until its budget is spent.
/// Cancelling stops a run where one slice of its budget ends: an endless loop given two slices of
/// instructions comes back `Cancelled` at the end of the first, where outside a cancelled scope the
/// same module runs through both and ends with the instruction budget.
#[test]
fn cancelling_stops_a_run_between_two_slices_of_its_budget() {
let spin = ok_module("(loop $l (br $l)) (i64.const 0)");
let p = Plugin::load(&spin, Limits { fuel_base: u64::MAX / 4, ..Limits::default() }).unwrap();
let p = Plugin::load(&spin, two_slices()).unwrap();
let token = vectorcraft_doc::cancel::CancelToken::new();
token.cancel();
let t = Instant::now();
let r = vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}"));
assert_eq!(r, Err(Error::Cancelled));
assert!(t.elapsed() < Duration::from_secs(3), "{:?}", t.elapsed());
// Outside a cancelled scope the same module still runs to its budget.
let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, ..Limits::default() });
assert_eq!(e, Error::Limit("instruction budget".into()));
assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into())));
}
/// Compiling a plug-in's code takes none of a run's instructions, so a first run takes as many as the
@@ -318,7 +350,7 @@ fn a_first_run_takes_no_more_instructions_than_the_next() {
fn a_heavy_filter_finishes_what_a_light_one_cannot() {
let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#;
let (light, heavy) = (build(&tpl::spinning(MANIFEST, 100_000_000, INPUT)), build(&tpl::spinning(heavy, 100_000_000, INPUT)));
assert_eq!(run_err(&light, Limits::default()).0, Error::Limit("instruction budget".into()));
assert_eq!(run_err(&light, Limits::default()), Error::Limit("instruction budget".into()));
let p = Plugin::load(&heavy, Limits::default()).unwrap();
assert_eq!((p.limits().fuel_base, p.limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS));
assert_eq!(heavy_terms(), (5, 20));
+43 -3
View File
@@ -28,7 +28,7 @@
use std::cell::Cell;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};
use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard, PoisonError};
use vectorcraft_doc::placed_document::MAX_DEPTH;
use vectorcraft_doc::{ImageBlob, Node, PlacedDocument};
@@ -69,6 +69,8 @@ struct Bitmaps {
static BITMAPS: LazyLock<Mutex<Bitmaps>> = LazyLock::new(Default::default);
/// Bitmaps being made.
static PENDING: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
/// Signaled, under [`PENDING`]'s lock, when the last bitmap being made stops being pending.
static IDLE: Condvar = Condvar::new();
/// Bitmaps that could not be made (neither the file nor a preview could be read): not asked for
/// again.
static FAILED: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
@@ -123,6 +125,24 @@ pub fn busy() -> bool {
!lock(&PENDING).is_empty()
}
/// Bitmap `key` stops being pending; when none is left, [`IDLE`] is signaled.
fn finish(key: &BitmapKey) {
let mut pending = lock(&PENDING);
pending.remove(key);
if pending.is_empty() {
IDLE.notify_all();
}
}
/// Wait until no bitmap is being made ([`busy`] is false).
#[cfg(test)]
pub(crate) fn wait_idle() {
let mut pending = lock(&PENDING);
while !pending.is_empty() {
pending = IDLE.wait(pending).unwrap_or_else(PoisonError::into_inner);
}
}
/// Is a bitmap of file `key` being made?
#[cfg(test)]
pub(crate) fn pending_for(key: &str) -> bool {
@@ -237,12 +257,32 @@ thread_local! {
static DEPTH: Cell<usize> = const { Cell::new(0) };
}
#[cfg(test)]
thread_local! {
/// The deepest this thread has drawn inside placed documents since [`reset_deepest`].
static DEEPEST: Cell<usize> = const { Cell::new(0) };
}
/// Start counting how deep this thread draws inside placed documents ([`deepest`]).
#[cfg(test)]
pub(crate) fn reset_deepest() {
DEEPEST.with(|d| d.set(0));
}
/// The deepest this thread has drawn inside placed documents since [`reset_deepest`].
#[cfg(test)]
pub(crate) fn deepest() -> usize {
DEEPEST.with(Cell::get)
}
/// While alive: drawing inside a placed document, one level deeper.
struct Inside;
impl Inside {
fn enter() -> Self {
DEPTH.with(|d| d.set(d.get() + 1));
#[cfg(test)]
DEEPEST.with(|d| d.set(d.get().max(depth())));
Inside
}
}
@@ -323,7 +363,7 @@ fn run(r: &mut Renderer, mut job: Job) {
lock(&FAILED).insert(job.key.clone());
}
}
lock(&PENDING).remove(&job.key);
finish(&job.key);
};
match scope {
Some(scoped) => scoped(&mut body),
@@ -356,7 +396,7 @@ mod workers {
let key = job.key.clone();
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::run(&mut r, *job))).is_err() {
super::lock(&super::FAILED).insert(key.clone());
super::lock(&super::PENDING).remove(&key);
super::finish(&key);
}
}
});
+31 -21
View File
@@ -85,31 +85,43 @@ fn placed_node(id: u64, key: &str, width: f64, height: f64, xf: Affine) -> Node
/// Held shut, [`gated_blue_page`] makes the background worker wait before reading a file, so a
/// frame drawn meanwhile shows the placeholders whatever the scheduler does (#5152: a fast worker
/// could finish between scheduling a bitmap and the frame looking it up again).
static GATE_SHUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
static GATE_SHUT: std::sync::Mutex<bool> = std::sync::Mutex::new(false);
/// Signaled when the gate opens.
static GATE_OPENED: std::sync::Condvar = std::sync::Condvar::new();
/// The thread drawing while the gate is shut: it never waits (a file read there is drawn exactly).
static GATE_HOLDER: std::sync::Mutex<Option<std::thread::ThreadId>> = std::sync::Mutex::new(None);
/// [`blue_page`] once the gate opens (at most 10 s), except on the thread that shut it. Every test
/// here registers it: the first registration stays, so all of them must agree (open, it is
/// [`blue_page`] once the gate opens, except on the thread that shut it. Every test here
/// registers it: the first registration stays, so all of them must agree (open, it is
/// `blue_page`).
fn gated_blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
let here = std::thread::current().id();
let holder = *GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let t = std::time::Instant::now();
while holder != Some(here) && GATE_SHUT.load(std::sync::atomic::Ordering::SeqCst) && t.elapsed().as_secs() < 10 {
std::thread::sleep(std::time::Duration::from_millis(1));
if holder != Some(here) {
let mut shut = GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
while *shut {
shut = GATE_OPENED.wait(shut).unwrap_or_else(std::sync::PoisonError::into_inner);
}
}
blue_page(p, bytes)
}
/// Shut the gate for the calling thread's frames.
fn shut_gate() {
*GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::thread::current().id());
GATE_SHUT.store(true, std::sync::atomic::Ordering::SeqCst);
/// The gate shut by [`shut_gate`]; dropping it opens the gate, also when the test fails while it
/// is shut.
struct Gate;
impl Drop for Gate {
fn drop(&mut self) {
*GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = false;
GATE_OPENED.notify_all();
}
}
fn open_gate() {
GATE_SHUT.store(false, std::sync::atomic::Ordering::SeqCst);
/// Shut the gate for the calling thread's frames, until the [`Gate`] is dropped.
fn shut_gate() -> Gate {
*GATE_HOLDER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(std::thread::current().id());
*GATE_SHUT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true;
Gate
}
/// Held by the tests that draw placed documents from bitmaps, which share the bitmaps, their
@@ -129,12 +141,9 @@ fn render(d: &Document, progressive: bool) -> Rendered {
Renderer::new().render(d, 100, 100, Affine::IDENTITY, &opts)
}
/// Wait for the background bitmaps (at most 10 s).
/// Wait for the background bitmaps.
fn settle() {
let t = std::time::Instant::now();
while placed_document::busy() && t.elapsed().as_secs() < 10 {
std::thread::sleep(std::time::Duration::from_millis(5));
}
placed_document::wait_idle();
assert!(!placed_document::busy(), "bitmaps still coming");
}
@@ -433,9 +442,9 @@ fn a_ready_bitmap_draws_again_where_its_file_shows() {
let mut r = Renderer::new();
let generation = placed_document::generation();
// The first frame shows the placeholders: the worker waits until it is drawn.
shut_gate();
let gate = shut_gate();
let before = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
open_gate();
drop(gate);
settle();
let made = placed_document::made_between(generation, placed_document::generation()).expect("known");
let files = |keys: &[&str]| keys.iter().map(|k| k.to_string()).collect::<std::collections::HashSet<_>>();
@@ -532,9 +541,10 @@ fn a_placed_document_kept_as_its_preview_draws_the_preview() {
fn a_document_that_places_itself_draws_a_few_levels_deep_then_stops() {
let _serial = serial();
let d = doc_with("loop-1", b"loop");
let t = std::time::Instant::now();
placed_document::reset_deepest();
let r = render(&d, false);
assert!(t.elapsed().as_secs() < 10);
let deepest = placed_document::deepest();
assert!((2..=vectorcraft_doc::placed_document::MAX_DEPTH).contains(&deepest), "drawn {deepest} levels deep");
assert_eq!(&r.pixel(50, 30)[..3], &[0, 0, 255]);
// On screen too.
render(&d, true);
+29
View File
@@ -235,6 +235,35 @@ fn flat_triangles_stop_at_their_budget() {
assert!(work >= all, "{work} of {all}");
}
#[test]
fn an_inside_bevel_stays_inside_a_collapsing_convex_outline() {
for points in [
vec![Point::new(30.0, 26.0), Point::new(100.0, 26.0), Point::new(100.0, 28.0), Point::new(30.0, 28.0)],
vec![Point::new(0.0, 0.0), Point::new(56.0, 42.0), Point::new(55.6, 44.2), Point::new(-0.4, 2.2)],
vec![Point::new(0.0, 0.0), Point::new(6.0, 0.0), Point::new(3.0, 4.0)],
] {
let mut path = BezPath::new();
path.move_to(points[0]);
for &point in &points[1..] {
path.line_to(point);
}
path.close_path();
let (path, bounds) = shape(&path);
let bevel = Bevel { shape: BevelShape::Cove, width: 4.3, height: 10.3, inside: true, ..Bevel::default() };
let options = Extrude { depth: 17.2, bevel: Some(bevel), ..Extrude::default() };
let solid = extrude_meshed(&path, FillRule::NonZero, bounds, options, front()).unwrap();
assert!(!solid.facets.is_empty());
for point in solid.facets.iter().flat_map(|facet| facet.contours.iter().flatten()) {
for (&a, &b) in points.iter().zip(points.iter().cycle().skip(1)) {
assert!((b - a).cross(*point - a) >= -1e-8, "{point:?} escaped {points:?}");
}
}
let mesh = solid.mesh().unwrap();
assert!(mesh.parts.contains(&MeshPart::Front), "the front cap has area");
assert!(closed(&mesh), "the cap and bands meet for {points:?}");
}
}
#[test]
fn a_beveled_extrusion_stays_closed() {
let mut b = BezPath::new();
+37 -22
View File
@@ -2,8 +2,8 @@ use vectorcraft_geom::kurbo::ParamCurveDeriv;
use super::outline::{self, Along, Budget, CURVE_TOLERANCE};
use super::rings::{
CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area,
solid_rings_traced, square_corners,
CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, collapse_width, curve_pieces, inset, left,
signed_area, solid_rings_traced, square_corners,
};
use super::side;
use super::{
@@ -791,6 +791,35 @@ fn steps(o: &Extrude) -> Vec<Step> {
out
}
/// The steps and their shared outline for drawing, surface measurements and mesh export.
fn extrude_profile(path: &PathData, rule: FillRule, size: f64, o: &Extrude) -> Result<(Vec<Step>, Vec<Ring>), String> {
let mut steps = steps(o);
let bands = steps.len().saturating_sub(1);
let caps = if o.cap { 2 } else { 0 };
let most = curve_pieces(path, size, bands, caps)?;
let mut rings = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?;
if let (Some(bevel), [ring]) = (o.bevel, rings.as_slice())
&& bevel.inside
&& let Some(width) = collapse_width(ring)
&& bevel.width > width
{
// Use one width for the cap and every end of every band. The profile still runs
// through the requested depth and meets the wall at the original outline.
let scale = width / bevel.width;
for step in &mut steps {
step.inset *= scale;
}
steps.dedup_by(|a, b| (a.inset - b.inset).abs() < 1e-9 && (a.t - b.t).abs() < 1e-12);
}
// The corners the bevel opens are cut square past the miter limit.
if let Some(side) = steps.iter().map(|s| s.inset).find(|w| *w != 0.0) {
for ring in &mut rings {
*ring = square_corners(ring, side);
}
}
Ok((steps, rings))
}
/// The face a band between steps `s0` and `s1` borders: +1 between two front bevel steps, -1 when
/// it reaches a back bevel step, and 0 for a wall.
fn band_face(s0: &Step, s1: &Step) -> f64 {
@@ -957,17 +986,9 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio
if o.depth <= 0.0 {
return plane_faces(path, rule, bounds, view, keep);
}
let steps = steps(&o);
// One face for each edge of the outline in each band between two steps, and the two caps:
// counted before any point is sampled, and again on the rings, which can have more points
// once contours that meet are merged.
let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 });
let size = bounds.width().max(bounds.height());
let most = curve_pieces(path, size, bands, caps)?;
// Every inset of one extrusion goes the same way: into the shape for a bevel inside, out of it
// for one outside. The corners that way opens are cut square past the miter limit.
let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0);
let traced: Vec<Ring> = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect();
let (steps, traced) = extrude_profile(path, rule, size, &o)?;
let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 });
let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect();
let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add);
if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES {
@@ -1220,12 +1241,9 @@ pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options:
if o.depth <= 0.0 {
return Ok(path.bounds().map(|b| end(PlanarFace::Front, b)).into_iter().collect());
}
let steps = steps(&o);
let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 });
let size = bounds.width().max(bounds.height());
let most = curve_pieces(path, size, bands, caps)?;
let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0);
let traced: Vec<Ring> = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?.iter().map(|r| square_corners(r, side)).collect();
let (steps, traced) = extrude_profile(path, rule, size, &o)?;
let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 });
// A solid past the face limit is refused, as [`extrude_faces`] refuses it.
let edges = traced.iter().map(|r| r.points.len()).fold(0usize, usize::saturating_add);
if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES {
@@ -1264,12 +1282,9 @@ pub fn extrude_side_size(path: &PathData, rule: FillRule, bounds: Rect, options:
if o.depth <= 0.0 {
return None;
}
let steps = steps(&o);
let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 });
let size = bounds.width().max(bounds.height());
let most = curve_pieces(path, size, bands, caps).ok()?;
let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0);
let traced: Vec<Ring> = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most).ok()?.iter().map(|r| square_corners(r, side)).collect();
let (steps, traced) = extrude_profile(path, rule, size, &o).ok()?;
let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 });
let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect();
// A solid past the face limit is refused, as [`extrude_faces`] refuses it.
let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add);
+36
View File
@@ -476,6 +476,42 @@ pub(super) fn left(a: Point, b: Point) -> (f64, f64) {
if l < 1e-12 { (0.0, 0.0) } else { (-dy / l, dx / l) }
}
/// The safe inward width of a single straight triangle or parallelogram. At the first
/// collision the whole ring becomes a point or a segment, so no advancing edges remain.
/// This assumes ordinary miters, whose vertices lie on both inset edge lines.
pub(super) fn collapse_width(ring: &Ring) -> Option<f64> {
let points = ring.points.as_slice();
let [a, b, c, ..] = points else { return None };
if points.len() > 4 || ring.spans.iter().any(Option::is_some) {
return None;
}
let (u, v) = (*b - *a, *c - *b);
let area = u.cross(v);
if area <= 0.0 {
return None;
}
// Allow the rounding from a transform of a parallelogram. The final width stays below
// the collision by more than this tolerance.
let scale = points.iter().map(|p| p.x.abs().max(p.y.abs())).fold(1.0, f64::max);
let tolerance = 32.0 * f64::EPSILON * scale;
let width = match points {
[_, _, _] => area / (u.hypot() + v.hypot() + a.distance(*c)),
[_, _, _, d] if (*d - *a - v).hypot() <= tolerance => area / (2.0 * u.hypot().max(v.hypot())),
_ => return None,
};
let cycle = points.iter().copied().cycle();
let miters_follow_edges = cycle.clone().zip(cycle.clone().skip(1)).zip(cycle.skip(2)).take(points.len()).all(|((a, b), c)| {
let (ax, ay) = left(a, b);
let (bx, by) = left(b, c);
// The squared cosine of the half angle between the normals is (1 + dot) / 2.
ax * bx + ay * by >= 2.0 / (MITER_LIMIT * MITER_LIMIT) - 1.0
});
// Leave a subpixel cap for the mesh triangulator and room for roundoff in the offset.
// The subpixel allowance alone never takes more than half the available width.
let margin = 1e-4_f64.min(width / 2.0).max(8.0 * tolerance);
miters_follow_edges.then_some((width - margin).max(0.0))
}
/// `ring` moved `w` points towards its filled side (negative: away from it), each corner along
/// its bisector, its miter limited to [`MITER_LIMIT`] times `w` so sharp corners don't shoot off.
/// A point given twice (a corner [`square_corners`] cut) moves each copy along its one edge's
+6 -5
View File
@@ -7,6 +7,7 @@ use std::borrow::Cow;
use craft::menu::Node;
use craft::ui::canvas::ViewCommands;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::{LengthUnits, UnitKind};
use serde_json::{Value, json};
@@ -221,16 +222,16 @@ pub(crate) fn open(app: &mut VectorcraftApp, id: &str) -> Option<Result<Value, S
};
let fields = form::fields_of(&rows, opening.as_object()?);
let opened = match command {
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |_| dialog(GRID, grid_rows(lengths))),
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |_| dialog(REPLACE, replace_rows())),
GRID => super::dialogs::open(app, &GRID_SPEC, fields, move |fields| dialog(GRID, grid_rows(lengths)).values(Bind::bound(fields))),
REPLACE => super::dialogs::open(app, &REPLACE_SPEC, fields, |fields| dialog(REPLACE, replace_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)
dialog(OPACITY, opacity_rows()).ok_enabled(min <= max).values(Bind::bound(fields))
}),
SORT => super::dialogs::open(app, &SORT_SPEC, fields, |_| dialog(SORT, sort_rows())),
SORT => super::dialogs::open(app, &SORT_SPEC, fields, |fields| dialog(SORT, sort_rows()).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())
dialog(SIZE, size_rows(lengths)).ok_enabled(either).ok_reason(tl!("Tick Width or Height.").into()).values(Bind::bound(fields))
}),
};
Some(opened)
@@ -4,6 +4,7 @@ use vectorcraft_engine::Session;
use super::ZOOM;
use crate::addons::dialogs::tests as host;
use crate::tests::panel_harness::Panel as Harness;
use crate::{VectorcraftApp, menus};
/// An app with a window, where its dialogs open, and two rectangles without a stroke, both selected.
@@ -29,6 +30,85 @@ fn click(app: &mut VectorcraftApp, label: &str) {
menus::invoke(app, &id, p);
}
/// Replace a numeric field's text and commit by moving focus, without confirming the dialog.
fn type_number(panel: &mut Harness, label: &str, text: &str) {
panel.click(label);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.frame();
}
#[test]
fn real_grid_edits_reach_the_preview_and_confirmed_geometry() {
let (app, a, b) = app();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Arrange in Grid…");
type_number(&mut panel, "Columns", "1");
type_number(&mut panel, "V Spacing", "7");
let id = host::dialog_id(&panel.app());
assert_eq!(host::read(&panel.app(), id, |f| f.int("columns")), Some(1));
let preview = {
let app = panel.app();
(bounds(&app, a), bounds(&app, b))
};
assert!((preview.0.center().x - preview.1.center().x).abs() < 1e-6);
assert!((preview.1.y0 - preview.0.y1 - 7.0).abs() < 1e-6);
panel.click("OK");
panel.frame();
let app = panel.app();
assert_eq!((bounds(&app, a), bounds(&app, b)), preview);
assert!(!app.any_dialog_open());
}
#[test]
fn real_size_keyboard_edits_keep_unticked_sides_unchanged() {
let (app, a, b) = app();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Set Size of Each…");
panel.frame();
panel.focus("Height");
panel.key(egui::Key::Space, egui::Modifiers::NONE);
// Width's number follows its checkbox in keyboard order; the number has no separate caption.
panel.focus("Width");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text("30");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.frame();
let id = host::dialog_id(&panel.app());
assert_eq!(host::read(&panel.app(), id, |f| (f.number("width"), f.bool("heightOn"))), (Some(30.0), Some(false)));
panel.click("OK");
panel.frame();
let app = panel.app();
let (first, second) = (bounds(&app, a), bounds(&app, b));
assert_eq!((first.width(), first.height()), (30.0, 10.0));
assert_eq!((second.width(), second.height()), (30.0, 40.0));
}
#[test]
fn real_opacity_edits_drive_validation_confirmation_and_cancel() {
let (app, a, b) = app();
let mut panel = Harness::new(app, crate::tests::picks::dialogs);
click(&mut panel.app(), "Randomize Opacity…");
type_number(&mut panel, "Minimum", "80");
type_number(&mut panel, "Maximum", "20");
assert!(!panel.enabled("OK"), "a minimum above the maximum disables confirmation");
type_number(&mut panel, "Maximum", "80");
assert!(panel.enabled("OK"));
panel.click("OK");
panel.frame();
let opacity = |panel: &Harness, id| panel.app().session.doc().unwrap().doc.node(id).unwrap().opacity;
assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6);
click(&mut panel.app(), "Randomize Opacity…");
type_number(&mut panel, "Minimum", "25");
type_number(&mut panel, "Maximum", "25");
assert!((opacity(&panel, a) - 0.25).abs() < 1e-6);
panel.click("Cancel");
panel.frame();
assert!((opacity(&panel, a) - 0.8).abs() < 1e-6 && (opacity(&panel, b) - 0.8).abs() < 1e-6);
}
#[test]
fn set_size_of_each_sets_the_sides_ticked() {
let (mut app, a, b) = app();
+2 -1
View File
@@ -3,6 +3,7 @@
//! labels show, and whether only the swatches selected in the Swatches panel are drawn. It
//! previews on the canvas and runs `addon.color.swatchLegend` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
@@ -75,7 +76,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
if fields.list("names").is_some_and(|names| !names.is_empty()) {
rows.push(Param::new("selectedOnly", tl!("Selected Swatches Only"), ParamKind::bool(false)));
}
ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Create Swatch Legend"), rows).values(Bind::bound(fields)).previews(true)
})
}
@@ -1,6 +1,90 @@
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
use serde_json::json;
use crate::VectorcraftApp;
use crate::tests::panel_harness::Panel;
use craft::behavior::Mixed;
use craft::ui::contract::Role;
use vectorcraft_doc::NodeKind;
fn assert_edited_legend(app: &VectorcraftApp) {
let state = app.session.active().unwrap();
let group = state.doc.node(state.selection.objects[0]).unwrap();
assert_eq!(group.name.as_deref(), Some("Swatch Legend"));
let children = group.children().unwrap();
let chips: Vec<_> = children.iter().filter(|node| matches!(node.kind, NodeKind::Path { .. })).collect();
let labels: Vec<_> = children
.iter()
.filter_map(|node| match &node.kind {
NodeKind::Text(text) => Some(text.plain_text()),
_ => None,
})
.collect();
assert_eq!(chips.len(), 3, "only the three selected swatches are drawn");
assert_eq!(labels.len(), 3);
let bounds = |index: usize| chips[index].geometric_bounds().unwrap();
assert!((bounds(0).width() - 40.0).abs() < 1e-6, "the typed chip size reaches the legend");
assert!((bounds(1).x0 - bounds(0).x0 - 50.0).abs() < 1e-6, "the typed gap separates columns");
assert!((bounds(2).x0 - bounds(0).x0).abs() < 1e-6 && (bounds(2).y0 - bounds(0).y0 - 50.0).abs() < 1e-6, "two columns wrap the third chip");
for label in labels {
assert!(
label.lines().any(|line| line.starts_with('#')) && label.lines().any(|line| line.starts_with("C=")),
"the selected value formats reach the label: {label}"
);
assert!(["Ink", "Paper", "Signal"].contains(&label.lines().next().unwrap()));
}
}
/// Real controls change the preview's layout and labels; Cancel restores the drawing, while
/// OK with Preview switched off applies the same hosted fields in one undo step.
#[test]
fn keyboard_and_checkbox_edits_reach_legend_preview_ok_and_cancel() {
for commit in [false, true] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
for (name, color) in [("Ink", "#123456"), ("Paper", "#f8f4e8"), ("Signal", "#cc2211")] {
app.run("swatch.new", json!({"name": name, "color": color})).unwrap();
}
app.ui.swatches_panel.set_swatches(vec!["Ink".into(), "Paper".into(), "Signal".into()]);
let before = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
crate::menus::invoke(&mut panel.app(), super::COMMAND, json!({}));
panel.frame();
assert_eq!(panel.toggled("Preview"), Some(Mixed::Same(true)), "Preview starts on");
assert!(panel.app().session.in_interaction(), "the initial legend is previewed");
if commit {
panel.click_role("Preview", Role::CHECK_BOX);
assert!(!panel.app().session.in_interaction());
}
panel.click_role("Selected Swatches Only", Role::CHECK_BOX);
panel.click_role("HEX", Role::CHECK_BOX);
panel.click_role("CMYK", Role::CHECK_BOX);
for (label, input) in [("Columns", "2"), ("Size", "40 pt"), ("Gap", "10 pt")] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(input);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
}
if commit {
assert!(panel.app().session.active().unwrap().doc == before, "Preview off leaves the drawing alone");
panel.click("OK");
assert_edited_legend(&panel.app());
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
} else {
assert_edited_legend(&panel.app());
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo, "Preview adds no undo step");
panel.click("Cancel");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
}
assert!(!panel.app().session.in_interaction());
assert!(panel.app().session.active().unwrap().doc == before, "Cancel or Undo restores the original drawing");
assert!(crate::tests::picks::open_dialogs(&panel.app()).is_empty());
}
}
/// The names of the swatches chosen in the Swatches panel are sent only with Selected Swatches Only, and only when
/// there are some; the values go only for the ticked boxes.
#[test]
+2
View File
@@ -244,6 +244,7 @@ impl VectorcraftApp {
three_d_dialog: None,
three_d: Default::default(),
export_dialogs: Default::default(),
slice_dialogs: Default::default(),
package_document: None,
web_export: Default::default(),
flattener_preview: Default::default(),
@@ -387,6 +388,7 @@ impl VectorcraftApp {
}
font_menu::end_previews(self, &out.ended_previews);
edits::end_removed(self, &out.removed_gestures);
dialogs::three_d::sync_graphics_source(self);
let lang = self.ui_language();
if self.host.lang() != lang {
self.host = Arc::new(self.host.with_lang(lang));
+2 -1
View File
@@ -279,8 +279,9 @@ pub(crate) fn released_on_pane(app: &VectorcraftApp, art: CarriedArt, at: Pos2,
/// to the drag session. Moves of anchors or segments stay reshapes. `covered`: another window is over the canvas at the
/// pointer. → whether a carry runs.
pub(crate) fn carry_out(app: &mut VectorcraftApp, cx: &mut ToolContext<'_>, pointer: &ToolPointer, covered: bool) -> bool {
let Some(reverts) = app.session.active().map(|st| st.reverts) else { return false };
let Some(art) = carried(app, cx, pointer, covered) else { return false };
let panel = PanelDrag::Art { document: art.document, ids: art.ids.clone() };
let panel = PanelDrag::Art { document: art.document, reverts, ids: art.ids.clone() };
cx.start_drag_also(art, Arc::new(panel), DragPreview::None);
true
}
+68
View File
@@ -445,6 +445,74 @@ fn button(pos: Pos2, pressed: bool) -> Event {
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }
}
#[test]
fn a_canvas_art_drag_cannot_make_a_graphic_style_after_file_revert() {
use crate::tests::panel_harness::Panel;
use craft::ui::runtime::drag;
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
fn canvas_and_styles(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
egui::Panel::top("audit-styles").exact_size(220.0).show(ui, |ui| crate::panels::graphic_styles::show(app, ui));
canvas::show(app, ui);
}
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id.0]})).unwrap();
app.run("graphicStyle.new", json!({"name": "Drop Target"})).unwrap();
let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-artwork-drop-revert-{}.vectorcraft", std::process::id())));
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
app.run("paint.setFill", json!({"color": "#00ff00", "ids": [id.0]})).unwrap();
app.run("select.none", json!({})).unwrap();
app.select_tool("selection");
let mut panel = Panel::new(app, canvas_and_styles);
let carry_to_style = |panel: &mut Panel| {
let at = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0));
let target = panel.rect("Drop Target").center();
panel.frame_with(vec![Event::PointerMoved(at), button(at, true)]);
panel.frame_with(vec![Event::PointerMoved(at + egui::vec2(20.0, 0.0))]);
assert!(panel.app().session.active().unwrap().interaction.is_some(), "the Selection tool starts a move");
panel.frame_with(vec![Event::PointerMoved(target)]);
panel.frame();
let carried = drag::active::<PanelDrag>(panel.ctx());
assert!(matches!(carried.as_deref(), Some(PanelDrag::Art { ids, .. }) if ids == &[id]), "the canvas starts the panel payload");
assert!(drag::mark(panel.ctx()).is_some(), "Graphic Styles accepts artwork dragged from the current contents");
};
carry_to_style(&mut panel);
let (uid, reverts) = {
let app = panel.app();
let state = app.session.active().unwrap();
(state.uid, state.reverts)
};
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
let styles = |app: &VectorcraftApp| app.session.active().unwrap().doc.graphic_styles.len();
let count = {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.reverts), (uid, reverts + 1));
assert!(state.doc.node(id).is_some(), "the restored object keeps the same ID");
styles(&app)
};
panel.frame();
assert!(drag::mark(panel.ctx()).is_none());
panel.release();
assert_eq!(styles(&panel.app()), count, "a drag from discarded art cannot create a style from restored art");
carry_to_style(&mut panel);
panel.release();
assert_eq!(styles(&panel.app()), count + 1, "a fresh drag can still create a style from the restored artwork");
}
/// A Selection, Direct Selection or Group Selection move that leaves the canvas hands the art to the drag session
/// with the ids the move started with, and the move waits where it was last.
#[test]
+52 -3
View File
@@ -25,7 +25,7 @@ use std::collections::BTreeSet;
use craft::behavior::IconId;
use craft::behavior::dock::{Action, DockEdge, DockPlacement, Target};
use craft::ui::buttons::IconButton;
use craft::ui::contract::{PopupKind, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::contract::{Bind, PopupKind, Props as _, Show as _, ShowContainer as _, Trigger};
use craft::ui::dialog::DialogResult;
use craft::ui::display::Divider;
use craft::ui::menu::{Menu, MenuItem};
@@ -477,8 +477,8 @@ fn shown_again(app: &mut VectorcraftApp, id: u32, hidden: bool) {
fn open_new(app: &mut VectorcraftApp) -> Result<(), String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let fields = DialogFields::from_pairs([("name", blank_name(&app.ui))]);
let dialog = HostedParamDialog::new(&ctx, NEW_KEY, fields, |_| {
ParamDialog::new(NEW_KEY, tl!("New Toolbar"), vec![Param::new("name", tl!("Name:"), ParamKind::text(""))])
let dialog = HostedParamDialog::new(&ctx, NEW_KEY, fields, |fields| {
ParamDialog::new(NEW_KEY, tl!("New Toolbar"), vec![Param::new("name", tl!("Name:"), ParamKind::text(""))]).values(Bind::bound(fields))
});
crate::dialogs::host::open_held(app, dialog, |app, answer: &ParamResult| {
let name = match answer.fields.get("name") {
@@ -692,6 +692,55 @@ mod tests {
VectorcraftApp::new(Session::new(), Default::default())
}
#[test]
fn the_new_toolbar_dialog_creates_and_retries_the_typed_name() {
use crate::tests::panel_harness::Panel;
use crate::tests::picks::open_dialogs;
use egui::{Key, Modifiers};
fn type_name(panel: &mut Panel, name: &str) {
panel.click("Name");
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(name);
panel.key(Key::Tab, Modifiers::NONE);
}
let mut panel = Panel::new(crate::testing::windowed(app()), crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
panel.app().run(NEW_KEY, json!({})).unwrap();
panel.frame();
let suggested = blank_name(&panel.app().ui);
assert_eq!(panel.value("Name").as_deref(), Some(suggested.as_str()), "the dialog opens with the suggested name");
type_name(&mut panel, "Drawing tools");
panel.click("OK");
panel.frame();
assert!(find(&panel.app().ui, "Drawing tools").is_some(), "the typed name replaces the suggestion");
assert_eq!(panel.app().ui.custom_toolbars.len(), 1);
assert!(open_dialogs(&panel.app()).is_empty());
panel.app().run(NEW_KEY, json!({})).unwrap();
type_name(&mut panel, "drawing TOOLS");
panel.click("OK");
panel.frame();
assert_eq!(panel.app().ui.custom_toolbars.len(), 1, "a duplicate name creates nothing");
assert_eq!(open_dialogs(&panel.app()).len(), 1, "refusal keeps the editable dialog");
assert_eq!(panel.value("Name").as_deref(), Some("drawing TOOLS"));
type_name(&mut panel, "Retried tools");
panel.click("OK");
panel.frame();
assert!(find(&panel.app().ui, "Retried tools").is_some(), "a corrected name can be retried");
assert_eq!(panel.app().ui.custom_toolbars.len(), 2);
assert!(open_dialogs(&panel.app()).is_empty());
panel.app().run(NEW_KEY, json!({})).unwrap();
type_name(&mut panel, "Discarded tools");
panel.click("Cancel");
panel.frame();
assert!(find(&panel.app().ui, "Discarded tools").is_none());
assert_eq!(panel.app().ui.custom_toolbars.len(), 2);
assert!(open_dialogs(&panel.app()).is_empty());
}
/// The items of Window › Toolbars: (label, command id, params).
fn toolbars_menu(app: &VectorcraftApp) -> Vec<(String, String, Value)> {
let window = crate::menus::menu_tree_named(true, &crate::menus::Listed::of(app))
+302 -29
View File
@@ -10,11 +10,14 @@
use craft::behavior::IconId;
use craft::ui::choice::Segmented;
use std::sync::{Arc, Weak};
use craft::ui::contract::{Bind, Entry, Show as _};
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::{CustomContext, DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::LengthUnits;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, Selection};
use super::host::{HeldOptions, open_held_with};
use super::preview::LivePreview; // PLAN: assumed path of wg.A20's `LivePreview`
@@ -32,8 +35,72 @@ const PREVIEW_LABEL: &str = "Blend Options";
/// Spacing modes: (value, label).
pub(crate) const SPACING: [(&str, &str); 3] = [("smooth", "Smooth Color"), ("steps", "Specified Steps"), ("distance", "Specified Distance")];
pub(crate) struct Open {
opening: Arc<()>,
document: (u64, u64),
blends: Vec<NodeId>,
preview: LivePreview,
preview_selection: Option<Weak<Selection>>,
}
impl Open {
fn selection_matches(&self, app: &VectorcraftApp) -> bool {
self.blends == app.session.selected_blend_ids()
}
fn drawing_problem(&self, app: &VectorcraftApp) -> Option<&'static str> {
let (uid, reverts) = self.document;
match app.session.active() {
Some(st) if (st.uid, st.reverts) == (uid, reverts) => None,
Some(st) if st.uid == uid => Some(tl!("The document was reverted. Reopen this dialog to continue.")),
_ => Some(tl!("Return to the original drawing to apply Blend Options.")),
}
}
fn selection_snapshot(app: &VectorcraftApp) -> Option<&Arc<Selection>> {
app.session.active().and_then(|st| st.interaction.as_ref().map(|it| &it.selection))
}
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
self.drawing_problem(app).is_none()
&& self
.preview_selection
.as_ref()
.zip(Self::selection_snapshot(app))
.is_some_and(|(source, current)| source.as_ptr() == Arc::as_ptr(current))
}
fn take_preview(&mut self) -> LivePreview {
self.preview_selection = None;
std::mem::take(&mut self.preview)
}
fn later_selection<'a>(&self, app: &'a VectorcraftApp) -> Option<&'a Selection> {
let st = app.session.active()?;
let before = &st.interaction.as_ref()?.selection;
(&st.selection != before.as_ref()).then_some(&st.selection)
}
fn cancel_preview(&mut self, app: &mut VectorcraftApp) {
if self.owns_preview(app) {
let selection = self.later_selection(app).cloned();
self.take_preview().cancel(app);
if let Some(selection) = selection {
let _ = app.session.select(|_, current| *current = selection);
}
}
}
fn cancel(mut self, app: &mut VectorcraftApp) {
self.cancel_preview(app);
}
}
/// Open Blend Options on the selected blend's options (else those new blends start with).
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
if let Some(retired) = app.object_dialogs.blend.take() {
retired.cancel(app);
}
let mut info = app.session.execute("object.blend.info", &json!({})).map_err(|e| e.to_string())?;
let target = info["target"].as_str().unwrap_or("defaults").to_owned();
let Some(o) = info.as_object_mut() else { return Err("no blend options".into()) };
@@ -49,17 +116,24 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let lengths = general_lengths(app);
// Only a blend previews: the defaults target has nothing on the canvas to show.
let on_blend = target == "blend";
app.object_dialogs.blend = on_blend.then(LivePreview::default);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| dialog(on_blend, lengths));
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(preview) = app.object_dialogs.blend.take() {
preview.cancel(app);
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let document = app.session.active().map(|st| (st.uid, st.reverts));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(on_blend, lengths).values(Bind::bound(fields)));
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(move |app| {
if app.object_dialogs.blend.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled))
&& let Some(open) = app.object_dialogs.blend.take()
{
open.cancel(app);
}
});
if open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).is_none() {
app.object_dialogs.blend = None;
return Err("no window".into());
}
if on_blend && let Some(document) = document {
app.object_dialogs.blend =
Some(Open { opening, document, blends: app.session.selected_blend_ids(), preview: LivePreview::default(), preview_selection: None });
}
Ok(Value::Null)
}
@@ -126,44 +200,65 @@ fn params(fields: &DialogFields) -> Value {
/// Runs the live preview of the open dialog while its Preview box is on.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut preview) = app.object_dialogs.blend.take() else { return };
let Some(mut open) = app.object_dialogs.blend.take() else { return };
let state = app
.dialogs()
.and_then(|d| d.with(|host| host.get_by_id::<HostedParamDialog>(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields())))));
let owns_preview = open.owns_preview(app);
if let Some((previewing, p)) = state
&& (!previewing || app.session.has_selected_blend())
&& open.drawing_problem(app).is_none()
&& (!app.session.in_interaction() || owns_preview)
{
// With no blend selected, the command sets application defaults instead of previewing artwork.
// The answer only reports the preview's status, which the preview itself shows.
let _ = preview.run(app, previewing, PREVIEW_LABEL, CMD, &p);
if !owns_preview {
open.take_preview();
} else if open.later_selection(app).is_some() {
// The next preview must start from the user's current selection.
open.cancel_preview(app);
}
// Only the blends that supplied the opening values can preview this draft.
let on = previewing && open.selection_matches(app);
let ran = open.preview.run(app, on, PREVIEW_LABEL, CMD, &p).is_some();
if !on {
open.preview_selection = None;
} else if ran {
open.preview_selection = Open::selection_snapshot(app).map(Arc::downgrade);
}
}
app.object_dialogs.blend = Some(preview);
app.object_dialogs.blend = Some(open);
}
/// OK: keeps the preview as one undo step on a blend; sets the defaults otherwise.
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let on_blend = result.fields.text("__target") == Some("blend");
if on_blend != app.session.has_selected_blend() {
let reason = if on_blend {
tl!("Select a blend before applying these options.")
} else {
tl!("Deselect any selected blends before applying the options for new blends.")
};
return Err(reason.to_owned());
if on_blend {
let open = app.object_dialogs.blend.as_ref().ok_or("Blend Options is no longer open")?;
if let Some(reason) = open.drawing_problem(app) {
return Err(reason.to_owned());
}
if app.session.in_interaction() && !open.owns_preview(app) {
return Err(tl!("Finish the current edit before applying Blend Options.").into());
}
if !open.selection_matches(app) {
return Err(tl!("Select the original blends before applying these options.").into());
}
} else if app.session.has_selected_blend() {
return Err(tl!("Deselect any selected blends before applying the options for new blends.").into());
}
let p = params(&result.fields);
if !on_blend {
return app.run(CMD, p).map(|_| ());
}
let preview = app.object_dialogs.blend.take().unwrap_or_default();
match preview.commit(app, CMD, p) {
Ok(_) => Ok(()),
Err(e) => {
// The dialog stays open on the reason and keeps previewing.
app.object_dialogs.blend = Some(LivePreview::default());
Err(e)
}
let mut open = app.object_dialogs.blend.take().ok_or("Blend Options is no longer open")?;
if open.later_selection(app).is_some() {
open.cancel_preview(app);
}
let owned = open.owns_preview(app);
let preview = open.take_preview();
let preview = if owned { preview } else { LivePreview::default() };
preview.commit(app, CMD, p).map(|_| ()).inspect_err(|_| {
// The dialog stays open on the refusal and can start a new preview.
app.object_dialogs.blend = Some(open);
})
}
#[cfg(test)]
@@ -226,13 +321,17 @@ mod tests {
fn app_with_smooth_blend() -> (VectorcraftApp, u64) {
let mut app = app();
let id = add_blend_drawing(&mut app);
(app, id)
}
fn add_blend_drawing(app: &mut VectorcraftApp) -> u64 {
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
for x in [0, 200] {
app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap();
}
app.run("select.all", json!({})).unwrap();
let id = app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap();
(app, id)
app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap()
}
#[test]
@@ -381,4 +480,178 @@ mod tests {
let s = spec(&app, id);
assert_eq!((s.spacing, s.orientation), (BlendSpacing::Steps(7), BlendOrientation::AlignToPath));
}
#[test]
fn blend_step_count_keeps_a_live_keyboard_edit() {
use craft::ui::testing::Fixture;
use std::cell::RefCell;
use std::rc::Rc;
let (mut app, blend) = app_with_smooth_blend();
app.run("object.blend.options", json!({"id": blend, "spacing": "steps", "steps": 7})).unwrap();
let app = Rc::new(RefCell::new(app));
let shown = app.clone();
let mut fixture = Fixture::new(move |ui| {
let mut app = shown.borrow_mut();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| host.run(ui));
super::super::host::pump(&mut app, ui.ctx());
});
fixture.room(egui::vec2(880.0, 720.0));
{
let mut app = app.borrow_mut();
app.ui_ctx = Some(fixture.ctx().clone());
open(&mut app).unwrap();
}
fixture.settle();
assert_eq!(fields(&app.borrow()).int("steps"), Some(7), "the dialog opens with the blend's existing step count");
let steps = fixture.by_label("Steps").expect("the enabled Steps field");
fixture.click(&steps).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("9").key(egui::Key::Tab, egui::Modifiers::NONE).settle();
{
let mut app = app.borrow_mut();
assert_eq!(fields(&app).int("steps"), Some(9), "the hosted form keeps its keyboard edit");
confirm(&mut app);
assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(9));
}
}
#[test]
fn blend_options_preview_and_cancel_leave_another_drawings_blend_alone() {
let (mut app, original) = app_with_smooth_blend();
let second = add_blend_drawing(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
open(&mut app).unwrap();
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
frame(&mut app);
assert_eq!(spec(&app, original).spacing, BlendSpacing::Steps(7));
app.run("document.activate", json!({"index": 1})).unwrap();
frame(&mut app);
assert_eq!(spec(&app, second).spacing, BlendSpacing::SmoothColor);
confirm(&mut app);
assert!(is_open(&app));
assert_eq!(spec(&app, second).spacing, BlendSpacing::SmoothColor);
app.session.begin_interaction("An independent blend edit").unwrap();
app.session.preview(CMD, &json!({"id": second, "steps": 11})).unwrap();
cancel(&mut app);
assert!(app.session.in_interaction());
assert_eq!(spec(&app, second).spacing, BlendSpacing::Steps(11));
}
#[test]
fn blend_options_does_not_apply_to_art_restored_by_revert() {
let (mut app, blend) = app_with_smooth_blend();
let dir = vectorcraft_testkit::TempDir::new("blend-options-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run(CMD, json!({"id": blend, "steps": 4})).unwrap();
open(&mut app).unwrap();
set(&app, "steps", json!(7));
frame(&mut app);
assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7));
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [blend]})).unwrap();
frame(&mut app);
assert_eq!(spec(&app, blend).spacing, BlendSpacing::SmoothColor);
let undo = app.session.active().unwrap().history.undo.len();
confirm(&mut app);
assert!(is_open(&app));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
cancel(&mut app);
open(&mut app).unwrap();
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
confirm(&mut app);
assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7));
}
#[test]
fn deselect_after_blend_preview_stays_in_effect() {
let (mut app, blend) = app_with_smooth_blend();
let undo = app.session.active().unwrap().history.undo.len();
let defaults = app.session.prefs.blend_options;
open(&mut app).unwrap();
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
frame(&mut app);
assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7));
app.run("select.none", json!({})).unwrap();
frame(&mut app);
assert!(app.session.active().unwrap().selection.objects.is_empty(), "rolling back the preview preserves Deselect");
frame(&mut app);
assert!(!app.session.in_interaction());
assert_eq!(spec(&app, blend).spacing, BlendSpacing::SmoothColor);
confirm(&mut app);
assert!(is_open(&app), "OK waits for a selected blend");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.session.prefs.blend_options, defaults);
app.run("select.set", json!({"ids": [blend]})).unwrap();
frame(&mut app);
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn cancel_keeps_a_selection_made_after_blend_preview() {
let (mut app, blend) = app_with_smooth_blend();
let path = app.run("shape.rectangle", json!({"x": 90, "y": 90, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [blend]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
open(&mut app).unwrap();
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
frame(&mut app);
assert_eq!(spec(&app, blend).spacing, BlendSpacing::Steps(7));
app.run("select.set", json!({"ids": [path]})).unwrap();
cancel(&mut app);
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(path)]);
assert_eq!(spec(&app, blend).spacing, BlendSpacing::SmoothColor);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(!app.session.in_interaction());
}
#[test]
fn blend_options_do_not_transfer_to_another_blend_in_the_same_drawing() {
let (mut app, original) = app_with_smooth_blend();
let ends = [35, 235].map(|x| app.run("shape.rectangle", json!({"x": x, "y": 120, "width": 20, "height": 20})).unwrap()["id"].clone());
app.run("select.set", json!({"ids": ends})).unwrap();
let other = app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [original]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
open(&mut app).unwrap();
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
frame(&mut app);
assert_eq!(spec(&app, original).spacing, BlendSpacing::Steps(7));
app.run("select.set", json!({"ids": [other]})).unwrap();
frame(&mut app);
frame(&mut app);
assert_eq!(spec(&app, original).spacing, BlendSpacing::SmoothColor);
assert_eq!(spec(&app, other).spacing, BlendSpacing::SmoothColor, "the old form does not preview another blend");
assert!(!app.session.in_interaction());
confirm(&mut app);
assert!(is_open(&app), "OK waits for the blends that opened the form");
assert_eq!(app.session.active().unwrap().selection.objects, [vectorcraft_doc::NodeId(other)]);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("select.set", json!({"ids": [original]})).unwrap();
frame(&mut app);
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(spec(&app, original).spacing, BlendSpacing::Steps(7));
assert_eq!(spec(&app, other).spacing, BlendSpacing::SmoothColor);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
}
+344 -28
View File
@@ -10,7 +10,7 @@
//! effect's defaults for the rest.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::{Arc, Weak};
use craft::host::{PickRequest, Picked};
use craft::ui::contract::Bind;
@@ -18,6 +18,7 @@ use craft::ui::dialog::{DialogId, PromptChoice, StandardPrompt};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamResult};
use craft::ui::runtime::memory::{Lifetime, SaveKey};
use serde_json::{Map, Value, json};
use vectorcraft_doc::Selection;
use super::effect_params::{EffectCx, effect_params, heading, label};
use super::form;
@@ -51,6 +52,8 @@ pub(crate) struct Open {
pub id: DialogId,
/// Identity of this opening, since effect dialogs reuse the same dialog ID.
opening: Arc<()>,
/// The drawing and its file generation when the dialog was opened.
source: Option<(u64, u64)>,
/// The item the effect goes to, resolved.
target: Value,
/// The parameters that find the applied effect (`item`, `aligned`).
@@ -66,12 +69,65 @@ pub(crate) struct Open {
opened: Map<String, Value>,
/// The live preview OK keeps and Cancel rolls back.
pub preview: LivePreview,
preview_owner: Option<PreviewOwner>,
/// What the rows need from the app.
pub cx: EffectCx,
/// Whether the Edit or Add New question is still open.
asking: bool,
}
/// The interaction and preview last written by this opening.
struct PreviewOwner {
selection: Weak<Selection>,
command: Option<(String, Value)>,
}
fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> {
app.session.active().map(|doc| (doc.uid, doc.reverts))
}
impl Open {
fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> {
let active = active_drawing(app);
if active == self.source {
Ok(())
} else if active.map(|(id, _)| id) == self.source.map(|(id, _)| id) {
Err(tl!("The document was reverted. Reopen this dialog to continue.").into())
} else {
Err(tl!("Return to the original drawing to apply the effect").into())
}
}
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
self.source == active_drawing(app)
&& self.preview_owner.as_ref().is_some_and(|owner| {
app.session.active().and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| {
owner.selection.upgrade().is_some_and(|selection| Arc::ptr_eq(&selection, &interaction.selection))
&& owner.command == interaction.preview
})
})
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.owns_preview(app) {
self.preview.cancel(app);
}
}
fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result<bool, String> {
if self.owns_preview(app) {
return Ok(true);
}
// A tab switch normally rolls the preview back. A new edit can now hold the interaction.
self.preview = LivePreview::default();
self.preview_owner = None;
if app.session.in_interaction() {
app.keep_typing()?;
}
Ok(!app.session.in_interaction())
}
}
/// Match an automation request's blend-mode spelling to the mode shown in the targeted effect dialog.
pub(crate) fn normalize_set_mode(app: &VectorcraftApp, id: DialogId, params: &mut Value) {
let Some(open) = app.effect_dialogs.effect.as_ref() else { return };
@@ -111,6 +167,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let mut open = Open {
id: DialogId::NULL,
opening: Arc::new(()),
source: active_drawing(app),
target: target.clone(),
edit_target,
index: None,
@@ -118,6 +175,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
aligned: p.get("aligned").and_then(Value::as_bool) == Some(true),
opened: Map::new(),
preview: LivePreview::default(),
preview_owner: None,
cx: EffectCx::new(app, id, false),
asking: false,
};
@@ -149,6 +207,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) -
let open = Open {
id: DialogId::NULL,
opening: Arc::new(()),
source: active_drawing(app),
target: Value::Null,
edit_target: json!({}),
index: None,
@@ -156,6 +215,7 @@ pub(crate) fn open_last(app: &mut VectorcraftApp, effect: &str, params: Value) -
aligned: false,
opened: Map::new(),
preview: LivePreview::default(),
preview_owner: None,
cx: EffectCx::new(app, effect, false),
asking: false,
};
@@ -248,6 +308,9 @@ fn ask(app: &mut VectorcraftApp, mut open: Open) -> Result<Value, String> {
.button(PromptChoice::Alternate, tl!("Add New").to_string())
.button(PromptChoice::Cancel, tl!("Cancel").to_string());
let Some(dialogs) = app.dialogs() else { return Err("no window".into()) };
if let Some(old) = app.effect_dialogs.effect.take() {
old.cancel_preview(app);
}
open.id = dialogs.with(|h| h.open(prompt));
open.asking = true;
app.effect_dialogs.effect = Some(open);
@@ -259,7 +322,7 @@ fn ask(app: &mut VectorcraftApp, mut open: Open) -> Result<Value, String> {
fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map<String, Value>, seed: Map<String, Value>) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
if let Some(old) = app.effect_dialogs.effect.take() {
old.preview.cancel(app);
old.cancel_preview(app);
}
let id = open.cx.id.clone();
let fresh = open.index.is_none();
@@ -296,29 +359,47 @@ fn launch(app: &mut VectorcraftApp, mut open: Open, baseline: Map<String, Value>
};
if warp_new { dialog.remember(WARP_KEY).remember_for(Lifetime::Run) } else { dialog }
});
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(open) = app.effect_dialogs.effect.take() {
open.preview.cancel(app);
let cancelled = Arc::clone(&open.opening);
let confirmed = Arc::clone(&open.opening);
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(move |app| {
if let Some(open) = take_opening(app, &cancelled) {
open.cancel_preview(app);
}
});
let options = HeldOptions { cancel: Some(cancel), ..Default::default() };
let dialog_id = open_held_with(app, dialog, move |app, result| finish(app, &ctx, result), options).ok_or("no window")?;
let dialog_id = open_held_with(app, dialog, move |app, result| finish(app, &ctx, &confirmed, result), options).ok_or("no window")?;
open.id = dialog_id;
open.asking = false;
app.effect_dialogs.effect = Some(open);
Ok(Value::Null)
}
/// Take the current effect only when it is the opening that registered the callback.
fn take_opening(app: &mut VectorcraftApp, opening: &Arc<()>) -> Option<Open> {
app.effect_dialogs.effect.as_ref().filter(|open| Arc::ptr_eq(opening, &open.opening))?;
app.effect_dialogs.effect.take()
}
/// What OK runs: the command keeps the preview as one undo step. An `Err` keeps the dialog open
/// with the reason, and the record with a fresh preview.
fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -> Result<(), String> {
let Some(mut open) = app.effect_dialogs.effect.take() else { return Ok(()) };
fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, opening: &Arc<()>, result: &ParamResult) -> Result<(), String> {
let Some(mut open) = take_opening(app, opening) else { return Ok(()) };
if let Err(why) = open.check_source(app) {
app.effect_dialogs.effect = Some(open);
return Err(why);
}
let (cmd, params) = command(&open, &result.fields);
// An edit that sends nothing changes nothing and records no step: the preview rolls back.
if cmd == "effect.setParams" && params.get("warpStyle").is_none() && params["params"].as_object().is_some_and(Map::is_empty) {
open.preview.cancel(app);
open.cancel_preview(app);
return Ok(());
}
let ready =
open.ready_to_edit(app).and_then(|ready| if ready { Ok(()) } else { Err(tl!("Finish the current edit before applying the effect").into()) });
if let Err(why) = ready {
app.effect_dialogs.effect = Some(open);
return Err(why);
}
let preview = std::mem::take(&mut open.preview);
match preview.commit(app, cmd, params.clone()) {
Ok(_) => {
@@ -333,6 +414,7 @@ fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -
Ok(())
}
Err(e) => {
open.preview_owner = None;
app.effect_dialogs.effect = Some(open);
Err(e)
}
@@ -400,21 +482,30 @@ pub(super) fn command_for(
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let _ = ctx;
let Some(open) = app.effect_dialogs.effect.take() else { return };
let open = if open.asking {
match answer(app, open) {
Some(open) => open,
None => return,
}
if open.asking {
answer(app, open);
} else {
open
};
drive(app, open);
drive(app, open);
}
}
/// The answer of the Edit or Add New question; `open` back while it is still asked.
fn answer(app: &mut VectorcraftApp, mut open: Open) -> Option<Open> {
let result = app.dialogs()?.with(|h| h.take_by_id::<StandardPrompt>(open.id))?;
let choice = result.ok().map_or(PromptChoice::Cancel, |answer| answer.choice);
/// The answer of the Edit or Add New question; retain the opening while the question is still visible.
fn answer(app: &mut VectorcraftApp, mut open: Open) {
let Some(dialogs) = app.dialogs() else { return };
let (waiting, result) = dialogs.with(|host| {
if host.get_by_id::<StandardPrompt>(open.id).is_some() { (true, None) } else { (false, host.take_by_id::<StandardPrompt>(open.id)) }
});
if waiting {
app.effect_dialogs.effect = Some(open);
return;
}
let choice = result.and_then(|result| result.ok()).map_or(PromptChoice::Cancel, |answer| answer.choice);
if choice != PromptChoice::Cancel
&& let Err(why) = open.check_source(app)
{
app.status(why);
return;
}
let id = open.cx.id.clone();
let launched = match (choice, open.index) {
(PromptChoice::Proceed, Some(k)) => {
@@ -428,12 +519,11 @@ fn answer(app: &mut VectorcraftApp, mut open: Open) -> Option<Open> {
open.index = None;
launch(app, open, defaults_of(&id), Map::new())
}
_ => return None,
_ => return,
};
if let Err(e) = launched {
app.status(e);
}
None
}
/// The fields show what the effect stores, also for a value set while the dialog is open: Scribble's 270° angle
@@ -455,6 +545,10 @@ fn show_stored(cx: &EffectCx, d: &mut HostedParamDialog) {
/// One frame of the open dialog: the preview of its values, and the requests its rows filed.
fn drive(app: &mut VectorcraftApp, mut open: Open) {
let Some(dialogs) = app.dialogs() else { return };
if open.check_source(app).is_err() {
app.effect_dialogs.effect = Some(open);
return;
}
let Some((fields, previewing, path)) = dialogs.with(|h| {
h.get_mut_by_id::<HostedParamDialog>(open.id).map(|d| {
show_stored(&open.cx, d);
@@ -464,10 +558,26 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) {
app.effect_dialogs.effect = Some(open);
return;
};
let (cmd, params) = command(&open, &fields);
let english = vectorcraft_effects::effect_info(&open.cx.id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_default();
// `run` reports a failed preview itself.
let _ = open.preview.run(app, previewing, &english, cmd, &params);
if previewing || open.owns_preview(app) {
match open.ready_to_edit(app) {
Ok(true) => {
let (cmd, params) = command(&open, &fields);
let english = vectorcraft_effects::effect_info(&open.cx.id).map(|i| i.label.trim_end_matches('…').to_string()).unwrap_or_default();
let ran = open.preview.run(app, previewing, &english, cmd, &params);
if !previewing {
open.preview_owner = None;
} else if ran.is_some() {
open.preview_owner = app
.session
.active()
.and_then(|doc| doc.interaction.as_ref())
.map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), command: interaction.preview.clone() });
}
}
Ok(false) => {}
Err(why) => app.status(why),
}
}
if let Some(request) = path {
let (id, key) = (open.id, request.key);
let opening = Arc::clone(&open.opening);
@@ -475,8 +585,11 @@ fn drive(app: &mut VectorcraftApp, mut open: Open) {
app.effect_dialogs.effect.as_ref().is_some_and(|current| current.id == id && Arc::ptr_eq(&opening, &current.opening))
};
let same_opening = is_current.clone();
let source = open.source;
let is_live = move |app: &VectorcraftApp| {
same_opening(app) && app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
same_opening(app)
&& app.session.documents().iter().any(|doc| Some((doc.uid, doc.reverts)) == source)
&& app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
};
pick_texture_while(app, Owner::Document, is_live, move |app, path, fields| {
if !is_current(app) {
@@ -587,6 +700,39 @@ mod tests {
app.session.doc().unwrap().history.undo.len()
}
#[test]
fn edit_and_add_new_still_open_after_an_idle_effect_prompt() {
for (choice, editing) in [("proceed", true), ("alternate", false)] {
let mut app = app();
let node = rect(&mut app, 10);
app.run("effect.apply", json!({"ids": [node], "effect": "distort.roughen", "item": null, "params": {"size": 19, "detail": 8}})).unwrap();
app.run("select.set", json!({"ids": [node]})).unwrap();
let undo = steps(&app);
assert_eq!(app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(), json!({"pending": "effectExists"}));
let prompt = id(&app);
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
for _ in 0..3 {
super::super::host::pump(&mut app, &ctx);
assert!(host.with(|h| h.get_by_id::<StandardPrompt>(prompt).is_some()));
}
host.with(|h| {
h.set_json_field(&ctx, prompt, "choice", json!(choice)).unwrap();
assert!(h.confirm_by_id(&ctx, prompt));
});
super::super::host::pump(&mut app, &ctx);
let open = app.effect_dialogs.effect.as_ref().expect("the accepted choice opens the effect options");
assert!(!open.asking);
assert_eq!(open.cx.editing, editing);
assert_eq!(open.index, editing.then_some(0));
if editing {
assert_eq!(number(&mut app, "size"), Some(19.0));
}
assert_eq!(steps(&app), undo, "choosing the options has not yet committed an edit");
}
}
/// An applied effect's dialog opened on a shared row of a mixed selection (`aligned`) edits
/// each object's own copy on OK: the row changed is sent, every other value stays as stored.
#[test]
@@ -879,4 +1025,174 @@ mod tests {
ok(&mut app);
assert_eq!(params(&app, node)["centerX"].as_f64(), Some(0.5));
}
fn standalone_effect_source(app: &mut VectorcraftApp) {
app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap();
set(app, "size", json!(16.0));
set(app, "preview", json!(true));
}
fn effect_frame(app: &mut VectorcraftApp) {
let ctx = app.ui_ctx.clone().unwrap();
super::super::host::pump(app, &ctx);
}
#[test]
fn old_effect_approval_does_not_answer_a_new_edit_or_add_question() {
let mut app = app();
let first = rect(&mut app, 10);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let second = rect(&mut app, 80);
app.run("effect.apply", json!({"ids": [second], "effect": "distort.roughen", "params": {"size": 19, "detail": 8}})).unwrap();
app.run("select.set", json!({"ids": [second]})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap();
set(&mut app, "size", json!(16.0));
let old_id = id(&app);
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
assert!(!host.with(|h| h.confirm_by_id(&ctx, old_id)));
assert_eq!(host.with(|h| h.held_state(old_id)), Some(craft::ui::dialog::HeldOk::Waiting));
app.run("document.activate", json!({"index": 1})).unwrap();
let before = app.session.active().unwrap().doc.clone();
let undo = steps(&app);
assert_eq!(app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(), json!({"pending": "effectExists"}));
let question = id(&app);
assert_ne!(question, old_id);
effect_frame(&mut app);
assert_eq!(app.session.active().unwrap().doc, before, "old approval leaves the second drawing intact");
assert_eq!(steps(&app), undo);
let current = app.effect_dialogs.effect.as_ref().expect("the new question still has its opening");
assert_eq!(current.id, question);
assert!(current.asking);
host.with(|h| {
h.set_json_field(&ctx, question, "choice", json!("proceed")).unwrap();
assert!(h.confirm_by_id(&ctx, question));
});
effect_frame(&mut app);
set(&mut app, "size", json!(28.0));
ok(&mut app);
assert_eq!(params(&app, second)["size"], 28.0);
assert_eq!(steps(&app), undo + 1);
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(first)).unwrap().appearance.effects.is_empty());
}
#[test]
fn standalone_effect_preview_stays_with_the_opening_drawing() {
let mut app = app();
let original = rect(&mut app, 10);
standalone_effect_source(&mut app);
effect_frame(&mut app);
assert_eq!(params(&app, original)["size"], 16.0);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
rect(&mut app, 80);
let other = app.session.active().unwrap().doc.clone();
effect_frame(&mut app);
assert!(app.session.active().unwrap().doc == other, "effect preview reached the other drawing");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
effect_frame(&mut app);
assert_eq!(params(&app, original)["size"], 16.0, "preview resumes on the opening drawing");
}
#[test]
fn standalone_effect_ok_can_be_retried_on_the_opening_drawing() {
let mut app = app();
let original = rect(&mut app, 10);
standalone_effect_source(&mut app);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
rect(&mut app, 80);
let before = app.session.active().unwrap().doc.clone();
let history = steps(&app);
ok(&mut app);
assert!(app.session.active().unwrap().doc == before, "effect OK reached the other drawing");
assert_eq!(steps(&app), history);
app.run("document.activate", json!({"index": 0})).unwrap();
let history = steps(&app);
ok(&mut app);
assert_eq!(params(&app, original)["size"], 16.0);
assert_eq!(steps(&app), history + 1);
}
#[test]
fn standalone_effect_cancel_preserves_the_other_drawings_edit() {
let mut app = app();
rect(&mut app, 10);
standalone_effect_source(&mut app);
effect_frame(&mut app);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
rect(&mut app, 80);
app.session.begin_interaction("Other drawing's edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
let before = app.session.active().unwrap().doc.clone();
let (ctx, id) = (app.ui_ctx.clone().unwrap(), id(&app));
assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id)));
effect_frame(&mut app);
assert!(app.session.in_interaction(), "effect Cancel ended the other drawing's edit");
assert!(app.session.active().unwrap().doc == before);
}
#[test]
fn standalone_effect_cancel_preserves_a_replaced_preview_in_the_same_drawing() {
let mut app = app();
rect(&mut app, 10);
standalone_effect_source(&mut app);
effect_frame(&mut app);
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
let before = app.session.active().unwrap().doc.clone();
let (ctx, id) = (app.ui_ctx.clone().unwrap(), id(&app));
assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id)));
effect_frame(&mut app);
assert!(app.session.in_interaction(), "effect Cancel ended a different preview on the same interaction");
assert!(app.session.active().unwrap().doc == before);
}
#[test]
fn standalone_effect_replacement_keeps_its_own_preview() {
let mut app = app();
let node = rect(&mut app, 10);
standalone_effect_source(&mut app);
effect_frame(&mut app);
app.run("effect.dialog", json!({"effect": "distort.zigZag"})).unwrap();
set(&mut app, "size", json!(12.0));
set(&mut app, "preview", json!(true));
effect_frame(&mut app);
assert!(app.effect_dialogs.effect.is_some(), "a replaced dialog's Cancel removed the new opening");
assert_eq!(params(&app, node)["size"], 12.0);
ok(&mut app);
assert_eq!(params(&app, node)["size"], 12.0);
}
#[test]
fn standalone_effect_ok_cannot_change_the_reloaded_drawing() {
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let folder = vectorcraft_testkit::TempDir::new("effect-opening-revert");
let path = folder.join("drawing.vectorcraft");
let original = rect(&mut app, 10);
app.run("file.saveAs", json!({"path": path})).unwrap();
rect(&mut app, 80);
app.run("select.set", json!({"ids": [original]})).unwrap();
let source = app.session.active().unwrap();
let (uid, generation) = (source.uid, source.reverts);
standalone_effect_source(&mut app);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reloaded = app.session.active().unwrap();
assert_eq!(reloaded.uid, uid);
assert_ne!(reloaded.reverts, generation);
app.run("select.set", json!({"ids": [original]})).unwrap();
let before = app.session.active().unwrap().doc.clone();
let history = steps(&app);
ok(&mut app);
assert!(app.session.active().unwrap().doc == before, "effect OK reached the reloaded drawing");
assert_eq!(steps(&app), history);
standalone_effect_source(&mut app);
ok(&mut app);
assert_eq!(params(&app, original)["size"], 16.0, "a fresh opening applies to the restored drawing");
}
}
+94 -7
View File
@@ -308,6 +308,8 @@ struct LibraryDoc {
/// What the dialog reads from the app: the app pushes it in every pass ([`pump`]), since the body gets no app.
struct Lists {
/// The drawing contents these names and thumbnails came from.
drawing: (u64, u64),
/// The document's design names.
designs: Vec<String>,
/// The loaded libraries' designs the document lacks ([`library_designs`]).
@@ -324,6 +326,7 @@ impl Lists {
let designs = names(app)?;
let st = app.session.active().ok_or("no document open")?;
Ok(Lists {
drawing: (st.uid, st.reverts),
designs,
libraries: library_designs(app),
has_art: !st.selection.is_empty(),
@@ -408,6 +411,7 @@ pub(crate) struct GraphDesignDialog {
/// What [`pump`] takes from the open dialog to run.
struct Work {
actions: Vec<Action>,
list_drawing: (u64, u64),
answer: Option<(Answer, GraphTarget)>,
document: Option<(u64, u64)>,
}
@@ -455,9 +459,14 @@ impl GraphDesignDialog {
self.set_selection(keys);
}
/// Takes what the app pushed in, and drops the selected designs it no longer has.
/// Takes what the app pushed in, and drops selections and drafts that no longer belong to it.
fn feed(&mut self, lists: Lists) {
let drawing_changed = self.lists.drawing != lists.drawing;
self.lists = lists;
if self.kind == Kind::Design && drawing_changed {
self.select(self.lists.designs.first().map(|name| DesignKey::document(name)).into_iter().collect());
return;
}
let chosen = self.chosen();
let kept: Vec<DesignKey> = chosen.iter().filter(|k| self.lists.holds(k)).cloned().collect();
if kept.len() != chosen.len() {
@@ -468,7 +477,7 @@ impl GraphDesignDialog {
fn take_work(&mut self) -> Work {
let answer = self.held.take().and_then(|answer| self.target.clone().map(|target| (answer, target)));
let document = self.target.as_ref().map(|target| target.document);
Work { actions: std::mem::take(&mut self.actions), answer, document }
Work { actions: std::mem::take(&mut self.actions), list_drawing: self.lists.drawing, answer, document }
}
/// What OK files.
@@ -847,10 +856,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let Some(work) = dialogs.with(|host| host.get_mut::<GraphDesignDialog>().map(GraphDesignDialog::take_work)) else { return };
let mut effects = Effects::default();
for action in &work.actions {
match app.run("graph.design", action.params()) {
Ok(r) => action.apply(&r, &mut effects),
Err(e) => app.status(e),
if app.session.active().is_some_and(|active| (active.uid, active.reverts) == work.list_drawing) {
for action in &work.actions {
match app.run("graph.design", action.params()) {
Ok(r) => action.apply(&r, &mut effects),
Err(e) => app.status(e),
}
}
}
let answered = work.answer.map(|(answer, target)| answer.run(app, &target));
@@ -879,7 +890,7 @@ mod tests {
use egui_kittest::kittest::Queryable;
use serde_json::{Value, json};
use super::GraphDesignDialog;
use super::{Action, GraphDesignDialog};
use crate::VectorcraftApp;
fn app_with_design() -> (VectorcraftApp, egui::Context) {
@@ -920,6 +931,82 @@ mod tests {
assert!(!dialogs.with(|host| host.is_open::<GraphDesignDialog>()));
}
fn graph_design_manager_changes_drawing(queued_rename: bool) {
for revert in [false, true] {
let (mut app, ctx) = app_with_design();
let dir = vectorcraft_testkit::TempDir::new("graph-design-manager-drawing");
if revert {
let path = dir.join("graph-designs.vectorcraft");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("shape.rectangle", json!({"x": 35, "y": 20, "width": 15, "height": 10})).unwrap();
} else {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 35, "y": 20, "width": 15, "height": 10})).unwrap();
app.run("graph.design", json!({"new": true})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
}
super::open_design(&mut app).unwrap();
set(&app, &ctx, "name", json!("Old draft")).unwrap();
let uid = app.session.active().unwrap().uid;
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 700.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if !std::mem::replace(&mut fonts, true) {
crate::testing::install(ui.ctx());
return;
}
app.dialogs().unwrap().with(|host| host.run(ui));
},
app,
);
h.run_steps(4);
if queued_rename {
h.get_by_label("Rename").click_accesskit();
h.run_steps(1);
let dialogs = h.state().dialogs().unwrap();
let queued = dialogs.with(|host| matches!(host.get::<GraphDesignDialog>().unwrap().actions.as_slice(), [Action::Rename { .. }]));
assert!(queued, "the old list filed a Rename action before the drawing changed");
}
let app = h.state_mut();
if revert {
let generation = app.session.active().unwrap().reverts;
app.run("file.revert", json!({"confirmed": true})).unwrap();
let drawing = app.session.active().unwrap();
assert_eq!((drawing.uid, drawing.reverts), (uid, generation + 1));
} else {
app.run("document.activate", json!({"index": 1})).unwrap();
assert_ne!(app.session.active().unwrap().uid, uid);
}
let undo = app.session.active().unwrap().history.undo.len();
super::pump(app, &ctx);
assert_eq!(super::names(app).unwrap(), ["New Design"], "an old Rename action leaves other drawing contents intact");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(fields(app)["name"], "New Design", "the old Name draft is retired when the list refreshes");
set(app, &ctx, "name", json!("Fresh draft")).unwrap();
h.run_steps(2);
h.get_by_label("Rename").click();
h.run_steps(3);
let app = h.state_mut();
super::pump(app, &ctx);
assert_eq!(super::names(app).unwrap(), ["Fresh draft"], "the refreshed list can rename its own design");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
}
#[test]
fn graph_design_manager_refreshes_rename_drafts_after_the_drawing_changes() {
graph_design_manager_changes_drawing(false);
}
#[test]
fn graph_design_manager_drops_queued_renames_after_the_drawing_changes() {
graph_design_manager_changes_drawing(true);
}
#[test]
fn graph_column_and_marker_keep_their_opening_graph() {
for (graph_kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
@@ -63,7 +63,10 @@ fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result<V
if !active.is_some_and(|active| active.uid == document) {
return Err(tl!("This graphic style belongs to the document that opened the dialog.").to_owned());
}
target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ())
target
.run(app, result.fields.text("name").unwrap_or_default())
.map(|_| ())
.map_err(|reason| crate::i18n::message(crate::i18n::current(), &reason))
};
host::open_held(app, dialog, ok).ok_or("no window")?;
Ok(Value::Null)
+2 -3
View File
@@ -8,7 +8,6 @@ use super::{
width_point,
};
use crate::VectorcraftApp;
use crate::dialogs::preview::LivePreview;
/// What the object dialogs keep between frames. Held OK records are `app.held`, not here.
#[derive(Default)]
@@ -27,8 +26,8 @@ pub(crate) struct ObjectDialogs {
pub flare: Option<flare_options::Open>,
/// The open shape dialog's Constrain state, shared with its link control.
pub shape_link: bool,
/// The open Blend Options dialog's live preview.
pub blend: Option<LivePreview>,
/// The open Blend Options dialog's drawing and live preview.
pub blend: Option<blend_options::Open>,
/// The open Indexed Color dialog's live preview.
pub indexed: Option<indexed_color::Open>,
/// The open Gap Options dialog's live preview.
@@ -34,7 +34,7 @@ const CENTRE: usize = 4;
const FREE: [&str; 4] = ["transforms", "fileDimensions", "fit", "fill"];
fn params() -> Vec<Param> {
let options = PRESERVE.iter().map(|(value, label)| ((*value).to_owned(), Label::from(*label))).collect();
let options = PRESERVE.iter().map(|(value, label)| ((*value).to_owned(), Label::from(tl!(label).to_owned()))).collect();
vec![
Param::new("preserve", tl!("Preserve:"), ParamKind::choice(options, Some("transforms".into()))),
reference_param("align", tl!("Alignment:")).enabled_when_in("preserve", FREE),
@@ -654,6 +654,9 @@ mod tests {
/// set, and redraw the documents.
#[test]
fn cancel_puts_back_a_view_whose_profile_was_removed() {
if !crate::testing::in_own_process("dialogs::proof_setup::tests::cancel_puts_back_a_view_whose_profile_was_removed") {
return;
}
let _v = DefaultProofView::new();
let (mut app, ctx) = app();
let name = "Proof Setup Removed RGB";
@@ -760,6 +763,9 @@ mod tests {
/// stays open with the proof view as it was.
#[test]
fn ok_with_an_unknown_device_keeps_the_dialog_open() {
if !crate::testing::in_own_process("dialogs::proof_setup::tests::ok_with_an_unknown_device_keeps_the_dialog_open") {
return;
}
let _v = DefaultProofView::new();
let (mut app, ctx) = app();
let name = "Proof Setup Gone RGB";
@@ -285,6 +285,9 @@ fn save_summary_sees_a_deleted_flattener_preset() {
/// dialog stays open: they are then refused, and nothing is written.
#[test]
fn save_summary_sees_a_removed_profile() {
if !crate::testing::in_own_process("dialogs::save_pdf::tests::save_summary_sees_a_removed_profile") {
return;
}
use vectorcraft_color::cms;
let name = "Summary Stamp CMYK";
// The built-in CMYK profile's file renamed `name`: padded with spaces, which names drop.
+145 -8
View File
@@ -12,8 +12,8 @@ use craft::draw::ui::slice::{
DivideBy, DivideSlices, DivideSlicesDialog, SliceBackground, SliceCellAlign, SliceCellVAlign, SliceKind, SliceOptions, SliceOptionsDialog,
};
use craft::theme::Srgba;
use craft::ui::dialog::DialogResult;
use serde_json::{Map, Value, json};
use vectorcraft_doc::NodeId;
use crate::VectorcraftApp;
// PLAN: assumed `crate::canvas::general_lengths(app: &VectorcraftApp) -> LengthUnits` (cv.B5b)
@@ -24,6 +24,31 @@ pub const OPTIONS: &str = "sliceOptions";
/// The dialog kind of Divide Slices.
pub const DIVIDE: &str = "divideSlices";
#[derive(Default)]
pub(crate) struct SliceDialogs {
options: Option<Target>,
divide: Option<Target>,
}
/// The document and effective slice selection used when opening either dialog.
#[derive(PartialEq)]
struct Target {
document: u64,
slices: Vec<NodeId>,
}
impl Target {
fn new(document: u64, mut slices: Vec<NodeId>) -> Self {
slices.sort_unstable();
Self { document, slices }
}
fn current(app: &VectorcraftApp) -> Option<Self> {
let document = app.session.active()?.uid;
Some(Self::new(document, app.session.selected_slice_ids()))
}
}
/// The command's key of each slice type, alignment and vertical alignment.
const KINDS: [(&str, SliceKind); 3] = [("image", SliceKind::Image), ("noImage", SliceKind::NoImage), ("htmlText", SliceKind::HtmlText)];
const ALIGNS: [(&str, SliceCellAlign); 4] =
@@ -95,6 +120,7 @@ fn divide_json(d: &DivideSlices) -> Value {
/// Open Slice Options on the selected slices' options (those of the first one).
pub fn open_options(app: &mut VectorcraftApp) -> Result<Value, String> {
let source = Target::current(app).ok_or("no document open")?;
let v = app.session.execute("object.slice.options", &json!({})).map_err(|e| e.to_string())?;
let map = v.as_object().cloned().unwrap_or_default();
let mut kinds = vec![SliceKind::Image, SliceKind::NoImage];
@@ -102,7 +128,12 @@ pub fn open_options(app: &mut VectorcraftApp) -> Result<Value, String> {
kinds.push(SliceKind::HtmlText);
}
let dialog = SliceOptionsDialog::new(options_of(&map)).kinds(&kinds);
app.dialogs().ok_or("no window")?.with(|host| host.open(dialog));
app.dialogs().ok_or("no window")?.with(|host| {
host.open(dialog);
// Replacing a still-open dialog leaves its Cancel behind.
let _ = host.take::<SliceOptionsDialog>();
});
app.slice_dialogs.options = Some(source);
Ok(Value::Null)
}
@@ -110,10 +141,16 @@ pub fn open_options(app: &mut VectorcraftApp) -> Result<Value, String> {
pub fn open_divide(app: &mut VectorcraftApp) -> Result<Value, String> {
let lengths = general_lengths(app);
let st = app.session.active().ok_or("no document open")?;
let first = st.selection.slices.iter().chain(&st.selection.objects).find_map(|id| st.doc.slice_bounds(*id));
let selected = app.session.selected_slice_ids();
let first = selected.iter().find_map(|id| st.doc.slice_bounds(*id));
let source = Target::new(st.uid, selected);
let (w, h) = first.map_or((50.0, 50.0), |r| (r.width() / 2.0, r.height() / 2.0));
let dialog = DivideSlicesDialog::new(DivideSlices::new(Some(DivideBy::Count(2)), Some(DivideBy::Count(2)))).lengths(lengths).start_sizes(h, w);
app.dialogs().ok_or("no window")?.with(|host| host.open(dialog));
app.dialogs().ok_or("no window")?.with(|host| {
host.open(dialog);
let _ = host.take::<DivideSlicesDialog>();
});
app.slice_dialogs.divide = Some(source);
Ok(Value::Null)
}
@@ -123,11 +160,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(host) = app.dialogs() else { return };
let (options, divide) = host.with(|h| (h.take::<SliceOptionsDialog>(), h.take::<DivideSlicesDialog>()));
let answers = [
options.and_then(|r| if let DialogResult::Ok(o) = r { Some(("object.slice.options", options_json(&o))) } else { None }),
divide.and_then(|r| if let DialogResult::Ok(d) = r { Some(("object.slice.divide", divide_json(&d))) } else { None }),
options.and_then(|r| {
let source = app.slice_dialogs.options.take();
r.ok().map(|o| (source, "object.slice.options", options_json(&o)))
}),
divide.and_then(|r| {
let source = app.slice_dialogs.divide.take();
r.ok().map(|d| (source, "object.slice.divide", divide_json(&d)))
}),
];
for (cmd, params) in answers.into_iter().flatten() {
if let Err(e) = app.run(cmd, params) {
for (source, cmd, params) in answers.into_iter().flatten() {
if !source.is_some_and(|source| Some(source) == Target::current(app)) {
app.status(tl!("The slice selection changed while the dialog was open."));
} else if let Err(e) = app.run(cmd, params) {
app.status(e);
}
}
@@ -137,6 +182,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
mod tests {
use super::*;
use craft::ui::dialog::{DialogHost, DialogId};
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
fn app() -> VectorcraftApp {
@@ -171,6 +217,97 @@ mod tests {
enabled
}
fn add_slice(app: &mut VectorcraftApp, x: f64) -> NodeId {
let id = app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.run("object.slice.make", json!({"ids": [id]})).unwrap();
NodeId(id)
}
fn select_slice(app: &mut VectorcraftApp, id: NodeId) {
app.run("object.slice.select", json!({"slices": [id.0]})).unwrap();
}
fn check_changed_selection(dialog: &str, divide: bool) {
let mut app = app();
let source = app.session.active().unwrap().doc.slice_ids()[0];
let destination = add_slice(&mut app, 80.0);
select_slice(&mut app, source);
app.run(dialog, json!({})).unwrap();
if !divide {
set(&app, "name", json!("Original"));
}
select_slice(&mut app, destination);
let st = app.session.active().unwrap();
let undo = st.history.undo.len();
let document = st.doc.clone();
assert!(ok(&mut app));
let st = app.session.active().unwrap();
assert_eq!(*st.doc, *document, "the changed selection is untouched");
assert_eq!(st.history.undo.len(), undo);
assert_eq!(app.ui.status, "The slice selection changed while the dialog was open.");
}
#[test]
fn stale_slice_dialog_options_leaves_the_new_selection_untouched() {
check_changed_selection("object.slice.options", false);
}
#[test]
fn stale_slice_dialog_divide_leaves_the_new_selection_untouched() {
check_changed_selection("object.slice.divide", true);
}
#[test]
fn stale_slice_dialog_refuses_a_different_document_with_matching_selected_ids() {
let mut app = app();
let from = app.session.active().unwrap().doc.slice_ids()[0];
app.run("object.slice.options", json!({})).unwrap();
set(&app, "name", json!("Source"));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let to = add_slice(&mut app, 0.0);
select_slice(&mut app, to);
assert_eq!(from, to, "selection IDs are local to each document");
let st = app.session.active().unwrap();
let undo = st.history.undo.len();
assert!(ok(&mut app));
let st = app.session.active().unwrap();
assert_eq!(st.doc.slice_options(to).unwrap().name, "");
assert_eq!(st.history.undo.len(), undo);
}
#[test]
fn replacing_slice_options_keeps_the_new_dialogs_target() {
let mut app = app();
app.run("object.slice.options", json!({})).unwrap();
let other = add_slice(&mut app, 80.0);
select_slice(&mut app, other);
app.run("object.slice.options", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
pump(&mut app, &ctx);
set(&app, "name", json!("Replacement"));
assert!(ok(&mut app));
assert_eq!(app.session.active().unwrap().doc.slice_options(other).unwrap().name, "Replacement");
}
#[test]
fn confirming_slice_options_still_works_when_the_same_slices_are_selected_in_a_different_order() {
let mut app = app();
let first = app.session.active().unwrap().doc.slice_ids()[0];
let second = add_slice(&mut app, 80.0);
app.run("object.slice.select", json!({"slices": [first.0, second.0]})).unwrap();
app.run("object.slice.options", json!({})).unwrap();
set(&app, "alt", json!("Two slices"));
app.run("object.slice.select", json!({"slices": [second.0, first.0]})).unwrap();
assert!(ok(&mut app));
let document = &app.session.active().unwrap().doc;
assert_eq!(document.slice_options(first).unwrap().alt, "Two slices");
assert_eq!(document.slice_options(second).unwrap().alt, "Two slices");
}
#[test]
fn slice_options_opens_on_the_selection_and_ok_sets_them() {
let mut app = app();
+106 -1
View File
@@ -131,8 +131,9 @@ fn options(fields: &DialogFields) -> Value {
fn confirm(app: &mut VectorcraftApp, params: &Value, result: &ParamResult) -> Result<(), String> {
let mut params = params.clone();
params["text"] = options(&result.fields);
crate::place::run_for_user(app, &params)?;
app.ui.text_import = params["text"].clone();
crate::place::run_for_user(app, &params).map(|_| ())
Ok(())
}
/// What the three import dialogs' tests share: a window for the host, and the open dialog's fields,
@@ -229,6 +230,110 @@ mod tests {
found
}
#[test]
fn refused_text_import_does_not_change_the_next_files_options() {
use craft::ui::dialog::HeldOk;
use egui::accesskit::{Role, TreeUpdate};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
fn control(tree: &TreeUpdate, source: &str, role: Role, scope: Option<Rect>) -> Rect {
fn plain(label: &str) -> &str {
label.trim_end().trim_end_matches([':', ':']).trim_end()
}
let caption = crate::i18n::t(source);
tree.nodes
.iter()
.map(|(_, node)| node)
.filter(|node| node.role() == role && node.label().is_some_and(|label| plain(label) == plain(caption)))
.filter_map(|node| {
let b = node.bounds()?;
Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))
})
.find(|rect| scope.is_none_or(|modal| modal.contains(rect.center())))
.unwrap_or_else(|| panic!("missing {role:?} {caption:?} in {scope:?}"))
}
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut app = host::app();
app.session.prefs.interface_language = "en".into();
app.placing.off_the_ui_thread = true;
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
let rect = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [rect]})).unwrap();
let prior = json!({"platform": "windows", "characterSet": "unicode", "removeLineReturns": false, "removeParagraphReturns": false});
app.ui.text_import = prior.clone();
let ctx = app.ui_ctx.clone().unwrap();
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
time += 0.1;
let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() };
crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap()
};
let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate| {
for _ in 0..5 {
frame(app, vec![]);
}
frame(app, vec![])
};
let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate, pos| {
frame(app, vec![Event::PointerMoved(pos)]);
for pressed in [true, false] {
frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(app, vec![]);
};
let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate, key, modifiers| {
for pressed in [true, false] {
frame(app, vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }]);
}
};
let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(b"one two")});
let mut replace = file.clone();
replace["replace"] = json!(true);
settle(&mut app, &mut frame);
assert_eq!(app.run("file.place", replace).unwrap()["dialog"], KIND);
let tree = settle(&mut app, &mut frame);
let modal = control(&tree, "Text Import Options", Role::Dialog, None);
assert!(screen.expand(0.5).contains_rect(modal));
let checkbox = control(&tree, "Replace", Role::CheckBox, Some(modal));
click(&mut app, &mut frame, checkbox.center());
let tree = settle(&mut app, &mut frame);
let number = control(&tree, "or more spaces with a tab", Role::SpinButton, Some(modal));
let ok = control(&tree, "OK", Role::Button, Some(modal));
click(&mut app, &mut frame, number.center());
press(&mut app, &mut frame, Key::A, Modifiers::COMMAND);
frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("4".into())]);
press(&mut app, &mut frame, Key::Tab, Modifiers::NONE);
settle(&mut app, &mut frame);
let fields = host::fields(&app, KIND);
assert_eq!(fields["replaceSpaces"], true, "actual toggle");
assert_eq!(fields["spaces"].as_f64(), Some(4.0), "actual focused text");
// The original drawing is still open, but an automation command removed the Replace target.
app.run("select.set", json!({"ids": []})).unwrap();
let history = app.session.doc().unwrap().history.undo.len();
click(&mut app, &mut frame, ok.center());
let tree = settle(&mut app, &mut frame);
let opened = host::open_dialog(&app, KIND).expect("the refusal kept the dialog open");
let refusal = app.dialogs().unwrap().with(|h| h.held_state(opened.id));
assert!(
matches!(refusal, Some(HeldOk::Refused(reason)) if reason.as_str().contains("select the one object")),
"expected Replace target refusal"
);
assert_eq!(app.session.doc().unwrap().history.undo.len(), history, "refused import did not edit the document");
let modal = control(&tree, "Text Import Options", Role::Dialog, None);
let cancel = control(&tree, "Cancel", Role::Button, Some(modal));
click(&mut app, &mut frame, cancel.center());
settle(&mut app, &mut frame);
assert!(!host::is_open(&app, KIND), "Cancel closed the refusal");
assert_eq!(app.run("file.place", file).unwrap()["dialog"], KIND);
let fields = host::fields(&app, KIND);
assert_eq!((fields["replaceSpaces"].as_bool(), fields["spaces"].as_f64()), (Some(false), Some(3.0)));
assert_eq!(app.ui.text_import, prior, "only accepted settings are remembered");
}
#[test]
fn placing_a_text_file_asks_for_the_import_options_then_places_area_type() {
let mut app = host::app();
+13 -5
View File
@@ -63,8 +63,8 @@ pub(crate) struct Data {
pub bevels_file: bool,
/// The active document, for the symbol pictures.
pub doc: Option<Arc<Document>>,
/// The document that owns the object IDs accepted by the Graphics drop target.
pub document_uid: Option<u64>,
/// The opening document generation while it can still supply artwork to the Graphics drop target.
pub document: Option<(u64, u64)>,
/// The active document's version.
pub revision: u64,
/// Whether the active document has a selection.
@@ -87,7 +87,7 @@ pub(crate) fn data(app: &VectorcraftApp, effect: Option<&str>, params: &Map<Stri
bevels: effect.map(|e| revolve::bevel_options(app, params, e).0).unwrap_or_default(),
bevels_file: app.session.bevels.path().is_some(),
doc: st.map(|s| s.doc.clone()),
document_uid: st.map(|s| s.uid),
document: st.map(|s| (s.uid, s.reverts)),
revision: st.map_or(0, |s| s.revision),
selected: st.is_some_and(|s| !s.selection.objects.is_empty()),
surfaces: None,
@@ -352,6 +352,13 @@ fn surfaces(app: &mut VectorcraftApp, s: &Session, fields: &DialogFields, params
Some(listed)
}
/// Refresh drop eligibility before the dialog can receive a release in this frame.
pub(crate) fn sync_graphics_source(app: &VectorcraftApp) {
let Some(open) = &app.three_d_dialog else { return };
let source = open.source.filter(|&(uid, reverts)| app.session.documents().iter().any(|d| (d.uid, d.reverts) == (uid, reverts)));
open.data.write().unwrap_or_else(PoisonError::into_inner).document = source;
}
/// Once per frame: refreshes the rows' data, runs the preview, and, with Preview off, tries the values so the dialog
/// still says why OK would fail. `refuse` is called only from a result this pump produced: an idle pump leaves a
/// refusal standing until the values change.
@@ -467,16 +474,17 @@ mod drawing_tests {
fn three_d_ownership_preview_resumes_only_in_the_opening_drawing() {
let (mut app, original) = drawing();
open_effect(&mut app, true);
let first = app.session.active().unwrap().uid;
frame(&mut app);
assert_eq!(applied(&app, original), [EXTRUDE]);
let opening_document = read(&app.three_d_dialog.as_ref().unwrap().data).doc.clone().unwrap();
let other = second_drawing(&mut app);
frame(&mut app);
assert!(applied(&app, other).is_empty(), "3D preview reached the other drawing");
assert!(!app.session.in_interaction());
assert!(!gizmo_shown(&app));
assert!(!crate::canvas::revolve_editing(&app));
assert_eq!(read(&app.three_d_dialog.as_ref().unwrap().data).document_uid, Some(first));
let drawn_document = read(&app.three_d_dialog.as_ref().unwrap().data).doc.clone().unwrap();
assert!(Arc::ptr_eq(&drawn_document, &opening_document), "Map Art keeps the opening document");
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app);
assert_eq!(applied(&app, original), [EXTRUDE]);
@@ -174,11 +174,12 @@ fn body(ui: &mut Ui, fields: &mut DialogFields, cx: &mut CustomContext, data: &D
fn library(ui: &mut Ui, data: &Data, apply: bool) -> Option<Action> {
Text::new(tl!("Graphics")).show(ui);
let mut action = None;
let (Some(doc), Some(uid)) = (data.doc.clone(), data.document_uid) else { return action };
let Some(doc) = data.doc.clone() else { return action };
let source_drawing = data.document;
let names: Vec<String> = doc.symbols.iter().map(|s| s.name.clone()).collect();
let keys = crate::panels::symbols::document_symbols(&doc, data.revision);
let source = keyed(&names[..], |name: &String| name.clone()).with_text(|name| Cow::Borrowed(name.as_str()));
let drop_art = DropAction::<PanelDrag>::new(move |drag| matches!(drag, PanelDrag::Art { document, .. } if *document == uid));
let drop_art = DropAction::<PanelDrag>::new(move |drag| source_drawing.is_some_and(|(uid, reverts)| drag.artwork_for(uid, reverts).is_some()));
let mut dropped = drop_art.show(ui, |ui, _| {
TileGrid::new(tl!("Graphics")).activate(ActivateOn::Click).show_items(ui, &source, &mut |name, _| {
let tip = if apply { name.clone() } else { format!("{name}: {}", tl!("Select a 3D object to map the graphic onto it.")) };
@@ -199,7 +200,9 @@ fn library(ui: &mut Ui, data: &Data, apply: bool) -> Option<Action> {
action = Some(Action::Map(name));
}
}
if let Some(PanelDrag::Art { ids, .. }) = dropped.output.dropped {
if let Some((uid, reverts)) = source_drawing
&& let Some(ids) = dropped.output.dropped.as_ref().and_then(|drag| drag.artwork_for(uid, reverts))
{
action = Some(Action::Add(Some(ids.iter().map(|id| id.0).collect())));
}
if clicked(&Button::new(tl!("Add as Single Graphic")).enabled(data.selected).show(ui)) {
@@ -207,3 +210,73 @@ fn library(ui: &mut Ui, data: &Data, apply: bool) -> Option<Action> {
}
action
}
#[cfg(test)]
mod tests {
use super::*;
use crate::VectorcraftApp;
use crate::tests::panel_harness::Panel;
use craft::ui::contract::{ListDrag, Role};
use craft::ui::list::{List, ListRow};
use craft::ui::runtime::drag;
fn draw_graphics(app: &mut VectorcraftApp, ui: &mut Ui) {
let st = app.session.active().unwrap();
let payload = PanelDrag::Art { document: st.uid, reverts: st.reverts, ids: st.selection.objects.clone() };
ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| {
let keys = keyed(&[0_usize], |key: &usize| *key);
List::<usize>::new("Artwork")
.drag_payload(move |_: &ListDrag<usize>| Some(payload.clone()))
.show_items(ui, &keys, &mut |_, _| ListRow::new("Dragged artwork"));
});
if let Some(open) = &app.three_d_dialog {
let data = open.data.read().unwrap();
let _ = library(ui, &data, true);
}
}
#[test]
fn held_graphics_drag_is_refused_after_the_opening_drawing_reverts() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let dir = vectorcraft_testkit::TempDir::new("three-d-graphics-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let shape = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 50, "height": 50})).unwrap()["id"].clone();
app.run("threeD.addGraphic", json!({"name": "Opening Graphic"})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("shape.rectangle", json!({"x": 120, "y": 90, "width": 45, "height": 40})).unwrap();
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
assert!(app.session.set_active(0));
app.run("select.set", json!({"ids": [shape]})).unwrap();
let mut panel = Panel::new(app, draw_graphics);
panel.room(egui::vec2(800.0, 820.0));
super::super::three_d::open(&mut panel.app(), &json!({"effect": INFLATE})).unwrap();
panel.frame();
let from = panel.rect("Dragged artwork").center();
let to = panel.rect("Opening Graphic").center();
panel.drag_hold_role("Dragged artwork", Role::LIST_ITEM, to - from);
assert!(drag::mark(panel.ctx()).is_some(), "the opening drawing's drag is accepted");
assert!(panel.app().session.set_active(1));
panel.frame();
assert!(drag::mark(panel.ctx()).is_some(), "switching drawings retains the opening drawing's drag");
{
let mut app = panel.app();
assert!(app.session.set_active(0));
let source = app.session.active().unwrap();
let (uid, generation) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!(restored.uid, uid);
assert_ne!(restored.reverts, generation);
assert!(app.session.set_active(1));
}
panel.frame();
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the same drag is still in progress");
assert!(drag::mark(panel.ctx()).is_none(), "the drop stops accepting artwork from the reverted generation");
let _ = panel.rect("Opening Graphic");
panel.release();
}
}
+136 -8
View File
@@ -52,6 +52,9 @@ pub(crate) struct Open {
pub id: DialogId,
/// The preview OK commits and Cancel rolls back.
pub preview: LivePreview,
document: u64,
/// The tool reset count when the current preview record was created.
preview_tool_resets: u64,
}
/// Whether [`rows`] draws the link and the Relative / Absolute choice (Transform Each) or only the
@@ -470,6 +473,7 @@ fn form(fields: &mut DialogFields, shared: Shared, lengths: LengthUnits) -> Para
/// Opens Transform Each on the values it was last confirmed with.
pub(crate) fn open(app: &mut VectorcraftApp) {
let Some(ctx) = app.ui_ctx.clone() else { return };
let Some(document) = app.session.active().map(|doc| doc.uid) else { return };
let shared = shared_size(app, app.session.general_unit());
let lengths = crate::canvas::general_lengths(app); // PLAN: assumed path of cv.B5b
let mut f = opening_fields(app, &ctx);
@@ -482,19 +486,34 @@ pub(crate) fn open(app: &mut VectorcraftApp) {
let dialog = HostedParamDialog::new(&ctx, KEY, f, move |fields| form(fields, shared, lengths));
let options = HeldOptions { cancel: Some(Box::new(cancel)), ..Default::default() };
if let Some(id) = open_held_with(app, dialog, move |app, result| ok(app, &ctx, result), options) {
app.object_dialogs.each = Some(Open { id, preview: LivePreview::default() });
app.object_dialogs.each = Some(Open { id, preview: LivePreview::default(), document, preview_tool_resets: app.session.tool_resets() });
}
}
/// Cancel rolls the preview back.
fn cancel(app: &mut VectorcraftApp) {
if let Some(open) = app.object_dialogs.each.take() {
if let Some(open) = app.object_dialogs.each.take()
&& app.session.active().is_some_and(|doc| doc.uid == open.document)
&& app.session.tool_resets() == open.preview_tool_resets
{
open.preview.cancel(app);
}
}
/// Applies the confirmed values as one undo step.
fn commit(app: &mut VectorcraftApp, f: &DialogFields) -> Result<(), String> {
let open = app.object_dialogs.each.as_ref().ok_or("the Transform Each dialog is closed")?;
if app.session.active().is_none_or(|doc| doc.uid != open.document) {
let reason = if app.session.documents().iter().any(|doc| doc.uid == open.document) {
"switch back to the document where Transform Each was opened"
} else {
"the document where Transform Each was opened has closed"
};
return Err(reason.into());
}
if app.session.tool_resets() != open.preview_tool_resets && app.session.in_interaction() {
return Err("finish the active edit before applying Transform Each".into());
}
let p = with_scale_options(app, f, command_params(app, f))?;
let preview = app.object_dialogs.each.as_mut().map(|o| std::mem::take(&mut o.preview)).unwrap_or_default();
preview.commit(app, CMD, p).map(|_| ())
@@ -527,18 +546,28 @@ fn ok(app: &mut VectorcraftApp, ctx: &egui::Context, result: &ParamResult) -> Re
/// Each frame: previews the dialog's values while Preview is on, and turns a press of Copy into a
/// confirm with `copy` set.
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(id) = app.object_dialogs.each.as_ref().map(|o| o.id) else { return };
let Some((id, document)) = app.object_dialogs.each.as_ref().map(|o| (o.id, o.document)) else { return };
let Some(dialogs) = app.dialogs() else { return };
let Some((previewing, fields, action)) =
dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), d.fields().clone(), d.take_action())))
else {
return;
};
let mut p = command_params(app, &fields);
add_scale_options(app, &fields, &mut p);
if let Some(mut open) = app.object_dialogs.each.take() {
// The preview reports its own status; the answer of a run is not needed here.
let _ = open.preview.run(app, previewing, "Transform Each", CMD, &p);
if app.session.active().is_some_and(|doc| doc.uid == document)
&& let Some(mut open) = app.object_dialogs.each.take()
{
let tool_resets = app.session.tool_resets();
if open.preview_tool_resets == tool_resets || !app.session.in_interaction() {
if open.preview_tool_resets != tool_resets {
// A switch already ended the earlier preview.
open.preview = LivePreview::default();
open.preview_tool_resets = tool_resets;
}
let mut p = command_params(app, &fields);
add_scale_options(app, &fields, &mut p);
// The preview reports its own status; the answer of a run is not needed here.
let _ = open.preview.run(app, previewing, "Transform Each", CMD, &p);
}
app.object_dialogs.each = Some(open);
}
if action.as_deref() == Some(COPY) {
@@ -688,6 +717,105 @@ mod tests {
h.run_steps(3);
}
fn open_with_two_documents() -> (Harness, NodeId) {
let (mut app, first) = square_app();
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 70, "y": 50, "width": 30, "height": 65})).unwrap();
app.run("select.all", json!({})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
let mut h = start(app);
open(h.state_mut());
h.run_steps(2);
(h, first)
}
#[test]
fn preview_and_ok_stay_on_the_opening_document() {
let (mut h, first) = open_with_two_documents();
set(&mut h, "moveH", json!(45));
h.run_steps(2);
assert!(h.state().session.in_interaction(), "the opening document has a preview");
h.state_mut().run("document.activate", json!({"index": 1})).unwrap();
let other = h.state().session.doc().unwrap().doc.clone();
set(&mut h, "moveH", json!(100));
h.run_steps(2);
assert_eq!(h.state().session.doc().unwrap().doc, other, "Preview must leave the other document unchanged");
assert!(!h.state().session.in_interaction());
confirm(&mut h);
assert_eq!(h.state().session.doc().unwrap().doc, other, "OK must leave the other document unchanged");
assert!(h.state().object_dialogs.each.is_some(), "the draft is still open");
h.state_mut().run("document.activate", json!({"index": 0})).unwrap();
confirm(&mut h);
let doc = &h.state().session.doc().unwrap().doc;
assert!((doc.node(first).unwrap().geometric_bounds().unwrap().x0 - 120.0).abs() < 1e-6);
}
#[test]
fn copy_stays_on_the_opening_document() {
let (mut h, _) = open_with_two_documents();
set(&mut h, "preview", json!(false));
set(&mut h, "moveH", json!(100));
h.run_steps(2);
h.state_mut().run("document.activate", json!({"index": 1})).unwrap();
let other = h.state().session.doc().unwrap().doc.clone();
h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click();
h.run_steps(4);
assert_eq!(h.state().session.doc().unwrap().doc, other, "Copy must leave the other document unchanged");
assert_ne!(field(&h, COPY), Some(FieldValue::Bool(true)), "a refused Copy clears its flag");
h.state_mut().run("document.activate", json!({"index": 0})).unwrap();
h.get_by_role_and_label(egui::accesskit::Role::Button, "Copy").click();
h.run_steps(4);
assert_eq!(h.state().session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
}
#[test]
fn cancel_keeps_the_other_documents_gesture_active() {
let (mut h, _) = open_with_two_documents();
set(&mut h, "moveH", json!(45));
h.run_steps(2);
assert!(h.state().session.in_interaction());
h.state_mut().run("document.activate", json!({"index": 1})).unwrap();
let app = h.state_mut();
app.session.begin_interaction("Another gesture").unwrap();
app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
let (ctx, id) = (h.ctx.clone(), id(&h));
assert!(h.state().dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id)));
h.run_steps(3);
assert_eq!(h.state().session.doc().unwrap().doc, other, "Cancel preserves the other document's gesture");
assert!(h.state().session.in_interaction());
}
#[test]
fn switching_back_preserves_a_gesture_that_started_after_the_preview() {
let (mut h, _) = open_with_two_documents();
set(&mut h, "moveH", json!(45));
h.run_steps(2);
assert!(h.state().session.in_interaction());
let app = h.state_mut();
app.run("document.activate", json!({"index": 1})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.session.begin_interaction("Another gesture").unwrap();
app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap();
let gesture = app.session.doc().unwrap().doc.clone();
set(&mut h, "moveH", json!(100));
h.run_steps(2);
confirm(&mut h);
assert_eq!(h.state().session.doc().unwrap().doc, gesture, "Preview and OK leave the newer gesture alone");
assert!(h.state().session.in_interaction());
let (ctx, id) = (h.ctx.clone(), id(&h));
assert!(h.state().dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id)));
h.run_steps(2);
assert_eq!(h.state().session.doc().unwrap().doc, gesture, "Cancel also leaves the newer gesture alone");
assert!(h.state().session.in_interaction());
}
#[test]
fn ok_transforms_each_and_keeps_the_scale_options() {
let (mut app, node) = square_app();
+43 -2
View File
@@ -67,7 +67,7 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool
app.status(tl!("no document").to_string());
return true;
};
let document = st.uid;
let document = (st.uid, st.reverts);
let vars = st.doc.variables.clone();
let mut fields = DialogFields::new();
match id {
@@ -137,10 +137,13 @@ pub fn open(app: &mut VectorcraftApp, id: &str, preselect: Option<&str>) -> bool
/// Runs `command` with what the confirmed `result` says. A data set dialog answers the error, which
/// keeps it open with what was typed (a taken or empty name); any other command's error goes to the
/// status line and the dialog closes.
fn ok(app: &mut VectorcraftApp, document: u64, command: &str, result: &ParamResult) -> Result<(), String> {
fn ok(app: &mut VectorcraftApp, (document, reverts): (u64, u64), command: &str, result: &ParamResult) -> Result<(), String> {
let Some(st) = app.session.active().filter(|st| st.uid == document) else {
return Err(tl!("These changes belong to the document this dialog was opened for.").to_owned());
};
if st.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
let params = params_of(command, result, &st.doc.variables);
let Err(e) = app.run(command, params) else { return Ok(()) };
if matches!(command, "dataset.new" | "dataset.set") {
@@ -426,6 +429,44 @@ mod tests {
assert_eq!(sets["datasets"][0]["values"]["Title"], json!(null));
}
#[test]
fn a_data_set_draft_does_not_overwrite_values_restored_by_revert() {
let mut app = app_with_variables();
let dir = vectorcraft_testkit::TempDir::new("variable-draft-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("dataset.new", json!({"name": "Row", "values": {"Title": "Saved", "Badge": false}})).unwrap();
app.run("dataset.select", json!({"name": "Row"})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("data-set.vectorcraft")})).unwrap();
let uid = app.session.active().unwrap().uid;
let reverts = app.session.active().unwrap().reverts;
app.run("dataset.set", json!({"name": "Row", "values": {"Title": "In memory", "Badge": true}})).unwrap();
assert!(open(&mut app, "dataset.set", None));
set(&mut app, &value_key("Title"), json!("Stale draft"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let state = app.session.active().unwrap();
assert_eq!(state.uid, uid);
assert_ne!(state.reverts, reverts);
let undo = state.history.undo.len();
let saved = app.run("dataset.list", json!({})).unwrap();
assert_eq!(saved["datasets"][0]["values"]["Title"], json!({"text": "Saved"}));
ok(&mut app);
assert_eq!(app.run("dataset.list", json!({})).unwrap(), saved, "the old draft leaves the restored row intact");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(is_open(&app));
let (ctx, id) = (ctx(&app), open_id(&app));
assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id)));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(open(&mut app, "dataset.set", None));
set(&mut app, &value_key("Title"), json!("Fresh draft"));
ok(&mut app);
let edited = app.run("dataset.list", json!({})).unwrap();
assert_eq!(edited["datasets"][0]["values"]["Title"], json!({"text": "Fresh draft"}));
assert_eq!(edited["datasets"][0]["values"]["Badge"], json!({"visible": false}));
}
#[test]
fn editing_a_dataset_opens_with_the_rows_own_values() {
let mut app = app_with_variables();
+2
View File
@@ -288,6 +288,8 @@ pub struct VectorcraftApp {
pub(crate) three_d: panels::three_d::Model,
/// The open export option dialogs and what runs after each.
pub(crate) export_dialogs: dialogs::export_host::ExportDialogs,
/// The document and selection used by each open slice dialog.
pub(crate) slice_dialogs: dialogs::slices::SliceDialogs,
/// The drawing and loaded contents the open Package dialog saves and collects.
pub(crate) package_document: Option<(u64, u64)>,
/// Save for Web's renders and colour table.
+10 -2
View File
@@ -26,8 +26,8 @@ pub enum PanelDrag {
/// (`graphicStyle.new`), or with Alt held replaces the style it is dropped on with that
/// object's look (`graphicStyle.redefine`), the Symbols panel a symbol of it all
/// (`symbol.new`), the Swatches panel a pattern swatch of a copy (`object.pattern.make`) and
/// the Brushes panel an Art brush (`brush.new`).
Art { document: u64, ids: Vec<vectorcraft_doc::NodeId> },
/// the Brushes panel an Art brush (`brush.new`). `reverts` identifies the contents it came from.
Art { document: u64, reverts: u64, ids: Vec<vectorcraft_doc::NodeId> },
/// A Libraries panel graphic (`item`: its id in `library`): the canvas places a copy centred
/// where it is dropped (`library.use`); the panel moves it to where it is dropped.
LibraryGraphic { library: String, item: String },
@@ -53,6 +53,14 @@ pub struct SwatchRows {
}
impl PanelDrag {
/// The artwork IDs while the destination still shows the contents the drag came from.
pub(crate) fn artwork_for(&self, uid: u64, reload_count: u64) -> Option<&[vectorcraft_doc::NodeId]> {
match self {
Self::Art { document, reverts, ids } if (*document, *reverts) == (uid, reload_count) => Some(ids),
_ => None,
}
}
/// `paint` dragged from a Fill/Stroke proxy, a Recent Colors chip, a Color Guide color or the
/// Gradient panel's thumbnail. A gradient carries no placement: it fits the art it lands on
/// (freeform points are placed afresh there, coloured like the dragged ones).
+6 -3
View File
@@ -509,6 +509,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
return;
};
let uid = st.uid;
let reverts = st.reverts;
let model = app.ui.asset_export_panel.docs.entry(uid).or_default();
model.selection.items.retain(|id| st.doc.asset(*id).is_some());
let grid_id = ui.scope_id().with(("asset-export-grid", uid));
@@ -553,7 +554,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
footer = Some(bar);
});
let zone = footed.show(ui, |ui, _| {
let drop_art = DropAction::<PanelDrag>::new(move |p| matches!(p, PanelDrag::Art { document, .. } if *document == uid));
let drop_art = DropAction::<PanelDrag>::new(move |p| p.artwork_for(uid, reverts).is_some());
drop_art.sizing(Sizing::Fill).show(ui, |ui, _| {
if st.doc.assets.is_empty() {
Notice::new(Tone::Neutral, tl!("Drag art here, or select it and click +. Hold Alt for one asset of several objects."))
@@ -571,8 +572,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
})
});
if let Some(PanelDrag::Art { ids, .. }) = zone.inner.and_then(|zone| zone.output.dropped) {
seen.dropped = Some((ids.into_iter().map(|id| id.0).collect(), alt));
if let Some(payload) = zone.inner.and_then(|zone| zone.output.dropped)
&& let Some(ids) = payload.artwork_for(uid, reverts)
{
seen.dropped = Some((ids.iter().map(|id| id.0).collect(), alt));
}
for event in events {
match event {
+10 -11
View File
@@ -380,12 +380,9 @@ fn takes_art(ty: &str) -> bool {
matches!(ty, "scatter" | "art" | "pattern")
}
/// The ids of art dragged off the canvas of the document `doc` (its uid).
fn art_of(payload: &PanelDrag, doc: u64) -> Option<Vec<u64>> {
match payload {
PanelDrag::Art { document, ids, .. } if *document == doc => Some(ids.iter().map(|id| id.0).collect()),
_ => None,
}
/// The ids of art dragged from the displayed drawing.
fn art_of(payload: &PanelDrag, uid: u64, reverts: u64) -> Option<Vec<u64>> {
payload.artwork_for(uid, reverts).map(|ids| ids.iter().map(|id| id.0).collect())
}
/// The library and name of a brush dragged out of a brush library panel; a folder or another kind's item is none.
@@ -547,7 +544,7 @@ fn keys_of(sel: &Selection<String>, doc: u64) -> Selection<BrushKey> {
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let (list, current) = brushes(app);
let doc = app.session.active().map(|st| st.doc.clone());
let (uid, revision) = app.session.active().map_or((0, 0), |st| (st.uid, st.revision));
let (uid, revision, reverts) = app.session.active().map_or((0, 0, 0), |st| (st.uid, st.revision, st.reverts));
let memo = app.session.active().map(document_brushes).unwrap_or_default();
let first = by_name(&memo);
let multi = picked(app, &list, current.as_deref());
@@ -584,7 +581,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// the pass that drops and the held ones in a rerun pass, which takes no drop.
let art_onto = PresetDrop::new::<PanelDrag>(DropPlace::Onto, move |payload: &PanelDrag, at: &DropAt<BrushKey>| {
let DropAt::Onto(key) = at else { return false };
art_of(payload, uid).is_some()
payload.artwork_for(uid, reverts).is_some()
&& !key.group
&& type_of(first, key).is_some_and(takes_art)
&& craft::ui::runtime::pointer::frame(&ctx).pick_mods.alt
@@ -607,7 +604,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let mut footed = None;
let shown = Stack::new().label(tl!("Brushes")).fill().footer(|ui, _| footed = Some(footer(app, ui, on))).show(ui, |ui, _| {
let library = DropAction::<ListDrag<LibraryKey>>::new(|drag| library_brush(drag).is_some()).sizing(Sizing::Fill).show(ui, |ui, _| {
let art = DropAction::<PanelDrag>::new(move |payload| art_of(payload, uid).is_some()).sizing(Sizing::Fill).show(ui, |ui, _| browser(ui));
let art = DropAction::<PanelDrag>::new(move |payload| payload.artwork_for(uid, reverts).is_some())
.sizing(Sizing::Fill)
.show(ui, |ui, _| browser(ui));
(art.output.dropped, art.inner.unwrap_or_default())
});
(library.output.dropped, library.inner.unwrap_or_default())
@@ -642,7 +641,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
PresetEvent::Menu { target, command, .. } => item_command(app, &target, &command, multi.as_ref()),
PresetEvent::Reorder(edit) => move_brush(app, &rows(uid, &memo, &hidden), first, &edit),
PresetEvent::Dropped { at, payload, .. } => {
if let (DropAt::Onto(key), Some(ids)) = (&at, payload.get::<PanelDrag>().and_then(|p| art_of(p, uid))) {
if let (DropAt::Onto(key), Some(ids)) = (&at, payload.get::<PanelDrag>().and_then(|p| art_of(p, uid, reverts))) {
crate::dialogs::brush_replace_art::replace(app, &key.name, &ids);
}
}
@@ -650,7 +649,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
// Art dropped on the list opens New Brush for that art, as the New Brush button opens it for the selection.
if let Some(ids) = art_drop.as_ref().and_then(|p| art_of(p, uid))
if let Some(ids) = art_drop.as_ref().and_then(|p| art_of(p, uid, reverts))
&& let Err(e) = app.run("ui.newBrush", json!({ "ids": ids }))
{
app.status(e);
+4 -4
View File
@@ -258,8 +258,8 @@ fn drops_on_the_panel_run_their_commands() {
let star = t.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5}))["id"].as_u64().unwrap();
// Nothing selected: what New Brush makes comes from the dropped art.
t.run("select.none", json!({}));
let document = t.app().session.active().unwrap().uid;
t.drags(PanelDrag::Art { document, ids: vec![NodeId(star)] });
let (document, reverts) = t.app().session.active().map(|st| (st.uid, st.reverts)).unwrap();
t.drags(PanelDrag::Art { document, reverts, ids: vec![NodeId(star)] });
let (lib, before) = (t.run("brush.list", json!({})), brushes(&t.app()).0);
let at = t.target(on).center();
t.drop_at(at, modifiers);
@@ -275,8 +275,8 @@ fn drops_on_the_panel_run_their_commands() {
for (name, part) in [("Dots", "art"), ("Arrow", "art"), ("Chain", "side")] {
let mut t = Trial::new();
let id = t.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 12}))["id"].as_u64().unwrap();
let document = t.app().session.active().unwrap().uid;
t.drags(PanelDrag::Art { document, ids: vec![NodeId(id)] });
let (document, reverts) = t.app().session.active().map(|st| (st.uid, st.reverts)).unwrap();
t.drags(PanelDrag::Art { document, reverts, ids: vec![NodeId(id)] });
let steps = undo_count(&t.app());
let at = t.target(name).center();
t.drop_at(at, Modifiers::ALT);
+61 -2
View File
@@ -275,10 +275,10 @@ impl DisplayOrder<usize> for Names<'_> {
impl ItemSource<usize> for Names<'_> {}
/// A single-choice `Select` over `labels`: the index picked this pass.
/// The index of a committed choice over `labels`.
fn select(ui: &mut Ui, label: &'static str, current: usize, labels: &[&'static str]) -> Option<usize> {
let entries: Vec<Entry<usize>> = labels.iter().enumerate().map(|(i, l)| Entry::new(i, Label::from(*l))).collect();
Select::new(label, Bind::given(current), &entries).show(ui).value().copied()
Select::new(label, Bind::given(current), &entries).show(ui).events.committed().copied()
}
/// The color mode menu (CMYK, RGB, Lab and HSB) and its rows, each a rail and a number field, for the
@@ -654,6 +654,65 @@ mod tests {
&app.session.prefs.color_themes
}
#[test]
fn color_theme_choice_escape_keeps_custom_colors_and_selection() {
use crate::tests::panel_harness::Panel;
use egui::{Key, Modifiers};
let mut app = app();
let starting = five_colors(&mut app);
let undo = undo_len(&app);
let next = Harmony::ALL[0];
let label = harmony::label(next);
let mut panel = Panel::new(app, show);
assert_eq!(panel.value_role("Rule:", Role::COMBO_BOX).as_deref(), Some("Custom"));
panel.click_role("Rule:", Role::COMBO_BOX);
assert!(panel.shows(label), "the list is open");
panel.key(Key::ArrowDown, Modifiers::NONE);
let browsing = draft(&mut panel.app());
panel.key(Key::Escape, Modifiers::NONE);
assert!(!panel.shows(label), "Escape closes the list");
let cancelled = draft(&mut panel.app());
assert_eq!(cancelled, starting, "Escape keeps the original draft");
assert_eq!(browsing, starting, "browsing keeps the original draft");
assert_eq!(undo_len(&panel.app()), undo);
panel.click_role("Rule:", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
let applied = draft(&mut panel.app());
assert_eq!(applied.rule, Some(next));
assert_eq!(applied.colors, harmony::theme(next, starting.colors[starting.sel]));
assert_eq!(applied.sel, 0);
assert_eq!(undo_len(&panel.app()), undo);
}
#[test]
fn color_theme_choice_escape_keeps_slider_mode() {
use crate::tests::panel_harness::Panel;
use egui::{Key, Modifiers};
let mut app = app();
let starting = five_colors(&mut app);
app.ui.color_themes_panel.mode = Some(ColorPanelMode::RgbSliders);
let mut panel = Panel::new(app, show);
assert_eq!(panel.value_role("Color Mode:", Role::COMBO_BOX).as_deref(), Some("RGB"));
panel.click_role("Color Mode:", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
let browsing = panel.app().ui.color_themes_panel.mode;
panel.key(Key::Escape, Modifiers::NONE);
let cancelled = panel.app().ui.color_themes_panel.mode;
assert_eq!(cancelled, Some(ColorPanelMode::RgbSliders));
assert_eq!(browsing, Some(ColorPanelMode::RgbSliders));
assert_eq!(draft(&mut panel.app()), starting);
panel.click_role("Color Mode:", Role::COMBO_BOX);
panel.key(Key::ArrowDown, Modifiers::NONE);
panel.key(Key::Enter, Modifiers::NONE);
assert_eq!(panel.app().ui.color_themes_panel.mode, Some(ColorPanelMode::LabSliders));
assert_eq!(draft(&mut panel.app()), starting);
}
#[test]
fn a_short_color_themes_panel_keeps_create_actions_in_view() {
use craft::ui::testing::pointer;
+10 -9
View File
@@ -467,7 +467,7 @@ const AT_START: usize = 2;
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// The document is shared (an `Arc`): holding it while drawing copies nothing.
let Some((uid, doc)) = app.session.active().map(|d| (d.uid, d.doc.clone())) else {
let Some((uid, reverts, doc)) = app.session.active().map(|d| (d.uid, d.reverts, d.doc.clone())) else {
super::empty_state(ui, "dc-graphic-styles", tl!("No document"), tl!("Open a document to see its graphic styles."));
return;
};
@@ -484,7 +484,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
// The browser's own state (an open rename field, the scroll position) is kept per document.
let browser_id = ui.make_persistent_id(("graphic-styles-browser", uid));
let list = PresetBrowser::<StyleKey>::list_id(browser_id);
let takes_object = move |drag: &PanelDrag, _: &DropAt<StyleKey>| dropped_object(drag, uid).is_some();
let takes_object = move |drag: &PanelDrag, _: &DropAt<StyleKey>| dropped_object(drag, uid, reverts).is_some();
// A style dragged from this panel's list.
let ours = move |drag: &ListDrag<StyleKey>| drag.list == list;
let svg = |name: &'static str| IconSpec::svg(IconId::new(name));
@@ -610,9 +610,9 @@ fn reorder(app: &mut VectorcraftApp, edit: EditEvent<ReorderMove<StyleKey>>) {
/// The object whose look a dropped payload carries: the first of the art dragged from this document, or the
/// Appearance panel's object.
fn dropped_object(drag: &PanelDrag, uid: u64) -> Option<NodeId> {
fn dropped_object(drag: &PanelDrag, uid: u64, reverts: u64) -> Option<NodeId> {
match drag {
PanelDrag::Art { document, ids } if *document == uid => ids.first().copied(),
PanelDrag::Art { .. } => drag.artwork_for(uid, reverts)?.first().copied(),
PanelDrag::Appearance(id) => Some(*id),
_ => None,
}
@@ -624,7 +624,7 @@ fn dropped(app: &mut VectorcraftApp, at: &DropAt<StyleKey>, payload: &DropPayloa
DropAt::Onto(name) => Some(name.as_str()),
_ => None,
};
let object = app.session.active().and_then(|st| dropped_object(payload.get::<PanelDrag>()?, st.uid));
let object = app.session.active().and_then(|st| dropped_object(payload.get::<PanelDrag>()?, st.uid, st.reverts));
let style = payload.get::<ListDrag<StyleKey>>().map(|drag| drag.grabbed.as_str());
drop_on(app, onto, object, style, alt);
}
@@ -1427,9 +1427,10 @@ mod tests {
app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap();
let (red, green) = (doc(&app).graphic_style("Red").unwrap().appearance.fill_paint(), doc(&app).node(oval).unwrap().appearance.fill_paint());
let n = names(&app);
let document = app.session.active().unwrap().uid;
for payload in [PanelDrag::Art { document, ids: vec![oval] }, PanelDrag::Appearance(oval)] {
drop_on(&mut app, Some("Red"), dropped_object(&payload, document), None, true);
let st = app.session.active().unwrap();
let (document, reverts) = (st.uid, st.reverts);
for payload in [PanelDrag::Art { document, reverts, ids: vec![oval] }, PanelDrag::Appearance(oval)] {
drop_on(&mut app, Some("Red"), dropped_object(&payload, document, reverts), None, true);
let d = doc(&app);
assert_eq!(d.graphic_style("Red").unwrap().appearance.fill_paint(), green);
assert_eq!(d.node(oval).unwrap().extras().graphic_style, d.graphic_style("Red").map(|g| g.id));
@@ -1455,7 +1456,7 @@ mod tests {
fn with_artwork(app: &mut VectorcraftApp, ui: &mut Ui) {
let st = app.session.active().unwrap();
let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() };
let payload = PanelDrag::Art { document: st.uid, reverts: st.reverts, ids: st.selection.objects.clone() };
ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| {
let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key);
List::<usize>::new("Artwork")
+15 -6
View File
@@ -190,7 +190,7 @@ fn swatch_add(drag: &PanelDrag, library: &str) -> Option<(ItemKind, Value)> {
/// which keep their test, can read it: what a drop into a group, or out of every group, does.
struct Membership {
library: String,
active_document: Option<u64>,
active_document: Option<(u64, u64)>,
/// The group of each grouped item, by its index in the library's groups.
index: HashMap<(ItemKind, String), usize>,
/// The groups' names, in the library's order.
@@ -198,7 +198,7 @@ struct Membership {
}
impl Membership {
fn of(library: &str, lib: &Library, active_document: Option<u64>) -> Self {
fn of(library: &str, lib: &Library, active_document: Option<(u64, u64)>) -> Self {
let index = lib.group_index().into_iter().map(|((kind, item), group)| ((kind, item.to_string()), group)).collect();
Membership { library: library.to_string(), active_document, index, names: lib.groups.iter().map(|g| g.name.clone()).collect() }
}
@@ -210,8 +210,9 @@ impl Membership {
PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())),
PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())),
PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())),
PanelDrag::Art { document, ids } if Some(*document) == self.active_document => {
let ids: Vec<u64> = ids.iter().map(|id| id.0).collect();
PanelDrag::Art { .. } => {
let (uid, reverts) = self.active_document?;
let ids: Vec<u64> = drag.artwork_for(uid, reverts)?.iter().map(|id| id.0).collect();
Some(Grab::New(ItemKind::Graphic, json!({ "kind": "graphic", "ids": ids })))
}
PanelDrag::Paint { .. } => swatch_add(drag, library).map(|(kind, add)| Grab::New(kind, add)),
@@ -305,7 +306,15 @@ struct View<'a> {
}
impl<'a> View<'a> {
fn new(library: &'a str, lib: &'a Library, query: &str, list: bool, fill_active: bool, active_document: Option<u64>, can_apply: bool) -> Self {
fn new(
library: &'a str,
lib: &'a Library,
query: &str,
list: bool,
fill_active: bool,
active_document: Option<(u64, u64)>,
can_apply: bool,
) -> Self {
let membership = Membership::of(library, lib, active_document);
let query = query.trim().to_lowercase();
let searching = !query.is_empty();
@@ -776,7 +785,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
return;
};
let acts = RefCell::new(Vec::new());
let active_document = app.session.active().map(|st| st.uid);
let active_document = app.session.active().map(|st| (st.uid, st.reverts));
let has_doc = active_document.is_some();
{
// PLAN: assumed `UiState::{libraries_list_view: bool, library_search: String, library_groups_closed: HashSet<(String, String)>}` (ap.AS17, hub-w1).
+2 -1
View File
@@ -71,7 +71,8 @@ fn art(app: &mut VectorcraftApp, x: f64, name: Option<&str>) -> Vec<vectorcraft_
/// New art at `x`, as the canvas drags it.
fn art_drag(app: &mut VectorcraftApp, x: f64) -> PanelDrag {
let ids = art(app, x, None);
PanelDrag::Art { document: app.session.active().unwrap().uid, ids }
let state = app.session.active().unwrap();
PanelDrag::Art { document: state.uid, reverts: state.reverts, ids }
}
fn graphics(app: &mut VectorcraftApp) -> Vec<String> {
+3 -2
View File
@@ -408,6 +408,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
};
let dragged_doc = Arc::clone(&thumbs.doc);
let document = st.uid;
let reverts = st.reverts;
let shown_app: &VectorcraftApp = app;
let browser = SwatchesPanel::new(&data, Bind::bound(&mut model.state), Srgba::rgb(0.0, 0.0, 0.0))
.drag_payload(move |drag: &ListDrag<SwatchKey>| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag))))
@@ -417,8 +418,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) {
_ => vec![],
})
.row_items(|key| row_items(shown_app, key))
.takes_drop::<PanelDrag>(DropPlace::Between, |drag, _| dnd::accepts(drag, document))
.takes_drop::<PanelDrag>(DropPlace::Onto, |drag, _| dnd::accepts(drag, document))
.takes_drop::<PanelDrag>(DropPlace::Between, |drag, _| dnd::accepts(drag, document, reverts))
.takes_drop::<PanelDrag>(DropPlace::Onto, |drag, _| dnd::accepts(drag, document, reverts))
.select(SelectMode::Multi)
.search(model.show_find)
.reveal(focus.map(SwatchKey::Swatch))
+3 -5
View File
@@ -5,12 +5,11 @@ use craft::keymap::Mods;
use craft::ui::contract::{DropAt, ReorderMove};
/// Swatches take paints, and take swatch rows or canvas art from the current document.
pub(super) fn accepts(drag: &PanelDrag, document: u64) -> bool {
pub(super) fn accepts(drag: &PanelDrag, document: u64, reverts: u64) -> bool {
match drag {
PanelDrag::Paint { rows: Some(rows), .. } => rows.document == document,
PanelDrag::Paint { .. } => true,
PanelDrag::Art { document: source, .. } => *source == document,
_ => false,
_ => drag.artwork_for(document, reverts).is_some(),
}
}
@@ -45,7 +44,6 @@ impl Drop {
Some(Drop::Move { names: r.names.clone(), target, after, with })
}
PanelDrag::Paint { paint, .. } => Some(Drop::New { paint: paint.clone(), target, replace: mods.alt, spot: mods.cmd }),
// PLAN: assumed `Art { document: u64, ids: Vec<NodeId> }` (widgets-w13).
PanelDrag::Art { ids, .. } => Some(Drop::Pattern { ids: ids.iter().map(|id| id.0).collect(), target, replace: mods.alt }),
_ => None,
}
@@ -88,7 +86,7 @@ fn place(shown: &[SwatchKey], at: &DropAt<SwatchKey>) -> (Option<String>, bool)
/// `drag` dropped onto a swatch or between rows of the `shown` list (ap.AP2 `Dropped`); a gap with no
/// row under the pointer is the end of the list.
pub(super) fn on_dropped(app: &mut VectorcraftApp, shown: &[SwatchKey], at: &DropAt<SwatchKey>, drag: &PanelDrag, mods: Mods) {
if !app.session.active().is_some_and(|st| accepts(drag, st.uid)) {
if !app.session.active().is_some_and(|st| accepts(drag, st.uid, st.reverts)) {
return;
}
let (target, after) = place(shown, at);
+4 -2
View File
@@ -163,7 +163,8 @@ fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() {
let drag = rows_drag(&app, "Red", &["Red"]);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let before = doc(&app);
assert!(!dnd::accepts(&drag, app.session.active().unwrap().uid));
let state = app.session.active().unwrap();
assert!(!dnd::accepts(&drag, state.uid, state.reverts));
dropped_below(&mut app, drag.clone(), none());
dropped(&mut app, drag, "Green", alt());
assert_eq!(doc(&app).swatches, before.swatches);
@@ -171,7 +172,8 @@ fn a_foreign_swatch_row_payload_cannot_move_or_replace_local_swatches() {
/// Art `ids` dragged off the canvas.
fn art_drag(app: &VectorcraftApp, ids: Vec<vectorcraft_doc::NodeId>) -> PanelDrag {
PanelDrag::Art { document: app.session.active().map(|st| st.uid).unwrap_or_default(), ids }
let (document, reverts) = app.session.active().map_or((0, 0), |st| (st.uid, st.reverts));
PanelDrag::Art { document, reverts, ids }
}
/// The browser's reorder committing `names` before row `before` (a colour group: into it).
+10 -12
View File
@@ -530,7 +530,9 @@ const AT_START: usize = 4;
/// list becomes a symbol (Shift at the release keeps the art as ordinary art); dropped on a symbol
/// with Alt it redefines that symbol in one undo step.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some((doc, revision, uid, has_sel)) = app.session.active().map(|st| (st.doc.clone(), st.revision, st.uid, !st.selection.is_empty())) else {
let Some((doc, revision, uid, reverts, has_sel)) =
app.session.active().map(|st| (st.doc.clone(), st.revision, st.uid, st.reverts, !st.selection.is_empty()))
else {
return;
};
let keys = document_symbols(&doc, revision);
@@ -575,7 +577,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
.show(ui, |ui, _| {
// Art dropped anywhere on the list becomes a symbol; dropped on a symbol, the browser's
// own target takes it.
DropAction::<PanelDrag>::new(move |drag| art_of(drag, uid).is_some()).show(ui, |ui, _| {
DropAction::<PanelDrag>::new(move |drag| art_of(drag, uid, reverts).is_some()).show(ui, |ui, _| {
let mut state = PresetState::new();
state.zoom = zoom;
PresetBrowser::new(tl!("Symbols"), Bind::bound(&mut state), &source)
@@ -587,7 +589,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
.row_menu(PresetRowMenu::Host)
.row_items(|key: &SymbolKey| item_rows(&linked, &key.name))
.takes_drop(PresetDrop::new::<PanelDrag>(DropPlace::Onto, move |drag: &PanelDrag, _: &DropAt<SymbolKey>| {
art_of(drag, uid).is_some()
art_of(drag, uid, reverts).is_some()
}))
.empty(tl!("No symbols in this document"))
.show(ui)
@@ -605,7 +607,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
if let Some((dropped, events)) = taken {
if let Some((drag, mods)) = dropped
&& let Some(ids) = art_of(&drag, uid)
&& let Some(ids) = art_of(&drag, uid, reverts)
{
new_symbol(app, ids, mods.shift);
}
@@ -630,7 +632,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
PresetEvent::Dropped { at, payload, mods, .. } => {
let Some(ids) = payload.get::<PanelDrag>().and_then(|drag| art_of(drag, uid)) else { continue };
let Some(ids) = payload.get::<PanelDrag>().and_then(|drag| art_of(drag, uid, reverts)) else { continue };
if !mods.alt {
new_symbol(app, ids, mods.shift);
} else if let Some(target) = at.key()
@@ -683,13 +685,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// The ids of art dragged off the canvas of document `uid`; `None` for another drag or art of
/// another document.
fn art_of(drag: &PanelDrag, uid: u64) -> Option<&[NodeId]> {
match drag {
PanelDrag::Art { document, ids, .. } if *document == uid && !ids.is_empty() => Some(ids),
_ => None,
}
/// The ids of the nonempty artwork dragged from the displayed drawing.
fn art_of(drag: &PanelDrag, uid: u64, reverts: u64) -> Option<&[NodeId]> {
drag.artwork_for(uid, reverts).filter(|ids| !ids.is_empty())
}
/// Whether the art `ids` can redefine a symbol of `doc`: every object is still there and none is a
+2 -2
View File
@@ -92,7 +92,7 @@ fn panel(app: VectorcraftApp) -> Panel {
fn art_and_symbols(app: &mut VectorcraftApp, ui: &mut Ui) {
use craft::ui::contract::{ListDrag, ShowCollection as _};
if let Some(st) = app.session.active() {
let document = st.uid;
let (document, reverts) = (st.uid, st.reverts);
let mut named = Vec::new();
st.doc.walk(|n| {
if let Some(name) = &n.name {
@@ -104,7 +104,7 @@ fn art_and_symbols(app: &mut VectorcraftApp, ui: &mut Ui) {
let ids: Vec<NodeId> = named.iter().map(|(_, id)| *id).collect();
ui.allocate_ui(vec2(ui.available_width(), 200.0), |ui| {
let _ = craft::ui::list::List::<usize>::new("Art off the canvas")
.drag_payload(move |drag: &ListDrag<usize>| ids.get(drag.grabbed).map(|id| PanelDrag::Art { document, ids: vec![*id] }))
.drag_payload(move |drag: &ListDrag<usize>| ids.get(drag.grabbed).map(|id| PanelDrag::Art { document, reverts, ids: vec![*id] }))
.show_items(ui, &rows, &mut |key, _| craft::ui::list::ListRow::new(named[*key].0.clone()));
});
}
@@ -62,7 +62,7 @@ fn art_and_assets(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
use craft::ui::list::{List, ListRow};
let st = app.session.active().unwrap();
let payload = crate::panel_drag::PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() };
let payload = crate::panel_drag::PanelDrag::Art { document: st.uid, reverts: st.reverts, ids: st.selection.objects.clone() };
ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| {
let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key);
List::<usize>::new("Artwork")
@@ -42,6 +42,9 @@ fn uncalibrated_cmyk_marks_nothing() {
/// color settings stay the same; the panel keeps drawing through the change.
#[test]
fn the_grid_is_computed_again_after_a_profile_is_loaded() {
if !crate::testing::in_own_process("panels::tests_color_wheel_gamut::the_grid_is_computed_again_after_a_profile_is_loaded") {
return;
}
let mut p = Panel::new(app("#3366cc", "box", true));
/// Unregisters the profile when dropped, also after a failed assertion.
struct Unregister(&'static str);
+1 -1
View File
@@ -696,7 +696,7 @@ fn three_d_graphics_accepts_artwork_only_from_its_document() {
fn with_artwork(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
let st = app.session.active().unwrap();
let payload = PanelDrag::Art { document: st.uid, ids: st.selection.objects.clone() };
let payload = PanelDrag::Art { document: st.uid, reverts: st.reverts, ids: st.selection.objects.clone() };
ui.allocate_ui(egui::vec2(ui.available_width(), 80.0), |ui| {
let keys = craft::behavior::keyed(&[0_usize], |key: &usize| *key);
List::<usize>::new("Artwork")
+2 -1
View File
@@ -166,9 +166,10 @@ pub fn refresh(app: &VectorcraftApp, ctx: &egui::Context) {
}
if let Some(queue) = &state.queue {
let read = root.clone();
let clock = app.session.script_listing_clock();
// The app's own folder, read for the person at the keyboard.
queue.submit(root, Priority::VISIBLE, move |_| {
vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&read))
vectorcraft_engine::file_access::unconfined(|| vectorcraft_engine::script::folder::list(&read, clock))
});
}
if !state.loaded && state.first_read.is_none() {
+21
View File
@@ -91,6 +91,27 @@ pub(crate) fn custom_dictionary() -> std::sync::MutexGuard<'static, ()> {
HELD.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Runs the test `name` (its path in the crate, such as `canvas::tests::a_test`) alone in a child test process, for a
/// test that loads or removes a color profile. The loaded profiles are the whole process's, and the canvas's frame key
/// holds their generation ([`vectorcraft_color::cms::profiles_generation`]), so a profile loaded in this process while
/// another test renders changes that test's keys. In the child it returns `true`, and the test goes on. Here it waits
/// for the child, fails when the child's test fails, and returns `false`.
pub(crate) fn in_own_process(name: &str) -> bool {
const CHILD: &str = "VECTORCRAFT_TEST_OWN_PROCESS";
if std::env::var_os(CHILD).is_some_and(|v| v == name) {
return true;
}
let output =
std::process::Command::new(std::env::current_exe().unwrap()).args(["--exact", name, "--nocapture"]).env(CHILD, name).output().unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
"{name} failed in its own process:\n{stdout}\n{}",
String::from_utf8_lossy(&output.stderr),
);
false
}
/// The default proof view, held: View › Proof Colors, Overprint Preview and Separations Preview are the whole process's
/// and the canvas draws through them, so a test that sets them, or that compares the canvas's renders, holds this. It
/// leaves the default view when it is dropped.
+5 -1
View File
@@ -7,6 +7,7 @@ use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::scripts::TOO_LARGE;
use vectorcraft_engine::script::MAX_SOURCE_BYTES;
use vectorcraft_engine::script::folder::Clock;
use super::script_dialogs::{cancel, confirm, frame, is_open, key, open_id, pump, set};
use crate::dialogs::script_run::{
@@ -15,8 +16,11 @@ use crate::dialogs::script_run::{
use crate::tests::picks::{Picker, scripted};
use crate::{VectorcraftApp, menus, script_runs};
/// An app with a document, whose folder listings take no time.
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), crate::Services::default()));
let mut session = Session::new();
session.set_script_listing_clock(Clock::Fixed(std::time::Duration::ZERO));
let mut app = crate::testing::windowed(VectorcraftApp::new(session, crate::Services::default()));
app.run("file.new", json!({})).unwrap();
app
}
+16 -1
View File
@@ -32,9 +32,10 @@ fn folder(name: &str) -> vectorcraft_testkit::TempDir {
dir
}
/// An app with a document whose Scripts folder is `dir`'s.
/// An app with a document whose Scripts folder is `dir`'s, and whose folder listings take no time.
fn app(dir: &std::path::Path) -> VectorcraftApp {
let mut session = Session::new();
session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(Duration::ZERO));
session.attach_scripts_dir(dir.join("Scripts"));
let mut app = VectorcraftApp::new(session, crate::Services::default());
app.ui_ctx = Some(ctx());
@@ -304,6 +305,20 @@ fn the_menu_notes_a_listing_that_stopped_and_a_folder_it_cannot_read() {
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn the_menu_listing_stops_when_the_sessions_clock_is_past_the_time_limit() {
let dir = folder("clock");
let mut app = app(&dir);
write(&dir, "a.js", "");
let late = vectorcraft_engine::script::folder::MAX_SCAN + Duration::from_millis(1);
app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(late));
read(&app);
assert_eq!(shape(&scripts()), format!("({}), -, {FIXED}", scripts_menu::TRUNCATED));
app.session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(Duration::ZERO));
read(&app);
assert_eq!(shape(&scripts()), format!("a, -, {FIXED}"));
}
#[test]
fn a_menu_listing_under_a_read_root_leaves_out_scripts_outside_it() {
use vectorcraft_engine::file_access::{AutomationRoots, confine};
+27 -3
View File
@@ -4,7 +4,7 @@
use std::io::Cursor;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, mpsc};
use std::sync::{Arc, Mutex, MutexGuard, mpsc};
use std::time::Duration;
use craft::platform::clipboard::{Clipboard, ClipboardBackend, ClipboardError, ClipboardImage, Flavor};
@@ -13,11 +13,33 @@ use craft::ui::shell::embed;
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, Shape, vec2};
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_ui_egui::{Services, VectorcraftApp, background};
use vectorcraft_ui_egui::{Services, VectorcraftApp, background, i18n};
const COPIED: &str = "Copied the value";
const LENGTH: &str = "234 pt";
static CASE: Mutex<()> = Mutex::new(());
// Integration binaries use a process-wide locale, and the Location case draws in French and
// German. Each app holds the guard, so cases run one at a time, and restores the language.
struct Language {
_lock: MutexGuard<'static, ()>,
previous: i18n::Lang,
}
impl Language {
fn english() -> Self {
let lock = CASE.lock().unwrap_or_else(|e| e.into_inner());
let previous = i18n::current();
i18n::set_current(i18n::Lang::EN);
Self { _lock: lock, previous }
}
}
impl Drop for Language {
fn drop(&mut self) {
i18n::set_current(self.previous);
}
}
type ClipboardOffers = Arc<Mutex<Vec<Vec<Flavor>>>>;
struct Board(ClipboardOffers);
@@ -57,10 +79,12 @@ struct App {
app: VectorcraftApp,
ctx: egui::Context,
time: f64,
_language: Language,
}
impl App {
fn new() -> Self {
let language = Language::english();
let mut app = VectorcraftApp::new(Session::new(), Services::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 200, "y": 150, "width": 20, "height": 20})).unwrap();
@@ -68,7 +92,7 @@ impl App {
let ctx = egui::Context::default();
ctx.enable_accesskit();
embed::install(&ctx, craft::ui::testing::install_spec(), &vectorcraft_ui_egui::ui_fonts()).unwrap();
let mut a = Self { app, ctx, time: 0.0 };
let mut a = Self { app, ctx, time: 0.0, _language: language };
a.settle();
a
}
+1
View File
@@ -232,6 +232,7 @@ fn startup_scripts_wait_for_the_choice_and_disable_and_continue_leaves_out_the_o
std::fs::write(launch_dir.join("launch-1-dead.json"), item.to_string()).unwrap();
let stopped = ui::begin_launch(Some(&launch_dir), false);
let mut session = Session::new();
session.set_script_listing_clock(vectorcraft_engine::script::folder::Clock::Fixed(std::time::Duration::ZERO));
session.attach_startup_scripts_dir(scripts);
session.prefs.run_startup_scripts = true;
let mut app = VectorcraftApp::new(session, Services::default());
+5 -1
View File
@@ -97,7 +97,9 @@ private editing data. VectorCraft:
and the paragraph's hyphenation options and tab stops. Stroked type keeps its stroke's cap, join and miter limit. Type filled or
stroked with a pattern keeps its pattern, placed in the document as a path's pattern fill would be: a character's paint names
an art style of one paint, and the pattern is in that style (its colour in the text document is black). A pattern the file
doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one
doesn't define, or a style that isn't a pattern, keeps the colour as before. Type set in a spot ink or a global process
colour keeps it, at its tint: that style holds the ink's name and tint (the text document keeps only its process values), and
the type is linked to the document's swatch of that name, the one art in the same ink is linked to. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one
frame whose last lines the file sets but which don't fit here (the fallback font, or a descent
past the frame's bottom) may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines, with a warning when it does.
RGB in the PDF page's `ICCBased` spaces keeps the file's numbers in a `.ai` (the `uncalibrated_rgb`
@@ -422,6 +424,8 @@ Stop opacity on translated artboards remains outside this regression coverage.
| Date | Change | Summary |
|---|---|---|
| 2026-11-27 | minor | `.ai` save: type in a spot ink, a global process colour or Registration keeps its swatch link and its tint. Its fill and stroke in the text document name (key 5 of the paint) an art style of one paint, `0 1 Xd`, whose paint is the colour as a path's fill writes it (`x`, `Xx`, `Xk`, `Xs`), the form `.ai` import reads since the change below; key 0 still holds the process values at the tint. Each style is read back before it is written and kept only when the reader gives the same swatch and tint, so such type no longer counts among the attributes of type left out; a link to a process swatch that isn't global still does. Test `ai_editing::tests::type_in_spot_and_global_colors_reads_back_linked_at_its_tint` |
| 2026-11-27 | minor | `.ai` and EPS import: type set in a spot ink or a global process colour keeps its ink. In the text document a character's fill or stroke is a colour (key 0: grey, RGB or CMYK) and the name of an art style (key 5). In users' files (used locally, never committed) that style is one paint (`/SimpleStyle`), always its fill's, for a stroke too; for a spot ink or a global process colour it is `c m y k (name) tint x`, `Xx` or `Xk`, and key 0 keeps only the ink's process values at that tint. Such type came in as that process colour, so it separated onto the process plates, and white type in a white ink onto none. It now takes the style's paint: the colour at its tint, linked to the document's swatch of that name, which the style's colour makes when the art doesn't (after the art's colours, before the header's custom colours). A style whose paint is a process colour or a gradient, one that also sets a stroke's colour or pattern (before or after the fill's) or another fill paint after it, one whose `Xd` doesn't turn on its fill alone, and a paint that names no style of the file, keep the colour of key 0 as before; type filled with a gradient still comes in black. Tests `type_set_in_a_spot_ink_takes_it_from_the_art_style_its_paint_names` in `crates/eps/src/import/tests_native.rs`, `a_run_painted_by_a_swatch_colours_art_style_takes_the_swatch` in `crates/eps/src/import/ate.rs` and `only_a_style_of_one_swatch_colour_holds_it_for_type` in `crates/eps/src/import/ai/style/tests.rs`. Scores and estimates unchanged. |
| 2026-11-26 | minor | `.ai` and EPS import: where the text document makes the type of every text object that shows, point type made from it is matched with the page's type where it draws. Made type has no layout when it is matched, and its box was the estimate of type without one (0.55 em a character, running right from its anchor): beside right-aligned type, over half of centered type, across vertical type, and too short for a wide font. The page's type there was counted as type with no text object, with the note "some of the page's type has no text object in the layers, so it is left out" (a loss, so `convert` wouldn't write over the file), and the made type went on to be weighed against the page as type the page may not draw, and could be taken out. The box of made point type that shows now comes from its layout in the fonts the import has; the text object keeps no layout, so the document measures it when it opens, as before. Files where some text object's type isn't made keep the estimate: there the page's pieces where made type draws can belong to text objects stacked on it. The page comparison takes the same box for the layers' type areas (`type_areas` in `compare.rs`): made point type that differs from the page (laid out again, or in another font) counts as type where it draws, whatever its alignment. Counted as art beside the estimate, it could send the file to its PDF part or page, or be noted as art that differs. A file whose layers failed the comparison that way and opened without it now passes it and shows its notes. Tests `right_aligned_and_centered_point_type_takes_the_pages_type_where_it_draws`, `centered_point_type_at_a_heading_s_size_takes_the_pages_type_where_it_draws` and `right_aligned_point_type_that_differs_from_the_page_differs_as_type` in `crates/eps/src/import/tests_native.rs`, and `made_point_type_s_box_is_where_its_alignment_and_orientation_draw_it` in `crates/eps/src/import/native/slots.rs`. Scores and estimates unchanged. |
| 2026-11-22 | minor | EPS import: type in a Type 1 or Type 42 font the file carries, whose family isn't available, is drawn in a TrueType font built from the glyphs the file shows (outlines and advances from the font program), kept with the document as PDF import keeps a PDF's (#4569), and spaced by those glyphs' own advances; once its text is edited it takes the fallback font. A string that draws a character with another glyph than the one kept for it comes in as outlines. The warning names those families with PDF import's words ("show as the file draws them, in the fonts it carries, until their text is edited"). Fonts the file only names, Type 3 fonts and type from an Illustrator editing copy are unchanged. Tests `embedded_type1_type_draws_with_the_files_glyphs`, `a_second_glyph_for_a_character_keeps_its_type_as_outlines`, `kept_type1_glyphs_survive_saving_and_go_when_the_text_is_edited`, `type_in_fonts_that_arent_available_is_named_in_a_warning` in `crates/eps/src/import/tests_type1.rs`, `type_in_a_carried_type42_font_draws_with_the_files_glyphs` in `crates/eps/src/import/tests_type42.rs`; scores unchanged |
| 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged |
+1
View File
@@ -3457,6 +3457,7 @@ rules for these objects:
Pending packets count once toward that limit. Library installation checks its members before
publishing `ExternalObject`, in both ES5 and ES2015 realms. Serialization consumes fuel even
when its escaped output exceeds the packet limit. Packet-info scans and metadata size accounting during edits also consume fuel.
Property getters charge fuel before copying the selected text and locale or scanning whole-array language options.
The sidecar-write host binding accepts packets up to VectorCraft's 8 MiB packet limit.
- A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity,
one with text beside its `rdf:Description` elements or their properties, and one nested more than 64 elements deep
+1 -1
View File
@@ -106,7 +106,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
`XMPFile` updates restart open `File` readers with a UTF-8 byte order mark or UTF-16 encoding at the beginning of the new UTF-8 packet. Unmarked UTF-8 readers keep their position, limited to the new packet's length. Written packets omit a leading XML declaration and retain the following packet bytes. Nonempty language inherited by an `rdf:Description` is rejected as unavailable; explicit property-level language qualifiers are retained. Native file state is separate from script properties, and a successful close or the next script file run releases its packet buffers. Registered namespaces and expanded XML values count toward the script's heap limit. String-packet validation does not retain expanded XML values. On Unix, a folder flush failure after writing reports the written replacement and refreshes open readers while keeping the pending packet for retry. A failed `Realm::define_external_object` call can be retried; a call after a successful installation returns an internal error and preserves registered namespaces.
`XMPMeta.getLocalizedText` returns the selected `XMPProperty`, including its locale and option flags. VectorCraft returns `undefined` for an absent property or empty language alternative. `appendArrayItem` preserves explicit optional argument positions.
`XMPMeta.getLocalizedText` returns the selected `XMPProperty`, including its locale and option flags. VectorCraft returns `undefined` for an absent property or empty language alternative. `appendArrayItem` preserves explicit optional argument positions. Property getters charge fuel before copying the selected text and locale or scanning whole-array language options.
### Feature revisions
+3 -2
View File
@@ -146,8 +146,9 @@ object is where the art was.
Holes stay holes, with walls of their own. Bevels move each corner along its bisector. A corner the bevel opens (a
sharp point with the bevel outside, a narrow notch with it inside) whose miter would reach past four times the width is
cut square across instead; at the other corners the miter is limited to four times the width. A bevel wider than a
narrow part of the shape folds over itself. Each facet has a seam ([Seams](#seams)).
cut square across instead; at the other corners the miter is limited to four times the width. An inside bevel on
a single straight triangle or parallelogram with ordinary miters stops before its edges meet, keeping the requested
bevel height. Other outlines can still fold where a bevel is wider than a narrow part of the shape. Each facet has a seam ([Seams](#seams)).
### Custom bevels
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""Checks for ci-clear-rolling-cache.py with recorded GitHub API answers; no network.
python3 scripts/ci-clear-rolling-cache-tests.py
"""
from datetime import datetime, timedelta, timezone
import importlib.util
from pathlib import Path
import unittest
_spec = importlib.util.spec_from_file_location("clear", Path(__file__).with_name("ci-clear-rolling-cache.py"))
clear = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(clear)
WARM = "gate / cache warm (ubuntu-24.04)"
ME = [{"name": "cold cache clear", "status": "in_progress"}]
def warm_job(status, conclusion=None, steps=(), started_at="2026-11-28T03:40:00Z"):
return {
"name": WARM,
"status": status,
"conclusion": conclusion,
"started_at": started_at,
"steps": [{"name": n, "status": s, "conclusion": c} for n, s, c in steps],
}
def earlier(conclusion):
return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}]
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)])))
self.assertTrue(clear.saving(warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Setup", "in_progress", None)])))
def test_other_post_steps_are_not_the_save(self):
job = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Harden runner", "in_progress", None)])
self.assertFalse(clear.saving(job))
def test_a_leg_canceled_during_its_save_saves_nothing(self):
job = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")])
self.assertTrue(clear.saving(job))
self.assertTrue(clear.saves_nothing(job))
def test_a_leg_that_ended_with_its_save_still_running_saves_nothing(self):
job = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)])
self.assertTrue(clear.saves_nothing(job))
def test_a_running_or_finished_save_counts_as_saved(self):
running = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Setup", "in_progress", None)])
done = warm_job("completed", "failure", [("Gate", "completed", "success"), ("Post Setup", "completed", "success"),
("Post Harden runner", "completed", "failure")])
self.assertFalse(clear.saves_nothing(running))
self.assertFalse(clear.saves_nothing(done))
def test_a_failed_step_before_the_save_saves_nothing(self):
job = lambda c: warm_job("in_progress", steps=[("Gate", "completed", c), ("Post Setup", "in_progress", None)])
self.assertTrue(clear.saves_nothing(job("failure")))
self.assertTrue(clear.saves_nothing(job("cancelled")))
self.assertFalse(clear.saves_nothing(job("success")))
tolerated = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Trim the cache entry to this build", "completed", "failure"),
("Post Setup", "in_progress", None)])
self.assertFalse(clear.saves_nothing(tolerated))
class Deadline(unittest.TestCase):
began = datetime(2026, 11, 28, 3, 37, tzinfo=timezone.utc)
def test_the_wait_is_timed_from_the_leg_start(self):
late = warm_job("in_progress", started_at="2026-11-28T04:00:00Z")
before_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS - 60)
after_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS + 60)
self.assertGreater((before_limit - self.began).total_seconds(), clear.GIVE_UP_SECONDS)
self.assertFalse(clear.gave_up(late, before_limit, self.began))
self.assertTrue(clear.gave_up(late, after_limit, self.began))
def test_a_leg_that_never_starts_is_timed_from_the_script_start(self):
queued = warm_job("queued", started_at="2026-11-28T03:38:00Z")
later = self.began + timedelta(seconds=clear.GIVE_UP_SECONDS + 60)
self.assertFalse(clear.gave_up(None, self.began + timedelta(minutes=10), self.began))
self.assertTrue(clear.gave_up(None, later, self.began))
self.assertTrue(clear.gave_up(queued, later, self.began))
class Jobs(unittest.TestCase):
def test_only_the_warm_leg_counts(self):
jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}]
self.assertEqual(clear.warm_job(jobs), jobs[2])
def test_a_rerun_of_this_job_alone_skips_a_leg_that_succeeded(self):
self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")}))
self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]}))
self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")}))
def test_a_leg_that_did_not_succeed_is_waited_for(self):
self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")}))
self.assertFalse(clear.not_in_attempt(ME, {}))
self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")}))
def test_a_rerun_of_all_jobs_is_waited_for(self):
self.assertFalse(clear.not_in_attempt(ME + [{"name": "cache prune", "status": "in_progress"}], {1: earlier("success")}))
def test_a_failed_select_or_build_stops_the_wait(self):
done = lambda n, c: {"name": n, "status": "completed", "conclusion": c}
self.assertTrue(clear.legs_stopped([done("gate / select legs", "failure")]))
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")]))
class Caches(unittest.TestCase):
def test_every_page_is_read(self):
entries = [{"id": n, "key": f"v2-rust-a013-gate-crates-Linux-x64-{n}"} for n in range(2 * clear.PAGE_SIZE + 3)]
pages = []
def fetch(page):
pages.append(page)
start = (page - 1) * clear.PAGE_SIZE
return {"actions_caches": entries[start:start + clear.PAGE_SIZE]}
self.assertEqual(clear.all_caches(fetch), entries)
self.assertEqual(pages, [1, 2, 3])
def test_only_rolling_crates_entries_are_deleted(self):
caches = [
{"key": "v2-rust-a013-gate-crates-Linux-x64-46055934-01d60c35"},
{"key": "v2-rust-a013-gate-Linux-x64-46055934-01d60c35"},
{"key": "v1-affinity-rust-a013-gate-Linux-x64-b541f517-01d60c35"},
{"key": "v0-rust-build-Linux-x64-1fd829d9-01d60c35"},
]
self.assertEqual(clear.rolling_entries(caches), caches[:1])
def test_entries_created_after_the_run_started_are_kept(self):
rolling = lambda created: {"key": "v2-rust-ab-gate-crates-Linux-x64-1", "created_at": created}
old, same_minute_push = rolling("2026-11-27T03:00:00.5Z"), rolling("2026-11-28T03:40:00Z")
self.assertEqual(clear.created_before([old, same_minute_push], "2026-11-28T03:37:10Z"), [old])
if __name__ == "__main__":
unittest.main(verbosity=2)
+184
View File
@@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""The nightly cold run deletes the rolling crates entries just before it saves its own.
python3 scripts/ci-clear-rolling-cache.py needs GH_TOKEN, GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT
The cold run (ci.yml, `cold-build`) never restores the rolling entry, so the old one only adds to
the cache while the new one is saved: two entries of about 4.6 GB each, beside the others, go over
the repository's 10 GB limit and GitHub evicts the corpus, SonarCloud and Windows ARM64 entries. The
gate's `cache warm` leg saves in its `Post Setup` step; this deletes the old entries when that step
starts. Pull requests and pushes that start in the minutes between restore nothing from the
deleted entry and build cold once. Deleting is the only write; the entry the cold run saves does not
exist yet when this runs. Only entries created before this run started are deleted: a push or pull
request run in the same minutes may have saved an entry of its own, and the cold run's own save is
never touched. A leg that failed or was canceled saves nothing: its old entries stay, and this
exits 1, so "Re-run failed jobs" runs it again beside the re-run leg. The same holds for a leg that
ends, canceled or failed, before its save step finished. It also exits 1 when the leg has not
reached its save 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.
"""
from datetime import datetime, timezone
import json
import os
import re
import subprocess
import sys
import time
REF = 'refs/heads/main'
WARM_JOB = re.compile(r'^gate / cache warm \(')
# 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 \()')
PRUNE_JOB = 'cache prune'
ROLLING = '-gate-crates-'
# The gate-setup action's post step, which saves the dependency cache (craft-common-actions
# actions/gate-setup, under the gate's `Setup` step).
SAVE_STEP = 'Post Setup'
POLL_SECONDS = 20
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
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',)
NO_SAVE = 'the cache warm leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg'
def save_step(job):
return next((s for s in job.get('steps', []) if s['name'] == SAVE_STEP), None)
def saving(job):
"""True once the job's save step has started."""
step = save_step(job)
return step is not None and step['status'] in ('in_progress', 'completed')
def failed(job):
"""True when a step before the post steps failed or was canceled: the leg then saves no entry."""
return any(not s['name'].startswith('Post ') and s['name'] not in TOLERATED_FAILURES and s.get('conclusion') in STOPPED for s in job.get('steps', []))
def saves_nothing(job):
"""True when the leg saves no entry: a step before the save stopped, the save step did not
succeed, or the job ended before its save step finished."""
if failed(job):
return True
step = save_step(job)
if step is not None and step['status'] == 'completed':
return step.get('conclusion') != 'success'
return job.get('status') == 'completed'
def gave_up(job, now, began):
"""True once GIVE_UP_SECONDS have passed since the warm leg started, or since `began` (this
script's start) while the leg has not started."""
started = job.get('started_at') if job and job.get('status') in ('in_progress', 'completed') else None
return (now - (parse_time(started) if started else began)).total_seconds() > GIVE_UP_SECONDS
def all_caches(fetch):
"""Every cache entry, one page at a time: `fetch(page)` returns one page of actions/caches."""
entries, page = [], 1
while True:
batch = (fetch(page) or {}).get('actions_caches', [])
entries += batch
if len(batch) < PAGE_SIZE:
return entries
page += 1
def warm_job(jobs):
return next((j for j in jobs if WARM_JOB.match(j['name'])), None)
def legs_stopped(jobs):
"""True when a job the gate's legs need failed or was canceled, so the warm leg never starts."""
return any(NEEDED_JOBS.match(j['name']) and j['status'] == 'completed' and j.get('conclusion') in STOPPED for j in jobs)
def not_in_attempt(jobs, earlier_jobs):
"""True when no prune job is listed and the most recent earlier warm leg succeeded."""
if any(j['name'] == PRUNE_JOB for j in jobs):
return False
for attempt in sorted(earlier_jobs, reverse=True):
job = warm_job(earlier_jobs[attempt])
if job is not None:
return job.get('conclusion') == 'success'
return False
def rolling_entries(caches):
return [c for c in caches if ROLLING in c['key']]
def created_before(entries, started):
"""The entries created before `started`, an ISO 8601 timestamp (`run_started_at`)."""
limit = parse_time(started)
return [c for c in entries if parse_time(c['created_at']) < limit]
def parse_time(text):
return datetime.fromisoformat(text.replace('Z', '+00:00'))
def gh(*args):
out = subprocess.run(['gh', 'api', *args], check=True, capture_output=True, text=True).stdout
return json.loads(out) if out.strip() else None
def main():
repo, run, attempt = os.environ['GITHUB_REPOSITORY'], os.environ['GITHUB_RUN_ID'], os.environ.get('GITHUB_RUN_ATTEMPT', '1')
began = datetime.now(timezone.utc)
earlier_jobs = {}
while True:
jobs = gh(f'repos/{repo}/actions/runs/{run}/attempts/{attempt}/jobs?per_page=100') or {}
job = warm_job(jobs.get('jobs', []))
if job and saving(job):
break
if job is None:
for earlier in range(int(attempt) - 1, 0, -1):
if earlier not in earlier_jobs:
previous = gh(f'repos/{repo}/actions/runs/{run}/attempts/{earlier}/jobs?per_page=100') or {}
earlier_jobs[earlier] = previous.get('jobs', [])
if warm_job(earlier_jobs[earlier]) is not None:
break
if not_in_attempt(jobs.get('jobs', []), earlier_jobs):
print('the cache warm leg is not part of this attempt (it succeeded in an earlier one); nothing deleted')
return
if legs_stopped(jobs.get('jobs', [])):
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:
print(f'::error::{NO_SAVE}')
return 1
print('the cache warm leg finished without a save step; nothing deleted')
return
if gave_up(job, datetime.now(timezone.utc), began):
print('::error::the cache warm leg never reached its save; nothing deleted')
return 1
time.sleep(POLL_SECONDS)
if saves_nothing(job):
print(f'::error::{NO_SAVE}')
return 1
started = gh(f'repos/{repo}/actions/runs/{run}')['run_started_at']
caches = all_caches(lambda page: gh(f'repos/{repo}/actions/caches?ref={REF}&sort=created_at&direction=asc&per_page={PAGE_SIZE}&page={page}'))
for c in created_before(rolling_entries(caches), started):
print(f"delete {c['key']} ({c['size_in_bytes'] / 1e9:.2f} GB)")
result = subprocess.run(['gh', 'api', '-X', 'DELETE', f"repos/{repo}/actions/caches/{c['id']}"], capture_output=True, text=True)
if result.returncode:
if '(HTTP 404)' in result.stderr:
print(f"already deleted {c['key']}")
else:
print(result.stderr, end='', file=sys.stderr)
return result.returncode
if __name__ == '__main__':
sys.exit(main())