mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 17:05:55 +01:00
Merge main into feat/stylus-wheel
This commit is contained in:
commit
faffba01ae
150 files changed
+10189
-1008
No files matched your search
@@ -17,25 +17,25 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
affinity3:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
AFFINITY_CORPUS_REQUIRED: "1"
|
||||
CARGO_PROFILE_DEV_DEBUG: "0"
|
||||
CARGO_PROFILE_TEST_DEBUG: "0"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Install Rust
|
||||
uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: "1.95"
|
||||
- name: Fetch pinned and checksum-verified corpus
|
||||
run: cargo xtask corpus --affinity
|
||||
- name: Parse every file and freeze actual Affinity 3 feature retention
|
||||
run: cargo test -p vectorcraft-affinity --all-features -- --nocapture
|
||||
- name: Check every artboard, native save, SVG, PDF and PSD exports
|
||||
run: cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
timeout-minutes: 30
|
||||
toolchain: "1.95"
|
||||
# As before: no craft-fonts, apt packages, wasm target or nextest.
|
||||
craft-fonts-ref: ""
|
||||
targets: ""
|
||||
tools: ""
|
||||
dev-debug: "0"
|
||||
env: |
|
||||
AFFINITY_CORPUS_REQUIRED=1
|
||||
CARGO_PROFILE_TEST_DEBUG=0
|
||||
# Its own cache, apart from ci.yml's gate.
|
||||
cache-version: v1-affinity
|
||||
command: |
|
||||
# Pinned and checksum-verified corpus.
|
||||
cargo xtask corpus --affinity
|
||||
# Parse every file and freeze actual Affinity 3 feature retention.
|
||||
cargo test -p vectorcraft-affinity --all-features -- --nocapture
|
||||
# Every artboard, native save, SVG, PDF and PSD export.
|
||||
cargo test -p vectorcraft-engine --test affinity_artboards --test affinity_text --test affinity_corpus -- --nocapture
|
||||
@@ -30,51 +30,9 @@ jobs:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
|
||||
git-sources:
|
||||
name: Git dependencies come from storytold
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Git dependencies come from storytold
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; }
|
||||
# Source replacement, patches and path overrides in cargo config never show up
|
||||
# in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key.
|
||||
# Cargo still reads the legacy .cargo/config.
|
||||
python3 - <<'PY'
|
||||
import os, sys, tomllib
|
||||
for path in (".cargo/config", ".cargo/config.toml"):
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
config = tomllib.load(open(path, "rb"))
|
||||
replaced = [name for name, source in config.get("source", {}).items()
|
||||
if isinstance(source, dict) and "replace-with" in source]
|
||||
if replaced or "patch" in config or "paths" in config:
|
||||
print(f"{path} replaces, patches or overrides a source")
|
||||
sys.exit(1)
|
||||
PY
|
||||
# Fails when Cargo.lock is out of date with the manifests.
|
||||
cargo metadata --locked --format-version 1 > /dev/null
|
||||
python3 - <<'PY'
|
||||
import sys, tomllib
|
||||
lock = tomllib.load(open("Cargo.lock", "rb"))
|
||||
bad = sorted({p["source"] for p in lock.get("package", [])
|
||||
if p.get("source", "").startswith("git+")
|
||||
and not p["source"].startswith("git+https://github.com/storytold/")})
|
||||
if bad:
|
||||
print("Git dependencies outside github.com/storytold:", *bad, sep="\n")
|
||||
sys.exit(1)
|
||||
PY
|
||||
|
||||
release:
|
||||
needs: [git-sources, credits]
|
||||
needs: credits
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
@@ -20,7 +20,7 @@ Every non-code asset in this repository (icons, images, fonts, example art, colo
|
||||
|
||||
**Policy (mandatory):** VectorCraft contains **no Adobe iconography, images, artwork, presets, swatch/brush/symbol/pattern libraries or ICC profiles**. Every asset is either original work by VectorCraft contributors, or third-party material under an open licence (OSI open source, public domain / CC0, or Creative Commons that allows redistribution), and it is attributed below. Screenshots of Adobe software are never committed. The one exception is the ArtCraft name, wordmark and logos in `docs/brand/`: ArtCraft trademarks, not open source, usable only under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
|
||||
|
||||
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets and the vector tool cursors (`crates/ui-egui/src/cursors.rs`).
|
||||
Generated-in-code art is original and has no file to list. This covers the default swatches, brushes, symbols, patterns, graphic styles, image-trace presets, the vector tool cursors (`crates/ui-egui/src/cursors.rs`) and the Learn panel's practice samples (`crates/ui-egui/src/panels/learn/samples.rs`).
|
||||
|
||||
**Font files are never committed here.** Fonts shared by the Crafting Apps live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). The small Latin UI/document fonts below predate that rule and stay.
|
||||
|
||||
|
||||
@@ -567,6 +567,112 @@ pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
|
||||
groups.into_iter().map(|g| g.2).collect()
|
||||
}
|
||||
|
||||
/// Colors that [`weigh`] moves from one row to another as one: a color they are shown by, how
|
||||
/// often the art uses them and the row they are in. A fixed unit (such as the color a row is
|
||||
/// shown by) stays in its row.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct WeighUnit {
|
||||
pub color: Color,
|
||||
pub uses: f64,
|
||||
pub row: usize,
|
||||
pub fixed: bool,
|
||||
}
|
||||
|
||||
/// The unit-by-row comparisons one [`weigh`] makes, at most.
|
||||
const WEIGH_WORK: usize = 50_000_000;
|
||||
|
||||
/// The uses of `u` that count: a positive finite number, else 0.
|
||||
fn unit_uses(u: &WeighUnit) -> f64 {
|
||||
if u.uses.is_finite() && u.uses > 0.0 { u.uses } else { 0.0 }
|
||||
}
|
||||
|
||||
/// Each row's share of the uses of `units`, in percent (0 for every row when nothing is used).
|
||||
/// Units whose row is past `rows`, or whose uses are not a positive finite number, count nothing.
|
||||
pub fn row_shares(units: &[WeighUnit], rows: usize) -> Vec<f64> {
|
||||
let mut sums = vec![0.0; rows];
|
||||
for u in units {
|
||||
if let Some(s) = sums.get_mut(u.row) {
|
||||
*s += unit_uses(u);
|
||||
}
|
||||
}
|
||||
let total: f64 = sums.iter().sum();
|
||||
if total <= 0.0 {
|
||||
return vec![0.0; rows];
|
||||
}
|
||||
sums.iter().map(|s| s / total * 100.0).collect()
|
||||
}
|
||||
|
||||
/// For Recolor Artwork's Prominent Colors (our own rule): the row each of `units` goes to so that
|
||||
/// each row's share of the uses comes as near its share of `weights` as whole units allow. One
|
||||
/// unit moves at a time, while a move brings the rows' shares nearer their weights (the sum of
|
||||
/// every row's distance from its weight falls); of those moves, the one taken is the unit nearest
|
||||
/// in Lab (CIEDE2000) to the color of the row it goes to (`anchors`), compared with the row it
|
||||
/// leaves; on a tie, the move that brings the shares nearest. Fixed units, units in a row past
|
||||
/// `anchors` and units used no times stay where they are. Weights that are negative or not finite
|
||||
/// count as 0; when no weight is positive, every unit stays. The moves stop after
|
||||
/// [`WEIGH_WORK`] comparisons of a unit with a row, and when the movable units times the rows pass
|
||||
/// it, every unit stays.
|
||||
pub fn weigh(units: &[WeighUnit], anchors: &[Color], weights: &[f64]) -> Vec<usize> {
|
||||
let mut row: Vec<usize> = units.iter().map(|u| u.row).collect();
|
||||
let n = anchors.len();
|
||||
let given = |r: usize| weights.get(r).copied().filter(|x| x.is_finite() && *x > 0.0).unwrap_or(0.0);
|
||||
// Scaled by the largest weight first, so the sum stays finite.
|
||||
let top = (0..n).map(given).fold(0.0, f64::max);
|
||||
let w = |r: usize| if top > 0.0 { given(r) / top } else { 0.0 };
|
||||
let sum_w: f64 = (0..n).map(w).sum();
|
||||
let movable: Vec<usize> = (0..units.len()).filter(|&i| !units[i].fixed && units[i].row < n && unit_uses(&units[i]) > 0.0).collect();
|
||||
let per_pass = movable.len().saturating_mul(n);
|
||||
if sum_w <= 0.0 || n < 2 || movable.is_empty() || per_pass > WEIGH_WORK {
|
||||
return row;
|
||||
}
|
||||
let mut sums = vec![0.0; n];
|
||||
for u in units.iter().filter(|u| u.row < n) {
|
||||
sums[u.row] += unit_uses(u);
|
||||
}
|
||||
let total: f64 = sums.iter().sum();
|
||||
let target: Vec<f64> = (0..n).map(|r| w(r) / sum_w * total).collect();
|
||||
let anchor_labs: Vec<Lab> = anchors.iter().map(|c| c.to_lab()).collect();
|
||||
// Each movable unit's distance to each row's color.
|
||||
let dist: Vec<Vec<f32>> = movable
|
||||
.iter()
|
||||
.map(|&i| {
|
||||
let l = units[i].color.to_lab();
|
||||
anchor_labs.iter().map(|a| delta_e2000(*a, l)).collect()
|
||||
})
|
||||
.collect();
|
||||
// A move must bring the shares nearer by more than rounding.
|
||||
let eps = total * 1e-9;
|
||||
for _ in 0..WEIGH_WORK / per_pass {
|
||||
let mut best: Option<(f32, f64, usize, usize)> = None;
|
||||
for (m, &i) in movable.iter().enumerate() {
|
||||
let (a, x) = (row[i], unit_uses(&units[i]));
|
||||
let before_a = (sums[a] - target[a]).abs();
|
||||
let after_a = (sums[a] - x - target[a]).abs();
|
||||
for b in (0..n).filter(|&b| b != a) {
|
||||
let gain = before_a + (sums[b] - target[b]).abs() - after_a - (sums[b] + x - target[b]).abs();
|
||||
if gain <= eps {
|
||||
continue;
|
||||
}
|
||||
let cost = dist[m][b] - dist[m][a];
|
||||
let better = match best {
|
||||
None => true,
|
||||
Some((c, g, ..)) => cost < c || (cost == c && gain > g),
|
||||
};
|
||||
if better {
|
||||
best = Some((cost, gain, m, b));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, _, m, b)) = best else { break };
|
||||
let i = movable[m];
|
||||
let x = unit_uses(&units[i]);
|
||||
sums[row[i]] -= x;
|
||||
sums[b] += x;
|
||||
row[i] = b;
|
||||
}
|
||||
row
|
||||
}
|
||||
|
||||
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Palette(Vec<(Color, Lab)>);
|
||||
@@ -911,4 +1017,55 @@ mod tests {
|
||||
assert!(matches!(Rng::new(3).saturation_brightness(Color::lab(50.0, 40.0, 20.0)), Color::Lab { .. }));
|
||||
assert_eq!(Rng::new(3).saturation_brightness(Color::gray(0.4)).to_hsb()[1], 0.0, "greys stay grey");
|
||||
}
|
||||
|
||||
fn unit(color: Color, uses: f64, row: usize, fixed: bool) -> WeighUnit {
|
||||
WeighUnit { color, uses, row, fixed }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_shares_are_percent_of_the_uses() {
|
||||
let units = [unit(Color::rgb(1.0, 0.0, 0.0), 3.0, 0, true), unit(Color::rgb(0.0, 0.0, 1.0), 1.0, 1, true), unit(Color::WHITE, 5.0, 4, false)];
|
||||
assert_eq!(row_shares(&units, 2), vec![75.0, 25.0]);
|
||||
assert_eq!(row_shares(&[], 2), vec![0.0, 0.0]);
|
||||
assert_eq!(row_shares(&[unit(Color::WHITE, f64::NAN, 0, false)], 1), vec![0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_the_nearest_colors_toward_the_weights() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
let units = [
|
||||
unit(red, 1.0, 0, true),
|
||||
unit(Color::rgb(0.9, 0.1, 0.3), 1.0, 0, false),
|
||||
unit(Color::rgb(0.5, 0.0, 0.8), 1.0, 0, false),
|
||||
unit(blue, 1.0, 1, true),
|
||||
];
|
||||
// Equal weights: the reddish purple, nearer blue than the red-pink is, moves.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.0]), vec![0, 0, 1, 1]);
|
||||
// Most of the weight on blue: both movable colors go, the row's own color stays.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[0.0, 1.0]), vec![0, 1, 1, 1]);
|
||||
// Weights already met, or none positive: nothing moves.
|
||||
assert_eq!(weigh(&units, &[red, blue], &[3.0, 1.0]), vec![0, 0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[0.0, f64::NAN]), vec![0, 0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1e308, 1e308]), vec![0, 0, 1, 1], "huge weights act as equal ones");
|
||||
assert_eq!(weigh(&units, &[red], &[1.0]), vec![0, 0, 0, 1], "a row past the anchors keeps its units");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_takes_whole_units_and_stops_when_no_move_helps() {
|
||||
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
// A heavy unit: moving it would overshoot by more than staying misses.
|
||||
let units = [unit(red, 1.0, 0, true), unit(Color::rgb(0.8, 0.0, 0.2), 10.0, 0, false), unit(blue, 10.0, 1, true)];
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 1.4]), vec![0, 0, 1]);
|
||||
assert_eq!(weigh(&units, &[red, blue], &[1.0, 20.0]), vec![0, 1, 1]);
|
||||
// Many units: the result still follows the weights.
|
||||
let many: Vec<WeighUnit> = (0..400).map(|i| unit(Color::rgb(i as f32 / 400.0, 0.2, 1.0 - i as f32 / 400.0), 1.0, 0, i == 0)).collect();
|
||||
let rows = weigh(&many, &[Color::rgb(0.0, 0.2, 1.0), Color::rgb(1.0, 0.2, 0.0)], &[1.0, 3.0]);
|
||||
assert_eq!(rows.iter().filter(|r| **r == 1).count(), 300);
|
||||
assert!(rows[399] == 1 && rows[1] == 0, "the reddest colors go to the red row");
|
||||
// Past the work limit (8,000 units by 7,000 rows) nothing moves.
|
||||
let units: Vec<WeighUnit> = (0..8_000).map(|i| unit(Color::WHITE, 1.0, 0, i == 0)).collect();
|
||||
let anchors = vec![Color::BLACK; 7_000];
|
||||
let weights = vec![1.0; 7_000];
|
||||
assert!(weigh(&units, &anchors, &weights).iter().all(|r| *r == 0));
|
||||
}
|
||||
}
|
||||
+99
-17
@@ -1327,27 +1327,39 @@ impl Spine {
|
||||
let s = if s.is_finite() { s.clamp(0.0, self.length()) } else { 0.0 };
|
||||
let sp = &self.subpath;
|
||||
let n = sp.segment_count();
|
||||
let mut start = 0.0;
|
||||
for i in 0..n {
|
||||
let c = sp.segment(i);
|
||||
let end = self.anchor_length(i + 1).unwrap_or(self.length());
|
||||
if s <= end || i + 1 == n {
|
||||
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
|
||||
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
|
||||
let e = c.eval(t);
|
||||
let tv = c.deriv().eval(t).to_vec2();
|
||||
// Where a handle sits on its anchor the derivative vanishes there: take the
|
||||
// direction between points a little before and after instead.
|
||||
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
|
||||
return (Point::new(e.x, e.y), tv.y.atan2(tv.x));
|
||||
}
|
||||
start = end;
|
||||
if n == 0 {
|
||||
return (self.pts.first().copied().unwrap_or_default(), 0.0);
|
||||
}
|
||||
// Only a spine without segments gets here: the loop returns at the last one.
|
||||
(self.pts.first().copied().unwrap_or_default(), 0.0)
|
||||
let i = segment_at(&self.anchors, n, s, || {});
|
||||
let c = sp.segment(i);
|
||||
let start = if i == 0 { 0.0 } else { self.anchor_length(i).unwrap_or(0.0) };
|
||||
let end = self.anchor_length(i + 1).unwrap_or(self.length());
|
||||
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
|
||||
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
|
||||
let e = c.eval(t);
|
||||
let tv = c.deriv().eval(t).to_vec2();
|
||||
// Where a handle sits on its anchor the derivative vanishes there: take the
|
||||
// direction between points a little before and after instead.
|
||||
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
|
||||
(Point::new(e.x, e.y), tv.y.atan2(tv.x))
|
||||
}
|
||||
}
|
||||
|
||||
/// The segment of a spine with `n` segments (`n > 0`) that holds arc length `s`: the first one whose
|
||||
/// end is at or past `s`, or the last one when none is. `anchors` holds the arc length at each
|
||||
/// anchor, so segment `i` ends at `anchors[i + 1]`, and the last segment of a closed spine, which has
|
||||
/// no entry for its end, ends at the spine's length. The lengths never decrease (each is a sum of
|
||||
/// distances that are not negative, at most `+inf` and never NaN), so a binary search finds the
|
||||
/// segment in about `log2(n)` comparisons. `probe` is called once for each comparison.
|
||||
fn segment_at(anchors: &[f64], n: usize, s: f64, mut probe: impl FnMut()) -> usize {
|
||||
let ends = anchors.get(1..n.min(anchors.len())).unwrap_or_default();
|
||||
ends.partition_point(|&end| {
|
||||
probe();
|
||||
end < s
|
||||
})
|
||||
.min(n.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// The anchor of the first subpath each key sits on, when they are all valid for `n` anchors.
|
||||
fn pinned(spec: &BlendSpec, keys: usize, n: usize) -> Option<Vec<usize>> {
|
||||
(spec.key_anchors.len() == keys && keys >= 2 && spec.key_anchors.iter().all(|a| (*a as usize) < n))
|
||||
@@ -1892,6 +1904,76 @@ mod tests {
|
||||
assert!(end.is_finite(), "{end}");
|
||||
}
|
||||
|
||||
/// [`Spine::at_length`] by walking the segments from the first, as a reference for the search.
|
||||
fn walked_at_length(sp: &Spine, s: f64) -> (Point, f64) {
|
||||
let s = if s.is_finite() { s.clamp(0.0, sp.length()) } else { 0.0 };
|
||||
let n = sp.subpath.segment_count();
|
||||
let mut start = 0.0;
|
||||
for i in 0..n {
|
||||
let c = sp.subpath.segment(i);
|
||||
let end = sp.anchor_length(i + 1).unwrap_or(sp.length());
|
||||
if s <= end || i + 1 == n {
|
||||
let local_s = (s - start).max(0.0) / (end - start).max(1e-12) * c.arclen(1e-9);
|
||||
let t = c.inv_arclen(local_s, 1e-9).clamp(0.0, 1.0);
|
||||
let e = c.eval(t);
|
||||
let tv = c.deriv().eval(t).to_vec2();
|
||||
let tv = if tv.hypot2() < 1e-24 { c.eval((t + 1e-3).min(1.0)) - c.eval((t - 1e-3).max(0.0)) } else { tv };
|
||||
return (Point::new(e.x, e.y), tv.y.atan2(tv.x));
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
panic!("a spine without segments")
|
||||
}
|
||||
|
||||
/// The search picks the same segment as walking them in order, so points and tangents stay the
|
||||
/// same: on open and closed spines, one segment, curves, and zero-length segments whose anchors
|
||||
/// share an arc length; at every anchor, between anchors, at both ends, past them, and for
|
||||
/// values that are not finite.
|
||||
#[test]
|
||||
fn spine_lookup_matches_walking_the_segments() {
|
||||
let p = Point::new;
|
||||
let bow = SubPath::new(
|
||||
vec![Anchor::smooth(p(0.0, 0.0), p(50.0, 50.0)), Anchor::smooth(p(100.0, 0.0), p(150.0, -50.0)), Anchor::corner(p(200.0, 0.0))],
|
||||
false,
|
||||
);
|
||||
let spines = [
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(10.0, 0.0), p(10.0, 0.0), p(10.0, 0.0), p(30.0, 5.0), p(30.0, 5.0)], false),
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0)], true),
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(40.0, 0.0), p(40.0, 30.0), p(0.0, 0.0)], true),
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(25.0, 25.0)], false),
|
||||
SubPath::polyline(&[p(0.0, 0.0), p(25.0, 25.0)], true),
|
||||
bow.clone(),
|
||||
SubPath { closed: true, ..bow },
|
||||
];
|
||||
for sub in spines {
|
||||
let sp = Spine::new(&PathData::single(sub)).unwrap();
|
||||
let len = sp.length();
|
||||
let mut lengths = vec![0.0, len, -1.0, len + 1.0, -len, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN];
|
||||
lengths.extend(sp.anchors.iter().flat_map(|&a| [a, a - 1e-9, a + 1e-9]));
|
||||
lengths.extend((0..=400).map(|k| len * k as f64 / 400.0));
|
||||
for s in lengths {
|
||||
assert_eq!(sp.at_length(s), walked_at_length(&sp, s), "s = {s} on {:?}", sp.anchors);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finding the segment for an arc length on a spine of thousands of segments takes a few
|
||||
/// comparisons, not one for each segment before it.
|
||||
#[test]
|
||||
fn spine_lookup_compares_a_few_segment_ends() {
|
||||
let pts: Vec<Point> = (0..=4096).map(|i| Point::new(i as f64, if i % 2 == 0 { 0.0 } else { 1.0 })).collect();
|
||||
let sp = Spine::new(&PathData::single(SubPath::polyline(&pts, false))).unwrap();
|
||||
let n = sp.subpath.segment_count();
|
||||
assert_eq!(n, 4096);
|
||||
for s in [sp.length() - 0.5, sp.length(), sp.length() / 2.0, 0.25] {
|
||||
let mut compared = 0;
|
||||
let i = segment_at(&sp.anchors, n, s, || compared += 1);
|
||||
assert!(compared <= 13, "{compared} comparisons at {s}");
|
||||
assert_eq!(sp.at_length(s), walked_at_length(&sp, s));
|
||||
assert!(sp.anchors[i] <= s && (i + 1 == n || s <= sp.anchors[i + 1]), "segment {i} at {s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn easing_keeps_the_ends_and_stays_monotone() {
|
||||
use crate::live::{BlendEase, BlendEaseType as K};
|
||||
|
||||
+158
-14
@@ -568,23 +568,167 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline of a 200 × 100 box whose top side is `pieces`, end to end from (0, 0) to
|
||||
/// (200, 0), and whose other sides are straight.
|
||||
fn top_of_pieces(pieces: &[CubicBez]) -> PathData {
|
||||
let pt = |p: Point| (p.x, p.y);
|
||||
let mut knots: Vec<Knot> = vec![];
|
||||
for (k, c) in pieces.iter().enumerate() {
|
||||
let h_in = if k == 0 { pt(c.p0) } else { pt(pieces[k - 1].p2) };
|
||||
knots.push((pt(c.p0), h_in, pt(c.p1)));
|
||||
}
|
||||
let last = pieces.last().unwrap();
|
||||
knots.push(((200.0, 0.0), pt(last.p2), (200.0, 0.0)));
|
||||
knots.extend([((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)), ((0.0, 100.0), (0.0, 100.0), (0.0, 100.0))]);
|
||||
outline(&knots)
|
||||
}
|
||||
|
||||
/// A top curve whose parameter runs fast at its start and slow at its end.
|
||||
const UNEVEN_TOP: CubicBez =
|
||||
CubicBez { p0: Point::new(0.0, 0.0), p1: Point::new(120.0, -60.0), p2: Point::new(190.0, -30.0), p3: Point::new(200.0, 0.0) };
|
||||
|
||||
#[test]
|
||||
fn a_split_curve_moves_the_top_object_share_to_its_new_anchor() {
|
||||
// Splitting the top curve at t = 0.3 keeps its shape but changes the polygon shares: the
|
||||
// new anchor lands at the first piece's share, not at u = 0.3.
|
||||
let top = CubicBez::new((0.0, 0.0), (40.0, -40.0), (160.0, -40.0), (200.0, 0.0));
|
||||
let (a, b) = (top.subsegment(0.0..0.3), top.subsegment(0.3..1.0));
|
||||
let path = outline(&[
|
||||
((0.0, 0.0), (0.0, 0.0), a.p1.into()),
|
||||
(a.p3.into(), a.p2.into(), b.p1.into()),
|
||||
((200.0, 0.0), b.p2.into(), (200.0, 0.0)),
|
||||
((200.0, 100.0), (200.0, 100.0), (200.0, 100.0)),
|
||||
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0)),
|
||||
]);
|
||||
let c = Coons::from_top_object(&path, None).unwrap();
|
||||
fn a_split_curve_keeps_the_top_object_patch() {
|
||||
// Splitting the top curve at t = 0.3, or into thirds, keeps its shape, and the patch stays
|
||||
// the unsplit curve's: the new anchors land at u = 0.3, 1/3 and 2/3 (to within how finely
|
||||
// the side is sampled), where the pieces' control polygons would have put them several
|
||||
// points away.
|
||||
let whole = Coons::from_top_object(&top_of_pieces(&[UNEVEN_TOP]), None).unwrap();
|
||||
for cuts in [vec![0.3], vec![1.0 / 3.0, 2.0 / 3.0]] {
|
||||
let ends: Vec<f64> = std::iter::once(0.0).chain(cuts.iter().copied()).chain([1.0]).collect();
|
||||
let pieces: Vec<CubicBez> = ends.windows(2).map(|w| UNEVEN_TOP.subsegment(w[0]..w[1])).collect();
|
||||
let c = Coons::from_top_object(&top_of_pieces(&pieces), None).unwrap();
|
||||
let total: f64 = pieces.iter().map(|p| polygon(*p)).sum();
|
||||
for (k, t) in cuts.iter().enumerate() {
|
||||
let anchor = pieces[k].p3;
|
||||
assert!(c.eval(*t, 0.0).distance(anchor) < 0.02, "{cuts:?}: u {t} → {:?}, want {anchor:?}", c.eval(*t, 0.0));
|
||||
let share: f64 = pieces[..=k].iter().map(|p| polygon(*p)).sum::<f64>() / total;
|
||||
assert!(c.eval(share, 0.0).distance(anchor) > 2.0, "{cuts:?}: the polygon share {share} lands on the anchor");
|
||||
}
|
||||
for (u, v) in [(0.1, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
|
||||
let (p, q) = (c.eval(u, v), whole.eval(u, v));
|
||||
assert!(p.distance(q) < 1e-9, "{cuts:?}: ({u}, {v}) → {p:?}, unsplit {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_curve_keeps_the_top_object_patch_when_split_at_a_cusp() {
|
||||
// The top curve stops at t = 0.25 (a cusp), and an anchor splits it there: both handles at
|
||||
// the split lie on the anchor, and the patch with the corners given stays the unsplit
|
||||
// curve's.
|
||||
let cusp = CubicBez::new((0.0, 0.0), (30.0, -40.0), (-58.0, 24.0), (200.0, 0.0));
|
||||
let pieces = [cusp.subsegment(0.0..0.25), cusp.subsegment(0.25..1.0)];
|
||||
assert!(pieces[0].p2.distance(pieces[0].p3) < 1e-9 && pieces[1].p1.distance(pieces[1].p0) < 1e-9);
|
||||
let whole = Coons::from_top_object(&top_of_pieces(&[cusp]), Some([0, 1, 2, 3])).unwrap();
|
||||
let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap();
|
||||
for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
|
||||
let (p, q) = (c.eval(u, v), whole.eval(u, v));
|
||||
assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_curve_keeps_the_top_object_patch_where_it_barely_moves_and_runs_straight() {
|
||||
// A straight top curve that barely moves at t = 0.25 and doesn't bend there: split there,
|
||||
// the handles at the split are a few thousandths of a point long and the pieces don't bend
|
||||
// at all, and the patch with the corners given stays the unsplit curve's.
|
||||
let slow = CubicBez::new((0.0, 0.0), (28.578125, 0.0), (-57.109375, 0.0), (200.0, 0.0));
|
||||
let pieces = [slow.subsegment(0.0..0.25), slow.subsegment(0.25..1.0)];
|
||||
let (into, out) = (pieces[0].p3.distance(pieces[0].p2), pieces[1].p0.distance(pieces[1].p1));
|
||||
assert!(into > 0.0 && out > 0.0 && into.max(out) < 0.01, "{into} {out}");
|
||||
let whole = Coons::from_top_object(&top_of_pieces(&[slow]), Some([0, 1, 2, 3])).unwrap();
|
||||
let c = Coons::from_top_object(&top_of_pieces(&pieces), Some([0, 2, 3, 4])).unwrap();
|
||||
for (u, v) in [(0.1, 0.0), (0.25, 0.0), (0.3, 0.2), (0.5, 0.5), (0.62, 0.0), (0.9, 0.7), (0.97, 1.0)] {
|
||||
let (p, q) = (c.eval(u, v), whole.eval(u, v));
|
||||
assert!(p.distance(q) < 1e-6, "({u}, {v}) → {p:?}, unsplit {q:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_joins_a_split_curve_saved_with_rounded_coordinates() {
|
||||
// A file saves the pieces of a curve split into thirds, or into tenths, with its
|
||||
// coordinates rounded to 0.001 pt, on an outline 5, 200 or 5,000 pt wide: the side is
|
||||
// still that curve, to within 0.02 pt.
|
||||
let round = |p: Point| Point::new((p.x * 1000.0).round() / 1000.0, (p.y * 1000.0).round() / 1000.0);
|
||||
for cuts in [3u32, 10] {
|
||||
let pieces: Vec<CubicBez> =
|
||||
(0..cuts).map(|k| UNEVEN_TOP.subsegment(f64::from(k) / f64::from(cuts)..f64::from(k + 1) / f64::from(cuts))).collect();
|
||||
for scale in [0.025, 1.0, 25.0] {
|
||||
let mut split = top_of_pieces(&pieces);
|
||||
split.transform(Affine::scale(scale));
|
||||
for a in split.subpaths.iter_mut().flat_map(|sp| sp.anchors.iter_mut()) {
|
||||
(a.p, a.h_in, a.h_out) = (round(a.p), round(a.h_in), round(a.h_out));
|
||||
}
|
||||
let mut whole = top_of_pieces(&[UNEVEN_TOP]);
|
||||
whole.transform(Affine::scale(scale));
|
||||
let (c, whole) = (Coons::from_top_object(&split, None).unwrap(), Coons::from_top_object(&whole, None).unwrap());
|
||||
for (u, v) in [(1.0 / 6.0, 0.0), (1.0 / 3.0, 0.0), (0.45, 0.0), (0.5, 0.5), (2.0 / 3.0, 0.0), (0.9, 0.3)] {
|
||||
let (p, q) = (c.eval(u, v), whole.eval(u, v));
|
||||
assert!(p.distance(q) < 0.02, "{cuts} pieces at {scale}x: ({u}, {v}) → {p:?}, unsplit {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_keeps_smoothly_joined_curves_apart() {
|
||||
// The top side's second piece leaves the split anchor in line with the first piece's
|
||||
// handle, but its far handle is 1 pt off the split curve's: the pieces are two curves, and
|
||||
// each takes the share of its control polygon.
|
||||
let (a, b) = (UNEVEN_TOP.subsegment(0.0..0.3), UNEVEN_TOP.subsegment(0.3..1.0));
|
||||
let b = CubicBez::new(b.p0, b.p1, b.p2 + Vec2::new(0.0, 1.0), b.p3);
|
||||
let c = Coons::from_top_object(&top_of_pieces(&[a, b]), None).unwrap();
|
||||
let share = polygon(a) / (polygon(a) + polygon(b));
|
||||
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
|
||||
assert!((share - 0.3).abs() > 0.01, "{share}");
|
||||
assert!((share - 0.3).abs() > 0.02, "{share}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_side_partly_of_one_curve_keeps_the_polygon_shares() {
|
||||
// The top side is a curve split at t = 0.3, then a straight segment: not all of it is one
|
||||
// curve, so each piece keeps the share of its control polygon.
|
||||
let curve = CubicBez::new((0.0, 0.0), (90.0, -45.0), (142.5, -22.5), (150.0, 0.0));
|
||||
let (a, b) = (curve.subsegment(0.0..0.3), curve.subsegment(0.3..1.0));
|
||||
let line = CubicBez::new((150.0, 0.0), (150.0 + 50.0 / 3.0, 0.0), (200.0 - 50.0 / 3.0, 0.0), (200.0, 0.0));
|
||||
let c = Coons::from_top_object(&top_of_pieces(&[a, b, line]), None).unwrap();
|
||||
let share = polygon(a) / (polygon(a) + polygon(b) + polygon(line));
|
||||
assert!(c.eval(share, 0.0).distance(a.p3) < 1e-9, "{:?}", c.eval(share, 0.0));
|
||||
// Joined into their curve, the two pieces would have put the anchor 0.3 of the way along
|
||||
// their part of the side.
|
||||
let joined = 0.3 * (polygon(a) + polygon(b)) / (polygon(a) + polygon(b) + polygon(line));
|
||||
assert!(c.eval(joined, 0.0).distance(a.p3) > 1.0, "{share} vs {joined}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_top_object_side_of_many_arcs_stays_on_them() {
|
||||
// A 120° arc of radius 500 drawn as `n` circular arcs, each close to a piece of one cubic
|
||||
// while the whole arc is not one: the side stays on the circle, and the content's middle
|
||||
// stays on the middle anchor, as the arcs' polygon shares put it.
|
||||
let centre = Point::new(300.0, 600.0);
|
||||
for n in [64u32, 128, 256] {
|
||||
let step = 120f64.to_radians() / f64::from(n);
|
||||
let reach = 500.0 * 4.0 / 3.0 * (step / 4.0).tan();
|
||||
let on = |a: f64| centre + Vec2::new(a.cos(), a.sin()) * 500.0;
|
||||
let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()) * reach;
|
||||
let mut anchors: Vec<Anchor> = (0..=n)
|
||||
.map(|i| {
|
||||
let a = (-150f64).to_radians() + step * f64::from(i);
|
||||
let p = on(a);
|
||||
let h_in = if i == 0 { p } else { p - tangent(a) };
|
||||
let h_out = if i == n { p } else { p + tangent(a) };
|
||||
Anchor { p, h_in, h_out, ..Anchor::corner(p) }
|
||||
})
|
||||
.collect();
|
||||
let (start, end) = (on((-150f64).to_radians()), on((-30f64).to_radians()));
|
||||
anchors.extend([Anchor::corner(Point::new(end.x, 800.0)), Anchor::corner(Point::new(start.x, 800.0))]);
|
||||
let path = PathData::single(SubPath::new(anchors, true));
|
||||
let c = Coons::from_top_object(&path, Some([0, n, n + 1, n + 2])).unwrap();
|
||||
let off = (0..=4000).map(|k| (c.eval(f64::from(k) / 4000.0, 0.0).distance(centre) - 500.0).abs()).fold(0.0, f64::max);
|
||||
assert!(off < 0.001, "{n} arcs: the side lies {off} pt off the circle");
|
||||
let mid = c.eval(0.5, 0.0);
|
||||
assert!(mid.distance(Point::new(300.0, 100.0)) < 0.001, "{n} arcs: the middle lands at {mid:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+93
-15
@@ -147,14 +147,18 @@ impl Coons {
|
||||
/// The patch of a top object's outline (the largest subpath of `path`), split into four sides
|
||||
/// at its corners. Each piece of a side between two anchors or corners takes a share of `u` or
|
||||
/// `v` in proportion to the length of its control polygon, spread along the piece by its own
|
||||
/// curve parameter. A segment without handles counts as a cubic with its handles a third of
|
||||
/// the way along, so the content spreads evenly along it. `corners` are the anchors (indices
|
||||
/// into the outline, in its own order) at the top left, top right, bottom right and bottom
|
||||
/// left, as a saved file gives them. They stay on those anchors when they run the way the
|
||||
/// outline does or the opposite way, so a reflected outline keeps them; without them, or when
|
||||
/// they don't fit the outline, each corner is found from the outline ([`top_object_corner`]).
|
||||
/// A straight segment closes an open subpath, and segments of no length are left out. A top
|
||||
/// object's envelope maps onto this patch.
|
||||
/// curve parameter. A side whose pieces, from corner to corner, are all one cubic curve split at
|
||||
/// anchors (each within 0.02 pt of that curve's piece) runs along that curve instead, by its
|
||||
/// parameter: splitting the curve of such a side at more anchors, without changing its shape,
|
||||
/// leaves how the side shares out the content as it was (corners found from the outline can
|
||||
/// still move). A segment without handles counts as a cubic with its handles a third of the way
|
||||
/// along, so the content spreads evenly along it. `corners` are the anchors (indices into the
|
||||
/// outline, in its own order) at the top left, top right, bottom right and bottom left, as a
|
||||
/// saved file gives them. They stay on those anchors when they run the way the outline does or
|
||||
/// the opposite way, so a reflected outline keeps them; without them, or when they don't fit
|
||||
/// the outline, each corner is found from the outline ([`top_object_corner`]). A straight
|
||||
/// segment closes an open subpath, and segments of no length are left out. A top object's
|
||||
/// envelope maps onto this patch.
|
||||
pub fn from_top_object(path: &PathData, corners: Option<[u32; 4]>) -> Option<Self> {
|
||||
let sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?;
|
||||
let mut sp = sp.clone();
|
||||
@@ -212,11 +216,12 @@ impl Coons {
|
||||
segs.get(i).map_or(Point::ZERO, |(c, _)| c.eval((s - i as f64).clamp(0.0, 1.0)))
|
||||
};
|
||||
// The side from `a` to `b`: its points, and where along it (0 to 1) each lies. It runs
|
||||
// through pieces of segments, split at `a` and `b`. Each piece takes its share of the side
|
||||
// by the length of its control polygon and holds points at even steps of its parameter
|
||||
// (at least 16, and at least `SIDE` points on the side), its ends included. A side of
|
||||
// many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS` points,
|
||||
// or one for each piece when it has more pieces than that.
|
||||
// through pieces of segments, split at `a` and `b`; when all of them are one curve split
|
||||
// at anchors ([`one_curve`]), it runs along that curve instead. Each piece takes its share
|
||||
// of the side by the length of its control polygon and holds points at even steps of its
|
||||
// parameter (at least 16, and at least `SIDE` points on the side), its ends included. A
|
||||
// side of many pieces takes fewer points in each, so it holds at most `MAX_SIDE_POINTS`
|
||||
// points, or one for each piece when it has more pieces than that.
|
||||
let side = |a: f64, b: f64| {
|
||||
let span = (b - a).rem_euclid(n);
|
||||
if !(span.is_finite() && span > 0.0) {
|
||||
@@ -232,8 +237,11 @@ impl Coons {
|
||||
}
|
||||
s = next;
|
||||
}
|
||||
let polygon = |c: &CubicBez| c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3);
|
||||
let mut weights: Vec<f64> = pieces.iter().map(polygon).collect();
|
||||
let pieces = match one_curve(&pieces) {
|
||||
Some(one) => vec![one],
|
||||
None => pieces,
|
||||
};
|
||||
let mut weights: Vec<f64> = pieces.iter().map(control_polygon).collect();
|
||||
let mut total: f64 = weights.iter().sum();
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
weights.iter_mut().for_each(|w| *w = 1.0);
|
||||
@@ -336,6 +344,76 @@ impl Coons {
|
||||
/// anchors.
|
||||
const MAX_SIDE_POINTS: usize = 1 << 16;
|
||||
|
||||
/// How far, in points, each control point of each piece of a top object's side may lie from the
|
||||
/// matching piece of one cubic curve for the side to run along that curve ([`one_curve`]); the side
|
||||
/// then lies within this of the pieces it is drawn with. A curve split into thirds or tenths and
|
||||
/// saved with its coordinates rounded to 0.001 pt stays within it, on outlines from 5 to 5,000 pt
|
||||
/// wide; coarser rounding, or a piece of a much smaller share of the curve, can take it past this.
|
||||
/// A smooth side that isn't one curve, such as an arc of a circle drawn in many pieces, lies
|
||||
/// further off as a whole, even where each pair of its pieces would not.
|
||||
const ONE_CURVE: f64 = 0.02;
|
||||
|
||||
/// The length of `c`'s control polygon.
|
||||
fn control_polygon(c: &CubicBez) -> f64 {
|
||||
c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3)
|
||||
}
|
||||
|
||||
/// The cubic curve that `pieces`, two or more end to end, are all pieces of, split at the anchors
|
||||
/// between them, when each control point of each piece lies within [`ONE_CURVE`] of the matching
|
||||
/// piece of that curve; `None` otherwise. Split at parameter `t`, a curve's handles on either side
|
||||
/// of the split lie in line, their lengths in proportion to the spans of its parameter the two
|
||||
/// pieces take; split where the curve stops (a cusp), both handles lie on the anchor, and the
|
||||
/// pieces' second derivatives there, in proportion to the squares of the spans, give the proportion
|
||||
/// instead (whichever of the two pairs is the longer). Those proportions give each piece's span, and the curve follows from the first
|
||||
/// piece's start and its handle, and the last piece's end and its handle, scaled up by their spans.
|
||||
/// Every piece is then checked against that curve's piece over its span, so error can't build up
|
||||
/// from one split to the next (the first piece's start and handle, and the last piece's end and
|
||||
/// handle, match by construction).
|
||||
fn one_curve(pieces: &[CubicBez]) -> Option<CubicBez> {
|
||||
let (first, last) = (pieces.first()?, pieces.last()?);
|
||||
if pieces.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let mut spans = Vec::with_capacity(pieces.len());
|
||||
spans.push(1.0);
|
||||
for pair in pieces.windows(2) {
|
||||
let [a, b] = pair else { return None };
|
||||
let (into, out) = (a.p3.distance(a.p2), b.p0.distance(b.p1));
|
||||
// How far each piece bends away from the anchor goes with the squares of the spans. Split
|
||||
// where the curve stops (a cusp), both handles lie on the anchor and say nothing of the
|
||||
// spans, and the bends say it; where the curve runs straight through the split, the bends
|
||||
// are nothing and the handles say it. Whichever pair is the longer is the one to go by.
|
||||
let bend_in = ((a.p3 - a.p2) - (a.p2 - a.p1)).hypot();
|
||||
let bend_out = ((b.p2 - b.p1) - (b.p1 - b.p0)).hypot();
|
||||
let ratio = if into.min(out) >= bend_in.min(bend_out) { out / into } else { (bend_out / bend_in).sqrt() };
|
||||
let next = spans.last().copied().unwrap_or(1.0) * ratio;
|
||||
if !(next.is_finite() && next > 0.0) {
|
||||
return None;
|
||||
}
|
||||
spans.push(next);
|
||||
}
|
||||
let total: f64 = spans.iter().sum();
|
||||
let (head, tail) = (spans.first().copied().unwrap_or(1.0) / total, spans.last().copied().unwrap_or(1.0) / total);
|
||||
if !(total.is_finite() && head > 0.0 && tail > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let one = CubicBez::new(first.p0, first.p0 + (first.p1 - first.p0) / head, last.p3 + (last.p2 - last.p3) / tail, last.p3);
|
||||
if ![one.p1, one.p2].iter().all(|p| p.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let near = |p: Point, q: Point| p.distance(q) <= ONE_CURVE;
|
||||
let mut from = 0.0;
|
||||
for (k, (piece, span)) in pieces.iter().zip(&spans).enumerate() {
|
||||
let to = if k + 1 == pieces.len() { 1.0 } else { (from + span / total).min(1.0) };
|
||||
let part = one.subsegment(from..to);
|
||||
if !(near(part.p0, piece.p0) && near(part.p1, piece.p1) && near(part.p2, piece.p2) && near(part.p3, piece.p3)) {
|
||||
return None;
|
||||
}
|
||||
from = to;
|
||||
}
|
||||
Some(one)
|
||||
}
|
||||
|
||||
/// How far into the outline's bounding box, as a share of its width and of its height, a corner
|
||||
/// of a top object looks for an anchor.
|
||||
const CORNER_REACH: f64 = 0.475;
|
||||
|
||||
@@ -87,6 +87,8 @@ pub struct SymbolBoxes<'a> {
|
||||
sliced_placed: Cell<u64>,
|
||||
/// The most objects of symbol art [`Self::sliced_visual`] places: [`MAX_SYMBOL_NODES`].
|
||||
sliced_most: u64,
|
||||
/// The widths [`Self::measured_width`] has measured, by kind and symbol name.
|
||||
widths: RefCell<HashMap<(&'static str, String), Option<f64>>>,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
@@ -107,6 +109,7 @@ impl Document {
|
||||
sliced: RefCell::default(),
|
||||
sliced_placed: Cell::new(0),
|
||||
sliced_most: MAX_SYMBOL_NODES,
|
||||
widths: RefCell::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,6 +250,18 @@ impl<'a> SymbolBoxes<'a> {
|
||||
self.art(name)?.brush
|
||||
}
|
||||
|
||||
/// The width `measure` gives for the symbol named `name`, measured once for these boxes for each
|
||||
/// `kind`, which names what `measure` measures. `measure` may call this again for other names.
|
||||
pub fn measured_width(&self, kind: &'static str, name: &str, measure: impl FnOnce() -> Option<f64>) -> Option<f64> {
|
||||
let key = (kind, name.to_string());
|
||||
if let Some(w) = self.widths.borrow().get(&key) {
|
||||
return *w;
|
||||
}
|
||||
let w = measure();
|
||||
self.widths.borrow_mut().insert(key, w);
|
||||
w
|
||||
}
|
||||
|
||||
/// How far the visual box of an instance of the symbol named `name` grows in boxes made by
|
||||
/// [`Self::with_brush_art`]: `16 × max(w, 1) + 8` for the widest stroke `w` that
|
||||
/// [`Self::brush_width`] finds, as far as the renderer grows the cull bounds of a brushed path
|
||||
|
||||
@@ -424,6 +424,8 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
if !kept {
|
||||
return None;
|
||||
}
|
||||
// The members' own effects run first, as on the canvas.
|
||||
crate::group::members_as_drawn(Some(d), &mut m);
|
||||
reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d));
|
||||
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
|
||||
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
|
||||
|
||||
@@ -209,6 +209,8 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
|
||||
Some(area) => Some(reshaped(&area, n, doc)),
|
||||
None => {
|
||||
let mut m = crate::reshape::outlined_members_with(None, doc, n, outline, nodes);
|
||||
// The members' own effects run first, as on the canvas.
|
||||
members_as_drawn(doc, &mut m);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes follow the effects as its members do.
|
||||
if carry.moves(&m.appearance) {
|
||||
@@ -225,6 +227,7 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
|
||||
let art = h(n).filter(|art| nodes.charge(art))?;
|
||||
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
|
||||
crate::reshape::outline_nested_text(doc, &mut art, false);
|
||||
members_as_drawn(doc, &mut art);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
|
||||
// The art's own fills and strokes follow the effects as its members do.
|
||||
if carry.moves(&art.appearance) {
|
||||
@@ -754,7 +757,8 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, hidden: bool, lo
|
||||
}
|
||||
|
||||
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box), and its
|
||||
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
|
||||
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
|
||||
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
|
||||
/// the members (after a clipping path) or above them, as its contents slot says. Its
|
||||
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
|
||||
@@ -790,6 +794,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
}
|
||||
if !fx.is_empty() {
|
||||
m = crate::reshape::outlined_members(doc, &m);
|
||||
members_as_drawn(doc, &mut m);
|
||||
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
|
||||
// The group's own fills and strokes paint the members as a whole: their gradients follow
|
||||
// the effects as the members' do.
|
||||
@@ -821,5 +826,83 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
Some(m)
|
||||
}
|
||||
|
||||
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
|
||||
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
|
||||
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
|
||||
/// draw. A clip group's clipping path stays as it is, and so do images, symbol instances and the
|
||||
/// other objects that `own_effects_art` leaves alone, and a group or layer with a 3D effect with
|
||||
/// everything in it. Calls nested in one another, through the
|
||||
/// groups and layers it walks and the art it evaluates (symbol art and Pathfinder members
|
||||
/// included), stop at [`vectorcraft_doc::depth::MAX_DEPTH`] deep, and together they replace at
|
||||
/// most [`crate::SYMBOL_ART_MAX_NODES`] members: past either limit, members stay as they are.
|
||||
pub(crate) fn members_as_drawn(doc: Option<&Document>, n: &mut Node) {
|
||||
let Some(_frame) = DrawnFrame::enter() else { return };
|
||||
let clip = usize::from(n.clips());
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for c in ch.iter_mut().skip(clip).filter(|c| c.visible) {
|
||||
if !DrawnFrame::take_member() {
|
||||
return;
|
||||
}
|
||||
// A group or layer with a 3D effect stays whole: the geometry effects listed after its 3D
|
||||
// effect reshape its 3D art.
|
||||
if is_container(c) && (crate::has_solid(c) || crate::has_revolve(c)) {
|
||||
continue;
|
||||
}
|
||||
let art = if !is_container(c) {
|
||||
crate::reshape::own_effects_art(doc, c)
|
||||
} else if has_pathfinder(c) || !crate::reshape::geometry_effects(c).is_empty() {
|
||||
evaluate_container(doc, c)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match art {
|
||||
Some(a) => *c = Arc::new(a),
|
||||
None if is_container(c) => members_as_drawn(doc, Arc::make_mut(c)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// How many [`members_as_drawn`] calls are running, one inside another, and how many members
|
||||
/// they have visited since the outermost one started.
|
||||
static DRAWN: std::cell::Cell<(usize, u64)> = const { std::cell::Cell::new((0, 0)) };
|
||||
}
|
||||
|
||||
/// One running [`members_as_drawn`] call, counted in [`DRAWN`] until it is dropped.
|
||||
struct DrawnFrame;
|
||||
|
||||
impl DrawnFrame {
|
||||
/// Count one more call; `None` when [`vectorcraft_doc::depth::MAX_DEPTH`] are running. The
|
||||
/// outermost call starts the count of members again.
|
||||
fn enter() -> Option<Self> {
|
||||
let (frames, members) = DRAWN.with(|d| d.get());
|
||||
if frames >= vectorcraft_doc::depth::MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
DRAWN.with(|d| d.set((frames + 1, if frames == 0 { 0 } else { members })));
|
||||
Some(DrawnFrame)
|
||||
}
|
||||
|
||||
/// Count one more member visited; `false` once [`crate::SYMBOL_ART_MAX_NODES`] have been.
|
||||
fn take_member() -> bool {
|
||||
let (frames, members) = DRAWN.with(|d| d.get());
|
||||
if members >= crate::SYMBOL_ART_MAX_NODES {
|
||||
return false;
|
||||
}
|
||||
DRAWN.with(|d| d.set((frames, members + 1)));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DrawnFrame {
|
||||
fn drop(&mut self) {
|
||||
DRAWN.with(|d| {
|
||||
let (frames, members) = d.get();
|
||||
d.set((frames.saturating_sub(1), members));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -555,6 +555,298 @@ fn a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_dist
|
||||
assert!(near(s, Point::new(0.0, 5.0)) && near(e, Point::new(20.0, 5.0)), "{s:?} {e:?}");
|
||||
}
|
||||
|
||||
/// The bounds of what `n` draws, as the renderer draws it: a group or layer with an appearance of
|
||||
/// its own as the art [`evaluate_container`] makes of it, and each visible path and compound path
|
||||
/// with the geometry effects still on it applied, then those of each visible fill and stroke that
|
||||
/// has some.
|
||||
fn drawn_bounds(n: &Node) -> Option<Rect> {
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
if let Some(m) = evaluate_container(None, n) {
|
||||
return drawn_bounds(&m);
|
||||
}
|
||||
if let Some(ch) = n.children()
|
||||
&& !matches!(n.kind, NodeKind::Compound { .. })
|
||||
{
|
||||
return ch.iter().filter_map(|c| drawn_bounds(c)).reduce(|a, b| a.union(b));
|
||||
}
|
||||
let (path, _) = crate::reshape::leaf_geometry(n)?;
|
||||
let geometry = |fx: &[Effect]| -> Vec<Effect> { fx.iter().filter(|e| e.visible && crate::is_geometry(&e.id)).cloned().collect() };
|
||||
let apply = |fx: &[Effect], p: &PathData| crate::apply_geometry(&geometry(fx), p, p.bounds().unwrap());
|
||||
let g = apply(&n.appearance.effects, &path);
|
||||
let items: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| paints(i) && !geometry(i.effects()).is_empty()).collect();
|
||||
if items.is_empty() {
|
||||
return g.bounds();
|
||||
}
|
||||
items.iter().filter_map(|i| apply(i.effects(), &g).bounds()).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
fn black() -> Appearance {
|
||||
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)
|
||||
}
|
||||
|
||||
/// A black 100 pt square from (100, 100).
|
||||
fn square_at_100() -> Node {
|
||||
Node::path(NodeId(1), shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), black())
|
||||
}
|
||||
|
||||
fn effect(id: &str, params: serde_json::Value) -> Effect {
|
||||
Effect { id: id.into(), params, visible: true }
|
||||
}
|
||||
|
||||
fn offset_10() -> Effect {
|
||||
effect("path.offsetPath", serde_json::json!({"offset": 10}))
|
||||
}
|
||||
|
||||
fn scaled(s: f64) -> Effect {
|
||||
effect("distort.transform", serde_json::json!({"scaleH": s, "scaleV": s}))
|
||||
}
|
||||
|
||||
fn with_effect(mut n: Node, e: Effect) -> Node {
|
||||
n.appearance.effects.push(e);
|
||||
n
|
||||
}
|
||||
|
||||
/// The width that a group with `e` holding `member` draws at.
|
||||
fn drawn_width(member: Node, e: Effect) -> f64 {
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(member)]), e);
|
||||
drawn_bounds(&g).unwrap().width()
|
||||
}
|
||||
|
||||
/// A member's own Offset Path runs before its group's Transform: the square offset by 10 pt to
|
||||
/// 120 pt, then scaled by half, is 60 pt wide (70 pt the other way round).
|
||||
#[test]
|
||||
fn a_members_own_offset_runs_before_its_groups_scale() {
|
||||
let w = drawn_width(with_effect(square_at_100(), offset_10()), scaled(50.0));
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A member's own Transform runs before its group's Offset Path: the square scaled to 200 pt, then
|
||||
/// offset by 10 pt, is 220 pt wide (240 pt the other way round).
|
||||
#[test]
|
||||
fn a_members_own_scale_runs_before_its_groups_offset() {
|
||||
let w = drawn_width(with_effect(square_at_100(), scaled(200.0)), offset_10());
|
||||
assert!((w - 220.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A member inside a plain group inside the group takes its own effects first too.
|
||||
#[test]
|
||||
fn a_member_of_a_plain_nested_group_takes_its_own_effects_first() {
|
||||
let w = drawn_width(Node::group(NodeId(5), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0));
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A nested group's own geometry effects run before the outer group's.
|
||||
#[test]
|
||||
fn a_nested_groups_own_effects_run_before_its_groups() {
|
||||
let w = drawn_width(with_effect(Node::group(NodeId(5), vec![Arc::new(square_at_100())]), offset_10()), scaled(50.0));
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A nested group's Pathfinder effect runs before the outer group's geometry effects: the back
|
||||
/// square minus the front one is 50 pt wide, and offset by 10 pt it is 70 pt (offsetting the
|
||||
/// squares first leaves 50 pt).
|
||||
#[test]
|
||||
fn a_nested_groups_pathfinder_runs_before_its_groups_effects() {
|
||||
let back = square_at_100();
|
||||
let front = Node::path(NodeId(2), shapes::rectangle(Rect::new(150.0, 100.0, 250.0, 200.0)), black());
|
||||
let nested = with_effect(Node::group(NodeId(5), vec![Arc::new(back), Arc::new(front)]), effect("pathfinder.subtract", serde_json::json!({})));
|
||||
let w = drawn_width(nested, offset_10());
|
||||
assert!((w - 70.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// The geometry effects of a member's own fill run before its group's: 60 pt, as for the
|
||||
/// member's own effect.
|
||||
#[test]
|
||||
fn a_members_fill_effects_run_before_its_groups() {
|
||||
let mut member = square_at_100();
|
||||
member.appearance.items[0].effects_mut().push(offset_10());
|
||||
let w = drawn_width(member, scaled(50.0));
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A member whose fills have geometry effects stays one element of a knockout group: its fills do
|
||||
/// not knock each other out.
|
||||
#[test]
|
||||
fn a_member_drawn_as_its_fills_stays_one_knockout_element() {
|
||||
let mut member = square_at_100();
|
||||
member.appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))));
|
||||
member.appearance.items[0].effects_mut().push(offset_10());
|
||||
let mut g = with_effect(Node::group(NodeId(10), vec![Arc::new(member)]), scaled(50.0));
|
||||
g.knockout = vectorcraft_doc::Knockout::On;
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let elements = Node::knockout_elements(art.children().unwrap());
|
||||
assert_eq!(elements.len(), 1, "{:?}", elements.iter().map(|e| (e.id, &e.kind)).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// The art a Pathfinder operation or compound shape takes from a group with geometry effects has
|
||||
/// the members' own effects applied first, as the canvas draws it.
|
||||
#[test]
|
||||
fn shape_art_of_a_group_applies_its_members_effects_first() {
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0));
|
||||
let art = shape_art(None, &g, None).unwrap();
|
||||
let w = drawn_bounds(&art).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
let leaves = member_leaves(None, &g, None);
|
||||
let w = leaves.iter().filter_map(drawn_bounds).reduce(|a, b| a.union(b)).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "leaves: {w}");
|
||||
}
|
||||
|
||||
/// A symbol instance's own geometry effects run after those of its symbol's members, as the canvas
|
||||
/// draws it and in the art a Pathfinder operation takes from it.
|
||||
#[test]
|
||||
fn a_symbol_instances_effects_run_after_its_symbols_members_own() {
|
||||
let art = Node::group(NodeId(20), vec![Arc::new(with_effect(square_at_100(), offset_10()))]);
|
||||
let instance =
|
||||
with_effect(Node::new(NodeId(6), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY }), scaled(50.0));
|
||||
let drawn = crate::reshape(None, &instance, Some(&art)).unwrap();
|
||||
let w = drawn_bounds(&drawn).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "drawn: {w}");
|
||||
let hook = move |_: &Node| Some(art.clone());
|
||||
let w = drawn_bounds(&shape_art(None, &instance, Some(&hook)).unwrap()).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "shape art: {w}");
|
||||
}
|
||||
|
||||
/// Export bakes the group as the canvas draws it.
|
||||
#[test]
|
||||
fn a_baked_group_applies_its_members_effects_first() {
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(with_effect(square_at_100(), offset_10()))]), scaled(50.0));
|
||||
d.insert(Some(layer), 0, g).unwrap();
|
||||
let baked = crate::bake_document(&d).unwrap();
|
||||
let w = baked.node(NodeId(10)).unwrap().geometric_bounds().unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A group whose Transform effect only moves and copies keeps its type when baked; a nested
|
||||
/// group's own Transform still runs before the copies: the nested square scaled by half to 50 pt
|
||||
/// and copied 200 pt to the right spans 250 pt (copying first, then scaling both copies about
|
||||
/// their middle, spans 150 pt).
|
||||
#[test]
|
||||
fn a_baked_group_that_keeps_its_type_applies_its_members_effects_first() {
|
||||
if skip_without_craft_fonts() {
|
||||
return;
|
||||
}
|
||||
let style = CharStyle { size: 24.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
let text = Node::new(NodeId(3), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 60.0), "Type", style))));
|
||||
let nested = with_effect(Node::group(NodeId(5), vec![Arc::new(square_at_100())]), scaled(50.0));
|
||||
let g = with_effect(
|
||||
Node::group(NodeId(10), vec![Arc::new(text), Arc::new(nested)]),
|
||||
effect("distort.transform", serde_json::json!({"moveH": 200, "copies": 1})),
|
||||
);
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, g).unwrap();
|
||||
let baked = crate::bake_document(&d).unwrap();
|
||||
let mut text = 0;
|
||||
baked.walk(|n| text += usize::from(matches!(n.kind, NodeKind::Text(_))));
|
||||
assert_eq!(text, 2, "the type stays type, copied");
|
||||
let w = baked.node(NodeId(5)).unwrap().geometric_bounds().unwrap().width();
|
||||
assert!((w - 250.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
/// A clip group's clipping path keeps its own effects; the clipped members take theirs first.
|
||||
#[test]
|
||||
fn a_clipping_path_keeps_its_own_effects_under_a_groups_effects() {
|
||||
let mut clip = with_effect(square_at_100(), offset_10());
|
||||
clip.id = NodeId(2);
|
||||
if let NodeKind::Path { clipping, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
}
|
||||
let clipped =
|
||||
Node::new(NodeId(5), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(with_effect(square_at_100(), offset_10()))], clip: true });
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(clipped)]), scaled(50.0));
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let clip_group = art.children().unwrap()[0].clone();
|
||||
let ch = clip_group.children().unwrap();
|
||||
assert!(matches!(ch[0].kind, NodeKind::Path { clipping: true, .. }), "{:?}", ch[0].kind);
|
||||
assert_eq!(crate::reshape::geometry_effects(&ch[0]).len(), 1, "the clipping path keeps its Offset Path");
|
||||
assert!(matches!(ch[1].kind, NodeKind::Group { .. }) && crate::reshape::geometry_effects(&ch[1]).is_empty(), "the member is drawn as its art");
|
||||
}
|
||||
|
||||
/// A member with a linked opacity mask keeps its own effects on it, so its mask moves with it
|
||||
/// under the group's Transform; so does a member with a 3D effect, whose later geometry effects
|
||||
/// apply to its 3D art.
|
||||
#[test]
|
||||
fn members_with_linked_masks_or_3d_effects_keep_their_own_effects() {
|
||||
let mut masked = with_effect(square_at_100(), offset_10());
|
||||
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(
|
||||
Node::path(NodeId(2), shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), black()),
|
||||
true,
|
||||
)));
|
||||
let mut solid = with_effect(square_at_100(), effect(crate::solids::EXTRUDE, serde_json::json!({})));
|
||||
solid.id = NodeId(3);
|
||||
solid.appearance.effects.push(scaled(50.0));
|
||||
let moved = effect("distort.transform", serde_json::json!({"moveH": 50, "strokes": true}));
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(masked), Arc::new(solid)]), moved);
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert!(matches!(ch[0].kind, NodeKind::Path { .. }) && crate::reshape::geometry_effects(&ch[0]).len() == 1, "{:?}", ch[0].kind);
|
||||
let mask = ch[0].extras().mask.as_deref().unwrap().art.geometric_bounds().unwrap();
|
||||
assert!((mask.x0 - 150.0).abs() < 1e-6, "the mask moves with the square: {mask:?}");
|
||||
assert!(matches!(ch[1].kind, NodeKind::Path { .. }) && ch[1].appearance.effects.len() == 2, "{:?}", ch[1].kind);
|
||||
}
|
||||
|
||||
/// A nested group with a 3D effect stays as it is, with its members: the Transform listed after
|
||||
/// its Extrude still applies to its 3D art.
|
||||
#[test]
|
||||
fn a_nested_group_with_a_3d_effect_keeps_its_own_effects() {
|
||||
let inner = with_effect(square_at_100(), offset_10());
|
||||
let mut solid = with_effect(Node::group(NodeId(5), vec![Arc::new(inner)]), effect(crate::solids::EXTRUDE, serde_json::json!({})));
|
||||
solid.appearance.effects.push(scaled(50.0));
|
||||
let moved = effect("distort.transform", serde_json::json!({"moveH": 50}));
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(solid)]), moved);
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let ch = art.children().unwrap();
|
||||
assert!(
|
||||
matches!(ch[0].kind, NodeKind::Group { .. }) && ch[0].id == NodeId(5) && ch[0].appearance.effects.len() == 2,
|
||||
"{:?}",
|
||||
ch[0].appearance.effects
|
||||
);
|
||||
let member = &ch[0].children().unwrap()[0];
|
||||
assert!(matches!(member.kind, NodeKind::Path { .. }) && crate::reshape::geometry_effects(member).len() == 1, "{:?}", member.kind);
|
||||
}
|
||||
|
||||
/// Members nested deeper than the depth limit keep their own effects as they are.
|
||||
#[test]
|
||||
fn members_past_the_depth_limit_stay_as_they_are() {
|
||||
let mut n = with_effect(square_at_100(), offset_10());
|
||||
for i in 0..vectorcraft_doc::depth::MAX_DEPTH {
|
||||
n = Node::group(NodeId(100 + i as u64), vec![Arc::new(n)]);
|
||||
}
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(n)]), scaled(50.0));
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut deepest = None;
|
||||
art.walk(&mut |c: &Node| {
|
||||
if c.id == NodeId(1) {
|
||||
deepest = Some(c.clone());
|
||||
}
|
||||
});
|
||||
let deepest = deepest.unwrap();
|
||||
assert!(matches!(deepest.kind, NodeKind::Path { .. }), "{:?}", deepest.kind);
|
||||
assert_eq!(crate::reshape::geometry_effects(&deepest).len(), 1);
|
||||
}
|
||||
|
||||
/// The depth limit counts nested groups with effects of their own too.
|
||||
#[test]
|
||||
fn nested_groups_with_effects_count_toward_the_depth_limit() {
|
||||
let mut n = with_effect(square_at_100(), offset_10());
|
||||
for i in 0..vectorcraft_doc::depth::MAX_DEPTH {
|
||||
n = with_effect(Node::group(NodeId(100 + i as u64), vec![Arc::new(n)]), effect("distort.transform", serde_json::json!({"moveH": 1})));
|
||||
}
|
||||
let g = with_effect(Node::group(NodeId(10), vec![Arc::new(n)]), scaled(50.0));
|
||||
let art = evaluate_container(None, &g).unwrap();
|
||||
let mut deepest = None;
|
||||
art.walk(&mut |c: &Node| {
|
||||
if c.id == NodeId(1) && matches!(c.kind, NodeKind::Path { .. }) {
|
||||
deepest = Some(c.clone());
|
||||
}
|
||||
});
|
||||
assert!(deepest.is_some_and(|d| crate::reshape::geometry_effects(&d).len() == 1), "the deepest member keeps its effect");
|
||||
}
|
||||
|
||||
/// An image or a symbol instance that a group's Transform effect moves takes the placed gradients
|
||||
/// of its own fills along, as a path does, and each copy takes them as many times as it takes the
|
||||
/// transform.
|
||||
|
||||
@@ -524,9 +524,10 @@ fn with_id(art: &Node, id: NodeId) -> Node {
|
||||
/// `n` as plain art that geometry effects can reshape, without its transparency and object
|
||||
/// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined),
|
||||
/// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by
|
||||
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), its
|
||||
/// fills and strokes carrying the geometry effects of the instance's active fill and stroke
|
||||
/// ([`add_instance_row_effects`]).
|
||||
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), as
|
||||
/// the art its members draw when the instance has geometry effects of its own
|
||||
/// ([`crate::group::members_as_drawn`]), its fills and strokes carrying the geometry effects of the
|
||||
/// instance's active fill and stroke ([`add_instance_row_effects`]).
|
||||
/// `None` for other kinds (images, paths, containers), and for an instance whose art placed
|
||||
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
|
||||
/// `doc`'s symbols that its instances show toward its instance budget.
|
||||
@@ -562,20 +563,16 @@ fn outline_art_with(
|
||||
Node::group(n.id, vec![Arc::new(a)])
|
||||
}
|
||||
// The object as the one piece the copies of its Transform effect are made from.
|
||||
_ if has_transform_art(n) || (apart && has_transform_copies(n)) => {
|
||||
let mut one = n.clone();
|
||||
one.opacity = 1.0;
|
||||
one.blend = Default::default();
|
||||
one.isolate = false;
|
||||
one.extras_mut().mask = None;
|
||||
one.appearance.effects.clear();
|
||||
Node::group(n.id, vec![Arc::new(one)])
|
||||
}
|
||||
_ if has_transform_art(n) || (apart && has_transform_copies(n)) => one_piece(n),
|
||||
_ if vectorcraft_doc::live::is_live(n) => evaluated_with(symbols, n, outline, nodes),
|
||||
_ => return None,
|
||||
};
|
||||
outline_nested_text(paint_doc, &mut art, false);
|
||||
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
|
||||
// The instance's own geometry effects reshape what the symbol's members draw.
|
||||
if !geometry_effects(n).is_empty() {
|
||||
crate::group::members_as_drawn(paint_doc, &mut art);
|
||||
}
|
||||
add_instance_row_effects(symbols, n, &mut art);
|
||||
}
|
||||
art.opacity = 1.0;
|
||||
@@ -843,18 +840,64 @@ fn as_art_opts(
|
||||
}
|
||||
// The art is a group with `n`'s id (for an image without fills or strokes that paint, a clip
|
||||
// group).
|
||||
let mut out = art;
|
||||
out.name = n.name.clone();
|
||||
out.visible = n.visible;
|
||||
out.opacity = n.opacity;
|
||||
out.blend = n.blend;
|
||||
out.isolate = n.isolate;
|
||||
Some(dressed(art, n))
|
||||
}
|
||||
|
||||
/// `art`, the art made of `n`, with `n`'s name, visibility, transparency, opacity mask and
|
||||
/// remaining (raster) effects.
|
||||
fn dressed(mut art: Node, n: &Node) -> Node {
|
||||
art.name = n.name.clone();
|
||||
art.visible = n.visible;
|
||||
art.opacity = n.opacity;
|
||||
art.blend = n.blend;
|
||||
art.isolate = n.isolate;
|
||||
// One element: its pieces never knock each other out.
|
||||
out.knockout = vectorcraft_doc::Knockout::Off;
|
||||
out.knockout_shape = n.knockout_shape;
|
||||
out.extras_mut().mask = n.extras().mask.clone();
|
||||
out.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
|
||||
Some(out)
|
||||
art.knockout = vectorcraft_doc::Knockout::Off;
|
||||
art.knockout_shape = n.knockout_shape;
|
||||
art.extras_mut().mask = n.extras().mask.clone();
|
||||
art.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
|
||||
art
|
||||
}
|
||||
|
||||
/// A group with `n`'s id holding `n` without its transparency, opacity mask and effects: the one
|
||||
/// piece that `n`'s own geometry effects reshape.
|
||||
fn one_piece(n: &Node) -> Node {
|
||||
let mut one = n.clone();
|
||||
one.opacity = 1.0;
|
||||
one.blend = Default::default();
|
||||
one.isolate = false;
|
||||
one.extras_mut().mask = None;
|
||||
one.appearance.effects.clear();
|
||||
Node::group(n.id, vec![Arc::new(one)])
|
||||
}
|
||||
|
||||
/// Path or compound path `n` with its own geometry effects applied, as the art it draws: with
|
||||
/// geometry effects in a visible fill or stroke of its own, a group of one path for each fill and
|
||||
/// stroke, its effects and that fill's or stroke's applied ([`crate::bake_type_appearance`]);
|
||||
/// otherwise a group with `n`'s id holding the path reshaped by its effects ([`reshape_leaves`]).
|
||||
/// The art keeps `n`'s id, name, visibility, transparency, opacity mask and raster effects. `None`
|
||||
/// for a guide, for other kinds of objects, for a path with a linked opacity mask or a 3D effect,
|
||||
/// and when `n` has no visible geometry effect of its own or in a visible fill or stroke.
|
||||
pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
|
||||
if !matches!(n.kind, NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. })
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| m.linked)
|
||||
|| crate::has_solid(n)
|
||||
|| crate::has_revolve(n)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) {
|
||||
// One element: its pieces never knock each other out.
|
||||
return crate::bake_type_appearance(doc, n).map(|art| Node { knockout: vectorcraft_doc::Knockout::Off, ..art });
|
||||
}
|
||||
let fx = geometry_effects(n);
|
||||
if fx.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut art = one_piece(n);
|
||||
reshape_leaves(&mut art, &fx, &n.appearance.effects, doc);
|
||||
transform_items(&mut art, doc);
|
||||
Some(dressed(art, n))
|
||||
}
|
||||
|
||||
/// Map every path under `art` (and its gradients), and every path in the art of the linked opacity
|
||||
|
||||
@@ -523,11 +523,12 @@ fn a_groups_transform_applies_after_its_members_own() {
|
||||
let mut on_fill = fill_square(33, vec![shadow(10.0, 0.0, 0.0)]);
|
||||
on_fill.appearance.effects = vec![turn()];
|
||||
let art = crate::evaluate_container(None, &group(32, vec![on_fill], vec![uneven()])).unwrap();
|
||||
assert!(near(&[fill_shadow(&node_in(&art, 33))], &[want]), "fill: {:?}", fill_shadow(&node_in(&art, 33)));
|
||||
// The member is drawn as its art: a group with its id holding the turned square.
|
||||
let filled = node_in(&art, 33).children().and_then(|ch| ch.first().map(|c| (**c).clone())).unwrap();
|
||||
assert!(near(&[fill_shadow(&filled)], &[want]), "fill: {:?}", fill_shadow(&filled));
|
||||
let nested = group(34, vec![group(35, vec![square(36, vec![shadow(10.0, 0.0, 0.0)])], vec![turn()])], vec![uneven()]);
|
||||
let art = crate::evaluate_container(None, &nested).unwrap();
|
||||
let inner = crate::evaluate_container(None, &node_in(&art, 35)).unwrap();
|
||||
assert!(near(&shadows_in(&inner), &[want]), "nested: {:?}", shadows_in(&inner));
|
||||
assert!(near(&shadows_in(&art), &[want]), "nested: {:?}", shadows_in(&art));
|
||||
}
|
||||
|
||||
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
|
||||
@@ -645,7 +646,8 @@ fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform
|
||||
let art = crate::evaluate_container(None, &g).unwrap();
|
||||
for (id, _, want) in &cases {
|
||||
let member = node_in(&art, *id);
|
||||
let drawn = shadows_in(&crate::reshape(None, &member, None).unwrap());
|
||||
// The member is drawn as its art, its fill's own Transform effect applied.
|
||||
let drawn = shadows_in(&member);
|
||||
assert!(!drawn.is_empty() && near(&drawn, &vec![*want; drawn.len()]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1365,17 +1365,19 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (fill, stroke) = (attrs.appearance.fill, attrs.appearance.stroke);
|
||||
let source_has = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind);
|
||||
let source_shows = |kind: bool| picked.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
|
||||
// A whole pick replaces the stack: it removes the rows of a kind the source has no row of.
|
||||
let whole = fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL;
|
||||
let (paints, opacities) = if append {
|
||||
let rows = (fill.color && source_shows(true), stroke.color && source_shows(false));
|
||||
(rows, rows)
|
||||
} else {
|
||||
(
|
||||
(fill.color, stroke.color || (stroke.weight && source_has(false))),
|
||||
(fill.transparency && source_has(true), stroke.transparency && source_has(false)),
|
||||
(fill.transparency && (whole || source_has(true)), stroke.transparency && (whole || source_has(false))),
|
||||
)
|
||||
};
|
||||
// A pick of some attributes edits the topmost row of its kind, which may be hidden; `append` and a whole pick write rows.
|
||||
let rows_written = append || (fill == FillAttrs::ALL && stroke == StrokeAttrs::ALL);
|
||||
let rows_written = append || whole;
|
||||
let top_shows = |id: NodeId, kind: bool| {
|
||||
let items = d.node(id).map_or(&[][..], |n| &n.appearance.items[..]);
|
||||
items.iter().rev().find(|it| it.is_fill() == kind).is_some_and(|it| it.visible())
|
||||
@@ -1389,6 +1391,9 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect()
|
||||
};
|
||||
let mut opacity_rows = top_opacity_changed(&before, d, &targets);
|
||||
// A written row that had paint before the pick counts too when the pick left it without paint, as in
|
||||
// `capture_series_writes`.
|
||||
opacity_rows.extend(painted_rows(&before, written(opacities)));
|
||||
opacity_rows.extend(painted_rows(d, written(opacities)));
|
||||
let mut rows = top_paint_changed(&before, d, &targets);
|
||||
rows.extend(painted_rows(d, written(paints)));
|
||||
|
||||
@@ -8,10 +8,22 @@ use super::{
|
||||
|
||||
// ---------- Smooth ----------
|
||||
|
||||
/// Refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
|
||||
fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
|
||||
/// The spread (points) of the Gaussian the Smooth tool smooths a path along its length with before
|
||||
/// refitting it, as a share of the tool's reach: a third, so each point is averaged with the stretch
|
||||
/// of path within the reach on either side of it. VectorCraft's own value.
|
||||
const SMOOTH_SPREAD: f64 = 1.0 / 3.0;
|
||||
|
||||
/// The options the Smooth tool refits with: the path smoothed along its length by a Gaussian of
|
||||
/// spread `sigma` (none at 0), then refitted within `tol` of that and within twice the distance the
|
||||
/// smoothing moved it, keeping a corner only where the path turns back on itself.
|
||||
fn refit_options(tol: f64, sigma: f64) -> SimplifyOptions {
|
||||
SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, smooth: sigma, smooth_moved_only: true }
|
||||
}
|
||||
|
||||
/// Smooth and refit the anchors of an open run `a[lo..=hi]` keeping its end points and outer handles.
|
||||
fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64) -> Vec<Anchor> {
|
||||
let piece = PathData::single(SubPath::new(anchors.to_vec(), false));
|
||||
let fitted = po::simplify_with(&piece, &SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() });
|
||||
let fitted = po::simplify_with(&piece, &refit_options(tol, sigma));
|
||||
let Some(mut out) = fitted.subpaths.into_iter().next().map(|s| s.anchors).filter(|a| a.len() >= 2) else { return anchors.to_vec() };
|
||||
let (f, l) = (anchors[0], anchors[anchors.len() - 1]);
|
||||
let last = out.len() - 1;
|
||||
@@ -25,7 +37,7 @@ fn refit_run(anchors: &[Anchor], tol: f64) -> Vec<Anchor> {
|
||||
out
|
||||
}
|
||||
|
||||
fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Option<SubPath> {
|
||||
fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Option<SubPath> {
|
||||
let n = sp.anchors.len();
|
||||
let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect();
|
||||
if n < 3 || !marked.iter().any(|m| *m) {
|
||||
@@ -33,11 +45,8 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio
|
||||
}
|
||||
if sp.closed {
|
||||
let Some(k) = marked.iter().position(|m| !m) else {
|
||||
// Everything is in range: smooth the whole closed path.
|
||||
let f = po::simplify_with(
|
||||
&PathData::single(sp.clone()),
|
||||
&SimplifyOptions { tolerance: tol, corner_angle_deg: 179.0, straight_lines: false, ..Default::default() },
|
||||
);
|
||||
// Everything is in range: smooth the whole closed path, across its start too.
|
||||
let f = po::simplify_with(&PathData::single(sp.clone()), &refit_options(tol, sigma));
|
||||
return f.subpaths.into_iter().next();
|
||||
};
|
||||
// Rotate so an untouched anchor comes first, duplicate it at the end and treat as open.
|
||||
@@ -48,14 +57,14 @@ fn smooth_subpath(sp: &SubPath, near: &dyn Fn(Point) -> bool, tol: f64) -> Optio
|
||||
open.anchors.push(open.anchors[0]);
|
||||
m.push(false);
|
||||
open.closed = false;
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol);
|
||||
let mut res = smooth_open(&open.anchors, &m, near, tol, sigma);
|
||||
let l = res.pop()?;
|
||||
if let Some(r0) = res.first_mut() {
|
||||
r0.h_in = l.h_in;
|
||||
}
|
||||
return Some(SubPath::new(res, true));
|
||||
}
|
||||
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol), false))
|
||||
Some(SubPath::new(smooth_open(&sp.anchors, &marked, near, tol, sigma), false))
|
||||
}
|
||||
|
||||
/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it
|
||||
@@ -84,10 +93,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez
|
||||
(hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0)))
|
||||
}
|
||||
|
||||
/// `anchors` with each run of `marked` ones refitted, together with the stretch of the segments
|
||||
/// leading into the run that is in the drag's reach (`near`): a short drag smooths what is under
|
||||
/// it, and the rest of a long segment next to it stays as it was (#1512).
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64) -> Vec<Anchor> {
|
||||
/// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted
|
||||
/// within `tol`, together with the stretch of the segments leading into the run that is in the
|
||||
/// drag's reach (`near`): a short drag smooths what is under it, and the rest of a long segment next
|
||||
/// to it stays as it was (#1512).
|
||||
fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool, tol: f64, sigma: f64) -> Vec<Anchor> {
|
||||
let n = anchors.len();
|
||||
let mut runs = vec![];
|
||||
let mut i = 0;
|
||||
@@ -127,7 +137,7 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
|
||||
head = Some(Anchor { h_out: far.p1, ..*outer });
|
||||
*outer = Anchor::with_handles(far.p3, far.p2, reach.p1);
|
||||
}
|
||||
let new = refit_run(&piece, tol);
|
||||
let new = refit_run(&piece, tol, sigma);
|
||||
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
|
||||
}
|
||||
out
|
||||
@@ -138,6 +148,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = points_param(p, "points", C)?;
|
||||
let radius = number_or(p, "radius", 12.0, C)?.max(0.0);
|
||||
let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_FIDELITY, 100.0);
|
||||
let sigma = radius * SMOOTH_SPREAD;
|
||||
let st = s.doc()?;
|
||||
let near = |q: Point| dist_to_polyline(&pts, q) <= radius;
|
||||
let mut plan = vec![];
|
||||
@@ -148,7 +159,7 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let subs: Vec<SubPath> = pd
|
||||
.subpaths
|
||||
.iter()
|
||||
.map(|sp| match smooth_subpath(sp, &near, tol) {
|
||||
.map(|sp| match smooth_subpath(sp, &near, tol, sigma) {
|
||||
Some(n) if n != *sp && n.anchors.len() >= 2 => {
|
||||
changed = true;
|
||||
n
|
||||
@@ -167,9 +178,13 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "ids": [], "before": 0, "after": 0 }));
|
||||
}
|
||||
let ids: Vec<NodeId> = plan.iter().map(|(id, _)| *id).collect();
|
||||
s.edit("Smooth", |d, _| {
|
||||
s.edit("Smooth", |d, sel| {
|
||||
for (id, np) in plan {
|
||||
*path_mut(d, id)? = np;
|
||||
// The smoothed path has new anchors, so the old anchor and segment indices are
|
||||
// dropped and the path stays selected whole.
|
||||
sel.anchors.remove(&id);
|
||||
sel.segments.remove(&id);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
@@ -678,12 +678,22 @@ fn undo_group_end(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// under an interaction that would then preview on, or cancel to, the document from before (#1719).
|
||||
/// A typing session also ends in the Type tool, whose caret and marked text (IME) must follow the
|
||||
/// document. A preview that Real-time Drawing off left unapplied is applied first, as the tool's own
|
||||
/// commit applies it; when it fails, the interaction is canceled.
|
||||
/// commit applies it; when it fails, the interaction is canceled. The applied preview's warning
|
||||
/// goes to the running command's result or the tool's status messages, as the tool's own commit
|
||||
/// reports it ([`Session::note_settled_warning`]).
|
||||
pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> {
|
||||
let typing = typing_in_progress(s);
|
||||
match s.unapplied_interaction_preview().filter(|_| !s.previewing) {
|
||||
Some((cmd, p)) if s.preview(&cmd, &p).is_err() => s.cancel_interaction()?,
|
||||
_ => s.commit_interaction()?,
|
||||
Some((cmd, p)) => match s.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str) {
|
||||
s.note_settled_warning(w);
|
||||
}
|
||||
s.commit_interaction()?
|
||||
}
|
||||
Err(_) => s.cancel_interaction()?,
|
||||
},
|
||||
None => s.commit_interaction()?,
|
||||
}
|
||||
if typing {
|
||||
s.set_tool_option("endTyping", &Value::Bool(true));
|
||||
|
||||
@@ -135,6 +135,9 @@ fn touch(a: &Rect, b: &Rect) -> bool {
|
||||
struct Sets {
|
||||
parent: Vec<usize>,
|
||||
seeded: Vec<bool>,
|
||||
/// How many open boxes the sweep's boxes met.
|
||||
#[cfg(test)]
|
||||
meets: usize,
|
||||
}
|
||||
|
||||
impl Sets {
|
||||
@@ -180,17 +183,25 @@ impl Sets {
|
||||
/// tops that knows the lowest bottom below each of its branches, so each box meets only the open
|
||||
/// boxes it overlaps, not every open one (many objects stacked in a column, sharing their
|
||||
/// horizontal extent, would otherwise compare every pair). An open box inside a later box of
|
||||
/// its group, ending no further right, is closed early: whatever overlaps it overlaps that box.
|
||||
/// Fails only when cancelled ([`vectorcraft_doc::cancel`]).
|
||||
/// its group, ending no further right, is closed early, and a box inside an open box of its group,
|
||||
/// ending no further right, isn't opened: whatever overlaps it overlaps that box. Fails only when
|
||||
/// cancelled ([`vectorcraft_doc::cancel`]).
|
||||
pub(super) fn overlapping(bounds: &[Option<Rect>]) -> Result<Vec<Vec<usize>>, Cancelled> {
|
||||
Ok(sweep(bounds, None)?.groups())
|
||||
}
|
||||
|
||||
/// [`overlapping`]'s sweep. With `see_through`, two boxes are joined only when one of them is
|
||||
/// see-through, and an open box is closed early only inside a later see-through box.
|
||||
/// see-through, and an open box is closed early, or a box isn't opened, only inside a see-through
|
||||
/// box. The open
|
||||
/// see-through boxes and the open boxes without transparency are then in trees of their own, and
|
||||
/// a box without transparency meets only the see-through ones.
|
||||
fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets, Cancelled> {
|
||||
let mut sets = Sets { parent: (0..bounds.len()).collect(), seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect() };
|
||||
let joins = |a: usize, b: usize| see_through.is_none_or(|s| s[a] || s[b]);
|
||||
let mut sets = Sets {
|
||||
parent: (0..bounds.len()).collect(),
|
||||
seeded: (0..bounds.len()).map(|i| see_through.is_some_and(|s| s[i])).collect(),
|
||||
#[cfg(test)]
|
||||
meets: 0,
|
||||
};
|
||||
let boxes: Vec<(usize, Rect)> = bounds.iter().enumerate().filter_map(|(i, b)| b.filter(finite).map(|b| (i, b))).collect();
|
||||
let n = boxes.len();
|
||||
// Each box's place in the tree: by top (then index).
|
||||
@@ -201,9 +212,11 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
for (pos, &k) in by_top.iter().enumerate() {
|
||||
leaf[k] = pos;
|
||||
}
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open).
|
||||
// The lowest bottom of the open boxes below each node (−∞: none open), in the tree of the
|
||||
// boxes without transparency (every box without `see_through`) and the see-through boxes'.
|
||||
let size = n.next_power_of_two().max(1);
|
||||
let mut low = vec![f64::NEG_INFINITY; 2 * size];
|
||||
let mut low = [vec![f64::NEG_INFINITY; 2 * size], if see_through.is_some() { vec![f64::NEG_INFINITY; 2 * size] } else { vec![] }];
|
||||
let tree = |k: usize| usize::from(see_through.is_some_and(|s| s[boxes[k].0]));
|
||||
let set = |low: &mut [f64], pos: usize, v: f64| {
|
||||
let mut i = pos + size;
|
||||
low[i] = v;
|
||||
@@ -226,43 +239,63 @@ fn sweep(bounds: &[Option<Rect>], see_through: Option<&[bool]>) -> Result<Sets,
|
||||
while let Some(&c) = by_right.get(closing)
|
||||
&& boxes[c].1.x1 < b.x0
|
||||
{
|
||||
set(&mut low, leaf[c], f64::NEG_INFINITY);
|
||||
set(&mut low[tree(c)], leaf[c], f64::NEG_INFINITY);
|
||||
closing += 1;
|
||||
}
|
||||
// The open boxes with their top at most this bottom and their bottom at least this top.
|
||||
// The open boxes it joins with their top at most this bottom and their bottom at least
|
||||
// this top: every one, or with `see_through` the see-through ones and, for a see-through
|
||||
// box, the others too.
|
||||
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
|
||||
let looks: &[usize] = match see_through {
|
||||
None => &[0],
|
||||
Some(_) if shadows => &[0, 1],
|
||||
Some(_) => &[1],
|
||||
};
|
||||
let below = tops.partition_point(|t| *t <= b.y1);
|
||||
met.clear();
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
for &t in looks {
|
||||
stack.clear();
|
||||
stack.push((1, 0, size));
|
||||
while let Some((node, lo, hi)) = stack.pop() {
|
||||
work += 1;
|
||||
if work.is_multiple_of(4096) {
|
||||
vectorcraft_doc::cancel::check()?;
|
||||
}
|
||||
if lo >= below || low[t][node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
stack.push((2 * node + 1, mid, hi));
|
||||
stack.push((2 * node, lo, mid));
|
||||
}
|
||||
if lo >= below || low[node] < b.y0 {
|
||||
continue;
|
||||
}
|
||||
if hi - lo == 1 {
|
||||
met.push(by_top[lo]);
|
||||
continue;
|
||||
}
|
||||
let mid = (lo + hi) / 2;
|
||||
stack.push((2 * node + 1, mid, hi));
|
||||
stack.push((2 * node, lo, mid));
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
sets.meets += met.len();
|
||||
}
|
||||
// An open box it met that holds it, ending no further right, and that joins whatever it
|
||||
// overlaps: whatever later overlaps this box overlaps that one and joins it, so this box
|
||||
// isn't opened.
|
||||
let holder = met.iter().copied().find(|&o| {
|
||||
let ob = boxes[o].1;
|
||||
see_through.is_none_or(|s| s[boxes[o].0]) && b.x1 <= ob.x1 && ob.y0 <= b.y0 && b.y1 <= ob.y1
|
||||
});
|
||||
// Whatever overlaps a box inside this one overlaps this one, and joins it when this one is
|
||||
// see-through.
|
||||
let shadows = see_through.is_none_or(|s| s[boxes[k].0]);
|
||||
for &o in &met {
|
||||
if joins(boxes[k].0, boxes[o].0) {
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
}
|
||||
sets.join(boxes[k].0, boxes[o].0);
|
||||
let ob = boxes[o].1;
|
||||
if shadows && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
|
||||
set(&mut low, leaf[o], f64::NEG_INFINITY);
|
||||
if shadows && Some(o) != holder && ob.x1 <= b.x1 && b.y0 <= ob.y0 && ob.y1 <= b.y1 {
|
||||
set(&mut low[tree(o)], leaf[o], f64::NEG_INFINITY);
|
||||
}
|
||||
}
|
||||
set(&mut low, leaf[k], b.y1);
|
||||
if holder.is_none() {
|
||||
set(&mut low[tree(k)], leaf[k], b.y1);
|
||||
}
|
||||
}
|
||||
Ok(sets)
|
||||
}
|
||||
@@ -392,6 +425,11 @@ mod tests {
|
||||
|
||||
/// What [`overlapping`] gives, comparing every pair.
|
||||
fn every_pair(bounds: &[Option<Rect>]) -> Vec<Vec<usize>> {
|
||||
every_pair_joining(bounds, |_, _| true)
|
||||
}
|
||||
|
||||
/// The groups of `bounds` comparing every pair, joining overlapping pairs that `joins`.
|
||||
fn every_pair_joining(bounds: &[Option<Rect>], joins: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> {
|
||||
let n = bounds.len();
|
||||
let mut group: Vec<usize> = (0..n).collect();
|
||||
let hit = |a: &Rect, b: &Rect| a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
|
||||
@@ -401,6 +439,7 @@ mod tests {
|
||||
for j in 0..n {
|
||||
if let (Some(a), Some(b)) = (bounds[i], bounds[j])
|
||||
&& hit(&a, &b)
|
||||
&& joins(i, j)
|
||||
&& group[j] < group[i]
|
||||
{
|
||||
group[i] = group[j];
|
||||
@@ -464,6 +503,69 @@ mod tests {
|
||||
assert_eq!(overlapping(&odd).unwrap(), vec![vec![0, 2], vec![1]]);
|
||||
}
|
||||
|
||||
/// `n` boxes sharing their left and top edges, each inside the one before.
|
||||
fn shrinking_nest(n: usize) -> Vec<Option<Rect>> {
|
||||
(0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64, 2.0 * (n - i) as f64))).collect()
|
||||
}
|
||||
|
||||
/// Each box of a nest that shrinks to the right and bottom meets only the outermost box, which
|
||||
/// stays open and holds it, not every box around it.
|
||||
#[test]
|
||||
fn a_shrinking_nest_meets_only_its_outermost_box() {
|
||||
let n = 512;
|
||||
let bounds = shrinking_nest(n);
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n - 1);
|
||||
assert_eq!(sets.groups(), every_pair(&bounds));
|
||||
assert_eq!(sets.groups(), vec![(0..n).collect::<Vec<_>>()]);
|
||||
// Equal boxes: the later one isn't opened and the earlier one stays open for the third.
|
||||
let same = [Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(9.0, 9.0, 20.0, 20.0))];
|
||||
assert_eq!(overlapping(&same).unwrap(), vec![vec![0, 1, 2]]);
|
||||
// With transparency, an opaque box isn't opened inside a see-through box, and boxes inside
|
||||
// an opaque box are opened: an opaque box that overlaps only the inner one still joins it
|
||||
// when that one is see-through.
|
||||
let see = [true, false];
|
||||
let mut sets = sweep(&bounds[..2], Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1]]);
|
||||
let held = [Some(Rect::new(0.0, 0.0, 20.0, 20.0)), Some(Rect::new(0.0, 0.0, 10.0, 10.0)), Some(Rect::new(5.0, 5.0, 8.0, 8.0))];
|
||||
let mut sets = sweep(&held, Some(&[false, true, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[true, false, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[false, false, true])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2]]);
|
||||
let mut sets = sweep(&held, Some(&[false, false, false])).unwrap();
|
||||
assert_eq!(sets.groups(), vec![vec![0], vec![1], vec![2]]);
|
||||
}
|
||||
|
||||
/// Boxes nested at shared corners and placed at random, some see-through, group with and
|
||||
/// without transparency as comparing every pair groups them.
|
||||
#[test]
|
||||
fn nested_and_scattered_boxes_group_as_comparing_every_pair() {
|
||||
let mut seed = 0x51_7cc1_b727_220au64;
|
||||
let mut next = |m: f64| {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
(seed % 1000) as f64 / 1000.0 * m
|
||||
};
|
||||
for round in 0..40 {
|
||||
let n = 6 + round * 3;
|
||||
let bounds: Vec<Option<Rect>> = (0..n)
|
||||
.map(|_| {
|
||||
// Corners on a coarse grid so that edges are often shared and boxes often nest.
|
||||
let (x, y) = ((next(6.0).floor()) * 10.0, (next(6.0).floor()) * 10.0);
|
||||
let (w, h) = ((next(5.0).floor() + 1.0) * 10.0, (next(5.0).floor() + 1.0) * 10.0);
|
||||
Some(Rect::new(x, y, x + w, y + h))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(overlapping(&bounds).unwrap(), every_pair(&bounds), "round {round}");
|
||||
let see: Vec<bool> = (0..n).map(|_| next(1.0) < 0.3).collect();
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.groups(), every_pair_joining(&bounds, |i, j| see[i] || see[j]), "round {round}, with transparency");
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled rectangle, unstroked.
|
||||
fn filled(id: u64, r: Rect) -> Node {
|
||||
let look = vectorcraft_doc::Appearance::basic(
|
||||
@@ -583,6 +685,62 @@ mod tests {
|
||||
assert_eq!(flatten_groups(&reach, &painted, &vec![false; n], 0.0).unwrap().len(), n);
|
||||
}
|
||||
|
||||
/// A small see-through box, then `n` opaque boxes nested around it, each inside the one
|
||||
/// before and sharing its left and top edges.
|
||||
fn nest_around_a_see_through_box(n: usize) -> (Vec<Option<Rect>>, Vec<bool>) {
|
||||
let mut bounds = vec![Some(Rect::new(0.0, 0.0, 1.0, 1.0))];
|
||||
bounds.extend((0..n).map(|i| Some(Rect::new(0.0, 0.0, 2.0 * (n - i) as f64 + 1.0, 2.0 * (n - i) as f64 + 1.0))));
|
||||
let mut see = vec![false; n + 1];
|
||||
see[0] = true;
|
||||
(bounds, see)
|
||||
}
|
||||
|
||||
/// Opaque boxes nested in each other around a see-through box each meet only the see-through
|
||||
/// box, not the open opaque boxes they can't join, and all join it.
|
||||
#[test]
|
||||
fn nested_opaque_boxes_meet_only_the_see_through_box() {
|
||||
let n = 512;
|
||||
let (bounds, see) = nest_around_a_see_through_box(n);
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
assert_eq!(sets.meets, n);
|
||||
assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]);
|
||||
// The unfiltered sweep that runs before it meets each box once too.
|
||||
let mut sets = sweep(&bounds, None).unwrap();
|
||||
assert_eq!(sets.meets, n);
|
||||
assert_eq!(sets.groups(), vec![(0..=n).collect::<Vec<_>>()]);
|
||||
let (painted, see) = nest_around_a_see_through_box(40);
|
||||
let reach: Vec<Option<Rect>> = painted.iter().map(|b| b.map(|b| b.inflate(1.0, 1.0))).collect();
|
||||
for fringe in [0.0, 0.7] {
|
||||
let groups = flatten_groups(&reach, &painted, &see, fringe).unwrap();
|
||||
check(&reach, &painted, &see, fringe, &groups, &format!("nest, fringe {fringe}"));
|
||||
assert_eq!(groups, vec![(0..=40).collect::<Vec<_>>()]);
|
||||
}
|
||||
}
|
||||
|
||||
/// An opaque box inside a later see-through box is closed: later boxes meet the see-through
|
||||
/// box instead, and join the opaque one through it.
|
||||
#[test]
|
||||
fn a_see_through_box_closes_an_opaque_box_inside_it() {
|
||||
// An opaque box, a see-through box around it, a see-through box over both and an opaque
|
||||
// box over the first.
|
||||
let bounds = [
|
||||
Some(Rect::new(0.0, 0.0, 10.0, 10.0)),
|
||||
Some(Rect::new(0.0, 0.0, 20.0, 20.0)),
|
||||
Some(Rect::new(5.0, 5.0, 30.0, 30.0)),
|
||||
Some(Rect::new(8.0, 8.0, 12.0, 12.0)),
|
||||
];
|
||||
let see = [false, true, true, false];
|
||||
let mut sets = sweep(&bounds, Some(&see)).unwrap();
|
||||
// The second box meets the first; the third meets the second; the fourth meets the second
|
||||
// and the third.
|
||||
assert_eq!(sets.meets, 4);
|
||||
assert_eq!(sets.groups(), vec![vec![0, 1, 2, 3]]);
|
||||
// Opaque boxes alone meet nothing.
|
||||
let mut sets = sweep(&bounds, Some(&[false; 4])).unwrap();
|
||||
assert_eq!(sets.meets, 0);
|
||||
assert_eq!(sets.groups().len(), 4);
|
||||
}
|
||||
|
||||
/// An opaque box between a member and its group's top that paints over the member joins, and
|
||||
/// so on along a chain; one under the member stays, but for one within the fringe.
|
||||
#[test]
|
||||
|
||||
@@ -1034,6 +1034,85 @@ fn an_opaque_pick_replaces_the_opacity_the_series_stores() {
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
|
||||
}
|
||||
|
||||
/// A column graph whose series 0 stores the 40% Multiply fill set on its first mark, and a mark of series 1 whose top fill
|
||||
/// row has no paint and is opaque and Normal: the session, the graph, series 0's marks and that source.
|
||||
fn marks_and_unpainted_source() -> (Session, NodeId, Vec<NodeId>, NodeId) {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id;
|
||||
s.execute("appearance.setItem", &json!({"ids": [source.0], "index": top_row(&s, source, true), "none": true})).unwrap();
|
||||
let fill = top_row(&s, marks[0], true);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": fill, "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
(s, id, marks, source)
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a fill row without paint onto a mark whose fill had paint replaces the fill opacity and blend
|
||||
/// mode another mark of the series stored: the series is drawn opaque and Normal again.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_that_unpaints_a_series_fill_clears_its_stored_transparency() {
|
||||
let (mut s, id, marks, source) = marks_and_unpainted_source();
|
||||
let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone();
|
||||
assert_eq!((mark.paint.is_none(), mark.opacity, mark.blend), (false, 1.0, BlendMode::Normal), "the target's fill row");
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let picked = s.doc().unwrap().doc.node(marks[1]).unwrap().appearance.fill().unwrap().clone();
|
||||
assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal));
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (None, None));
|
||||
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let fills: Vec<_> = series(&n, 0).children().unwrap().iter().filter_map(|m| m.appearance.fill().map(|f| (f.opacity, f.blend))).collect();
|
||||
assert!(fills.iter().all(|f| *f == (1.0, BlendMode::Normal)), "{fills:?}");
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a fill row without paint onto a mark whose fill had no paint before the pick either leaves the
|
||||
/// fill opacity and blend mode another mark of the series stored.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_of_an_already_unpainted_row_leaves_series_transparency() {
|
||||
let (mut s, id, marks, source) = marks_and_unpainted_source();
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": top_row(&s, marks[1], true), "none": true})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)), "a color set to None writes no opacity");
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
assert_eq!((kept.fill_opacity, kept.fill_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
}
|
||||
|
||||
/// A whole Eyedropper pick from a source with no fill row, or no stroke row, removes that row from the mark. Where the
|
||||
/// mark's row had paint, the pick replaces the opacity and blend mode another mark of the series stored for that kind
|
||||
/// of row. Where the mark's row had no paint, the stored values stay.
|
||||
#[test]
|
||||
fn a_whole_eyedropper_pick_that_removes_a_painted_row_clears_its_stored_transparency() {
|
||||
let stored = |s: &Session, id: NodeId, fill: bool| {
|
||||
let kept = spec(s, id).series_paints[0].clone();
|
||||
if fill { (kept.fill_opacity, kept.fill_blend) } else { (kept.stroke_opacity, kept.stroke_blend) }
|
||||
};
|
||||
for (fill, painted) in [(true, true), (false, true), (false, false)] {
|
||||
let (mut s, id, _, marks) = column_marks();
|
||||
let row = top_row(&s, marks[0], fill);
|
||||
if painted {
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[1].0], "index": row, "color": "#ff0000"})).unwrap();
|
||||
}
|
||||
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": row, "color": "#ff0000", "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
assert_eq!(stored(&s, id, fill), (Some(0.4), Some(BlendMode::Multiply)), "fill {fill}, painted {painted}");
|
||||
let source = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[0].id;
|
||||
s.execute("appearance.removeItem", &json!({"ids": [source.0], "index": top_row(&s, source, fill)})).unwrap();
|
||||
let was = spec(&s, id).series_paints;
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marks[1].0]})).unwrap();
|
||||
let mark = s.doc().unwrap().doc.node(marks[1]).unwrap().clone();
|
||||
assert!(!mark.appearance.items.iter().any(|it| it.is_fill() == fill), "the pick removed the row: fill {fill}");
|
||||
let want = if painted { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) };
|
||||
assert_eq!(stored(&s, id, fill), want, "fill {fill}, painted {painted}");
|
||||
if painted {
|
||||
let after = spec(&s, id).series_paints;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, was);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, after);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An appearance moved between two marks of one series leaves the series with the target's paint, not the source's
|
||||
/// empty one, and the series still shows when the graph is drawn again.
|
||||
#[test]
|
||||
@@ -1251,6 +1330,45 @@ fn a_style_that_removes_a_marks_stroke_replaces_the_kept_stroke_opacity() {
|
||||
}
|
||||
}
|
||||
|
||||
/// An Eyedropper pick from a stroke row without paint onto a marker whose stroke had paint replaces the stroke opacity and
|
||||
/// blend mode the series' Filled Lines band left, in the pick's undo step: the band's outline is drawn opaque and Normal
|
||||
/// again. A pick onto a marker whose stroke had no paint before the pick leaves them as they are.
|
||||
#[test]
|
||||
fn an_eyedropper_pick_that_unpaints_a_series_stroke_clears_its_stored_transparency() {
|
||||
for stroked in [true, false] {
|
||||
let (mut s, id, band) = band_graph();
|
||||
let parts = series_parts(&s, id, 0);
|
||||
let (marker, source) = (parts[1].id, parts[2].id);
|
||||
let st = parts[2].appearance.stroke().unwrap();
|
||||
assert_eq!((st.paint.is_none(), st.opacity, st.blend), (true, 1.0, BlendMode::Normal), "the source's stroke row");
|
||||
if stroked {
|
||||
let row = top_row(&s, marker, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [marker.0], "index": row, "color": "#ff0000"})).unwrap();
|
||||
}
|
||||
let row = top_row(&s, band, false);
|
||||
s.execute("appearance.setItem", &json!({"ids": [band.0], "index": row, "opacity": 40, "blend": "multiply"})).unwrap();
|
||||
let was = spec(&s, id).series_paints;
|
||||
assert_eq!((was[0].stroke_opacity, was[0].stroke_blend), (Some(0.4), Some(BlendMode::Multiply)));
|
||||
s.execute("appearance.copyFrom", &json!({"source": source.0, "ids": [marker.0]})).unwrap();
|
||||
let picked = s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke().unwrap().clone();
|
||||
assert_eq!((picked.paint.is_none(), picked.opacity, picked.blend), (true, 1.0, BlendMode::Normal), "stroked {stroked}");
|
||||
let kept = spec(&s, id).series_paints[0].clone();
|
||||
let want = if stroked { (None, None) } else { (Some(0.4), Some(BlendMode::Multiply)) };
|
||||
assert_eq!((kept.stroke_opacity, kept.stroke_blend), want, "stroked {stroked}");
|
||||
if stroked {
|
||||
let after = spec(&s, id).series_paints;
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, was);
|
||||
assert!(!s.doc().unwrap().doc.node(marker).unwrap().appearance.stroke_paint().is_none(), "the undo took back the pick");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(spec(&s, id).series_paints, after);
|
||||
}
|
||||
redrawn_band(&mut s, id);
|
||||
let st = series_parts(&s, id, 0)[0].appearance.stroke().unwrap().clone();
|
||||
assert_eq!((Some(st.opacity).filter(|o| *o < 1.0), Some(st.blend).filter(|b| *b != BlendMode::Normal)), want, "stroked {stroked}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Filled Lines band's stroke row removed with the Appearance panel or set to None with `paint.setStroke` leaves the
|
||||
/// band its color: an empty stored stroke is not a color for the band.
|
||||
#[test]
|
||||
|
||||
@@ -346,6 +346,36 @@ impl Library {
|
||||
}
|
||||
}
|
||||
|
||||
/// Name item `r` `name`, in its place in its kind's list; an item keyed by its name keeps its
|
||||
/// group under the new name (a graphic is keyed by its id, which stays).
|
||||
fn rename_item(&mut self, r: &ItemRef, name: &str) {
|
||||
fn set<'a>(mut names: impl Iterator<Item = &'a mut String>, from: &str, to: &str) {
|
||||
if let Some(n) = names.find(|n| n.as_str() == from) {
|
||||
*n = to.to_string();
|
||||
}
|
||||
}
|
||||
let from = r.item.as_str();
|
||||
match r.kind {
|
||||
ItemKind::Color => set(self.colors.iter_mut().map(|c| &mut c.name), from, name),
|
||||
ItemKind::Gradient => set(self.gradients.iter_mut().map(|g| &mut g.name), from, name),
|
||||
ItemKind::Pattern => set(self.patterns.iter_mut().map(|p| &mut p.name), from, name),
|
||||
ItemKind::CharStyle => set(self.char_styles.iter_mut().map(|t| &mut t.name), from, name),
|
||||
ItemKind::ParaStyle => set(self.para_styles.iter_mut().map(|t| &mut t.name), from, name),
|
||||
ItemKind::Graphic => {
|
||||
if let Some(g) = self.graphics.iter_mut().find(|g| g.id == from) {
|
||||
g.name = name.to_string();
|
||||
}
|
||||
return;
|
||||
}
|
||||
ItemKind::Unknown => return,
|
||||
}
|
||||
for x in self.groups.iter_mut().flat_map(|g| g.items.iter_mut()) {
|
||||
if x == r {
|
||||
x.item = name.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move item `r` next to `to`, an item of its kind: just before it, or just after it when
|
||||
/// `after`, in their kind's list (the order the panel shows them in).
|
||||
fn place_next_to(&mut self, r: &ItemRef, to: &ItemRef, after: bool) {
|
||||
@@ -683,7 +713,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Use Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
|
||||
has_doc,
|
||||
use_item
|
||||
),
|
||||
@@ -696,6 +726,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
remove_item
|
||||
),
|
||||
cmd!(
|
||||
"library.renameItem",
|
||||
"Rename Library Item",
|
||||
[],
|
||||
None,
|
||||
"{library?, kind, item: name (graphic: id or name), name: string (trimmed; 1 to 256 characters)} rename an item; it keeps its place and its group; another item of its kind with that name is an error, and its own name changes nothing; not undoable → {library, kind, item: its key now (graphic: its id), name}",
|
||||
always,
|
||||
rename_item
|
||||
),
|
||||
cmd!(
|
||||
"library.addToCharacterStyles",
|
||||
"Add to Character Styles",
|
||||
[],
|
||||
None,
|
||||
"{library?, item: a character style's name, recorded?: the style as it was when added (recorded in the journal so a replay matches)} add a library character style to the document's character styles without applying it (no text needs to be selected): a document style of that name with the same attributes is reused, a name taken by different attributes gets a number; a color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked; a new style is one undo step, a reused one none → {style: its name in the document, existing: bool}",
|
||||
has_doc,
|
||||
add_to_char_styles
|
||||
),
|
||||
cmd!(
|
||||
"library.createGroup",
|
||||
"New Library Group",
|
||||
@@ -1231,8 +1279,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Kind::CharStyle | Kind::ParaStyle => {
|
||||
let para = kind == Kind::ParaStyle;
|
||||
let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string();
|
||||
let attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default();
|
||||
let doc = &s.doc()?.doc;
|
||||
if !para {
|
||||
unlink_missing_swatches(doc, &mut attrs);
|
||||
}
|
||||
// Compared in the form the document stores them in.
|
||||
let attrs = super::textstyles::stored_style_attrs(doc, para, &attrs).unwrap_or(attrs);
|
||||
// The document's style of that name when it is the same; else a new one.
|
||||
let same = super::textstyles::style_attrs(doc, para, &name).is_some_and(|a| a == attrs);
|
||||
let style = if same { name } else { unique(&name, |n| super::textstyles::style_attrs(doc, para, n).is_some()) };
|
||||
@@ -1361,6 +1414,109 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
fn rename_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.renameItem";
|
||||
let (id, kind, item) = item_param(s, p, C)?;
|
||||
let name = match p.get("name") {
|
||||
None | Some(Value::Null) => return Err(bad(C, "missing `name`")),
|
||||
Some(Value::String(n)) => n.trim().to_string(),
|
||||
Some(_) => return Err(bad(C, "`name` must be a string")),
|
||||
};
|
||||
if name.is_empty() {
|
||||
return Err(bad(C, "missing `name`"));
|
||||
}
|
||||
if name.chars().count() > MAX_NAME {
|
||||
let (label, max) = ("`name`", MAX_NAME);
|
||||
return Err(bad(C, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
|
||||
let r = lib.item_ref(kind.item_kind(), item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
|
||||
// The item's name now, and whether another item of its kind has the new one.
|
||||
let mut same = false;
|
||||
let mut taken = false;
|
||||
for (_, key, shown) in lib.items().filter(|(k, ..)| *k == r.kind) {
|
||||
if key == r.item {
|
||||
same = shown == name;
|
||||
} else if shown == name {
|
||||
taken = true;
|
||||
}
|
||||
}
|
||||
let key = if r.kind == ItemKind::Graphic { r.item.clone() } else { name.clone() };
|
||||
let out = json!({ "library": id, "kind": str_param(p, "kind"), "item": key, "name": name });
|
||||
if same {
|
||||
return Ok(out);
|
||||
}
|
||||
if taken {
|
||||
return Err(bad(C, format!("the library has another item of that kind named `{name}`")));
|
||||
}
|
||||
s.libraries.change(&id, |lib| {
|
||||
lib.rename_item(&r, &name);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn add_to_char_styles(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.addToCharacterStyles";
|
||||
// A replay (the journal) carries what the style was, so it doesn't depend on the library.
|
||||
let data = match p.get("recorded").cloned() {
|
||||
Some(r) => r,
|
||||
None => {
|
||||
let id = library_id(s, p, C)?;
|
||||
let item = str_param(p, "item").ok_or_else(|| bad(C, "missing `item`"))?;
|
||||
let lib = s.libraries.get(&id).ok_or_else(|| bad(C, format!("no library `{id}`")))?;
|
||||
let t = lib.char_styles.iter().find(|t| t.name == item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?;
|
||||
let data = json!({ "name": t.name, "attrs": t.attrs });
|
||||
s.note_journal("recorded", data.clone());
|
||||
data
|
||||
}
|
||||
};
|
||||
let name = data.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Style").to_string();
|
||||
let mut attrs = data.get("attrs").and_then(Value::as_object).cloned().ok_or_else(|| bad(C, "the library item is damaged"))?;
|
||||
let doc = &s.doc()?.doc;
|
||||
unlink_missing_swatches(doc, &mut attrs);
|
||||
// Compared in the form the document stores them in.
|
||||
let attrs = super::textstyles::stored_style_attrs(doc, false, &attrs).unwrap_or(attrs);
|
||||
// The document's style of that name when it is the same; else a new one, which isn't applied.
|
||||
if super::textstyles::style_attrs(doc, false, &name).is_some_and(|a| a == attrs) {
|
||||
return Ok(json!({ "style": name, "existing": true }));
|
||||
}
|
||||
let style = unique(&name, |n| super::textstyles::style_attrs(doc, false, n).is_some());
|
||||
s.execute("charStyle.new", &json!({ "name": style, "attrs": attrs }))?;
|
||||
Ok(json!({ "style": style, "existing": false }))
|
||||
}
|
||||
|
||||
/// Unlink a library character style's `fill` and `stroke` colors (solid, and each gradient stop)
|
||||
/// from swatches that are not global or spot swatches of `doc`: an unlinked color keeps the color
|
||||
/// it shows at full tint, as [`clean_gradient`] keeps a library gradient's stops. A link to a
|
||||
/// global or spot swatch `doc` has stays, and takes that swatch's color.
|
||||
fn unlink_missing_swatches(doc: &vectorcraft_doc::Document, attrs: &mut Map<String, Value>) {
|
||||
let keep = |name: &str| doc.global_color(name).is_some();
|
||||
for key in ["fill", "stroke"] {
|
||||
let Some(mut paint) = attrs.get(key).and_then(|v| serde_json::from_value::<Paint>(v.clone()).ok()) else { continue };
|
||||
let mut changed = false;
|
||||
let mut unlink = |swatch: &mut Option<String>, tint: &mut f32| {
|
||||
if swatch.as_deref().is_some_and(|n| !keep(n)) {
|
||||
*swatch = None;
|
||||
*tint = 1.0;
|
||||
changed = true;
|
||||
}
|
||||
};
|
||||
match &mut paint {
|
||||
Paint::Solid { swatch, tint, .. } => unlink(swatch, tint),
|
||||
Paint::Gradient(g) => {
|
||||
for st in &mut g.gradient.stops {
|
||||
unlink(&mut st.swatch, &mut st.tint);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if changed && let Ok(v) = serde_json::to_value(&paint) {
|
||||
attrs.insert(key.to_string(), v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `p`'s `name`, trimmed and clipped, else `default`.
|
||||
fn name_param(p: &Value, default: &str) -> String {
|
||||
let mut name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or(default).to_string();
|
||||
|
||||
@@ -172,7 +172,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make with Top Object",
|
||||
["Object", "Envelope Distort"],
|
||||
Some("Cmd+Alt+C"),
|
||||
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length (type maps from its glyph outline bounds) → {id}",
|
||||
"{ids?} the topmost selected path becomes the envelope of the others: its outline splits into four sides at its corners, and each piece of a side takes a share of the content in proportion to its control polygon's length, and a side whose pieces are all one curve split at anchors follows that curve's parameter (type maps from its glyph outline bounds) → {id}",
|
||||
has_multi,
|
||||
env_make_top
|
||||
),
|
||||
|
||||
@@ -1228,7 +1228,7 @@ fn simplify(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(l) => po::simplify_level_tolerance(l),
|
||||
None => given_tolerance.unwrap_or(1.0),
|
||||
};
|
||||
let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, smooth: 0.0 };
|
||||
let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, ..Default::default() };
|
||||
// A path with segments direct-selected simplifies only their runs, and keeps those runs (and the
|
||||
// other anchors it had selected) direct-selected.
|
||||
let roots = selected_roots(s)?;
|
||||
|
||||
+123
-31
@@ -672,13 +672,53 @@ fn takes_over(s: &Session, plugin: &Plugin) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: runs once in the next `plugin.install` on this thread after its checks and before it
|
||||
/// installs, as another session changing the plug-ins in between would.
|
||||
pub(crate) static BEFORE_INSTALL: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once in the next `plugin.install` on this thread right after it reads the grant
|
||||
/// held for the id.
|
||||
pub(crate) static AFTER_GRANT_READ: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once in the next `plugin.install` on this thread after it installs and before it
|
||||
/// writes the store.
|
||||
pub(crate) static BEFORE_STORE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
/// Tests: runs once on this thread when [`hold_plugin_changes`] finds the lock held and waits.
|
||||
pub(crate) static WHILE_WAITING: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Held by `plugin.install` from its first read of the grant until the store holds what it
|
||||
/// installed, and throughout by `plugin.remove`, by loads of the stored plug-ins
|
||||
/// ([`Session::load_stored_plugins`]) and by loads of a plug-ins folder: these run one after the
|
||||
/// other across sessions.
|
||||
static PLUGIN_CHANGES: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Takes [`PLUGIN_CHANGES`], waiting while another session holds it.
|
||||
pub(crate) fn hold_plugin_changes() -> std::sync::MutexGuard<'static, ()> {
|
||||
match PLUGIN_CHANGES.try_lock() {
|
||||
Ok(held) => held,
|
||||
Err(std::sync::TryLockError::Poisoned(e)) => e.into_inner(),
|
||||
Err(std::sync::TryLockError::WouldBlock) => {
|
||||
#[cfg(test)]
|
||||
if let Some(waiting) = WHILE_WAITING.take() {
|
||||
waiting();
|
||||
}
|
||||
PLUGIN_CHANGES.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `plugin.install`: loads and checks the module, refuses `grant` and `allowHeavy` that neither an
|
||||
/// [`InstallApproval`] for this module nor the session allows, one that asks for a heavy budget
|
||||
/// unless `allowHeavy` says a person agreed, one that lists permissions no person has granted this
|
||||
/// very module unless `grant` lists them all, one that would take another module's place
|
||||
/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given; records
|
||||
/// the grant with the module's hash, keeps it for the next start and installs it → its
|
||||
/// `plugin.list` entry. A module that lists no permissions ends any grant held for its id.
|
||||
/// ([`takes_over`]) unless `replace` is true, and one whose SHA-256 isn't the `hash` given. It then
|
||||
/// checks the plug-in installed under the id and its grant again while it records the grant with
|
||||
/// the module's hash and installs it ([`registry::install_checked`]), and only then keeps both for
|
||||
/// the next start → its `plugin.list` entry. A refused install changes neither the plug-in store
|
||||
/// nor the plug-ins and grants of the process. A module that lists no permissions ends any grant
|
||||
/// held for its id. A `plugin.remove` in another session waits until the install has written the
|
||||
/// store.
|
||||
fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "plugin.install";
|
||||
// One use: spent whatever this install does.
|
||||
@@ -696,21 +736,36 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
{
|
||||
return Err(bad(C, "the module doesn't have the SHA-256 `hash` gives: nothing was installed"));
|
||||
}
|
||||
if replace == Some(false) && registry::get(plugin.id()).is_some() {
|
||||
return Err(bad(C, format!("a plug-in with id {:?} is already installed", plugin.id())));
|
||||
// A removal in another session waits until the store holds what this install wrote.
|
||||
let _held = hold_plugin_changes();
|
||||
// The grant the checks below count on, the approval included. The install checks it again,
|
||||
// with the plug-in installed under the id, before anything is stored: another session may
|
||||
// change either in between.
|
||||
let seen_grant = registry::granted(plugin.id());
|
||||
#[cfg(test)]
|
||||
if let Some(between) = AFTER_GRANT_READ.take() {
|
||||
between();
|
||||
}
|
||||
// Another module under the id gets the settings and cache kept for it: whoever installs it asks
|
||||
// the user first.
|
||||
if replace != Some(true) && takes_over(s, &plugin) {
|
||||
let installed_already = || bad(C, format!("a plug-in with id {:?} is already installed", plugin.id()));
|
||||
let taken_over = || {
|
||||
let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME);
|
||||
return Err(bad(
|
||||
bad(
|
||||
C,
|
||||
format!(
|
||||
"“{name}” is another module than the plug-in with id {:?} and would get the settings and cache kept for it: install it with `replace: true` once the user agrees",
|
||||
plugin.id()
|
||||
),
|
||||
));
|
||||
)
|
||||
};
|
||||
if replace == Some(false) && registry::get(plugin.id()).is_some() {
|
||||
return Err(installed_already());
|
||||
}
|
||||
// Another module under the id gets the settings and cache kept for it: whoever installs it asks
|
||||
// the user first.
|
||||
if replace != Some(true) && takes_over(s, &plugin) {
|
||||
return Err(taken_over());
|
||||
}
|
||||
let (installed_already, taken_over) = (installed_already(), taken_over());
|
||||
// `grant` and `allowHeavy` say that a person agreed, and a request alone can't say that.
|
||||
let approval = approval.filter(|a| a.covers(&plugin));
|
||||
if !s.plugin_grants_from_requests && ((grant.is_some() && approval.is_none()) || (allow_heavy && !approval.is_some_and(|a| a.heavy))) {
|
||||
@@ -744,15 +799,55 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// this very module already covers all of them.
|
||||
let m = plugin.manifest();
|
||||
let wanted = m.permissions();
|
||||
if !s.plugin_approved(&plugin) && !grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w))) {
|
||||
let needs_approval = || {
|
||||
let name = permissions::display_text(&m.name, permissions::MAX_SHOWN_NAME);
|
||||
let asked = permissions::names(&wanted).join(", ");
|
||||
return Err(bad(
|
||||
bad(
|
||||
C,
|
||||
format!(
|
||||
"“{name}” asks for the permissions {asked}: a person has to approve them in the desktop app, or pass `grant` in a session started with --allow-plugin-grants"
|
||||
),
|
||||
));
|
||||
)
|
||||
};
|
||||
let granted_here = grant.as_ref().is_some_and(|g| wanted.iter().all(|w| g.contains(w)));
|
||||
// Without a plug-in store, the grant read above approves the module or doesn't.
|
||||
let approved = match s.plugin_dir {
|
||||
None => !m.asks_permissions() || seen_grant.as_ref().is_some_and(|g| g.covers(&m.id, plugin.hash(), &wanted)),
|
||||
Some(_) => s.plugin_approved(&plugin),
|
||||
};
|
||||
if !approved && !granted_here {
|
||||
return Err(needs_approval());
|
||||
}
|
||||
let needs_approval = needs_approval();
|
||||
let (id, hash, asks) = (m.id.clone(), plugin.hash().to_string(), m.asks_permissions());
|
||||
let g = Grant { id: id.clone(), hash: hash.clone(), permissions: wanted };
|
||||
let update = if asks { registry::GrantUpdate::Record(GrantToken::after_engine_approval(g.clone())) } else { registry::GrantUpdate::Revoke };
|
||||
// Another module installed under the id since the checks above takes the place they found free,
|
||||
// or held by these bytes. A grant that changed since no longer approves what they approved,
|
||||
// unless `grant` approves this module by itself or the new grant covers it.
|
||||
let check = |installed: Option<&Plugin>, held: Option<&Grant>| {
|
||||
if let Some(installed) = installed {
|
||||
match replace {
|
||||
Some(false) => return Err(installed_already),
|
||||
None if installed.hash() != hash => return Err(taken_over),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if asks && !granted_here && held != seen_grant.as_ref() && !held.is_some_and(|h| h.covers(&id, &hash, &g.permissions)) {
|
||||
return Err(needs_approval);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_INSTALL.take() {
|
||||
between();
|
||||
}
|
||||
// The plug-in gets the settings and cache kept for its id. A module without permissions takes
|
||||
// the id over, so nothing the user approved for the id applies any more.
|
||||
let installed = registry::install_checked(plugin, update, check, || s.attach_plugin_storage(&id), err)?;
|
||||
#[cfg(test)]
|
||||
if let Some(between) = BEFORE_STORE.take() {
|
||||
between();
|
||||
}
|
||||
// Installed plug-ins stay installed after a restart (#2541). The module is written first and its
|
||||
// grant only once it is there; when the grant can't be written, the store gets the module it
|
||||
@@ -760,18 +855,14 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// which the grant doesn't cover. A write that reports a failure may still have put the old
|
||||
// module back, so the store is read again to tell which module it holds. A stored module that
|
||||
// can't be read back isn't replaced by one that needs a grant.
|
||||
let previous = s.stored_plugin_bytes(plugin.id());
|
||||
let mut stored = (previous.is_ok() || !m.asks_permissions()) && s.store_plugin(plugin.id(), &bytes);
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(plugin.id()).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
|
||||
if m.asks_permissions() {
|
||||
let g = Grant { id: m.id.clone(), hash: plugin.hash().to_string(), permissions: wanted };
|
||||
registry::grant(GrantToken::after_engine_approval(g.clone()));
|
||||
if stored && !s.store_grant(&m.id, Some(g)) {
|
||||
stored = !s.put_back_plugin(plugin.id(), previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
let previous = s.stored_plugin_bytes(&id);
|
||||
let mut stored = (previous.is_ok() || !asks) && s.store_plugin(&id, &bytes);
|
||||
let holds_new = |s: &Session| s.stored_plugin_bytes(&id).is_ok_and(|held| held.as_deref() == Some(&bytes[..]));
|
||||
if asks {
|
||||
if stored && !s.store_grant(&id, Some(g)) {
|
||||
stored = !s.put_back_plugin(&id, previous.ok().flatten().as_deref()) && holds_new(s);
|
||||
}
|
||||
} else {
|
||||
// This module takes the id over, so nothing the user approved for the id applies any more.
|
||||
registry::revoke(&m.id);
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
@@ -780,23 +871,21 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// approves nothing, and the new module stays; one that can't be opened or read may approve
|
||||
// the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
|
||||
if stored && !s.store_grant(&id, None) && s.holds_plugin_grant(&id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(&id, held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&m.id, writes);
|
||||
s.ignore_stored_grant(&id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
// It gets the settings and cache kept for its id.
|
||||
s.attach_plugin_storage(plugin.id());
|
||||
// Installing a disabled plug-in again (an updated version) turns it on for the next launch too,
|
||||
// also when it is disabled by its stored file alone (it stopped a launch while loading). When
|
||||
// the new version could not replace the stored file, the old one stays disabled.
|
||||
let file = s.stored_plugin_file(plugin.id());
|
||||
let file = s.stored_plugin_file(&id);
|
||||
let mut changed = false;
|
||||
if file.is_none() || stored {
|
||||
changed = safe_mode::set_enabled(&safe_mode::Item::of(&plugin), true);
|
||||
changed = safe_mode::set_enabled(&safe_mode::Item::of(&installed), true);
|
||||
if let Some(file) = file {
|
||||
changed |= safe_mode::set_enabled(&safe_mode::Item::file(file), true);
|
||||
}
|
||||
@@ -804,7 +893,6 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if changed {
|
||||
s.store_disabled_plugins();
|
||||
}
|
||||
let installed = registry::install(plugin).map_err(err)?;
|
||||
let mut v = describe_installed(&installed);
|
||||
if !unknown.is_empty() {
|
||||
v["unknownCommands"] = json!(unknown);
|
||||
@@ -904,6 +992,8 @@ fn load_folder(s: &Session, folder: &str) -> Value {
|
||||
None if crate::file_access::current().is_none() => Ok(()),
|
||||
None => Err(format!("automation path rejected: {} isn't valid text", f.display())),
|
||||
};
|
||||
// A `plugin.install` in another session finishes writing the store first.
|
||||
let _held = hold_plugin_changes();
|
||||
match registry::load_folder_where(std::path::Path::new(folder), allow, s.plugin_folder_approver()) {
|
||||
Ok(r) => {
|
||||
for id in &r.loaded {
|
||||
@@ -1074,6 +1164,8 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = str_param(p, "id").ok_or_else(|| bad("plugin.remove", "missing `id`"))?;
|
||||
// An install in another session finishes its store writes first.
|
||||
let _held = hold_plugin_changes();
|
||||
let installed = registry::get(id).is_some();
|
||||
// Settings and cache the store keeps for an id that isn't installed are deleted too.
|
||||
let stored = !installed && vectorcraft_plugins::manifest::valid_id(id) && s.has_plugin_storage(id);
|
||||
|
||||
@@ -478,6 +478,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"recolor.pickTheme",
|
||||
"recolor.randomize",
|
||||
"recolor.reduce",
|
||||
"recolor.weigh",
|
||||
"select.add",
|
||||
"select.all",
|
||||
"select.allOnArtboard",
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::recolor::{ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, cluster, same_ink};
|
||||
use vectorcraft_color::recolor::{
|
||||
ColorKey, GlobalAdjust, Method, Preserve, Rng, RowMap, WeighUnit, cluster, row_shares, same_ink, weigh as weigh_rows,
|
||||
};
|
||||
use vectorcraft_color::{Color, Paint, Swatch};
|
||||
use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
@@ -63,6 +65,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
pick_theme
|
||||
),
|
||||
cmd!(
|
||||
query "recolor.weigh",
|
||||
"Prominent Colors",
|
||||
[],
|
||||
None,
|
||||
"{map: rows [{from, to, …}] or {current: new} as recolor.apply, weights?: [numbers ≥ 0, one per row; an excluded row's is ignored, and at least one other must be above 0], ids?: as recolor.colors} → {map: the rows as given, each with its current colours (from) moved as below, shares: [one per row: its percent of the uses (recolor.colors' count) of the current colours of the rows that aren't excluded; 0 for an excluded row]} for Recolor Artwork's Prominent Colors (VectorCraft's own rule): without weights the rows stay as they are. With weights, current colours move one at a time between the rows that aren't excluded and have a new colour (to), while a move brings each row's share of the uses nearer its share of the weights, first the colour nearest in Lab to the first colour of the row it goes to compared with the row it leaves; a row's first colour stays in it, the tints of one global swatch in a row move together, a colour that another row with a new colour lists first stays where it is, the other rows with a new colour drop their entries for a colour that moves, and a use counts for the row recolor.apply recolors it with (rows with a new colour first, an exact colour before a hex one, the first row that lists it), else for the first other row that isn't excluded and lists it. The colours that can move are compared with the rows at most 50,000,000 times in all, and when they times the rows that aren't excluded pass that, none move. Changes nothing",
|
||||
has_doc,
|
||||
weigh
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1062,6 +1073,181 @@ fn colors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "colors": v }))
|
||||
}
|
||||
|
||||
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
|
||||
/// row per entry). The rows have already been read by [`parse_rows`].
|
||||
fn given_rows(p: &Value) -> Vec<Value> {
|
||||
match p.get("map") {
|
||||
Some(Value::Array(rows)) => rows
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut r = r.clone();
|
||||
if let Some(f) = r.get("from").filter(|f| !f.is_array()).cloned() {
|
||||
r["from"] = json!([f]);
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect(),
|
||||
Some(Value::Object(m)) => m.iter().map(|(k, v)| json!({"from": [k], "to": v})).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn weigh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "recolor.weigh";
|
||||
let rows = parse_rows(p, C)?;
|
||||
let weights = match p.get("weights") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::Array(a)) if a.len() == rows.len() => Some(
|
||||
a.iter()
|
||||
.map(|v| {
|
||||
v.as_f64()
|
||||
.filter(|x| x.is_finite() && *x >= 0.0)
|
||||
.ok_or_else(|| bad(C, format!("each weight must be a number of 0 or more (got {v})")))
|
||||
})
|
||||
.collect::<Result<Vec<f64>>>()?,
|
||||
),
|
||||
Some(v) => return Err(bad(C, format!("`weights` must be a list of {} numbers, one per row (got {v})", rows.len()))),
|
||||
};
|
||||
let active: Vec<usize> = (0..rows.len()).filter(|&i| !rows[i].exclude).collect();
|
||||
if let Some(w) = &weights
|
||||
&& !active.is_empty()
|
||||
&& !active.iter().any(|&i| w[i] > 0.0)
|
||||
{
|
||||
return Err(bad(C, "at least one row that isn't excluded needs a weight above 0"));
|
||||
}
|
||||
let (ids, only) = scope_ids(s, p, C)?;
|
||||
let st = s.doc()?;
|
||||
let mut used: Vec<Option<Used>> = used_colors(&st.doc, &ids, only.as_ref()).into_iter().map(Some).collect();
|
||||
let mut by_key: HashMap<ColorKey, usize> = HashMap::new();
|
||||
let mut by_hex: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
for (i, u) in used.iter().enumerate().filter_map(|(i, u)| Some((i, u.as_ref()?))) {
|
||||
by_key.insert(ColorKey::of(&u.color), i);
|
||||
by_hex.entry(u.color.to_hex()).or_default().push(i);
|
||||
}
|
||||
// Each current colour's uses and global swatch. A use counts where recolor.apply recolors it:
|
||||
// rows with a new colour first, exact colours before hex colours, the first row that lists it;
|
||||
// then the other rows that aren't excluded, in the same way. `owner` holds the row and entry that took each colour,
|
||||
// and `shadows` the entries of rows with a new colour whose colours other entries took.
|
||||
let mut owner: Vec<Option<(usize, usize)>> = vec![None; used.len()];
|
||||
let mut shadows: Vec<(usize, usize, Vec<usize>)> = vec![];
|
||||
let mut found: Vec<Vec<(usize, Option<String>)>> = rows.iter().map(|r| vec![(0, None); r.from.len()]).collect();
|
||||
for recolors in [true, false] {
|
||||
for hex in [false, true] {
|
||||
for (r, row) in rows.iter().enumerate().filter(|(_, r)| !r.exclude && r.new_color().is_some() == recolors) {
|
||||
for (e, m) in row.from.iter().enumerate().filter(|(_, m)| matches!(m, Match::Hex(_)) == hex) {
|
||||
let hits: Vec<usize> = match m {
|
||||
Match::Key(k) => by_key.get(k).copied().into_iter().collect(),
|
||||
Match::Hex(h) => by_hex.get(h).cloned().unwrap_or_default(),
|
||||
};
|
||||
let (mut uses, mut link, mut took, mut taken) = (0, None, false, vec![]);
|
||||
for i in hits {
|
||||
match used[i].take() {
|
||||
Some(u) => {
|
||||
uses += u.count;
|
||||
link = link.or(u.swatch);
|
||||
took = true;
|
||||
owner[i] = Some((r, e));
|
||||
}
|
||||
None => taken.push(i),
|
||||
}
|
||||
}
|
||||
found[r][e] = (uses, link);
|
||||
if recolors && !took && !taken.is_empty() {
|
||||
shadows.push((r, e, taken));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The units that move: in each row that isn't excluded, the colours linked to one global
|
||||
// swatch go together, each other colour on its own, and the unit of the first colour stays.
|
||||
let (mut units, mut members): (Vec<WeighUnit>, Vec<(usize, Vec<usize>)>) = (vec![], vec![]);
|
||||
let mut unit_of: HashMap<(usize, usize), usize> = HashMap::new();
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
let mut groups: Vec<(Option<&String>, Vec<usize>, usize)> = vec![];
|
||||
let mut by_link: HashMap<&String, usize> = HashMap::new();
|
||||
for (e, (uses, link)) in found[r].iter().enumerate() {
|
||||
let g = match link {
|
||||
Some(l) => *by_link.entry(l).or_insert_with(|| {
|
||||
groups.push((Some(l), vec![], 0));
|
||||
groups.len() - 1
|
||||
}),
|
||||
None => {
|
||||
groups.push((None, vec![], 0));
|
||||
groups.len() - 1
|
||||
}
|
||||
};
|
||||
groups[g].1.push(e);
|
||||
groups[g].2 += uses;
|
||||
}
|
||||
for (k, (_, entries, uses)) in groups.into_iter().enumerate() {
|
||||
for &e in &entries {
|
||||
unit_of.insert((r, e), units.len());
|
||||
}
|
||||
units.push(WeighUnit { color: rows[r].from[entries[0]].color(), uses: uses as f64, row: n, fixed: k == 0 });
|
||||
members.push((r, entries));
|
||||
}
|
||||
}
|
||||
// recolor.apply matches a colour to the first row with a new colour that lists it. A colour
|
||||
// that another such row's first colour also lists stays where it is; another row's other
|
||||
// entries for a colour that moves are dropped from that row below.
|
||||
let owners = |taken: &[usize]| -> Vec<usize> { taken.iter().filter_map(|&i| unit_of.get(&owner[i]?).copied()).collect() };
|
||||
for (_, _, taken) in shadows.iter().filter(|(_, e, _)| *e == 0) {
|
||||
for u in owners(taken) {
|
||||
units[u].fixed = true;
|
||||
}
|
||||
}
|
||||
if let Some(w) = &weights {
|
||||
// Only rows with a new colour recolor what they hold, so only they give and take colours.
|
||||
let movers: Vec<usize> = (0..active.len()).filter(|&n| rows[active[n]].new_color().is_some()).collect();
|
||||
let anchors: Vec<Color> =
|
||||
movers.iter().map(|&n| rows[active[n]].from.first().map(Match::color).or(rows[active[n]].to).unwrap_or_default()).collect();
|
||||
let mut mover_of = vec![None; active.len()];
|
||||
for (m, &n) in movers.iter().enumerate() {
|
||||
mover_of[n] = Some(m);
|
||||
}
|
||||
let at: Vec<Option<usize>> = units.iter().map(|u| mover_of[u.row]).collect();
|
||||
let sub: Vec<WeighUnit> = units.iter().zip(&at).filter_map(|(u, m)| Some(WeighUnit { row: (*m)?, ..*u })).collect();
|
||||
let to = weigh_rows(&sub, &anchors, &movers.iter().map(|&n| w[active[n]]).collect::<Vec<_>>());
|
||||
for ((u, _), m) in units.iter_mut().zip(&at).filter(|(_, m)| m.is_some()).zip(to) {
|
||||
u.row = movers[m];
|
||||
}
|
||||
}
|
||||
let mut out = given_rows(p);
|
||||
if weights.is_some() {
|
||||
// Each row's colours: those that stayed, in their order, then those that came to it.
|
||||
// A row's entry for a colour that moved to another row would take it back, so it goes.
|
||||
let moved = |u: usize| active[units[u].row] != members[u].0;
|
||||
let dropped: std::collections::HashSet<(usize, usize)> =
|
||||
shadows.iter().filter(|(_, e, taken)| *e != 0 && owners(taken).into_iter().any(moved)).map(|(r, e, _)| (*r, *e)).collect();
|
||||
let old: Vec<Vec<Value>> = out.iter().map(|r| r["from"].as_array().cloned().unwrap_or_default()).collect();
|
||||
let mut stayed: Vec<Vec<usize>> = active.iter().map(|_| vec![]).collect();
|
||||
let mut came: Vec<Vec<Value>> = active.iter().map(|_| vec![]).collect();
|
||||
for (u, (r, entries)) in units.iter().zip(&members) {
|
||||
let kept = entries.iter().copied().filter(|&e| !dropped.contains(&(*r, e)));
|
||||
if active[u.row] == *r {
|
||||
stayed[u.row].extend(kept);
|
||||
} else {
|
||||
came[u.row].extend(kept.filter_map(|e| old[*r].get(e).cloned()));
|
||||
}
|
||||
}
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
stayed[n].sort_unstable();
|
||||
let mut from: Vec<Value> = stayed[n].iter().filter_map(|&e| old[r].get(e).cloned()).collect();
|
||||
from.append(&mut came[n]);
|
||||
if let Some(row) = out.get_mut(r) {
|
||||
row["from"] = Value::Array(from);
|
||||
}
|
||||
}
|
||||
}
|
||||
let shares = row_shares(&units, active.len());
|
||||
let mut all = vec![0.0; rows.len()];
|
||||
for (n, &r) in active.iter().enumerate() {
|
||||
all[r] = shares[n];
|
||||
}
|
||||
Ok(json!({"map": out, "shares": all}))
|
||||
}
|
||||
|
||||
/// The `method` parameter (`default` without one, or for null). A `method` that is not a string,
|
||||
/// such as `5`, names no method.
|
||||
fn method_param(p: &Value, cmd: &str, default: Method) -> Result<Method> {
|
||||
|
||||
@@ -506,6 +506,13 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option<Map<St
|
||||
if para { Kind::Para } else { Kind::Char }.attrs(d, name)
|
||||
}
|
||||
|
||||
/// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None`
|
||||
/// when they don't pass its checks.
|
||||
pub(crate) fn stored_style_attrs(d: &Document, para: bool, attrs: &Map<String, Value>) -> Option<Map<String, Value>> {
|
||||
let kind = if para { Kind::Para } else { Kind::Char };
|
||||
attrs_param(d, &json!({ "attrs": attrs }), kind, "new", None).ok().flatten()
|
||||
}
|
||||
|
||||
/// The name `charStyle.new` (`para`: `paraStyle.new`) gives a style when it is given none: the
|
||||
/// first "Character Style N" ("Paragraph Style N") that no character style (paragraph style) of the
|
||||
/// document has.
|
||||
|
||||
@@ -135,6 +135,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
let mut story: Vec<TextRun> = vec![];
|
||||
let mut sources: Vec<TextObject> = vec![];
|
||||
let mut later_wins = vec![];
|
||||
let mut earlier_wins = vec![];
|
||||
let mut live = vec![];
|
||||
for id in &thread {
|
||||
match (text_of(doc, *id), text_of(before, *id)) {
|
||||
@@ -143,6 +144,9 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
// A frame whose first paragraph was just restyled gives the paragraph it
|
||||
// shares with the frame before it that style.
|
||||
later_wins.push(old.is_some_and(|o| o.para_at(0) != t.para_at(0)));
|
||||
// A frame whose last paragraph was just restyled keeps that style in the
|
||||
// paragraph it shares with the frame after it, even when it is empty.
|
||||
earlier_wins.push(old.is_some_and(|o| o.para_at(o.paragraph_count() - 1) != t.para_at(t.paragraph_count() - 1)));
|
||||
sources.push(t.clone());
|
||||
live.push(*id);
|
||||
}
|
||||
@@ -151,6 +155,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
(None, Some(old)) => {
|
||||
story.extend(old.runs.iter().cloned());
|
||||
later_wins.push(false);
|
||||
earlier_wins.push(false);
|
||||
sources.push(old.clone());
|
||||
}
|
||||
(None, None) => {}
|
||||
@@ -160,7 +165,7 @@ pub(crate) fn reflow(before: &Document, doc: &mut Document) {
|
||||
continue;
|
||||
}
|
||||
let source_refs: Vec<&TextObject> = sources.iter().collect();
|
||||
let paras = vectorcraft_text::thread::story_paras(&source_refs, &later_wins);
|
||||
let paras = vectorcraft_text::thread::story_paras_restyled(&source_refs, &later_wins, &earlier_wins);
|
||||
vectorcraft_text::edit::normalize(&mut story);
|
||||
if live.len() >= 2 {
|
||||
// Threaded frames keep their size: Auto Size is off for them (as in Illustrator).
|
||||
|
||||
@@ -60,6 +60,130 @@ fn a_restyled_empty_frame_keeps_its_style_before_an_unedited_empty_frame() {
|
||||
assert_eq!([hyphenates(a, 0), hyphenates(a, 1), hyphenates(b, 0), hyphenates(c, 0)], [false, true, true, true]);
|
||||
}
|
||||
|
||||
/// Every paragraph's left indent in frame `id`.
|
||||
fn left_indents(s: &Session, id: u64) -> Vec<f64> {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.paragraph_styles().iter().map(|p| p.left_indent).collect(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Area type `height` high holding `text`, threaded into `empties` empty rectangles after it.
|
||||
fn tail_thread(text: &str, height: f64, empties: usize) -> (Session, Vec<u64>) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap();
|
||||
let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": text, "area": {"width": 150, "height": height}})).unwrap());
|
||||
let mut ids = vec![a];
|
||||
for k in 0..empties {
|
||||
let x = 200.0 * (k + 1) as f64;
|
||||
ids.push(new_id(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 150, "height": 60})).unwrap()));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": ids})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
(s, ids)
|
||||
}
|
||||
|
||||
/// Restyling a frame's empty last paragraph (after its final paragraph break) gives that
|
||||
/// paragraph the style in the next frame as well, instead of the next frame's old style.
|
||||
#[test]
|
||||
fn editing_a_frames_empty_last_paragraph_survives_thread_reflow() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let a =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a\n", "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
assert_eq!([text(&s, a), text(&s, b)], ["a\n", ""]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0]));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
// The same format again changes nothing and records no undo step.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 0.0], vec![0.0]));
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0]));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
|
||||
// A format of the whole frame changes its last paragraph as well.
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "leftIndent": 20})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![20.0, 20.0], vec![20.0]));
|
||||
// Both frames formatted in one command agree.
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "leftIndent": 40})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![40.0, 40.0], vec![40.0]));
|
||||
}
|
||||
|
||||
/// The restyled empty last paragraph keeps its style when the next frame holds text that
|
||||
/// continues it, and across an unedited empty frame; a later restyle of a later frame still wins.
|
||||
#[test]
|
||||
fn a_restyled_empty_last_paragraph_keeps_its_style_against_later_frames() {
|
||||
// One line high: the text added to the next frame stays there.
|
||||
let (mut s, ids) = tail_thread("a\n", 20.0, 1);
|
||||
let (a, b) = (ids[0], ids[1]);
|
||||
s.execute("text.editRange", &json!({"id": b, "start": 0, "end": 0, "insert": "def"})).unwrap();
|
||||
assert_eq!([text(&s, a), text(&s, b)], ["a\n", "def"]);
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!([text(&s, a), text(&s, b)], ["a\n", "def"]);
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0]));
|
||||
|
||||
let (mut s, ids) = tail_thread("a\n", 60.0, 2);
|
||||
s.execute("text.setFormat", &json!({"ids": [ids[0]], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!(ids.iter().map(|id| left_indents(&s, *id)).collect::<Vec<_>>(), [vec![0.0, 30.0], vec![30.0], vec![30.0]]);
|
||||
s.execute("text.setFormat", &json!({"ids": [ids[2]], "leftIndent": 10})).unwrap();
|
||||
assert_eq!(ids.iter().map(|id| left_indents(&s, *id)).collect::<Vec<_>>(), [vec![0.0, 10.0], vec![10.0], vec![10.0]]);
|
||||
}
|
||||
|
||||
/// The restyled last paragraph keeps its style with type on a path on either side of the boundary.
|
||||
#[test]
|
||||
fn a_restyled_empty_last_paragraph_flows_onto_type_on_a_path() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap();
|
||||
let a = new_id(s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a\n", "area": {"width": 150, "height": 60}})).unwrap());
|
||||
let on_path = type_on_a_line(&mut s);
|
||||
s.execute("text.thread.add", &json!({"from": a, "to": on_path})).unwrap();
|
||||
assert_eq!([text(&s, a), text(&s, on_path)], ["a\n", ""]);
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!((left_indents(&s, a), left_indents(&s, on_path)), (vec![0.0, 30.0], vec![30.0]));
|
||||
|
||||
// Type on a path before area type.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 300})).unwrap();
|
||||
let on_path = type_on_a_line(&mut s);
|
||||
s.execute("text.editRange", &json!({"id": on_path, "start": 0, "end": 0, "insert": "a\n"})).unwrap();
|
||||
let b = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 10, "width": 150, "height": 60})).unwrap());
|
||||
s.execute("text.thread.add", &json!({"from": on_path, "to": b})).unwrap();
|
||||
assert_eq!([text(&s, on_path), text(&s, b)], ["a\n", ""]);
|
||||
s.execute("text.setFormat", &json!({"ids": [on_path], "start": 2, "end": 2, "leftIndent": 30})).unwrap();
|
||||
assert_eq!((left_indents(&s, on_path), left_indents(&s, b)), (vec![0.0, 30.0], vec![30.0]));
|
||||
}
|
||||
|
||||
/// A restyled empty last paragraph in a numbered list is counted once, and the next frame's
|
||||
/// first paragraph does not continue the paragraph before the break.
|
||||
#[test]
|
||||
fn a_restyled_empty_last_list_paragraph_keeps_the_counts() {
|
||||
let (mut s, ids) = tail_thread("One\nTwo\n", 60.0, 1);
|
||||
let (a, b) = (ids[0], ids[1]);
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a], "start": 8, "end": 8, "leftIndent": 30})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let frame = |id| match &doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
let (ta, tb) = (frame(a), frame(b));
|
||||
let shown = [ta.plain_text(), tb.plain_text()].concat();
|
||||
assert_eq!(shown, "One\nTwo\n");
|
||||
let split = ta.paragraph_count() - 1;
|
||||
assert_eq!(ta.para_at(split).left_indent, 30.0, "{:?}", [ta.plain_text(), tb.plain_text()]);
|
||||
assert_eq!(tb.para_at(0).left_indent, 30.0);
|
||||
assert!(tb.para_at(0).list.is_some());
|
||||
assert_eq!(tb.list_count as usize, split, "the paragraphs before the shared one are counted once");
|
||||
assert_eq!(tb.first_para_continues, !ta.plain_text().ends_with('\n'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_flows_reflows_on_edit_and_survives_delete() {
|
||||
let (mut s, a, b) = setup();
|
||||
|
||||
@@ -286,6 +286,9 @@ pub struct Session {
|
||||
/// While the active tool's actions run: their commands aren't "a command from outside the
|
||||
/// tool" ([`Session::after_command`]).
|
||||
pub(crate) in_tool_actions: bool,
|
||||
/// The warnings of the previews that settling an interaction applied, while a top-level command
|
||||
/// or the tool's actions collect them ([`Session::collect_settled_warnings`]).
|
||||
settled_warnings: Option<Vec<String>>,
|
||||
/// While [`Session::preview`] runs its command: its edits are the interaction's own.
|
||||
previewing: bool,
|
||||
/// The images Remove Background decoded during the interaction's preview steps, emptied when
|
||||
|
||||
@@ -321,7 +321,8 @@ impl Files {
|
||||
std::env::var("JSINCLUDE").map(|v| v.split(';').map(str::trim).filter(|p| !p.is_empty()).map(PathBuf::from).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The file being run now, as `$.fileName` gives it (empty for a script given as text).
|
||||
/// The file being run now: the script, or the file `$.evalFile` is running (empty for a script
|
||||
/// given as text). `$.fileName` gives it to code that `eval` or `Function` compiled.
|
||||
pub(crate) fn file_name(&self) -> String {
|
||||
self.frames.last().map(|f| f.shown.to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -822,6 +822,29 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// `$.fileName` read by the code at `site`: the file that code is in, by the source map of the
|
||||
/// source it came from (this run's script, a file `$.evalFile` gave, or code an earlier run of
|
||||
/// the named engine compiled), so a function keeps the file it was defined in. Code from a file
|
||||
/// `#include` inserted is in that file. A script given as text has no name, and neither has
|
||||
/// code whose map the named engine no longer keeps. Code that `eval` or `Function` compiled has
|
||||
/// no map, and is given the file being run now.
|
||||
fn file_name_at(&self, site: vectorcraft_js::CallSite) -> String {
|
||||
let name = |m: &include::SourceMap| m.locate(site.line, site.column).1.to_string();
|
||||
let tag = site.source;
|
||||
if tag == vectorcraft_js::UNKNOWN_SOURCE {
|
||||
return self.files.borrow().file_name();
|
||||
}
|
||||
let script = self.script_tag.get();
|
||||
match tag.checked_sub(script).filter(|_| script != vectorcraft_js::UNKNOWN_SOURCE) {
|
||||
Some(0) => name(&self.script_map.borrow()),
|
||||
Some(n) => self.eval_maps.borrow().get(n as usize - 1).map(name).unwrap_or_default(),
|
||||
None => {
|
||||
let kept = self.kept_maps.as_ref().map(|k| k.borrow());
|
||||
kept.as_ref().and_then(|k| k.get(tag)).map(|k| name(&k.map)).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a line to the run's console and, during a slice, to the session's.
|
||||
fn line(&self, entry: console::Entry, cut: bool) {
|
||||
let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry };
|
||||
@@ -1254,9 +1277,9 @@ fn each_line(text: &str, mut done: impl FnMut(String, bool)) {
|
||||
|
||||
/// The `$` object: `$.write(...values)` writes the values to the Script Console as `String(value)`
|
||||
/// gives them, one after another, and `$.writeln(...values)` does the same and ends the line.
|
||||
/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file
|
||||
/// being run and `$.includePath` the `#includepath` list. Its other members are
|
||||
/// [`dollar::members`].
|
||||
/// `$.evalFile(path[, timeout])` runs a file and gives its last value, `$.fileName` is the file the
|
||||
/// code reading it is in ([`Host::file_name_at`]) and `$.includePath` the `#includepath` list. Its
|
||||
/// other members are [`dollar::members`].
|
||||
fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcraft_js::Localization>) -> Vec<(String, HostItem)> {
|
||||
let writer = |end: bool| {
|
||||
let l = link.clone();
|
||||
@@ -1278,6 +1301,15 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
Ok(Data::String(text))
|
||||
}))
|
||||
};
|
||||
let file_name = {
|
||||
let l = link.clone();
|
||||
HostItem::SiteGetter(Rc::new(move |site| {
|
||||
let h = current(&l)?;
|
||||
let text = h.file_name_at(site);
|
||||
h.charge_call(text.len() as u64 + 2)?;
|
||||
Ok(Data::String(text))
|
||||
}))
|
||||
};
|
||||
let eval_file = {
|
||||
let (l, end, strict) = (link.clone(), link.clone(), link.clone());
|
||||
HostItem::Evaluator {
|
||||
@@ -1294,7 +1326,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc<vectorcra
|
||||
("write".into(), writer(false)),
|
||||
("writeln".into(), writer(true)),
|
||||
("evalFile".into(), eval_file),
|
||||
("fileName".into(), getter(include::Files::file_name)),
|
||||
("fileName".into(), file_name),
|
||||
("includePath".into(), getter(include::Files::include_path)),
|
||||
];
|
||||
items.extend(dollar::members(link, info, localization));
|
||||
|
||||
@@ -116,6 +116,7 @@ impl Session {
|
||||
screens_hand_off: None,
|
||||
recovery: Default::default(),
|
||||
in_tool_actions: false,
|
||||
settled_warnings: None,
|
||||
previewing: false,
|
||||
decoded_images: Default::default(),
|
||||
envelope_defaults: None,
|
||||
|
||||
@@ -234,6 +234,27 @@ impl Session {
|
||||
self.active().and_then(|d| d.interaction.as_ref().filter(|it| std::sync::Arc::ptr_eq(&it.doc, &d.doc)).and_then(|it| it.preview.clone()))
|
||||
}
|
||||
|
||||
/// Keep `warning`, from a preview that settling an interaction applied, for whatever collects
|
||||
/// such warnings now ([`Session::collect_settled_warnings`]). Nothing keeps it when nothing
|
||||
/// collects, so it is never reported with a later, unrelated command.
|
||||
pub(crate) fn note_settled_warning(&mut self, warning: &str) {
|
||||
if let Some(kept) = &mut self.settled_warnings
|
||||
&& !kept.iter().any(|w| w == warning)
|
||||
{
|
||||
kept.push(warning.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f`, and → its result with the warnings of the previews that settling an interaction
|
||||
/// applied while it ran ([`Session::note_settled_warning`]). Warnings an outer `f` collects are
|
||||
/// kept for it.
|
||||
pub(crate) fn collect_settled_warnings<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> (R, Vec<String>) {
|
||||
let outer = self.settled_warnings.replace(Vec::new());
|
||||
let r = f(self);
|
||||
let settled = std::mem::replace(&mut self.settled_warnings, outer).unwrap_or_default();
|
||||
(r, settled)
|
||||
}
|
||||
|
||||
pub fn begin_interaction(&mut self, label: &str) -> Result<()> {
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
|
||||
@@ -3,6 +3,27 @@ use super::{
|
||||
strip_replay_only, waits_for_tool_edit,
|
||||
};
|
||||
|
||||
/// A command's result `r` with the warnings of the previews that settling an interaction applied
|
||||
/// before it ran: `previewWarning` holds them, and `warning` too when the command gives none of its
|
||||
/// own, so the status bar shows the command's own warning when there is one. A null result becomes
|
||||
/// an object holding them; any other result that isn't an object is returned as it is.
|
||||
fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
|
||||
if settled.is_empty() {
|
||||
return r;
|
||||
}
|
||||
if r.is_null() {
|
||||
r = Value::Object(serde_json::Map::new());
|
||||
}
|
||||
if let Value::Object(m) = &mut r {
|
||||
let w = Value::String(settled.join("; "));
|
||||
if m.get("warning").is_none_or(Value::is_null) {
|
||||
m.insert("warning".into(), w.clone());
|
||||
}
|
||||
m.insert("previewWarning".into(), w);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back.
|
||||
fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> {
|
||||
@@ -54,7 +75,14 @@ impl Session {
|
||||
self.finish_tool_edit_later()?;
|
||||
}
|
||||
let outer = std::mem::replace(&mut self.reading, !spec.journal || JOURNALED_READS.contains(&id));
|
||||
let r = self.execute_spec(spec, id, params);
|
||||
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
|
||||
// before Undo) reports its warning in the command's result.
|
||||
let r = if self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| s.execute_spec(spec, id, params));
|
||||
r.map(|v| with_settled_warnings(v, &settled))
|
||||
} else {
|
||||
self.execute_spec(spec, id, params)
|
||||
};
|
||||
self.reading = outer;
|
||||
r
|
||||
}
|
||||
@@ -364,3 +392,25 @@ impl Session {
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::with_settled_warnings;
|
||||
|
||||
/// The command's own warning stays the one the status bar shows, and the settled preview's is
|
||||
/// kept beside it; a null result holds the preview's; other results are left as they are.
|
||||
#[test]
|
||||
fn settled_warnings_join_the_result() {
|
||||
let settled = ["a".to_string(), "b".to_string()];
|
||||
assert_eq!(
|
||||
with_settled_warnings(json!({"ran": 1, "warning": "own"}), &settled),
|
||||
json!({"ran": 1, "warning": "own", "previewWarning": "a; b"})
|
||||
);
|
||||
assert_eq!(with_settled_warnings(json!({"warning": null}), &settled), json!({"warning": "a; b", "previewWarning": "a; b"}));
|
||||
assert_eq!(with_settled_warnings(json!(null), &settled[..1]), json!({"warning": "a", "previewWarning": "a"}));
|
||||
assert_eq!(with_settled_warnings(json!([1]), &settled), json!([1]));
|
||||
assert_eq!(with_settled_warnings(json!({"ran": 1}), &[]), json!({"ran": 1}));
|
||||
}
|
||||
}
|
||||
@@ -421,6 +421,8 @@ impl Session {
|
||||
if safe_mode::active() {
|
||||
return;
|
||||
}
|
||||
// A `plugin.install` in another session writes the store before this reads it.
|
||||
let _held = crate::cmd::plugin::hold_plugin_changes();
|
||||
let grants = self.counted_grants(&dir);
|
||||
let limits = vectorcraft_plugins::Limits::default();
|
||||
let mut left = MAX_PLUGIN_STORE;
|
||||
|
||||
@@ -1367,6 +1367,28 @@ fn smooth_tool_reduces_jagged_path() {
|
||||
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 200.0));
|
||||
}
|
||||
|
||||
/// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no
|
||||
/// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag
|
||||
/// does not reach keeps its anchors selected, and undo brings the old selection back.
|
||||
#[test]
|
||||
fn smoothing_a_path_drops_its_direct_selected_anchors() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": 200.0 + if i % 2 == 0 { 0.0 } else { 1.5 }})).collect();
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
let other = line(&mut s, 100.0, 500.0, 300.0, 500.0);
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 38]], "mode": "set"})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
drag(&mut s, "smooth", &[(90.0, 200.0), (200.0, 200.0), (310.0, 200.0)], Mods::default());
|
||||
assert!(path(&s, id).anchor_count() < 20, "the path is smoothed");
|
||||
let sel = s.doc().unwrap().selection.clone();
|
||||
assert!(sel.contains(id) && sel.contains(other), "{sel:?}");
|
||||
assert!(!sel.anchors.contains_key(&id) && !sel.segments.contains_key(&id), "{sel:?}");
|
||||
assert_eq!(sel.anchors.get(&other), Some(&[(0, 1)].into()), "the path out of reach keeps its anchor");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&[(0, 38)].into()));
|
||||
}
|
||||
|
||||
/// #1512: a short drag over a small bump smooths the stretch of path under it. The long straight
|
||||
/// sides next to the bump stay straight lines from their far ends, which keep their place.
|
||||
#[test]
|
||||
@@ -1390,6 +1412,169 @@ fn a_short_smooth_drag_leaves_the_rest_of_long_segments_alone() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected path through `anchors` (x, y, and the in and out handles when given).
|
||||
fn smooth_test_path(s: &mut Session, anchors: &[serde_json::Value], closed: bool) -> NodeId {
|
||||
let r = s.execute("path.create", &json!({"anchors": anchors, "closed": closed})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// `path.smoothRegion` along `drag` with the Smooth tool's reach (12 pt at 100%) and default Fidelity.
|
||||
fn smooth_pass(s: &mut Session, drag: &[Point]) {
|
||||
let pts: Vec<_> = drag.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap();
|
||||
}
|
||||
|
||||
/// Points 1/32 of a segment apart along every segment of `p`.
|
||||
fn smooth_test_samples(p: &PathData) -> Vec<Point> {
|
||||
use kurbo::ParamCurve;
|
||||
let mut v = vec![];
|
||||
for sp in &p.subpaths {
|
||||
for i in 0..sp.segment_count() {
|
||||
let c = sp.segment(i);
|
||||
v.extend((0..32).map(|k| c.eval(f64::from(k) / 32.0)));
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// How much `p` turns along its length, in radians: a wobbly path turns much more than a smooth one.
|
||||
fn total_turning(p: &PathData) -> f64 {
|
||||
let pts = smooth_test_samples(p);
|
||||
pts.windows(3)
|
||||
.map(|w| (w[1] - w[0], w[2] - w[1]))
|
||||
.filter(|(u, v)| u.hypot() > 1e-9 && v.hypot() > 1e-9)
|
||||
.map(|(u, v)| u.cross(v).atan2(u.dot(v)).abs())
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Deterministic noise in -1..1.
|
||||
fn smooth_noise(seed: &mut u64) -> f64 {
|
||||
*seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
(*seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
|
||||
}
|
||||
|
||||
/// A drag along y = `y` from x = `x0` to `x1`, one point every 5 pt.
|
||||
fn smooth_drag_along(y: f64, x0: f64, x1: f64) -> Vec<Point> {
|
||||
let n = ((x1 - x0) / 5.0).ceil() as usize;
|
||||
(0..=n).map(|i| Point::new(x0 + (x1 - x0) * i as f64 / n as f64, y)).collect()
|
||||
}
|
||||
|
||||
/// Each drag of the Smooth tool smooths the path under it, and a second drag over the same place
|
||||
/// smooths it further, as the help page describes
|
||||
/// (https://helpx.adobe.com/illustrator/using/tool-techniques/smooth-tool.html): a curve that wobbles
|
||||
/// 4 pt either side of its line every 12 pt, with an anchor at each crest, wobbles less after each drag.
|
||||
#[test]
|
||||
fn each_smooth_drag_smooths_a_wobble_larger_than_fidelity_further() {
|
||||
let mut s = session();
|
||||
let anchors: Vec<_> = (0..=20)
|
||||
.map(|k| {
|
||||
let (x, y) = (100.0 + 12.0 * f64::from(k), if k % 2 == 0 { 196.0 } else { 204.0 });
|
||||
json!({"x": x, "y": y, "in": [x - 4.4, y], "out": [x + 4.4, y]})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let drag = smooth_drag_along(200.0, 90.0, 350.0);
|
||||
let wobble =
|
||||
|p: &PathData| smooth_test_samples(p).iter().filter(|q| (130.0..=310.0).contains(&q.x)).map(|q| (q.y - 200.0).abs()).fold(0.0, f64::max);
|
||||
let mut before = path(&s, id);
|
||||
for pass in 1..=2 {
|
||||
smooth_pass(&mut s, &drag);
|
||||
let after = path(&s, id);
|
||||
assert_ne!(after, before, "pass {pass} changes the path");
|
||||
let (t0, t1) = (total_turning(&before), total_turning(&after));
|
||||
assert!(t1 < 0.9 * t0, "pass {pass}: turning {t0} -> {t1}");
|
||||
let (w0, w1) = (wobble(&before), wobble(&after));
|
||||
assert!(w1 < 0.8 * w0, "pass {pass}: wobble {w0} -> {w1}");
|
||||
let (a, b) = (before.subpaths[0].anchors[0].p, after.subpaths[0].anchors[0].p);
|
||||
assert_eq!(a, b, "pass {pass}: the path keeps its start");
|
||||
before = after;
|
||||
}
|
||||
}
|
||||
|
||||
/// Smoothing a line with up to 1 pt of noise again and again, over all of it or over its middle,
|
||||
/// keeps it close to the line under the noise: each refit stays near the path it smooths.
|
||||
#[test]
|
||||
fn repeated_smooth_drags_stay_close_to_the_line_under_the_noise() {
|
||||
let off = |p: &PathData| {
|
||||
let d: Vec<f64> = smooth_test_samples(p).iter().map(|q| (q.y - 200.0).abs()).collect();
|
||||
(d.iter().sum::<f64>() / d.len() as f64, d.iter().copied().fold(0.0, f64::max))
|
||||
};
|
||||
for (x0, x1) in [(90.0, 410.0), (150.0, 350.0)] {
|
||||
let mut s = session();
|
||||
let mut seed = 7u64;
|
||||
let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, false);
|
||||
let drag = smooth_drag_along(200.0, x0, x1);
|
||||
let (mean0, _) = off(&path(&s, id));
|
||||
for pass in 1..=5 {
|
||||
smooth_pass(&mut s, &drag);
|
||||
let (mean, max) = off(&path(&s, id));
|
||||
assert!(
|
||||
mean <= 1.1 * mean0 && max <= 1.5,
|
||||
"drag {x0}-{x1}, pass {pass}: {mean} on average and {max} at most from the line, {mean0} before"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A drag over the whole of a noisy closed path leaves no corner where the path starts.
|
||||
#[test]
|
||||
fn smoothing_a_whole_closed_path_leaves_no_kink_at_its_start() {
|
||||
let mut s = session();
|
||||
let mut seed = 5u64;
|
||||
let (c, r) = (Point::new(300.0, 300.0), 80.0);
|
||||
let anchors: Vec<_> = (0..64)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) / 64.0 * std::f64::consts::TAU;
|
||||
let rr = r + 2.5 * smooth_noise(&mut seed);
|
||||
json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let ring: Vec<Point> = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect();
|
||||
smooth_pass(&mut s, &ring);
|
||||
let p = path(&s, id);
|
||||
let sp = &p.subpaths[0];
|
||||
assert!(sp.closed && sp.anchors.len() < 64, "{} anchors", sp.anchors.len());
|
||||
let (last, first) = (sp.segment(sp.segment_count() - 1), sp.segment(0));
|
||||
let tin = if last.p3.distance(last.p2) > 1e-9 { last.p3 - last.p2 } else { last.p3 - last.p1 };
|
||||
let tout = if first.p1.distance(first.p0) > 1e-9 { first.p1 - first.p0 } else { first.p2 - first.p0 };
|
||||
let kink = tin.cross(tout).atan2(tin.dot(tout)).abs().to_degrees();
|
||||
assert!(kink <= 1.0, "a {kink}° corner at the start");
|
||||
}
|
||||
|
||||
/// A drag over the whole of a closed path smooths a bump at its first anchor as much as the same
|
||||
/// bump on the far side of it.
|
||||
#[test]
|
||||
fn smoothing_a_whole_closed_path_smooths_a_bump_at_its_start() {
|
||||
let mut s = session();
|
||||
let (c, r) = (Point::new(300.0, 300.0), 80.0);
|
||||
let anchors: Vec<_> = (0..64)
|
||||
.map(|i| {
|
||||
let a = f64::from(i) / 64.0 * std::f64::consts::TAU;
|
||||
let rr = if i % 32 == 0 { r + 6.0 } else { r };
|
||||
json!({"x": c.x + rr * a.cos(), "y": c.y + rr * a.sin()})
|
||||
})
|
||||
.collect();
|
||||
let id = smooth_test_path(&mut s, &anchors, true);
|
||||
let ring: Vec<Point> = (0..=128).map(|i| f64::from(i) / 128.0 * std::f64::consts::TAU).map(|a| c + r * kurbo::Vec2::from_angle(a)).collect();
|
||||
// A Fidelity of 0.5 pt, so the refit follows the smoothed path closely on both sides.
|
||||
let pts: Vec<_> = ring.iter().map(|p| json!([p.x, p.y])).collect();
|
||||
s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.5})).unwrap();
|
||||
let p = path(&s, id);
|
||||
use std::f64::consts::{PI, TAU};
|
||||
// How far the path rises above the circle within 0.3 radians of the angle `near`.
|
||||
let bump = |near: f64| {
|
||||
let off = |q: &Point| (((q.y - c.y).atan2(q.x - c.x) - near + PI).rem_euclid(TAU) - PI).abs();
|
||||
smooth_test_samples(&p).iter().filter(|q| off(q) < 0.3).map(|q| q.distance(c) - r).fold(0.0, f64::max)
|
||||
};
|
||||
let (start, far) = (bump(0.0), bump(PI));
|
||||
assert!(far < 5.0, "the far bump stays {far} pt high");
|
||||
assert!(start <= far + 0.5, "the bump at the start stays {start} pt high, the far one {far} pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn join_tool_joins_two_lines() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -535,9 +535,9 @@ fn expanded_art_keeps_the_random_transforms_the_canvas_drew() {
|
||||
}
|
||||
|
||||
/// The reply lists each object whose appearance expanded once, by the id it has in the document,
|
||||
/// starting with the selected object. In "group copies" the two copies of the square share an id
|
||||
/// until Expand Appearance gives them ids of their own, and the reply names the group, then each
|
||||
/// copy by its new id.
|
||||
/// starting with the selected object. In "group copies" the group's art holds the square with its
|
||||
/// stroke's effect applied, so the reply names the group alone; the two copies of the square share
|
||||
/// ids until Expand Appearance gives every object in them an id of its own.
|
||||
#[test]
|
||||
fn the_reply_names_each_expanded_copy_by_its_own_id() {
|
||||
for case in RANDOM_CASES {
|
||||
@@ -551,8 +551,17 @@ fn the_reply_names_each_expanded_copy_by_its_own_id() {
|
||||
assert!(ids.iter().all(|&i| s.doc().unwrap().doc.node(NodeId(i)).is_some()), "{case}: {ids:?}");
|
||||
if case == "group copies" {
|
||||
let art = node(&s, id);
|
||||
let copies: Vec<u64> = art.children().unwrap()[0].children().unwrap().iter().map(|c| c.id.0).collect();
|
||||
assert_eq!(ids, [vec![id.0], copies].concat(), "{case}");
|
||||
assert_eq!(ids, [id.0], "{case}");
|
||||
let copies = art.children().unwrap();
|
||||
assert_eq!(copies.len(), 2, "{case}");
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut repeated = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if !seen.insert(n.id) {
|
||||
repeated.push(n.id);
|
||||
}
|
||||
});
|
||||
assert!(repeated.is_empty(), "{case}: {repeated:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -635,6 +635,210 @@ fn a_library_style_named_with_spaces_comes_in_trimmed() {
|
||||
assert_eq!((text.runs[0].style.size, text.runs[0].style.style_name.as_deref()), (31.0, Some("Body")));
|
||||
}
|
||||
|
||||
/// The size of the first run of text object `id`.
|
||||
fn run_size(s: &Session, id: &Value) -> f64 {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.runs[0].style.size,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add to Character Styles puts a library character style into the document's character styles
|
||||
/// without applying it, with or without type selected, in one undo step; the same style there is
|
||||
/// reused without a step, and a name taken by other attributes gets a number. A bad call changes
|
||||
/// nothing.
|
||||
#[test]
|
||||
fn a_library_character_style_is_added_to_the_document_without_applying_it() {
|
||||
let mut s = session();
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Headline", "attrs": {"size": 31.0}}, {"name": "Broken", "attrs": {"size": "big"}}]});
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
let styles = |s: &Session| s.doc().unwrap().doc.char_styles.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
|
||||
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
// Nothing selected.
|
||||
let before = undo(&s);
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline"), Some(false)));
|
||||
assert_eq!(styles(&s), ["Headline"]);
|
||||
assert_eq!(undo(&s), before + 1, "one undo step");
|
||||
let attrs = &s.doc().unwrap().doc.char_styles[0].attrs;
|
||||
assert_eq!(attrs.get("size"), Some(&json!(31.0)));
|
||||
// Selected type keeps its look.
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let before = undo(&s);
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline"), Some(true)));
|
||||
assert_eq!((undo(&s), run_size(&s, &t), styles(&s).len()), (before, 9.0, 1), "reused: no step, the type unchanged");
|
||||
// Another style of that name: numbered, still not applied.
|
||||
run(&mut s, "charStyle.setAttrs", json!({"name": "Headline", "attrs": {"size": 5}}));
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Headline"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Headline 2"), Some(false)));
|
||||
assert_eq!(run_size(&s, &t), 9.0);
|
||||
let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(NodeId(t.as_u64().unwrap())).unwrap().kind else { panic!("not text") };
|
||||
assert_eq!(text.runs[0].style.style_name, None, "no style applied");
|
||||
// Undo takes the added style back alone.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(styles(&s), ["Headline"]);
|
||||
// Bad calls: nothing changes.
|
||||
let before = (undo(&s), styles(&s));
|
||||
for bad in [
|
||||
json!({"library": lib}),
|
||||
json!({"library": lib, "item": 3}),
|
||||
json!({"library": lib, "item": "Nope"}),
|
||||
json!({"library": "Nope", "item": "Headline"}),
|
||||
json!({"library": lib, "item": "Broken"}),
|
||||
json!({"recorded": {"name": "X", "attrs": "damaged"}}),
|
||||
] {
|
||||
assert!(s.execute("library.addToCharacterStyles", &bad).is_err(), "{bad}");
|
||||
assert_eq!((undo(&s), styles(&s)), before, "{bad}");
|
||||
}
|
||||
// Without a document it isn't available.
|
||||
run(&mut s, "file.close", json!({}));
|
||||
assert!(s.active().is_none());
|
||||
assert!(s.execute("library.addToCharacterStyles", &json!({"library": lib, "item": "Headline"})).is_err());
|
||||
}
|
||||
|
||||
/// A library character style whose fill links to a swatch the document lacks is added and applied
|
||||
/// with the color it shows, unlinked at full tint; a global swatch of that name in the document
|
||||
/// keeps the link and gives its color.
|
||||
#[test]
|
||||
fn a_library_character_style_linked_to_a_missing_swatch_is_added_unlinked() {
|
||||
let base = vectorcraft_color::Color::rgb(0.2, 0.4, 0.6);
|
||||
let shown = base.tinted(0.5);
|
||||
let linked = vectorcraft_color::Paint::Solid { color: shown, swatch: Some("Brand".into()), tint: 0.5 };
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Accent", "attrs": {"size": 20.0, "fill": linked}}]});
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
let fill = |s: &Session, name: &str| {
|
||||
let st = s.doc().unwrap().doc.char_styles.iter().find(|c| c.name == name).map(|c| c.attrs.clone()).unwrap();
|
||||
serde_json::from_value::<vectorcraft_color::Paint>(st["fill"].clone()).unwrap()
|
||||
};
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
assert_eq!(fill(&s, "Accent"), vectorcraft_color::Paint::Solid { color: shown, swatch: None, tint: 1.0 });
|
||||
// Apply as well, on selected type.
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let r = run(&mut s, "library.use", json!({"library": lib, "kind": "charStyle", "item": "Accent"}));
|
||||
assert_eq!(r["style"], "Accent", "the added style is reused");
|
||||
assert_eq!(run_size(&s, &t), 20.0);
|
||||
// A document with a global swatch of that name keeps the link.
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
let other = vectorcraft_color::Color::rgb(0.8, 0.1, 0.1);
|
||||
run(&mut s, "swatch.new", json!({"name": "Brand", "color": other, "global": true}));
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
let vectorcraft_color::Paint::Solid { swatch, tint, .. } = fill(&s, "Accent") else { panic!("not a solid fill") };
|
||||
assert_eq!((swatch.as_deref(), tint), (Some("Brand"), 0.5));
|
||||
// The style with the document's swatch color is the same style: added again, it is reused.
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Accent"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Accent"), Some(true)));
|
||||
}
|
||||
|
||||
/// A library style is compared with the document's in the form the document stores it in, so a
|
||||
/// style whose file writes a size as a whole number is reused, by Add to Character Styles and by a
|
||||
/// click alike.
|
||||
#[test]
|
||||
fn a_library_style_is_reused_whatever_form_its_file_writes_it_in() {
|
||||
let data = json!({"name": "Kept", "charStyles": [{"name": "Whole", "attrs": {"size": 31}}], "paraStyles": [{"name": "Para", "attrs": {"left_indent": 4}}]});
|
||||
let mut s = session();
|
||||
let lib = run(&mut s, "library.import", json!({"data": data.to_string()}))["id"].as_str().unwrap().to_string();
|
||||
run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Whole"}));
|
||||
let r = run(&mut s, "library.addToCharacterStyles", json!({"library": lib, "item": "Whole"}));
|
||||
assert_eq!((r["style"].as_str(), r["existing"].as_bool()), (Some("Whole"), Some(true)));
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
for (kind, item) in [("charStyle", "Whole"), ("paraStyle", "Para"), ("paraStyle", "Para")] {
|
||||
assert_eq!(run(&mut s, "library.use", json!({"library": lib, "kind": kind, "item": item}))["style"], item);
|
||||
}
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!((d.char_styles.len(), d.para_styles.iter().filter(|p| p.name.starts_with("Para")).count()), (1, 1));
|
||||
}
|
||||
|
||||
/// Rename gives a library item a new name, trimmed, in its place and its group; a character style
|
||||
/// keeps its attributes, a graphic its id. Another item of its kind with that name, an empty or
|
||||
/// too long name, a name that isn't text and an unknown item or library are errors that change
|
||||
/// nothing; a name with path characters is a name like any other; the item's own name writes
|
||||
/// nothing; and the document's history is not touched.
|
||||
#[test]
|
||||
fn library_items_are_renamed_in_place() {
|
||||
let (mut s, g, c, st) = brand();
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 120, "text": "Body", "size": 9}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
let other = run(&mut s, "library.add", json!({"kind": "charStyle", "name": "Body"}))["name"].as_str().unwrap().to_string();
|
||||
run(&mut s, "library.createGroup", json!({"name": "Brand", "items": [{"kind": "charStyle", "item": st}, {"kind": "fillColor", "item": c}]}));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let attrs = run(&mut s, "library.get", json!({}))["charStyles"][0]["attrs"].clone();
|
||||
let r = run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": st, "name": " Title "}));
|
||||
assert_eq!((r["item"].as_str(), r["name"].as_str()), (Some("Title"), Some("Title")));
|
||||
let got = run(&mut s, "library.get", json!({}));
|
||||
assert_eq!(got["charStyles"][0], json!({"name": "Title", "attrs": attrs}), "first still, the attributes kept");
|
||||
assert_eq!(got["charStyles"][1]["name"], other.as_str());
|
||||
assert_eq!(groups(&mut s), [("Brand".into(), refs(&[("charStyle", "Title"), ("color", &c)]))]);
|
||||
// A colour keeps its group under its new name; a graphic keeps its id.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "strokeColor", "item": c, "name": "Navy"}));
|
||||
assert_eq!(groups(&mut s), [("Brand".into(), refs(&[("charStyle", "Title"), ("color", "Navy")]))]);
|
||||
let r = run(&mut s, "library.renameItem", json!({"kind": "graphic", "item": "Logo", "name": "Mark"}));
|
||||
assert_eq!(r["item"], g.as_str());
|
||||
let graphic = run(&mut s, "library.get", json!({}))["graphics"][0].clone();
|
||||
assert_eq!((graphic["id"].as_str(), graphic["name"].as_str()), (Some(g.as_str()), Some("Mark")));
|
||||
// Path characters are kept.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Title", "name": "a/b\\c:d"}));
|
||||
assert_eq!(style_order_of(&mut s)[0], "a/b\\c:d");
|
||||
// Errors change nothing.
|
||||
let before = run(&mut s, "library.get", json!({}));
|
||||
let long = "x".repeat(257);
|
||||
for bad in [
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": other}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": " "}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": long}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d", "name": 5}),
|
||||
json!({"kind": "charStyle", "item": "a/b\\c:d"}),
|
||||
json!({"kind": "charStyle", "item": "Nope", "name": "X"}),
|
||||
json!({"kind": "paraStyle", "item": "a/b\\c:d", "name": "X"}),
|
||||
json!({"kind": "brush", "item": "a/b\\c:d", "name": "X"}),
|
||||
json!({"library": "Nope", "kind": "charStyle", "item": "a/b\\c:d", "name": "X"}),
|
||||
] {
|
||||
assert!(s.execute("library.renameItem", &bad).is_err(), "{bad}");
|
||||
assert_eq!(run(&mut s, "library.get", json!({})), before, "{bad}");
|
||||
}
|
||||
// A style of another kind may have the name, and 256 characters are allowed.
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "a/b\\c:d", "name": "Navy"}));
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Navy", "name": "y".repeat(256)}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no document undo step");
|
||||
}
|
||||
|
||||
/// The current library's character style names, in order.
|
||||
fn style_order_of(s: &mut Session) -> Vec<String> {
|
||||
order(s, "charStyles", "name")
|
||||
}
|
||||
|
||||
/// A rename is kept in the library's file; renaming an item to its own name writes nothing; and a
|
||||
/// rename whose file can't be written is taken back.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_library_item_rename_is_saved_or_taken_back() {
|
||||
let dir = vectorcraft_testkit::temp_dir("library-rename-item");
|
||||
let folder = dir.to_string_lossy().to_string();
|
||||
let mut s = session();
|
||||
s.libraries.set_dir(Some(folder.clone()));
|
||||
let lib = run(&mut s, "library.create", json!({"name": "Kept"}))["id"].as_str().unwrap().to_string();
|
||||
let t = run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Body", "size": 12}))["id"].clone();
|
||||
run(&mut s, "select.set", json!({"ids": [t]}));
|
||||
run(&mut s, "library.add", json!({"kind": "charStyle", "name": "Body"}));
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Body", "name": "Text"}));
|
||||
let mut t2 = session();
|
||||
t2.libraries.set_dir(Some(folder.clone()));
|
||||
assert_eq!(style_order_of(&mut t2), ["Text"], "kept in the file");
|
||||
// The file can't be written (a folder stands where it goes): its own name still succeeds, as
|
||||
// it writes nothing; a new name fails and is taken back.
|
||||
let file = dir.join(format!("{lib}.vclibrary"));
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
std::fs::create_dir(&file).unwrap();
|
||||
run(&mut s, "library.renameItem", json!({"kind": "charStyle", "item": "Text", "name": " Text "}));
|
||||
assert!(s.execute("library.renameItem", &json!({"kind": "charStyle", "item": "Text", "name": "Copy"})).is_err());
|
||||
assert_eq!(style_order_of(&mut s), ["Text"], "taken back");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn libraries_are_kept_in_files_across_sessions() {
|
||||
|
||||
@@ -643,6 +643,32 @@ fn envelope_top_object_shares_a_side_by_control_polygon_length() {
|
||||
assert!(near(Point::new(500.0, 200.0)) < 0.5, "the middle of the bottom: {pts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn envelope_top_object_keeps_its_look_when_anchors_are_added() {
|
||||
// Add Anchor Points splits each segment of the top object in two without changing its shape.
|
||||
// The top curve's parameter runs fast at its start, so its halves have control polygons of
|
||||
// different lengths; the envelope still bends the two rectangles as the unsplit curve does.
|
||||
let made = |add_anchors: bool| {
|
||||
let mut s = session();
|
||||
let left = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
|
||||
let right = rect(&mut s, 200.0, 100.0, 100.0, 100.0);
|
||||
let d = "M400 100 C520 40 590 70 600 100 L600 200 L400 200 Z";
|
||||
let t = id_of(&s.execute("path.create", &json!({ "d": d })).unwrap());
|
||||
if add_anchors {
|
||||
sel(&mut s, &[t]);
|
||||
s.execute("object.path.addAnchorPoints", &json!({})).unwrap();
|
||||
assert_eq!(node(&s, t).path_data().map(|p| p.anchor_count()), Some(8));
|
||||
}
|
||||
sel(&mut s, &[left, right, t]);
|
||||
let e = id_of(&s.execute("object.envelope.makeWithTopObject", &json!({})).unwrap());
|
||||
all_anchors(&live::expand_live(&node(&s, e)))
|
||||
};
|
||||
let (plain, split) = (made(false), made(true));
|
||||
assert_eq!(plain.len(), split.len());
|
||||
let off = plain.iter().zip(&split).map(|(p, q)| p.distance(*q)).fold(0.0, f64::max);
|
||||
assert!(off < 1e-6, "the art moves by up to {off} pt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn envelope_release_and_expand() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -257,6 +257,25 @@ fn shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canva
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's Transform effect runs after its member's own Offset Path in Expand Appearance as on
|
||||
/// the canvas: the 100 pt square offset to 120 pt and scaled by half expands 60 pt wide.
|
||||
#[test]
|
||||
fn a_groups_effects_after_its_members_own_expand_as_the_canvas_draws_them() {
|
||||
let mut s = session();
|
||||
run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 10}}));
|
||||
run(&mut s, "object.group", json!({}));
|
||||
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"scaleH": 50, "scaleV": 50}}));
|
||||
let before = render(&s);
|
||||
run(&mut s, "effect.expandAppearance", json!({}));
|
||||
let after = render(&s);
|
||||
let diff = differing(&before, &after, 64);
|
||||
assert_eq!(diff, 0, "{diff} pixels differ");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let w = doc.node(doc.layers[0].id).and_then(|l| l.geometric_bounds()).unwrap().width();
|
||||
assert!((w - 60.0).abs() < 1e-6, "{w}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it() {
|
||||
// The object's own effect, and the fill's (the first appearance item).
|
||||
|
||||
@@ -2820,6 +2820,188 @@ fn a_failed_store_write_keeps_the_stored_module_with_its_grant() {
|
||||
vectorcraft_plugins::registry::revoke(id);
|
||||
}
|
||||
|
||||
/// An install refused because another session revoked the grant its checks relied on writes
|
||||
/// nothing: a store that kept the grant and lost the module gets no module back, its grants stay as
|
||||
/// they were, and the plug-in installed with the id and the other session's revoke stand. `grant`
|
||||
/// approves the module by itself.
|
||||
#[test]
|
||||
fn a_grant_revoked_while_installing_leaves_the_store_as_it_was() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-revoked-while-installing");
|
||||
let id = "test.engine.permissions.revokedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
let grants = folder.0.join("grants.json");
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
std::fs::remove_file(&module).unwrap();
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || {
|
||||
registry::revoke(id);
|
||||
})));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("asks for the permissions doc.read"), "{e}");
|
||||
assert!(!module.exists(), "no module is stored");
|
||||
assert_eq!(std::fs::read(&grants).unwrap(), recorded, "the grants stay as they were");
|
||||
assert!(registry::granted(id).is_none(), "the other session's revoke stands");
|
||||
assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&bytes)), "the installed plug-in stays");
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(Some(Box::new(move || {
|
||||
registry::revoke(id);
|
||||
})));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
assert_eq!(std::fs::read(&module).unwrap(), bytes, "a module `grant` approves is stored");
|
||||
assert!(registry::granted(id).is_some_and(|g| g.hash == sha256_hex(&bytes)));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// A plug-in another session installs with the id while a module is checked takes the place the
|
||||
/// checks found free. Without `replace`, or with `replace: false`, the install is refused, writes no
|
||||
/// module and leaves that plug-in installed; with `replace: true` the module takes its place.
|
||||
#[test]
|
||||
fn a_plug_in_installed_while_installing_needs_replace() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-installed-while-installing");
|
||||
let id = "test.engine.installedwhileinstalling";
|
||||
let ours = asking(id, "[]", &json!({"objects": []}));
|
||||
let theirs = asking(id, "[]", &json!({"objects": [], "documentData": null}));
|
||||
let data = vectorcraft_format::base64_encode(&ours);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
let installed = || registry::get(id).map(|p| p.hash().to_string());
|
||||
let meanwhile = |theirs: Vec<u8>| -> Option<Box<dyn FnOnce()>> {
|
||||
Some(Box::new(move || {
|
||||
registry::install_bytes(&theirs).unwrap();
|
||||
}))
|
||||
};
|
||||
|
||||
for (replace, why) in [(Value::Null, "is another module than"), (json!(false), "is already installed")] {
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs.clone()));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data, "replace": replace})).unwrap_err().to_string();
|
||||
assert!(e.contains(why), "{replace}: {e}");
|
||||
assert!(!module.exists(), "{replace}: no module is stored");
|
||||
assert_eq!(installed(), Some(sha256_hex(&theirs)), "{replace}: the other plug-in stays installed");
|
||||
registry::remove(id);
|
||||
}
|
||||
|
||||
crate::cmd::plugin::BEFORE_INSTALL.set(meanwhile(theirs));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "replace": true}));
|
||||
assert_eq!(std::fs::read(&module).unwrap(), ours);
|
||||
assert_eq!(installed(), Some(sha256_hex(&ours)));
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Without a plug-in store, the install's approval comes from the grant it read first, the one it
|
||||
/// checks again before it installs: a grant another session records after that read approves
|
||||
/// nothing, so a revoke that follows it can't be undone by the install recording it again.
|
||||
#[test]
|
||||
fn a_grant_recorded_and_revoked_while_installing_approves_nothing() {
|
||||
use vectorcraft_plugins::permissions::{Grant, GrantToken, Permission, sha256_hex};
|
||||
use vectorcraft_plugins::registry;
|
||||
let id = "test.engine.permissions.recordedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
let g = Grant { id: id.into(), hash: sha256_hex(&bytes), permissions: vec![Permission::DocRead] };
|
||||
crate::cmd::plugin::AFTER_GRANT_READ.set(Some(Box::new(move || {
|
||||
registry::grant(GrantToken::after_engine_approval(g));
|
||||
})));
|
||||
let e = s.execute("plugin.install", &json!({"dataBase64": data})).unwrap_err().to_string();
|
||||
assert!(e.contains("asks for the permissions doc.read"), "{e}");
|
||||
assert!(registry::get(id).is_none(), "nothing is installed");
|
||||
registry::revoke(id);
|
||||
}
|
||||
|
||||
/// A `plugin.remove` in another session while a module is installed waits until the install has
|
||||
/// written the store, then removes the module, its grant and the plug-in: nothing of it stays in
|
||||
/// the store for the next launch.
|
||||
#[test]
|
||||
fn a_removal_while_installing_leaves_nothing_in_the_store() {
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-removed-while-installing");
|
||||
let id = "test.engine.permissions.removedwhileinstalling";
|
||||
let bytes = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let data = vectorcraft_format::base64_encode(&bytes);
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
let module = std::path::PathBuf::from(s.stored_plugin_file(id).unwrap());
|
||||
let grants = folder.0.join("grants.json");
|
||||
|
||||
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
|
||||
let (handed, remover) = std::sync::mpsc::channel();
|
||||
let dir = folder.0.clone();
|
||||
crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || {
|
||||
let thread = std::thread::spawn(move || {
|
||||
let tell = said.clone();
|
||||
crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || {
|
||||
let _ = tell.send("waiting");
|
||||
})));
|
||||
let mut other = session();
|
||||
other.attach_plugin_store(dir);
|
||||
let removed = other.execute("plugin.remove", &json!({"id": id})).map(|_| ()).map_err(|e| e.to_string());
|
||||
let _ = said.send("removed");
|
||||
removed
|
||||
});
|
||||
// The removal has finished, or waits for this install.
|
||||
let first = heard.recv().unwrap_or("gone");
|
||||
let _ = handed.send((first, thread));
|
||||
})));
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"]}));
|
||||
let (first, thread) = remover.recv().unwrap();
|
||||
assert_eq!(thread.join().unwrap(), Ok(()));
|
||||
assert!(registry::get(id).is_none() && registry::granted(id).is_none(), "the plug-in and its grant are gone");
|
||||
assert!(!module.exists(), "no module stays in the store");
|
||||
assert!(!std::fs::read_to_string(&grants).is_ok_and(|g| g.contains(id)), "no grant stays in the store");
|
||||
assert_eq!(first, "waiting", "the removal waits for the install");
|
||||
}
|
||||
|
||||
/// Another session that attaches the plug-in store while a new version is installed loads the
|
||||
/// stored plug-ins once the install has written the store: the version that runs is the one the
|
||||
/// store keeps for the next launch.
|
||||
#[test]
|
||||
fn a_store_loaded_while_installing_loads_the_new_version() {
|
||||
use vectorcraft_plugins::permissions::sha256_hex;
|
||||
use vectorcraft_plugins::registry;
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-loaded-while-installing");
|
||||
let id = "test.engine.permissions.loadedwhileinstalling";
|
||||
let old = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let new = asking(id, r#"["doc.read"]"#, &json!({"objects": [], "documentData": null}));
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&old), "grant": ["doc.read"]}));
|
||||
|
||||
let (said, heard) = std::sync::mpsc::channel::<&'static str>();
|
||||
let (handed, loader) = std::sync::mpsc::channel();
|
||||
let dir = folder.0.clone();
|
||||
crate::cmd::plugin::BEFORE_STORE.set(Some(Box::new(move || {
|
||||
let thread = std::thread::spawn(move || {
|
||||
let tell = said.clone();
|
||||
crate::cmd::plugin::WHILE_WAITING.set(Some(Box::new(move || {
|
||||
let _ = tell.send("waiting");
|
||||
})));
|
||||
session().attach_plugin_store(dir);
|
||||
let _ = said.send("loaded");
|
||||
});
|
||||
// The load has finished, or waits for this install.
|
||||
let first = heard.recv().unwrap_or("gone");
|
||||
let _ = handed.send((first, thread));
|
||||
})));
|
||||
let data = vectorcraft_format::base64_encode(&new);
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": data, "grant": ["doc.read"], "replace": true}));
|
||||
let (first, thread) = loader.recv().unwrap();
|
||||
thread.join().unwrap();
|
||||
assert_eq!(registry::get(id).map(|p| p.hash().to_string()), Some(sha256_hex(&new)), "the new version runs");
|
||||
assert_eq!(std::fs::read(s.stored_plugin_file(id).unwrap()).unwrap(), new, "the store keeps the new version");
|
||||
assert_eq!(first, "waiting", "the load waits for the install");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// Runs the test `name` of this module again in a process of its own → whether this is that
|
||||
/// process. The list of disabled plug-ins is kept for the whole process, and the other tests here
|
||||
/// read it again each time they attach a plug-in store.
|
||||
|
||||
@@ -2473,6 +2473,65 @@ fn deferred_commit_forwards_preview_warnings() {
|
||||
assert!(ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type"))), "{ui:?}");
|
||||
}
|
||||
|
||||
/// A session with a rectangle selected, and type too with `with_type`, tool `tool` chosen,
|
||||
/// Real-time Drawing off, and an interaction labeled `label` whose deferred Bloat preview warns
|
||||
/// that type is skipped when type is selected.
|
||||
fn deferred_bloat(label: &str, with_type: bool, tool: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap();
|
||||
let text = s.execute("text.create", &json!({"x": 300, "y": 200, "text": "Hi"})).unwrap();
|
||||
let ids = if with_type { json!([rect["id"], text["id"]]) } else { json!([rect["id"]]) };
|
||||
s.execute("select.set", &json!({ "ids": ids })).unwrap();
|
||||
s.select_tool(tool, ViewInfo::default()).unwrap();
|
||||
set_pref(&mut s, "realTimeDrawing", json!(false));
|
||||
s.begin_interaction(label).unwrap();
|
||||
let p = json!({"tool": "bloat", "points": [[290.0, 200.0]], "width": 200.0, "height": 200.0});
|
||||
s.doc_mut().unwrap().interaction.as_mut().unwrap().preview = Some(("object.liquify".into(), p));
|
||||
s
|
||||
}
|
||||
|
||||
/// A command that applies a deferred preview before it runs (Undo, Clear History) reports the
|
||||
/// preview's warning in its result, as the tool's own commit reports it; the preview is its own
|
||||
/// step, which Undo takes back. A preview without a warning adds none.
|
||||
#[test]
|
||||
fn settling_a_deferred_preview_keeps_its_warning() {
|
||||
let mut s = deferred_bloat("Bloat", true, "selection");
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(r["undone"], "Bloat", "{r}");
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}");
|
||||
assert_eq!(r["previewWarning"], r["warning"], "{r}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before, "the preview was a step of its own, and Undo took it back");
|
||||
let r = s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(r.get("warning").is_none() && r.get("previewWarning").is_none(), "nothing was settled: {r}");
|
||||
|
||||
let mut s = deferred_bloat("Bloat", true, "selection");
|
||||
let r = s.execute("edit.clearHistory", &json!({})).unwrap();
|
||||
assert!(r["warning"].as_str().is_some_and(|w| w.contains("type")), "{r}");
|
||||
|
||||
let mut s = deferred_bloat("Bloat", false, "selection");
|
||||
let r = s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"undone": "Bloat"}));
|
||||
}
|
||||
|
||||
/// Typing kept as its own step when a tool's drag begins, or when a Cmd press lends the Selection
|
||||
/// tool, shows its applied preview's warning in the status bar.
|
||||
#[test]
|
||||
fn settling_typing_for_a_tool_shows_its_preview_warning() {
|
||||
use vectorcraft_tools::{Action, Mods};
|
||||
let warned = |ui: &[UiRequest]| ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m.contains("type")));
|
||||
let mut s = deferred_bloat("Typing", true, "selection");
|
||||
let ui = s.apply_actions(vec![Action::Begin("Move".into())]).unwrap();
|
||||
assert!(warned(&ui), "{ui:?}");
|
||||
|
||||
let mut s = deferred_bloat("Typing", true, "rectangle");
|
||||
let cmd = Mods { cmd: true, ..Default::default() };
|
||||
let ui = s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap();
|
||||
assert!(warned(&ui), "{ui:?}");
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 380.0).with_mods(cmd), ViewInfo::default()).unwrap();
|
||||
}
|
||||
|
||||
/// File Handling › Use Low Resolution Proxy for Linked EPS (#394): off by default; toggling it does
|
||||
/// not replace full-resolution pixels already in the document.
|
||||
#[test]
|
||||
|
||||
@@ -1348,3 +1348,159 @@ fn theme_picker_refuses_bad_params() {
|
||||
assert!(e.contains(msg), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
const RED: &str = "rgb 255 0 0";
|
||||
const PURPLE: &str = "rgb 128 0 204";
|
||||
const BLUE: &str = "rgb 0 0 255";
|
||||
|
||||
/// Two red rectangles, a purple one and a blue one, selected.
|
||||
fn prominent_art(s: &mut Session) -> [NodeId; 4] {
|
||||
let ids = [rect(s, json!("#ff0000")), rect(s, json!("#ff0000")), rect(s, json!("#8000cc")), rect(s, json!("#0000ff"))];
|
||||
select_all(s);
|
||||
ids
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_gives_each_rows_share_of_the_uses() {
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": BLUE, "to": null, "tint": 50}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map}));
|
||||
assert_eq!(r["shares"], json!([75.0, 25.0]));
|
||||
assert_eq!(
|
||||
r["map"],
|
||||
json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": null, "tint": 50}]),
|
||||
"rows as given, from as a list"
|
||||
);
|
||||
// An excluded row has no share, and the others share the uses.
|
||||
let excl = json!([{"from": [RED, PURPLE], "to": null}, {"from": [BLUE], "to": null, "exclude": true}]);
|
||||
assert_eq!(run(&mut s, "recolor.weigh", json!({"map": excl}))["shares"], json!([100.0, 0.0]));
|
||||
// An excluded row before another that lists the same colour doesn't take its uses.
|
||||
let first = json!([{"from": [RED], "exclude": true}, {"from": [RED]}, {"from": [BLUE, PURPLE]}]);
|
||||
assert_eq!(run(&mut s, "recolor.weigh", json!({"map": first}))["shares"], json!([0.0, 50.0, 50.0]));
|
||||
// A current colour that no art uses counts nothing, and a use counts for the first row only.
|
||||
let twice = json!({"map": [{"from": [RED, "#123456"]}, {"from": [RED, PURPLE, BLUE]}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", twice)["shares"], json!([50.0, 50.0]));
|
||||
// As recolor.apply matches them: an exact colour before a hex one, a row with a new colour first.
|
||||
let exact = json!({"map": [{"from": ["#ff0000", PURPLE], "to": "#00ff00"}, {"from": [RED, BLUE], "to": "#ffff00"}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", exact)["shares"], json!([25.0, 75.0]));
|
||||
let recolored = json!({"map": [{"from": [RED, PURPLE]}, {"from": [RED, BLUE], "to": "#ffff00"}]});
|
||||
assert_eq!(run(&mut s, "recolor.weigh", recolored)["shares"], json!([25.0, 75.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_colors_to_the_rows_weights_and_changes_nothing() {
|
||||
let mut s = session();
|
||||
let [_, _, purple, blue] = prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#00ff00"}, {"from": [BLUE], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]}));
|
||||
assert_eq!(r["map"], json!([{"from": [RED], "to": "#00ff00"}, {"from": [BLUE, PURPLE], "to": "#ffff00"}]));
|
||||
assert_eq!(r["shares"], json!([50.0, 50.0]));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#8000cc", "a query leaves the art alone");
|
||||
// Recoloring with the weighed rows gives the moved colour its new row's colour.
|
||||
select_all(&mut s);
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"]}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#ffff00");
|
||||
assert_eq!(fill(&s, blue).to_hex(), "#ffff00");
|
||||
// A row's first colour stays, however small its weight.
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [0, 1]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED]));
|
||||
assert_eq!(r["shares"], json!([50.0, 50.0]));
|
||||
// Excluded rows keep their colours and take none; their weights are ignored.
|
||||
let three =
|
||||
json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE], "to": "#000000", "exclude": true}, {"from": ["#00ff00"], "to": "#000000"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": three, "weights": [1, 50, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE]));
|
||||
// A row without a new colour recolors nothing, so it neither gives nor takes colours.
|
||||
let keep = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE]}, {"from": ["#00ff00"], "to": "#000000"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": keep, "weights": [0, 1, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!(["#00ff00", PURPLE]));
|
||||
}
|
||||
|
||||
/// A colour that two rows list moves only where recolor.apply recolors it with the row it moved
|
||||
/// to, so the shares describe the recolor.
|
||||
#[test]
|
||||
fn weigh_keeps_a_moved_color_from_rows_that_also_list_it() {
|
||||
const GREEN: &str = "rgb 0 255 0";
|
||||
let mut s = session();
|
||||
let [_, _, purple, _] = prominent_art(&mut s);
|
||||
rect(&mut s, json!("#00ff00"));
|
||||
select_all(&mut s);
|
||||
// The purple moves from the first row to the third; the second row's entry for it goes.
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [BLUE, PURPLE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED]));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
assert_eq!(r["map"][2]["from"], json!([GREEN, PURPLE]));
|
||||
assert_eq!(r["shares"], json!([40.0, 20.0, 40.0]));
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#ffff00", "the purple takes the row it moved to");
|
||||
// A colour that another row lists first stays: that row would take it back.
|
||||
let mut s = session();
|
||||
let [_, _, purple, _] = prominent_art(&mut s);
|
||||
rect(&mut s, json!("#00ff00"));
|
||||
select_all(&mut s);
|
||||
let map = json!([{"from": [RED, PURPLE], "to": "#000000"}, {"from": [PURPLE, BLUE], "to": "#ffffff"}, {"from": [GREEN], "to": "#ffff00"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [2, 1, 2]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([RED, PURPLE]));
|
||||
assert_eq!(r["map"][1]["from"], json!([PURPLE, BLUE]));
|
||||
assert_eq!(r["shares"], json!([60.0, 20.0, 20.0]));
|
||||
run(&mut s, "recolor.apply", json!({"map": r["map"], "method": "exact"}));
|
||||
assert_eq!(fill(&s, purple).to_hex(), "#000000", "the purple keeps the first row's colour");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_moves_the_tints_of_a_global_swatch_together() {
|
||||
let mut s = session();
|
||||
run(&mut s, "swatch.new", json!({"name": "Brand", "color": {"c": 0, "m": 80, "y": 90, "k": 0}, "global": true}));
|
||||
rect(&mut s, json!("#ff0000"));
|
||||
let full = rect(&mut s, json!("#00ff00"));
|
||||
let tint = rect(&mut s, json!("#00ff00"));
|
||||
rect(&mut s, json!("#0000ff"));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [full.0], "swatch": "Brand"}));
|
||||
run(&mut s, "paint.setFill", json!({"ids": [tint.0], "swatch": "Brand", "tint": 50}));
|
||||
select_all(&mut s);
|
||||
let brand: Vec<Value> = run(&mut s, "recolor.colors", json!({}))["colors"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|c| c["swatch"] == "Brand")
|
||||
.map(|c| c["key"].clone())
|
||||
.collect();
|
||||
assert_eq!(brand.len(), 2);
|
||||
let map = json!([{"from": [RED, brand[0], brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]);
|
||||
// Even weights would take one tint alone, which would split the swatch: nothing moves.
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 1]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE]));
|
||||
// The swatch's two colours move to the blue row as one.
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": map, "weights": [1, 3]}));
|
||||
assert_eq!(r["map"][1]["from"], json!([BLUE, brand[0], brand[1]]));
|
||||
assert_eq!(r["shares"], json!([25.0, 75.0]));
|
||||
// Colours that stay keep their order, a swatch's colours with another between them included.
|
||||
let split = json!([{"from": [brand[0], RED, brand[1]], "to": "#000000"}, {"from": [BLUE], "to": "#ffffff"}]);
|
||||
let r = run(&mut s, "recolor.weigh", json!({"map": split, "weights": [3, 1]}));
|
||||
assert_eq!(r["map"][0]["from"], json!([brand[0], RED, brand[1]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weigh_refuses_bad_weights() {
|
||||
let mut s = session();
|
||||
prominent_art(&mut s);
|
||||
let map = json!([{"from": [RED]}, {"from": [BLUE], "exclude": true}]);
|
||||
for (p, msg) in [
|
||||
(json!({"map": map, "weights": [1]}), "`weights` must be a list of 2 numbers, one per row"),
|
||||
(json!({"map": map, "weights": "1, 1"}), "`weights` must be a list of 2 numbers"),
|
||||
(json!({"map": map, "weights": [1, -1]}), "each weight must be a number of 0 or more (got -1)"),
|
||||
(json!({"map": map, "weights": [1, "2"]}), "each weight must be a number of 0 or more"),
|
||||
(json!({"map": map, "weights": [0, 5]}), "at least one row that isn't excluded needs a weight above 0"),
|
||||
(json!({"weights": [1, 1]}), "missing `map`"),
|
||||
(json!({"map": [{"to": "#ff0000"}]}), "each row needs `from`"),
|
||||
] {
|
||||
let e = s.execute("recolor.weigh", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(msg), "{p}: {e}");
|
||||
}
|
||||
}
|
||||
@@ -202,6 +202,52 @@ fn an_error_in_code_an_earlier_run_kept_is_at_that_runs_file_and_line() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `$.fileName` in code an earlier run of a named engine kept names the file that code is in: that
|
||||
/// run's script, a file it included or a file `$.evalFile` gave, not the file of the run that calls
|
||||
/// it. Code from a script given as text, and code whose place the engine no longer keeps, has no
|
||||
/// name; a dropped engine takes its functions with it.
|
||||
#[test]
|
||||
fn a_kept_function_reads_the_file_name_of_the_file_it_is_in() {
|
||||
let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-file-name-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
for dir in ["a", "b"] {
|
||||
std::fs::create_dir_all(base.join(dir)).unwrap();
|
||||
}
|
||||
std::fs::write(base.join("a/inc.jsxinc"), "function fromInclude() { return $.fileName; }").unwrap();
|
||||
std::fs::write(base.join("a/ev.jsxinc"), "\nfunction fromEval() { return $.fileName; }").unwrap();
|
||||
let def = base.join("a/def.jsx");
|
||||
std::fs::write(&def, "#targetengine e\nfunction where() { return $.fileName; }\n#include \"inc.jsxinc\"\n$.evalFile('ev.jsxinc');").unwrap();
|
||||
let caller = base.join("b/caller.jsx");
|
||||
let call = |s: &mut Session, text: &str| -> Vec<String> {
|
||||
std::fs::write(&caller, text).unwrap();
|
||||
let r = s.execute("script.run", &json!({"path": caller.to_string_lossy()})).unwrap();
|
||||
r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect()
|
||||
};
|
||||
let mut s = Session::new();
|
||||
s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap();
|
||||
let from_file = call(&mut s, "#targetengine e\nvc.log([where(), fromInclude(), fromEval(), $.fileName]);");
|
||||
let from_text = log(&mut s, "#targetengine e\nvc.log([where(), $.fileName, eval('where()'), eval('$.fileName')]);");
|
||||
run(&mut s, "#targetengine e\nfunction fromText() { return $.fileName; }").unwrap();
|
||||
let text_kept = call(&mut s, "#targetengine e\nvc.log([fromText(), $.fileName]);");
|
||||
// Each run's own place takes the room of the ones before, so def.jsx's places go.
|
||||
TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(300)));
|
||||
for _ in 0..20 {
|
||||
run(&mut s, "#targetengine e\nvar x = 1;").unwrap();
|
||||
}
|
||||
let evicted = call(&mut s, "#targetengine e\nvc.log([where(), fromEval(), $.fileName]);");
|
||||
TEST_KEPT_MAP_BYTES.with(|b| b.set(None));
|
||||
s.execute("script.engine.drop", &json!({"name": "e"})).unwrap();
|
||||
let dropped = log(&mut s, "#targetengine e\nvc.log(typeof where);");
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let ends = |names: &[String], ends: &[&str]| names.len() == ends.len() && names.iter().zip(ends).all(|(n, e)| n.ends_with(e));
|
||||
assert!(ends(&from_file, &["a/def.jsx", "a/inc.jsxinc", "a/ev.jsxinc", "b/caller.jsx"]), "{from_file:?}");
|
||||
let shown: Vec<String> = from_text[0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect();
|
||||
assert!(ends(&shown, &["a/def.jsx", "", "a/def.jsx", ""]) && shown[1].is_empty() && shown[3].is_empty(), "{shown:?}");
|
||||
assert!(text_kept[0].is_empty() && text_kept[1].ends_with("b/caller.jsx"), "{text_kept:?}");
|
||||
assert!(evicted[0].is_empty() && evicted[1].is_empty() && evicted[2].ends_with("b/caller.jsx"), "{evicted:?}");
|
||||
assert_eq!(dropped, json!(["undefined"]));
|
||||
}
|
||||
|
||||
/// A named engine keeps the places of its earlier runs' code within its budget, the oldest going
|
||||
/// first, and the code still runs once its place is gone.
|
||||
#[test]
|
||||
|
||||
@@ -374,6 +374,48 @@ fn script_eval_file_returns_last_value_and_shares_globals() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `$.fileName` names the file the code reading it is in: a function `$.evalFile` gave names its
|
||||
/// file after the file has returned, through nested files, and code an included file inserted names
|
||||
/// that file. Code that `eval` compiled names the file being run.
|
||||
#[test]
|
||||
fn script_file_name_names_the_file_of_the_code_that_reads_it() {
|
||||
let base = folder("filename");
|
||||
write(&base.join("main/inc.jsxinc"), "function fromInclude() { return $.fileName; }\nvar includedTop = $.fileName;");
|
||||
write(
|
||||
&base.join("main/sub/outer.jsx"),
|
||||
"function fromOuter() { return $.fileName; }\nvar before = $.fileName;\n$.evalFile('inner.jsx');\nvar after = $.fileName;\nfromInner();",
|
||||
);
|
||||
write(&base.join("main/sub/inner.jsx"), "function fromInner() { return $.fileName; }\n$.fileName;");
|
||||
let r = run(
|
||||
&base,
|
||||
"#include \"inc.jsxinc\"\nvar nested = $.evalFile('sub/outer.jsx');\n\
|
||||
vc.log([fromInclude(), includedTop, before, after, nested, fromOuter(), fromInner(), $.fileName, eval('$.fileName')]);",
|
||||
)
|
||||
.unwrap();
|
||||
let names: Vec<String> = r["log"][0].as_array().unwrap().iter().map(|v| v.as_str().unwrap().replace('\\', "/")).collect();
|
||||
let ends = [
|
||||
"main/inc.jsxinc",
|
||||
"main/inc.jsxinc",
|
||||
"sub/outer.jsx",
|
||||
"sub/outer.jsx",
|
||||
"sub/inner.jsx",
|
||||
"sub/outer.jsx",
|
||||
"sub/inner.jsx",
|
||||
"main/main.jsx",
|
||||
"main/main.jsx",
|
||||
];
|
||||
assert_eq!(names.len(), ends.len(), "{names:?}");
|
||||
for (name, end) in names.iter().zip(ends) {
|
||||
assert!(name.ends_with(end), "{name} ends with {end}: {names:?}");
|
||||
}
|
||||
// A script given as text has no name, and neither have the functions it defines.
|
||||
let r = Session::new()
|
||||
.execute("script.run", &json!({"source": "function f() { return $.fileName; }\nvc.log([f(), $.fileName]);", "name": "t.js"}))
|
||||
.unwrap();
|
||||
assert_eq!(r["log"], json!([["", ""]]));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_eval_file_outside_scope_refused() {
|
||||
let base = folder("evaloutside");
|
||||
|
||||
@@ -75,6 +75,15 @@ fn nine_slice_guide_preview(cmd: &str, p: &Value) -> bool {
|
||||
&& p.as_object().is_some_and(|m| m.contains_key("nineSliceGuides") && m.keys().all(|k| k == "name" || k == "nineSliceGuides"))
|
||||
}
|
||||
|
||||
/// `ui` with a status message first for each of `warnings` (which came before its requests) that it
|
||||
/// doesn't already show.
|
||||
fn with_status(mut ui: Vec<UiRequest>, warnings: Vec<String>) -> Vec<UiRequest> {
|
||||
let new: Vec<UiRequest> =
|
||||
warnings.into_iter().filter(|w| !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))).map(UiRequest::Status).collect();
|
||||
ui.splice(0..0, new);
|
||||
ui
|
||||
}
|
||||
|
||||
/// Requests from tools that only the frontend can fulfil.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UiRequest {
|
||||
@@ -227,24 +236,28 @@ impl Session {
|
||||
|
||||
/// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the
|
||||
/// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click,
|
||||
/// not Select Behind). The tool lent to stays as it was, unaware, until the release.
|
||||
fn lend_selection_tool(&mut self, ev: &PointerEvent) -> PointerEvent {
|
||||
/// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event
|
||||
/// for the tool, and the warnings of a preview that keeping the typing applied.
|
||||
fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec<String>)> {
|
||||
if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() {
|
||||
return *ev;
|
||||
return Ok((*ev, vec![]));
|
||||
}
|
||||
let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return *ev };
|
||||
let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) };
|
||||
// Typing in progress is kept as its own step first: the lent tool's drag previews from the
|
||||
// document its interaction started from, which would drop the typing (#1881).
|
||||
// document its interaction started from, which would drop the typing (#1881). When it
|
||||
// can't be kept, the press is not lent.
|
||||
let mut settled = vec![];
|
||||
if crate::cmd::typing_in_progress(self) {
|
||||
// Fails only without a document, and then there is no typing to keep.
|
||||
let _ = crate::cmd::settle_interaction(self);
|
||||
let (r, warnings) = self.collect_settled_warnings(crate::cmd::settle_interaction);
|
||||
r?;
|
||||
settled = warnings;
|
||||
}
|
||||
// The Selection and Group Selection tools act on the instance whole.
|
||||
self.select_whole_instance(id);
|
||||
let lent = self.make_tool(id);
|
||||
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
|
||||
self.lender = Some(std::mem::replace(&mut self.tool, lent));
|
||||
PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }
|
||||
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
|
||||
}
|
||||
|
||||
/// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the
|
||||
@@ -659,7 +672,8 @@ impl Session {
|
||||
}
|
||||
self.leave_draw_inside(ev, view)?;
|
||||
self.tell_tool_history_moved();
|
||||
let ev = &self.lend_selection_tool(ev);
|
||||
let (ev, settled) = self.lend_selection_tool(ev)?;
|
||||
let ev = &ev;
|
||||
let lent = self.lender.is_some();
|
||||
let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
|
||||
if !keep {
|
||||
@@ -670,7 +684,7 @@ impl Session {
|
||||
if keep && ev.kind == PointerKind::Up {
|
||||
self.keep_tool_settings();
|
||||
}
|
||||
self.apply_actions(acts)
|
||||
self.apply_actions(acts).map(|ui| with_status(ui, settled))
|
||||
});
|
||||
// The tool's own edits do not move the history for it. A selection tool that Cmd lends
|
||||
// edits for the lender, which hears of the edit at its next event.
|
||||
@@ -1375,7 +1389,14 @@ impl Session {
|
||||
/// Apply tool actions. Errors from previews are reported but keep the interaction alive.
|
||||
pub fn apply_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
|
||||
let outer = std::mem::replace(&mut self.in_tool_actions, true);
|
||||
let r = self.apply_tool_actions(acts);
|
||||
// A preview that settling applied (typing kept as its own step before a drag begins) shows
|
||||
// its warning in the status bar, as the tool's own commit shows its preview's.
|
||||
let r = if !outer && self.depth == 0 {
|
||||
let (r, settled) = self.collect_settled_warnings(|s| s.apply_tool_actions(acts));
|
||||
r.map(|ui| with_status(ui, settled))
|
||||
} else {
|
||||
self.apply_tool_actions(acts)
|
||||
};
|
||||
self.in_tool_actions = outer;
|
||||
if !outer && self.depth == 0 {
|
||||
self.trim_histories();
|
||||
|
||||
@@ -1038,7 +1038,7 @@ fn nested_symbol_instances_stop_at_the_symbol_art_limit() {
|
||||
/// The documents [`the_writer_counts_objects_as_the_reader_reads_them`] writes: groups, compound
|
||||
/// paths, guides, sublayers, clipping groups and layers, painted clipping paths, opacity masks,
|
||||
/// gradients, pattern definitions and tiles, images, type, symbol definitions and instances,
|
||||
/// objects with art styles and objects bound to variables.
|
||||
/// objects with art styles, objects bound to variables and live envelopes.
|
||||
fn counted() -> Vec<(&'static str, Document)> {
|
||||
vec![
|
||||
("sample", sample()),
|
||||
@@ -1053,6 +1053,7 @@ fn counted() -> Vec<(&'static str, Document)> {
|
||||
("painted clips", painted_clips()),
|
||||
("blend", blend_doc()),
|
||||
("brushes", brushes_document()),
|
||||
("envelopes", envelopes_document()),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -9068,3 +9069,446 @@ fn spread_gradients_past_the_stops_the_reader_reads_stay_gradients() {
|
||||
let Some(Paint::Gradient(swatch)) = back.swatch("Bands").map(|s| &s.paint) else { panic!("the swatch is lost") };
|
||||
assert!((200..=crate::import::MAX_GRADIENT_STOPS).contains(&swatch.gradient.stops.len()), "{} stops", swatch.gradient.stops.len());
|
||||
}
|
||||
|
||||
/// An envelope named `Bent` of `kind` around a red rectangle (40, 20)-(100, 80) and a blue one
|
||||
/// (100, 20)-(160, 80), with Fidelity `fidelity`, Edit Contents `editing` and `options`.
|
||||
fn envelope_node(
|
||||
doc: &mut Document,
|
||||
kind: vectorcraft_doc::live::EnvelopeKind,
|
||||
fidelity: f64,
|
||||
editing: bool,
|
||||
options: vectorcraft_doc::live::EnvelopeOptions,
|
||||
) -> Node {
|
||||
let content = vec![
|
||||
Arc::new(square(doc, Rect::new(40.0, 20.0, 100.0, 80.0), Color::rgb(1.0, 0.0, 0.0))),
|
||||
Arc::new(square(doc, Rect::new(100.0, 20.0, 160.0, 80.0), Color::rgb(0.0, 0.0, 1.0))),
|
||||
];
|
||||
let kind = NodeKind::Envelope { content, kind: Box::new(kind), fidelity, editing, options, frame: Box::default() };
|
||||
named(Node::new(doc.alloc_id(), kind), "Bent")
|
||||
}
|
||||
|
||||
/// A 200 × 100 document of envelope `kind` ([`envelope_node`]) alone.
|
||||
fn envelope_doc(
|
||||
kind: vectorcraft_doc::live::EnvelopeKind,
|
||||
fidelity: f64,
|
||||
editing: bool,
|
||||
options: vectorcraft_doc::live::EnvelopeOptions,
|
||||
) -> Document {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let envelope = envelope_node(&mut doc, kind, fidelity, editing, options);
|
||||
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
/// A grid of `rows`×`cols` patches over (30, 10)-(170, 90), row by row from the top left, with its
|
||||
/// sixth point moved.
|
||||
fn envelope_points(rows: u32, cols: u32) -> Vec<kurbo::Point> {
|
||||
let mut points: Vec<kurbo::Point> = (0..=rows)
|
||||
.flat_map(|r| {
|
||||
(0..=cols).map(move |c| kurbo::Point::new(30.0 + 140.0 * f64::from(c) / f64::from(cols), 10.0 + 80.0 * f64::from(r) / f64::from(rows)))
|
||||
})
|
||||
.collect();
|
||||
points[5] += kurbo::Vec2::new(5.0, -8.0);
|
||||
points
|
||||
}
|
||||
|
||||
/// The envelopes written live: warps (vertical, with distortions, and twisted), meshes (with
|
||||
/// handles of their own, one handle uneven, and with the smooth ones), top objects (a curved top
|
||||
/// side, and two segments to the top and bottom sides), with Edit Contents off and on.
|
||||
fn live_envelope_kinds() -> Vec<(&'static str, vectorcraft_doc::live::EnvelopeKind)> {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, H_RIGHT, WARP_NET, smooth_handles};
|
||||
let warp = |style: &str, bend: f64, h: f64, v: f64, horizontal: bool| EnvelopeKind::Warp {
|
||||
style: style.into(),
|
||||
bend,
|
||||
h,
|
||||
v,
|
||||
horizontal,
|
||||
version: WARP_NET,
|
||||
};
|
||||
let points = envelope_points(2, 3);
|
||||
let mut handles = smooth_handles(2, 3, &points);
|
||||
handles[5][H_RIGHT] += kurbo::Vec2::new(4.0, 6.0);
|
||||
let mut curved = kurbo::BezPath::new();
|
||||
curved.move_to((30.0, 10.0));
|
||||
curved.curve_to((70.0, -5.0), (130.0, -5.0), (170.0, 10.0));
|
||||
curved.line_to((170.0, 90.0));
|
||||
curved.line_to((30.0, 90.0));
|
||||
curved.close_path();
|
||||
let mut six = kurbo::BezPath::new();
|
||||
six.move_to((30.0, 10.0));
|
||||
for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (100.0, 95.0), (30.0, 90.0)] {
|
||||
six.line_to(p);
|
||||
}
|
||||
six.close_path();
|
||||
vec![
|
||||
("arc", warp("arc", 50.0, -20.0, 30.0, false)),
|
||||
("twist", warp("twist", -35.0, 0.0, 0.0, true)),
|
||||
("mesh", EnvelopeKind::Mesh { rows: 2, cols: 3, points: points.clone(), handles }),
|
||||
("smooth mesh", EnvelopeKind::Mesh { rows: 2, cols: 3, points, handles: vec![] }),
|
||||
("curved top object", EnvelopeKind::TopObject { path: PathData::from_bezpath(&curved), corners: None }),
|
||||
("six-anchor top object", EnvelopeKind::TopObject { path: PathData::from_bezpath(&six), corners: None }),
|
||||
]
|
||||
}
|
||||
|
||||
/// `doc` written and read back from its editing data: the top object on its first layer, the
|
||||
/// writer's warnings and the reader's notes.
|
||||
fn envelope_back(doc: &Document) -> (Node, Vec<String>, Vec<String>) {
|
||||
let (p, warnings) = private_data(doc, &opts()).unwrap();
|
||||
let (back, notes) = crate::ai_alone(&p.data).unwrap();
|
||||
let a = back.layers[0].children().unwrap();
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
((*a[0]).clone(), warnings, notes)
|
||||
}
|
||||
|
||||
/// Does reopened envelope kind `got` have the shape of `want`: a warp's style, bend, distortions
|
||||
/// and orientation; a mesh's grid and the handles that draw (those inside the grid); the patch a top
|
||||
/// object's outline makes?
|
||||
fn same_envelope_kind(want: &vectorcraft_doc::live::EnvelopeKind, got: &vectorcraft_doc::live::EnvelopeKind) -> bool {
|
||||
use vectorcraft_doc::live::{Coons, EnvelopeKind, H_DOWN, H_LEFT, H_RIGHT, H_UP, smooth_handles};
|
||||
let near = |a: kurbo::Point, b: kurbo::Point| a.distance(b) < 1e-3;
|
||||
match (want, got) {
|
||||
(
|
||||
EnvelopeKind::Warp { style, bend, h, v, horizontal, version },
|
||||
EnvelopeKind::Warp { style: s, bend: b, h: dh, v: dv, horizontal: hz, version: ver },
|
||||
) => style == s && horizontal == hz && version == ver && [(bend, b), (h, dh), (v, dv)].iter().all(|(x, y)| (*x - *y).abs() < 1e-9),
|
||||
(EnvelopeKind::Mesh { rows, cols, points, handles }, EnvelopeKind::Mesh { rows: r, cols: c, points: p, handles: hs }) => {
|
||||
let own = if handles.is_empty() { smooth_handles(*rows, *cols, points) } else { handles.clone() };
|
||||
let inside = |i: usize, slot: usize| {
|
||||
let (row, col) = (i / (*cols as usize + 1), i % (*cols as usize + 1));
|
||||
match slot {
|
||||
s if s == H_LEFT => col > 0,
|
||||
s if s == H_RIGHT => col < *cols as usize,
|
||||
s if s == H_UP => row > 0,
|
||||
s if s == H_DOWN => row < *rows as usize,
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
(rows, cols) == (r, c)
|
||||
&& points.len() == p.len()
|
||||
&& points.iter().zip(p).all(|(a, b)| near(*a, *b))
|
||||
&& own.iter().zip(hs).enumerate().all(|(i, (a, b))| (0..4).all(|s| !inside(i, s) || near(a[s].to_point(), b[s].to_point())))
|
||||
}
|
||||
(EnvelopeKind::TopObject { path, corners }, EnvelopeKind::TopObject { path: p, corners: c }) => {
|
||||
let (Some(a), Some(b)) = (Coons::from_top_object(path, *corners), Coons::from_top_object(p, *c)) else { return false };
|
||||
(0..=8).all(|j| {
|
||||
(0..=8).all(|i| a.eval(f64::from(i) / 8.0, f64::from(j) / 8.0).distance(b.eval(f64::from(i) / 8.0, f64::from(j) / 8.0)) < 1e-2)
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A PDF-compatible `.ai`'s editing data keeps a warp, a mesh and a top object envelope live, with
|
||||
/// Edit Contents off and on: VectorCraft's reader opens each as the same envelope, its contents,
|
||||
/// Fidelity, Edit Contents, Envelope Options and shape as saved, and its name, the drawn art saved
|
||||
/// with it drawing as the envelope does.
|
||||
#[test]
|
||||
fn envelopes_are_read_back_live() {
|
||||
use vectorcraft_doc::live::EnvelopeOptions;
|
||||
for (name, kind) in live_envelope_kinds() {
|
||||
for editing in [false, true] {
|
||||
let doc = envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW);
|
||||
let (back, warnings, notes) = envelope_back(&doc);
|
||||
let what = format!("{name}, editing {editing}");
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}");
|
||||
assert!(!notes.iter().any(|w| w == crate::import::ENVELOPE_DRAWN), "{what}: {notes:?}");
|
||||
let NodeKind::Envelope { content, kind: got, fidelity, editing: e, options, frame } = &back.kind else { panic!("{what}: {back:#?}") };
|
||||
assert_eq!((*fidelity, *e, *options, **frame), (50.0, editing, EnvelopeOptions::NEW, Affine::IDENTITY), "{what}");
|
||||
assert!(same_envelope_kind(&kind, got), "{what}: {got:?}");
|
||||
assert_eq!(back.name.as_deref(), Some("Bent"), "{what}");
|
||||
let colors: Vec<Option<Color>> = content.iter().map(|c| c.appearance.fill_paint().color()).collect();
|
||||
assert_eq!(colors, [Some(Color::rgb(1.0, 0.0, 0.0)), Some(Color::rgb(0.0, 0.0, 1.0))], "{what}");
|
||||
// Saved again as it opened (a top object now with the corners the file gives it), it
|
||||
// opens as the same envelope again.
|
||||
let mut again = Document::new(200.0, 100.0);
|
||||
let layer = again.layers[0].id;
|
||||
again.insert(Some(layer), usize::MAX, back.clone()).unwrap();
|
||||
let (twice, warnings, notes) = envelope_back(&again);
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{what}, saved again: {warnings:?}");
|
||||
let NodeKind::Envelope { kind: twice, .. } = &twice.kind else { panic!("{what}, saved again: {twice:#?} {notes:?}") };
|
||||
assert!(same_envelope_kind(&kind, twice), "{what}, saved again: {twice:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An envelope that is a symbol's art is written live in the symbol's definition, and the symbol
|
||||
/// opens with it as a live envelope.
|
||||
#[test]
|
||||
fn an_envelope_in_a_symbol_is_read_back_live() {
|
||||
use vectorcraft_doc::live::EnvelopeOptions;
|
||||
let kinds = live_envelope_kinds();
|
||||
for (name, kind) in kinds {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let art = envelope_node(&mut doc, kind.clone(), 50.0, false, EnvelopeOptions::NEW);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) });
|
||||
let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) });
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
let (p, warnings) = private_data(&doc, &opts()).unwrap();
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{name}: {warnings:?}");
|
||||
let (back, notes) = crate::ai_alone(&p.data).unwrap();
|
||||
let symbol = back.symbols.iter().find(|s| s.name == "Bent").unwrap_or_else(|| panic!("{name}: {:?}", back.symbols));
|
||||
let mut envelopes = vec![];
|
||||
symbol.art.walk(&mut |n| {
|
||||
if let NodeKind::Envelope { kind, .. } = &n.kind {
|
||||
envelopes.push((**kind).clone());
|
||||
}
|
||||
});
|
||||
assert!(matches!(envelopes.as_slice(), [k] if same_envelope_kind(&kind, k)), "{name}: {envelopes:?} {notes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An envelope with an opacity mask comes back live with its mask, and the plugin's `XP` follows
|
||||
/// the envelope's dictionary rather than its mask's art.
|
||||
#[test]
|
||||
fn an_envelope_with_an_opacity_mask_is_read_back_live() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let mut envelope = envelope_node(&mut doc, kind.clone(), 50.0, false, EnvelopeOptions::NEW);
|
||||
let gray = square(&mut doc, Rect::new(40.0, 20.0, 160.0, 80.0), Color::gray(0.5));
|
||||
let art = group(&mut doc, vec![gray], false);
|
||||
envelope.extras_mut().mask = Some(Box::new(OpacityMask::new(art, false)));
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
|
||||
let text = program(&doc);
|
||||
let (xp, mask) = (text.find(") 1 0 0 XP").unwrap_or(0), text.find("(AI9_Mask)").unwrap_or(usize::MAX));
|
||||
assert!(mask < xp, "{text}");
|
||||
let (back, warnings, notes) = envelope_back(&doc);
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
let NodeKind::Envelope { kind: got, .. } = &back.kind else { panic!("{back:#?} {notes:?}") };
|
||||
assert!(same_envelope_kind(&kind, got), "{got:?}");
|
||||
assert!(back.extras().mask.is_some(), "{back:#?}");
|
||||
}
|
||||
|
||||
/// As many envelopes are written live as the reader checks in one file, and the ones after them
|
||||
/// as their art, with a warning.
|
||||
#[test]
|
||||
fn envelopes_past_the_readers_checks_are_written_as_their_art() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let limit = crate::import::ENVELOPE_CHECKS;
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
for _ in 0..=limit {
|
||||
let points = [(30.0, 10.0), (170.0, 0.0), (30.0, 90.0), (170.0, 90.0)].map(kurbo::Point::from).to_vec();
|
||||
let kind = EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![] };
|
||||
let envelope = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
|
||||
}
|
||||
let (p, warnings) = private_data(&doc, &opts()).unwrap();
|
||||
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
let (back, notes) = crate::ai_alone(&p.data).unwrap();
|
||||
let a = back.layers[0].children().unwrap();
|
||||
let live = a.iter().filter(|n| matches!(n.kind, NodeKind::Envelope { .. })).count();
|
||||
assert_eq!((a.len(), live), (limit + 1, limit), "{notes:?}");
|
||||
assert!(!notes.iter().any(|n| n == crate::import::ENVELOPE_DRAWN), "{notes:?}");
|
||||
}
|
||||
|
||||
/// Every Envelope Options switch and the ends of Fidelity come back as saved.
|
||||
#[test]
|
||||
fn envelope_options_and_fidelity_are_read_back() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, PreserveShape};
|
||||
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
|
||||
let new = EnvelopeOptions::NEW;
|
||||
let all = [
|
||||
(new, 50.0),
|
||||
(EnvelopeOptions { anti_alias: false, ..new }, 0.0),
|
||||
(EnvelopeOptions { preserve_shape: PreserveShape::Transparency, ..new }, 100.0),
|
||||
(EnvelopeOptions { distort_linear_gradients: true, distort_pattern_fills: true, ..new }, 30.0),
|
||||
(EnvelopeOptions { distort_appearance: false, ..new }, 50.0),
|
||||
];
|
||||
for (options, fidelity) in all {
|
||||
let (back, _, notes) = envelope_back(&envelope_doc(kind.clone(), fidelity, false, options));
|
||||
let NodeKind::Envelope { options: o, fidelity: f, .. } = &back.kind else { panic!("{options:?}: {back:#?} {notes:?}") };
|
||||
assert_eq!((*o, *f), (options, fidelity));
|
||||
}
|
||||
}
|
||||
|
||||
/// With Distort Appearance, an envelope whose contents map from their bounds with their strokes
|
||||
/// saves that box's size, and opens mapping from the same box.
|
||||
#[test]
|
||||
fn an_envelope_mapping_from_its_contents_strokes_is_read_back() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_boxes, envelope_stroke_margin};
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut envelope = envelope_node(
|
||||
&mut doc,
|
||||
EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] },
|
||||
50.0,
|
||||
false,
|
||||
EnvelopeOptions::NEW,
|
||||
);
|
||||
let NodeKind::Envelope { content, options, .. } = &mut envelope.kind else { unreachable_envelope() };
|
||||
for c in content.iter_mut() {
|
||||
let fill = Arc::make_mut(c).appearance.fill_paint();
|
||||
Arc::make_mut(c).appearance = Appearance::basic(fill, solid(Color::BLACK), 8.0).into();
|
||||
}
|
||||
let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY).unwrap();
|
||||
options.bounds_margin = envelope_stroke_margin(stroked, plain).unwrap();
|
||||
let margin = options.bounds_margin;
|
||||
assert!(margin.iter().all(|m| *m > 0.0), "{margin:?}");
|
||||
doc.insert(Some(layer), usize::MAX, envelope).unwrap();
|
||||
let (back, warnings, notes) = envelope_back(&doc);
|
||||
assert!(!warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
let NodeKind::Envelope { options, .. } = &back.kind else { panic!("{back:#?} {notes:?}") };
|
||||
assert!(options.bounds_margin.iter().zip(margin).all(|(a, b)| (a - b).abs() < 1e-4), "{:?} {margin:?}", options.bounds_margin);
|
||||
}
|
||||
|
||||
/// A test's stand-in for a node that must be an envelope.
|
||||
fn unreachable_envelope() -> ! {
|
||||
panic!("not an envelope")
|
||||
}
|
||||
|
||||
/// The record is written in the order the reader reads it: on `%_` lines the group holding the
|
||||
/// grid, its dictionary with the options, the contents' block and the kind, then the distorted art
|
||||
/// on plain lines and the plugin's `XP`. While the contents are edited, the group holds them and
|
||||
/// the dictionary the grid.
|
||||
#[test]
|
||||
fn an_envelope_is_written_in_the_order_the_reader_reads_it() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
|
||||
for editing in [false, true] {
|
||||
let text = program(&envelope_doc(kind.clone(), 50.0, editing, EnvelopeOptions::NEW));
|
||||
let at = |s: &str| text.find(s).unwrap_or_else(|| panic!("{s} missing: {text}"));
|
||||
let (group, mesh, dictionary, block, key, style, xp) = (
|
||||
at("%_u\n"),
|
||||
at("%_/Mesh X!"),
|
||||
at("%_131073 /Int (AIDeformOptionsKey) ,\n%_50 /Int (AIDeformFidelityKey) ,\n"),
|
||||
at("%_X=\n"),
|
||||
at("%_ (AIDeformArtKey) ,\n"),
|
||||
at("%_2 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\n"),
|
||||
at("(Adobe Deform Plugin) 1 0 0 XP\n"),
|
||||
);
|
||||
assert!(group < dictionary && dictionary < block && block < key && key < style && style < xp, "{text}");
|
||||
assert_eq!(block < mesh, editing, "{text}");
|
||||
assert!(text.contains(&format!("%_{} /Bool (AIDeformEditModeKey) ,\n", u8::from(editing))), "{text}");
|
||||
// The distorted art is one group on plain lines, named as the envelope, right before the `XP`.
|
||||
let drawn = &text[style..xp];
|
||||
assert!(drawn.contains("\nu\n") && drawn.contains("(Bent) ; (AI10_ArtUID) ,"), "{drawn}");
|
||||
// The contents are on `%_` lines only: drawn once on plain lines, as the distorted art.
|
||||
assert_eq!(text.matches("(Adobe Deform Plugin)").count(), 1, "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Envelopes the reader would open in another shape, or not at all, are written as their distorted
|
||||
/// art with a warning, and open as that art: an envelope of type, one in a turned frame, a warp drawn
|
||||
/// without its style's net, a mesh the reader would lay out the other way round, a top object
|
||||
/// whose sides don't pair up, a Fidelity that isn't a whole number and bounds margins kept with
|
||||
/// Distort Appearance off. Other live objects keep their own warning.
|
||||
#[test]
|
||||
fn envelopes_the_reader_cannot_open_live_are_written_as_their_art() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let base =
|
||||
|| envelope_doc(EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }, 50.0, false, EnvelopeOptions::NEW);
|
||||
let change = |f: &dyn Fn(&mut NodeKind)| {
|
||||
let mut doc = base();
|
||||
let id = doc.layers[0].children().unwrap()[0].id;
|
||||
f(&mut doc.node_mut(id).unwrap().kind);
|
||||
doc
|
||||
};
|
||||
let typed = change(&|k| {
|
||||
if let NodeKind::Envelope { content, .. } = k {
|
||||
let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(50.0, 50.0), "Type", vectorcraft_doc::CharStyle::default());
|
||||
content.push(Arc::new(Node::new(vectorcraft_doc::NodeId(9_000), NodeKind::Text(Box::new(t)))));
|
||||
}
|
||||
});
|
||||
let turned = change(&|k| {
|
||||
if let NodeKind::Envelope { frame, .. } = k {
|
||||
**frame = Affine::rotate(0.3);
|
||||
}
|
||||
});
|
||||
let old_warp = change(&|k| {
|
||||
if let NodeKind::Envelope { kind, .. } = k {
|
||||
**kind = EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 };
|
||||
}
|
||||
});
|
||||
// Columns down the page and rows across: the reader turns the grid round.
|
||||
let sideways = change(&|k| {
|
||||
if let NodeKind::Envelope { kind, .. } = k {
|
||||
let points =
|
||||
(0..=3).flat_map(|r| (0..=2).map(move |c| kurbo::Point::new(30.0 + 70.0 * f64::from(c), 10.0 + 80.0 * f64::from(r) / 3.0))).collect();
|
||||
**kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: transpose(points, 3, 2), handles: vec![] };
|
||||
}
|
||||
});
|
||||
let mut uneven = kurbo::BezPath::new();
|
||||
uneven.move_to((30.0, 10.0));
|
||||
for p in [(100.0, 0.0), (170.0, 10.0), (170.0, 90.0), (30.0, 90.0)] {
|
||||
uneven.line_to(p);
|
||||
}
|
||||
uneven.close_path();
|
||||
let lopsided = change(&|k| {
|
||||
if let NodeKind::Envelope { kind, .. } = k {
|
||||
**kind = EnvelopeKind::TopObject { path: PathData::from_bezpath(&uneven), corners: None };
|
||||
}
|
||||
});
|
||||
let fractional = change(&|k| {
|
||||
if let NodeKind::Envelope { fidelity, .. } = k {
|
||||
*fidelity = 50.5;
|
||||
}
|
||||
});
|
||||
let margin_kept = change(&|k| {
|
||||
if let NodeKind::Envelope { options, .. } = k {
|
||||
options.distort_appearance = false;
|
||||
options.bounds_margin = [0.5; 4];
|
||||
}
|
||||
});
|
||||
let cases = [
|
||||
("type", typed),
|
||||
("turned", turned),
|
||||
("old warp", old_warp),
|
||||
("sideways mesh", sideways),
|
||||
("lopsided top object", lopsided),
|
||||
("fractional fidelity", fractional),
|
||||
("margin kept", margin_kept),
|
||||
];
|
||||
for (what, doc) in cases {
|
||||
let text = program(&doc);
|
||||
assert!(!text.contains("AIDeformOptionsKey"), "{what}: {text}");
|
||||
let (back, warnings, _) = envelope_back(&doc);
|
||||
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{what}: {warnings:?}");
|
||||
assert!(!warnings.iter().any(|w| w == writer::LIVE), "{what}: {warnings:?}");
|
||||
assert!(matches!(back.kind, NodeKind::Group { .. }), "{what}: {back:#?}");
|
||||
}
|
||||
let blend = export_ai_editing(&blend_doc(), &opts()).unwrap();
|
||||
assert!(blend.warnings.iter().any(|w| w == writer::LIVE) && !blend.warnings.iter().any(|w| w == writer::ENVELOPES), "{:?}", blend.warnings);
|
||||
}
|
||||
|
||||
/// `points`, a grid of `rows + 1` rows of `cols + 1` points, as `cols + 1` rows of `rows + 1`.
|
||||
fn transpose(points: Vec<kurbo::Point>, rows: usize, cols: usize) -> Vec<kurbo::Point> {
|
||||
(0..=cols).flat_map(|c| (0..=rows).map(move |r| (r, c))).map(|(r, c)| points[r * (cols + 1) + c]).collect()
|
||||
}
|
||||
|
||||
/// An envelope with its contents in an opacity mask's art is written as its art there, and an
|
||||
/// envelope in a group stays live.
|
||||
#[test]
|
||||
fn envelopes_in_masks_are_written_as_their_art_and_in_groups_stay_live() {
|
||||
let doc = envelopes_document();
|
||||
let (p, warnings) = private_data(&doc, &opts()).unwrap();
|
||||
let (back, notes) = crate::ai_alone(&p.data).unwrap();
|
||||
assert!(warnings.iter().any(|w| w == writer::ENVELOPES), "{warnings:?}");
|
||||
let mut live = 0;
|
||||
back.walk(|n| live += usize::from(matches!(n.kind, NodeKind::Envelope { .. })));
|
||||
assert_eq!(live, 3, "{notes:?}");
|
||||
}
|
||||
|
||||
/// A warp, a mesh envelope with its contents edited, a top object in a group, and an envelope in an
|
||||
/// opacity mask's art.
|
||||
fn envelopes_document() -> Document {
|
||||
use vectorcraft_doc::live::EnvelopeOptions;
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let kinds = live_envelope_kinds();
|
||||
let kind = |name: &str| kinds.iter().find(|(n, _)| *n == name).map(|(_, k)| k.clone()).unwrap();
|
||||
let warp = envelope_node(&mut doc, kind("arc"), 50.0, false, EnvelopeOptions::NEW);
|
||||
let mesh = envelope_node(&mut doc, kind("mesh"), 50.0, true, EnvelopeOptions::NEW);
|
||||
let top = envelope_node(&mut doc, kind("six-anchor top object"), 50.0, false, EnvelopeOptions::NEW);
|
||||
let top = group(&mut doc, vec![top], false);
|
||||
let mut masked = square(&mut doc, Rect::new(0.0, 0.0, 200.0, 100.0), Color::gray(0.5));
|
||||
let mask_art = envelope_node(&mut doc, kind("twist"), 50.0, false, EnvelopeOptions::NEW);
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false)));
|
||||
for n in [warp, mesh, top, masked] {
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
doc
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use crate::ai_ops::{self, unit};
|
||||
use crate::ps;
|
||||
|
||||
mod brushes;
|
||||
mod envelopes;
|
||||
mod images;
|
||||
mod paints;
|
||||
mod styles;
|
||||
@@ -25,6 +26,8 @@ mod variables;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) use brushes::BRUSHES;
|
||||
#[cfg(test)]
|
||||
pub(super) use envelopes::ENVELOPES;
|
||||
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_objects};
|
||||
#[cfg(test)]
|
||||
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, same_appearance};
|
||||
@@ -52,8 +55,7 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil
|
||||
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
|
||||
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
|
||||
pub(super) const LIVE: &str =
|
||||
"blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const ITEM_TRANSPARENCY: &str =
|
||||
"the opacity and blending modes of single fills and strokes are left out of the editing data for other apps";
|
||||
@@ -262,6 +264,12 @@ pub(super) struct Writer<'a> {
|
||||
brush_set: brushes::Brushes,
|
||||
/// Brushes may be written; false on a large canvas, where they are left out.
|
||||
pub(super) brushes_live: bool,
|
||||
/// The object just written is an envelope's distorted art, which the plugin's `XP` follows
|
||||
/// ([`Self::envelope`]).
|
||||
deform: bool,
|
||||
/// How many more envelopes may be written live: as many as the reader checks in one file
|
||||
/// ([`crate::import::ENVELOPE_CHECKS`]).
|
||||
envelopes_left: usize,
|
||||
}
|
||||
|
||||
impl<'a> Writer<'a> {
|
||||
@@ -319,6 +327,8 @@ impl<'a> Writer<'a> {
|
||||
in_look: false,
|
||||
brush_set: brushes::Brushes::default(),
|
||||
brushes_live: true,
|
||||
deform: false,
|
||||
envelopes_left: crate::import::ENVELOPE_CHECKS,
|
||||
objects: 0,
|
||||
left_out: 0,
|
||||
definition_objects: 0,
|
||||
@@ -694,29 +704,16 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
self.end_group("U", xy);
|
||||
}
|
||||
NodeKind::Blend { .. }
|
||||
| NodeKind::Envelope { .. }
|
||||
| NodeKind::Mesh(_)
|
||||
| NodeKind::Repeat(_)
|
||||
| NodeKind::PlacedDocument(_)
|
||||
| NodeKind::Intertwine { .. } => {
|
||||
if !self.open_group("u") {
|
||||
return;
|
||||
}
|
||||
self.warn(LIVE);
|
||||
if self.nest < MAX_NEST {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
for c in g.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
self.node(c);
|
||||
}
|
||||
self.nest -= 1;
|
||||
}
|
||||
self.end_group("U", xy);
|
||||
NodeKind::Envelope { .. } if self.envelope(n, xy) => {}
|
||||
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES)),
|
||||
NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
self.drawn_art(n, xy, Some(LIVE));
|
||||
}
|
||||
// Ruler guides are kept in the document's native copy only.
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
}
|
||||
// Taken before the dictionary, whose opacity mask art may hold envelopes of its own.
|
||||
let deform = std::mem::take(&mut self.deform);
|
||||
if self.body.len() > start {
|
||||
// A group's dictionary goes between its end and its state block.
|
||||
let block = (self.block_end == self.body.len() && self.block_start >= start).then(|| self.body.split_off(self.block_start));
|
||||
@@ -726,6 +723,29 @@ impl<'a> Writer<'a> {
|
||||
self.body.push_str(&b);
|
||||
}
|
||||
}
|
||||
// An envelope's plugin `XP` follows its distorted art, after the art's state block.
|
||||
if deform {
|
||||
self.line(&envelopes::plugin_line());
|
||||
}
|
||||
}
|
||||
|
||||
/// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given.
|
||||
fn drawn_art(&mut self, n: &Node, xy: Xy, warning: Option<&str>) {
|
||||
if !self.open_group("u") {
|
||||
return;
|
||||
}
|
||||
if let Some(w) = warning {
|
||||
self.warn(w);
|
||||
}
|
||||
if self.nest < MAX_NEST {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
for c in g.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
self.node(c);
|
||||
}
|
||||
self.nest -= 1;
|
||||
}
|
||||
self.end_group("U", xy);
|
||||
}
|
||||
|
||||
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
//! Envelopes (see [`crate::ai_editing`] for the form), written in the form VectorCraft's `.ai`
|
||||
//! reader opens as live envelopes again: on `%_` lines a group holding the grid that shapes the
|
||||
//! envelope (while its contents are edited, the contents), then that group's `/ArtDictionary` with
|
||||
//! Envelope Options as a bit word (`AIDeformOptionsKey`), Fidelity (`AIDeformFidelityKey`), Edit
|
||||
//! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation
|
||||
//! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance
|
||||
//! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the
|
||||
//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain
|
||||
//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written
|
||||
//! for it, one grid edge to each segment of its sides. An envelope the reader would open in another
|
||||
//! shape is written as its distorted art.
|
||||
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Point, Vec2};
|
||||
use vectorcraft_doc::live::{
|
||||
Coons, EnvelopeKind, EnvelopeOptions, GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint, PreserveShape, WARP_NET, envelope_content_boxes,
|
||||
envelope_grid, envelope_stroke_margin, warp_grid,
|
||||
};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, PathData};
|
||||
|
||||
use super::{MAX_NEST, Writer, Xy, hide};
|
||||
use crate::import::{DEFORM_PLUGIN, EnvelopeGridPoint as GridPoint, envelope_outline, envelope_upright, warp_number};
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const ENVELOPES: &str = "envelopes of type, envelopes without contents, envelopes in opacity masks, pattern tiles, art cut to a clipping object or other envelopes' contents, envelopes on the layers of a large canvas or in a turned or mirrored frame, warps drawn without their style's net, meshes and top objects that the data would open in another shape, envelopes with a Fidelity that isn't a whole number, envelopes that map from a box other than their contents' bounds with or without strokes or keep bounds margins with Distort Appearance off, envelopes after the first 256, and envelopes nested more than 8 deep are written as their art in the editing data for other apps";
|
||||
|
||||
/// The most rows or columns of an envelope's grid written (Make with Mesh's own limit, and the
|
||||
/// reader's).
|
||||
const MAX_GRID: usize = 50;
|
||||
/// How far, as a share of the diagonal of a top object's patch, the patch on the outline written for
|
||||
/// it may lie from its own at any of the places checked.
|
||||
const TOP_OBJECT_TOLERANCE: f64 = 1e-6;
|
||||
/// How far apart two bounds margins may be and still count as the same.
|
||||
const MARGIN_SLACK: f32 = 1e-5;
|
||||
|
||||
/// What an envelope's dictionary holds besides its contents: the entries before the contents' block,
|
||||
/// each on a line of its own, the kind (`AIDeformStyle`) and the grid that shapes it (`rows`, `cols`
|
||||
/// and its points with their handles, row by row from the top left, in the document), when it has
|
||||
/// one.
|
||||
struct Record {
|
||||
keys: String,
|
||||
style: u8,
|
||||
grid: Option<(usize, usize, Vec<GridPoint>)>,
|
||||
}
|
||||
|
||||
/// The `XP` that ends an envelope, after its distorted art.
|
||||
pub(super) fn plugin_line() -> String {
|
||||
format!("{} 1 0 0 XP", ps::bytes(DEFORM_PLUGIN.as_bytes()))
|
||||
}
|
||||
|
||||
/// Does `n`, or anything in it, hold type?
|
||||
fn holds_type(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Text(_)) || n.children().is_some_and(|c| c.iter().any(|k| holds_type(k)))
|
||||
}
|
||||
|
||||
/// The record of envelope `n` (its parts given), or `None` where the reader would open it in
|
||||
/// another shape than it has, or not as an envelope.
|
||||
fn record(
|
||||
n: &Node,
|
||||
content: &[Arc<Node>],
|
||||
kind: &EnvelopeKind,
|
||||
fidelity: f64,
|
||||
editing: bool,
|
||||
options: &EnvelopeOptions,
|
||||
frame: Affine,
|
||||
) -> Option<Record> {
|
||||
// The reader reads Fidelity as a whole number from 0 to 100, and bounds margins only with
|
||||
// Distort Appearance on.
|
||||
let whole = (0.0..=100.0).contains(&fidelity) && fidelity.fract() == 0.0;
|
||||
let margin_kept = !options.distort_appearance && options.bounds_margin != [0.0; 4];
|
||||
if content.is_empty() || frame != Affine::IDENTITY || !whole || margin_kept || content.iter().any(|c| holds_type(c)) {
|
||||
return None;
|
||||
}
|
||||
let mut keys = String::new();
|
||||
let bit = |on: bool, at: u32| i64::from(on) << at;
|
||||
let word = bit(options.distort_appearance, 0)
|
||||
| bit(options.distort_pattern_fills, 1)
|
||||
| bit(options.distort_linear_gradients, 2)
|
||||
| bit(!options.anti_alias, 16)
|
||||
| bit(options.preserve_shape == PreserveShape::ClippingMask, 17);
|
||||
let _ = writeln!(keys, "{word} /Int (AIDeformOptionsKey) ,");
|
||||
let _ = writeln!(keys, "{} /Int (AIDeformFidelityKey) ,", fidelity as i64);
|
||||
let _ = writeln!(keys, "{} /Bool (AIDeformEditModeKey) ,", u8::from(editing));
|
||||
let real = |keys: &mut String, v: f64, key: &str| {
|
||||
ps::push_num_places(keys, v, 9);
|
||||
let _ = writeln!(keys, " /Real ({key}) ,");
|
||||
};
|
||||
let (style, grid) = match kind {
|
||||
EnvelopeKind::Warp { style, bend, h, v, horizontal, version } => {
|
||||
let fraction = |p: f64| (p.is_finite() && (-100.0..=100.0).contains(&p)).then_some(p / 100.0);
|
||||
let (number, bend, h, v) = (warp_number(style)?, fraction(*bend)?, fraction(*h)?, fraction(*v)?);
|
||||
if *version != WARP_NET {
|
||||
return None;
|
||||
}
|
||||
let _ = writeln!(keys, "{number} /Int (DeformStyle) ,");
|
||||
real(&mut keys, h, "DeformHoriz");
|
||||
real(&mut keys, bend, "DeformValue");
|
||||
real(&mut keys, v, "DeformVert");
|
||||
let _ = writeln!(keys, "{} /Bool (Rotate) ,", u8::from(!*horizontal));
|
||||
// The grid of the warp's shape, for apps that read it.
|
||||
(1, warp_grid(n).and_then(|m| as_read(&m)).and_then(|(rows, cols, pts)| sized(rows, cols).map(|(r, c)| (r, c, pts))))
|
||||
}
|
||||
EnvelopeKind::Mesh { rows, cols, points, handles } => {
|
||||
let (r, c) = sized(*rows, *cols)?;
|
||||
let mesh = envelope_grid(*rows, *cols, points, handles)?;
|
||||
let pts = as_read(&mesh)?.2;
|
||||
// The reader lays the grid out with its first row at the top and its first column at the
|
||||
// left: a grid it would lay out another way round would map the contents another way.
|
||||
if !reads_as_written(r, c, &pts) {
|
||||
return None;
|
||||
}
|
||||
(2, Some((r, c, pts)))
|
||||
}
|
||||
EnvelopeKind::TopObject { path, corners } => (3, Some(top_object_grid(path, *corners)?)),
|
||||
};
|
||||
if options.distort_appearance {
|
||||
let (stroked, plain) = envelope_content_boxes(content, Affine::IDENTITY)?;
|
||||
let margin = options.bounds_margin;
|
||||
let same = |m: [f32; 4]| m.iter().zip(margin).all(|(a, b)| (a - b).abs() <= MARGIN_SLACK);
|
||||
// The reader maps from the size written when it matches the contents' bounds with their
|
||||
// strokes, and from their geometric bounds otherwise.
|
||||
let size = if margin == [0.0; 4] {
|
||||
plain
|
||||
} else if stroked != plain && envelope_stroke_margin(stroked, plain).is_some_and(same) {
|
||||
stroked
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
real(&mut keys, size.height(), "AIDeformArtHeightKey");
|
||||
real(&mut keys, size.width(), "AIDeformArtWidthKey");
|
||||
}
|
||||
Some(Record { keys, style, grid })
|
||||
}
|
||||
|
||||
/// `rows` and `cols` as sizes, when the reader reads a grid of them.
|
||||
fn sized(rows: u32, cols: u32) -> Option<(usize, usize)> {
|
||||
let (r, c) = (usize::try_from(rows).ok()?, usize::try_from(cols).ok()?);
|
||||
((1..=MAX_GRID).contains(&r) && (1..=MAX_GRID).contains(&c)).then_some((r, c))
|
||||
}
|
||||
|
||||
/// The points of grid `m` with their handles as the reader reads them back: the handles that point
|
||||
/// out of the grid, which nothing draws with, are left at the point. `None` for a grid of points
|
||||
/// or handles that aren't finite.
|
||||
fn as_read(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> {
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let finite = |v: Vec2| v.x.is_finite() && v.y.is_finite();
|
||||
let mut pts = Vec::with_capacity(m.points.len());
|
||||
for (i, q) in m.points.iter().enumerate() {
|
||||
if !finite(q.p.to_vec2()) || !q.handles.iter().all(|h| finite(*h)) {
|
||||
return None;
|
||||
}
|
||||
let (r, c) = (i / (cols + 1), i % (cols + 1));
|
||||
let mut h = q.handles;
|
||||
for (slot, out) in [(H_LEFT, c == 0), (H_RIGHT, c == cols), (H_UP, r == 0), (H_DOWN, r == rows)] {
|
||||
if out && let Some(h) = h.get_mut(slot) {
|
||||
*h = Vec2::ZERO;
|
||||
}
|
||||
}
|
||||
pts.push((q.p, h));
|
||||
}
|
||||
Some((m.rows, m.cols, pts))
|
||||
}
|
||||
|
||||
/// Does the reader lay out grid `pts` (`rows`×`cols` patches) as it is written?
|
||||
fn reads_as_written(rows: usize, cols: usize, pts: &[GridPoint]) -> bool {
|
||||
let points =
|
||||
pts.iter().map(|(p, handles)| MeshPoint { p: *p, color: vectorcraft_color::Color::BLACK, opacity: 1.0, handles: *handles }).collect();
|
||||
let mesh = GradientMesh { rows: rows as u32, cols: cols as u32, points };
|
||||
envelope_upright(&mesh).is_some_and(|(r, c, read)| (r as usize, c as usize) == (rows, cols) && read == pts)
|
||||
}
|
||||
|
||||
/// The grid a top object with outline `path` and corners `corners` is written with: its edge runs
|
||||
/// through the outline's anchors clockwise from the top left corner, one grid edge to a segment, so
|
||||
/// the top and bottom sides need as many segments as each other, as do the left and right sides;
|
||||
/// the points inside blend the sides. `None` where that grid's edge, read back as the top object's
|
||||
/// outline, doesn't give the same patch ([`Coons::from_top_object`]) at every place checked.
|
||||
fn top_object_grid(path: &PathData, corners: Option<[u32; 4]>) -> Option<(usize, usize, Vec<GridPoint>)> {
|
||||
let coons = Coons::from_top_object(path, corners)?;
|
||||
// The outline, as the patch takes it: the largest subpath.
|
||||
let mut sp = path.subpaths.iter().filter(|s| s.anchors.len() >= 2).max_by(|a, b| a.area().abs().total_cmp(&b.area().abs()))?.clone();
|
||||
let count = sp.anchors.len();
|
||||
let empty = |i: usize| {
|
||||
let c = sp.segment(i);
|
||||
[c.p1, c.p2, c.p3].iter().all(|p| p.distance(c.p0) <= 1e-9)
|
||||
};
|
||||
if !sp.closed || count < 4 || (0..count).any(empty) {
|
||||
return None;
|
||||
}
|
||||
let fits = |c: &[usize; 4]| {
|
||||
c.iter().all(|i| *i < count) && {
|
||||
let gaps = (0..4).map(|k| (c[(k + 1) % 4] + count - c[k]) % count);
|
||||
gaps.clone().all(|g| g > 0) && gaps.sum::<usize>() == count
|
||||
}
|
||||
};
|
||||
// Stored corners that fit keep the outline as drawn; otherwise it runs clockwise, and the
|
||||
// corners are the anchors the patch's corners lie on.
|
||||
let at = match corners.map(|c| c.map(|i| i as usize)).filter(fits) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
if sp.signed_area() < 0.0 {
|
||||
sp.reverse();
|
||||
}
|
||||
let find = |q: Point| sp.anchors.iter().position(|a| a.p.distance(q) <= 1e-9);
|
||||
let [tl, tr, br, bl] = coons.corners();
|
||||
let c = [find(tl)?, find(tr)?, find(br)?, find(bl)?];
|
||||
if !fits(&c) {
|
||||
return None;
|
||||
}
|
||||
c
|
||||
}
|
||||
};
|
||||
let gap = |k: usize| (at[(k + 1) % 4] + count - at[k]) % count;
|
||||
let (cols, rows) = (gap(0), gap(1));
|
||||
if gap(2) != cols || gap(3) != rows || cols > MAX_GRID || rows > MAX_GRID {
|
||||
return None;
|
||||
}
|
||||
let width = cols + 1;
|
||||
let mut pts: Vec<GridPoint> = vec![(Point::ZERO, [Vec2::ZERO; 4]); (rows + 1) * width];
|
||||
// Where the `k`th anchor from the top left corner goes, and the slots of the handles of the
|
||||
// segment from it to the next anchor: its own, and the next anchor's back.
|
||||
let place = |k: usize| -> (usize, usize, usize, usize) {
|
||||
if k < cols {
|
||||
(0, k, H_RIGHT, H_LEFT)
|
||||
} else if k < cols + rows {
|
||||
(k - cols, cols, H_DOWN, H_UP)
|
||||
} else if k < 2 * cols + rows {
|
||||
(rows, cols - (k - cols - rows), H_LEFT, H_RIGHT)
|
||||
} else {
|
||||
(rows - (k - 2 * cols - rows), 0, H_UP, H_DOWN)
|
||||
}
|
||||
};
|
||||
for k in 0..count {
|
||||
let i = (at[0] + k) % count;
|
||||
let seg = sp.segment(i);
|
||||
// A straight segment's patch spreads evenly along it, as a cubic's with its handles a third
|
||||
// of the way does.
|
||||
let (p1, p2) = if sp.segment_is_line(i) { (seg.p0.lerp(seg.p3, 1.0 / 3.0), seg.p0.lerp(seg.p3, 2.0 / 3.0)) } else { (seg.p1, seg.p2) };
|
||||
let (r, c, out, into) = place(k);
|
||||
let (nr, nc, _, _) = place((k + 1) % count);
|
||||
if let Some(q) = pts.get_mut(r * width + c) {
|
||||
q.0 = seg.p0;
|
||||
q.1[out] = p1 - seg.p0;
|
||||
}
|
||||
if let Some(q) = pts.get_mut(nr * width + nc) {
|
||||
q.1[into] = p2 - seg.p3;
|
||||
}
|
||||
}
|
||||
// The points inside, blended from the sides.
|
||||
let edge = |r: usize, c: usize| pts.get(r * width + c).map_or(Point::ZERO, |q| q.0).to_vec2();
|
||||
let mut inside = vec![];
|
||||
for r in 1..rows {
|
||||
for c in 1..cols {
|
||||
let (u, v) = (c as f64 / cols as f64, r as f64 / rows as f64);
|
||||
let p = (1.0 - v) * edge(0, c) + v * edge(rows, c) + (1.0 - u) * edge(r, 0) + u * edge(r, cols)
|
||||
- ((1.0 - u) * (1.0 - v) * edge(0, 0) + u * (1.0 - v) * edge(0, cols) + (1.0 - u) * v * edge(rows, 0) + u * v * edge(rows, cols));
|
||||
inside.push((r * width + c, p.to_point()));
|
||||
}
|
||||
}
|
||||
for (i, p) in inside {
|
||||
if let Some(q) = pts.get_mut(i) {
|
||||
q.0 = p;
|
||||
}
|
||||
}
|
||||
if !pts.iter().all(|(p, h)| p.is_finite() && h.iter().all(|h| h.is_finite())) || !reads_as_written(rows, cols, &pts) {
|
||||
return None;
|
||||
}
|
||||
// The top object the reader makes of the grid: its edge, with the corners of the grid.
|
||||
let outline = envelope_outline(rows as u32, cols as u32, &pts)?;
|
||||
let corners = [0, cols, cols + rows, 2 * cols + rows].map(|c| c as u32);
|
||||
let read = Coons::from_top_object(&outline, Some(corners))?;
|
||||
let [tl, tr, br, bl] = coons.corners();
|
||||
let reach = tl.distance(br).max(tr.distance(bl)).max(1.0) * TOP_OBJECT_TOLERANCE;
|
||||
const STEPS: usize = 8;
|
||||
let at = |i: usize| i as f64 / STEPS as f64;
|
||||
let same = (0..=STEPS).all(|j| (0..=STEPS).all(|i| coons.eval(at(i), at(j)).distance(read.eval(at(i), at(j))) <= reach));
|
||||
same.then_some((rows, cols, pts))
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Envelope `n`, of transparency `xy`, as a live envelope (see the module's form), outside opacity
|
||||
/// masks' art, pattern tiles, art cut to a clipping object and the layers of a large canvas. False,
|
||||
/// writing nothing, where it is written as its art instead: where the reader would open it in
|
||||
/// another shape, or some of it is left out for the object limit ([`Self::take_objects`]).
|
||||
pub(super) fn envelope(&mut self, n: &Node, xy: Xy) -> bool {
|
||||
let NodeKind::Envelope { content, kind, fidelity, editing, options, frame } = &n.kind else { return false };
|
||||
if self.hidden > 0 || self.clip.is_some() || self.nest >= MAX_NEST || !self.symbols_live || self.envelopes_left == 0 {
|
||||
return false;
|
||||
}
|
||||
let Some(record) = record(n, content, kind, *fidelity, *editing, options, **frame) else { return false };
|
||||
let start = self.body.len();
|
||||
let (state, gs, charges, bound) = (self.state, self.gs, self.charges(), self.bound.len());
|
||||
self.nest += 1;
|
||||
self.hidden += 1;
|
||||
// The group before the dictionary: the grid, or the contents while they are edited.
|
||||
let outer = std::mem::take(&mut self.body);
|
||||
let opened = self.open_group("u");
|
||||
if opened {
|
||||
if *editing {
|
||||
self.contents(content);
|
||||
} else {
|
||||
self.grid(record.grid.as_ref());
|
||||
}
|
||||
self.line("U");
|
||||
}
|
||||
let before = std::mem::replace(&mut self.body, outer);
|
||||
hide(&before, &mut self.body);
|
||||
self.body.push_str("%_/ArtDictionary :\n");
|
||||
hide(&record.keys, &mut self.body);
|
||||
self.body.push_str("%_X=\n");
|
||||
// The dictionary's art starts unlocked, shown and opaque, as an opacity mask's does.
|
||||
let outer = std::mem::take(&mut self.body);
|
||||
let at_block = self.state;
|
||||
(self.state, self.gs) = (Some((false, false)), Some(Xy::OPAQUE));
|
||||
if *editing {
|
||||
self.grid(record.grid.as_ref());
|
||||
} else if self.open_group("u") {
|
||||
self.contents(content);
|
||||
self.end_group("U", Xy::PLAIN);
|
||||
}
|
||||
let block = std::mem::replace(&mut self.body, outer);
|
||||
hide(&block, &mut self.body);
|
||||
(self.state, self.gs, self.block_end) = (at_block, None, usize::MAX);
|
||||
let _ = writeln!(self.body, "%_X+\n%_ (AIDeformArtKey) ,\n%_{} /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW", record.style);
|
||||
self.hidden -= 1;
|
||||
self.nest -= 1;
|
||||
// The distorted art, which takes the envelope's lock, visibility, transparency, name and
|
||||
// opacity mask.
|
||||
self.state(n.locked, !n.visible);
|
||||
self.drawn_art(n, xy, None);
|
||||
if !opened || self.left_out_since(charges) {
|
||||
let lines = self.body.split_off(start);
|
||||
self.give_back(charges, &lines);
|
||||
self.bound.truncate(bound);
|
||||
(self.state, self.gs, self.block_end) = (state, gs, usize::MAX);
|
||||
return false;
|
||||
}
|
||||
self.deform = true;
|
||||
self.envelopes_left -= 1;
|
||||
true
|
||||
}
|
||||
|
||||
/// An envelope's contents.
|
||||
fn contents(&mut self, content: &[Arc<Node>]) {
|
||||
for c in content {
|
||||
self.node(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its
|
||||
/// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners
|
||||
/// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle
|
||||
/// towards the previous one and a weight, in art space), from its top left one down, across and
|
||||
/// up, and `/E`. One object.
|
||||
fn grid(&mut self, grid: Option<&(usize, usize, Vec<GridPoint>)>) {
|
||||
let Some((rows, cols, pts)) = grid else { return };
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
let (rows, cols, width) = (*rows, *cols, cols + 1);
|
||||
let to_art = self.to_art;
|
||||
let s = &mut self.body;
|
||||
let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#");
|
||||
let num = |s: &mut String, v: f64| {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
};
|
||||
for c in 0..cols {
|
||||
for r in 0..rows {
|
||||
let _ = writeln!(s, "[{c} {r}] /P X#");
|
||||
// Each corner with the slots of its handles towards the next corner and the previous one.
|
||||
let corners = [((r, c), H_DOWN, H_RIGHT), ((r + 1, c), H_RIGHT, H_UP), ((r + 1, c + 1), H_UP, H_LEFT), ((r, c + 1), H_LEFT, H_DOWN)];
|
||||
for ((pr, pc), next, prev) in corners {
|
||||
let (p, h) = pts.get(pr * width + pc).copied().unwrap_or((Point::ZERO, [Vec2::ZERO; 4]));
|
||||
let at = |v: Vec2| to_art * (p + v);
|
||||
s.push_str("[0 1");
|
||||
for q in [at(Vec2::ZERO), at(h[next])] {
|
||||
num(s, q.x);
|
||||
num(s, q.y);
|
||||
}
|
||||
s.push_str(" 1");
|
||||
let q = at(h[prev]);
|
||||
num(s, q.x);
|
||||
num(s, q.y);
|
||||
s.push_str(" 1] /N X#\n");
|
||||
}
|
||||
s.push_str("/E X#\n");
|
||||
}
|
||||
}
|
||||
s.push_str("/End X!\n");
|
||||
}
|
||||
}
|
||||
@@ -82,12 +82,15 @@ use graphics::{GState, Out};
|
||||
use interp::{Fault, Interp};
|
||||
use obj::PsError;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::ENVELOPE_DRAWN;
|
||||
pub use ai::NameEncoding;
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::objects_read;
|
||||
pub(crate) use ai::{
|
||||
BRUSH_MANAGER, BrushesRead, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept,
|
||||
read_art_style, read_brush_object, read_style_list, style_moves_with, symbol_art_member, warp_number,
|
||||
BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS,
|
||||
MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object,
|
||||
read_style_list, style_moves_with, symbol_art_member, 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};
|
||||
|
||||
@@ -36,9 +36,9 @@ use crate::ps;
|
||||
|
||||
pub(crate) use brush::{BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object};
|
||||
pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN;
|
||||
#[cfg(test)]
|
||||
pub(crate) use envelope::MAX_CHECKED;
|
||||
pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN;
|
||||
pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright};
|
||||
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
|
||||
pub(crate) use frames::text_frames;
|
||||
pub use obj::{NameEncoding, Names};
|
||||
|
||||
@@ -41,7 +41,7 @@ use super::obj::Obj;
|
||||
use crate::import::native::compare::{MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, compare_scale, differ, differ_in_colour, differ_on_black};
|
||||
|
||||
/// The plugin that writes envelopes.
|
||||
pub(super) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use
|
||||
pub(crate) const PLUGIN: &str = "Adobe Deform Plugin"; // brand-ok: the plugin name the files use
|
||||
/// The note for an envelope that keeps its drawn art.
|
||||
pub(crate) const DRAWN: &str = "an envelope VectorCraft couldn't read as a live envelope comes in as its drawn art";
|
||||
/// The note for an envelope of type, which keeps its drawn art with its type hidden (unless the
|
||||
@@ -366,12 +366,12 @@ fn only_mesh(n: &Node) -> Option<&GradientMesh> {
|
||||
}
|
||||
|
||||
/// A grid point and its handles.
|
||||
type GridPoint = (Point, [Vec2; 4]);
|
||||
pub(crate) type GridPoint = (Point, [Vec2; 4]);
|
||||
|
||||
/// The points of mesh `m` as a `rows`×`cols` grid with its first row at the top and its first
|
||||
/// column at the left (y down), as an envelope's mesh lays them out; `None` for a grid out of range
|
||||
/// or with points that aren't finite.
|
||||
fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> {
|
||||
pub(crate) fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> {
|
||||
let (mut rows, mut cols) = (m.rows, m.cols);
|
||||
if rows == 0 || cols == 0 || rows > MAX_GRID || cols > MAX_GRID {
|
||||
return None;
|
||||
@@ -451,7 +451,7 @@ fn upright(m: &GradientMesh) -> Option<(u32, u32, Vec<GridPoint>)> {
|
||||
}
|
||||
|
||||
/// The outline of an upright grid: its edge, clockwise from the top left corner.
|
||||
fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option<PathData> {
|
||||
pub(crate) fn outline(rows: u32, cols: u32, pts: &[GridPoint]) -> Option<PathData> {
|
||||
let at = |r: u32, c: u32| pts.get((r * (cols + 1) + c) as usize).copied();
|
||||
// Each edge: from a point by one of its handles to the next point by one of its handles.
|
||||
type Edge = ((u32, u32), usize, (u32, u32), usize);
|
||||
|
||||
@@ -7730,6 +7730,55 @@ fn a_top_object_envelope_opens_live_with_its_outline() {
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A top object whose saved grid has three patches across, its top edge one curve split into
|
||||
/// thirds, maps its contents along that one curve. In this synthetic file the drawn art is drawn by
|
||||
/// VectorCraft's own map of the unsplit curve, so the envelope opens live only when the split side
|
||||
/// maps the same way, and the contents' first quarter ends a quarter of the way along the curve.
|
||||
#[test]
|
||||
fn a_top_object_whose_top_is_one_curve_split_in_thirds_opens_live() {
|
||||
use kurbo::{CubicBez, ParamCurve};
|
||||
use vectorcraft_doc::live::EnvelopeKind;
|
||||
// In the document: the top runs from (40, 20) to (160, 20), its parameter fast at the start.
|
||||
let top = CubicBez::new((40.0, 20.0), (112.0, -16.0), (154.0, 2.0), (160.0, 20.0));
|
||||
let thirds = [top.subsegment(0.0..1.0 / 3.0), top.subsegment(1.0 / 3.0..2.0 / 3.0), top.subsegment(2.0 / 3.0..1.0)];
|
||||
// Art space has y up: row 1 is the top. The bottom row and the columns are straight.
|
||||
let up = |p: Point| (p.x, 100.0 - p.y);
|
||||
let at = move |(i, j): (usize, usize)| {
|
||||
if j == 1 { up(if i == 0 { top.p0 } else { thirds[i - 1].p3 }) } else { (40.0 + 40.0 * i as f64, 20.0) }
|
||||
};
|
||||
let handle = move |p: (usize, usize), q: (usize, usize)| match (p, q) {
|
||||
((i, 1), (k, 1)) if k == i + 1 => up(thirds[i].p1),
|
||||
((i, 1), (k, 1)) if k + 1 == i => up(thirds[k].p2),
|
||||
_ => {
|
||||
let ((x, y), (u, v)) = (at(p), at(q));
|
||||
(x + (u - x) / 3.0, y + (v - y) / 3.0)
|
||||
}
|
||||
};
|
||||
let shape = mesh_text(3, 1, &at, &handle, None);
|
||||
// The contents: two red bars at the box's left and right ends, drawn by the unsplit curve.
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
bp.move_to(top.p0);
|
||||
bp.curve_to(top.p1, top.p2, top.p3);
|
||||
bp.line_to((160.0, 80.0));
|
||||
bp.line_to((40.0, 80.0));
|
||||
bp.close_path();
|
||||
let one_curve = EnvelopeKind::TopObject { path: vectorcraft_geom::PathData::from_bezpath(&bp), corners: Some([0, 1, 2, 3]) };
|
||||
let src = Rect::new(40.0, 20.0, 160.0, 80.0);
|
||||
let bars = [Rect::new(40.0, 20.0, 70.0, 80.0), Rect::new(130.0, 20.0, 160.0, 80.0)];
|
||||
let content: String = bars.iter().map(|b| format!("{RED}{}f\n", rect_path(b.x0, b.y0, b.x1, b.y1))).collect();
|
||||
let drawn: String = bars.iter().map(|b| drawn_box(&one_curve, src, *b)).collect();
|
||||
let r = read_ok(&layer(&envelope_of(&shape, ENVELOPE_KEYS, &content, 3, &drawn)));
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let a = art(&r.doc);
|
||||
assert_eq!(a.len(), 1, "{a:#?}");
|
||||
let (_, kind, ..) = live_envelope(&a[0]);
|
||||
let EnvelopeKind::TopObject { path, .. } = kind else { panic!("{kind:?}") };
|
||||
assert_eq!(path.anchor_count(), 8, "{path:?}");
|
||||
let map = vectorcraft_doc::live::envelope_mapper(kind, src);
|
||||
let (p, want) = (map(Point::new(70.0, 20.0)), top.eval(0.25));
|
||||
assert!((p - want).hypot() < 0.02, "{p:?}, want {want:?}");
|
||||
}
|
||||
|
||||
/// Envelope Options come from the options word, Fidelity from its own key.
|
||||
#[test]
|
||||
fn an_envelope_reads_its_options_and_fidelity() {
|
||||
|
||||
+228
-49
@@ -55,8 +55,99 @@ const MAX_DEVICE_N: usize = 32;
|
||||
const MISSING_PATTERN: &str = "missing patterns are written as mid-grey";
|
||||
const TOO_LARGE: &str = "the artwork is too large for EPS: what follows 256 MB of PostScript was left out";
|
||||
/// The most PostScript the page body may grow to: symbols and patterns that hold one another
|
||||
/// expand into every instance, so nesting depth alone doesn't bound the output.
|
||||
/// expand into every instance, so nesting depth alone doesn't bound the output. An image placed
|
||||
/// more than once counts its data once.
|
||||
const MAX_BODY: usize = 256 << 20;
|
||||
/// Most compressed bytes in one string of an image's samples at Level 2 (under PostScript's
|
||||
/// 65,535-byte string limit).
|
||||
const IMAGE_CHUNK: usize = 48 << 10;
|
||||
/// The start of the procedure that reads an image's data from the lines after it.
|
||||
const INLINE_SOURCE: &str = "{ /VCsrc currentfile /ASCII85Decode filter def\n";
|
||||
|
||||
/// An image as written: what sets up its color, its image dictionary and its compressed samples.
|
||||
/// Placed once, it is written where it is drawn, its data following the operators that read it.
|
||||
/// Placed more than once, its samples are written once in the setup as `VCim<i>` (a reusable
|
||||
/// stream at Level 3, an array of strings at Level 2) and each placement reads them from there.
|
||||
struct ImageCode {
|
||||
/// The color space or ink operators, each line ending in a line break.
|
||||
prelude: String,
|
||||
/// `<< /ImageType … /ImageMatrix […]` with its mask colors: the dictionary up to its data source.
|
||||
dict: String,
|
||||
/// The decoding filter of the samples: `/FlateDecode` or `/RunLengthDecode`.
|
||||
filter: &'static str,
|
||||
/// `image` or `imagemask`.
|
||||
op: &'static str,
|
||||
/// The compressed samples in ASCII85, as lines with the end marker.
|
||||
ascii: String,
|
||||
/// The compressed samples, kept at Level 2, where a reused image's samples are written as
|
||||
/// strings of at most [`IMAGE_CHUNK`] bytes.
|
||||
data: Vec<u8>,
|
||||
/// How many placements in the page draw it.
|
||||
uses: usize,
|
||||
/// The length of [`ImageCode::push_inline`]'s text.
|
||||
inline_len: usize,
|
||||
/// The length of [`ImageCode::reference`]'s text.
|
||||
ref_len: usize,
|
||||
}
|
||||
|
||||
impl ImageCode {
|
||||
/// The operators and data that draw the image where it is placed.
|
||||
fn push_inline(&self, s: &mut String) {
|
||||
s.push_str(&self.prelude);
|
||||
s.push_str(INLINE_SOURCE);
|
||||
s.push_str(&self.dict);
|
||||
s.push_str(&self.inline_read());
|
||||
s.push_str(&self.ascii);
|
||||
}
|
||||
|
||||
/// The end of the procedure [`ImageCode::push_inline`] writes. The procedure is read whole
|
||||
/// before it runs: the image data follows it, and flushing the ASCII85 filter afterwards reads
|
||||
/// past its end marker.
|
||||
fn inline_read(&self) -> String {
|
||||
format!("\n/DataSource VCsrc {} filter >> {}\nVCsrc flushfile }} exec\n", self.filter, self.op)
|
||||
}
|
||||
|
||||
/// The operators that draw the image `VCim<i>` holds, for an image placed more than once.
|
||||
fn reference(&self, i: usize, level: Level) -> String {
|
||||
match level {
|
||||
// The stream is read again from its start.
|
||||
Level::Three => {
|
||||
format!("{}VCim{i} resetfile\n{}\n/DataSource VCim{i} {} filter >> {}\n", self.prelude, self.dict, self.filter, self.op)
|
||||
}
|
||||
// A procedure gives the strings in turn, then an empty string: the end of the data.
|
||||
Level::Two => format!(
|
||||
"{}/VCi 0 def\n{}\n/DataSource {{VCi VCim{i} length lt {{VCim{i} VCi get /VCi VCi 1 add def}} {{()}} ifelse}} {} filter >> {}\n",
|
||||
self.prelude, self.dict, self.filter, self.op
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The setup's definition of `VCim<i>`: the image's compressed samples, once.
|
||||
fn resource(&self, i: usize, level: Level) -> String {
|
||||
let mut s = String::with_capacity(self.ascii.len() + 200);
|
||||
match level {
|
||||
Level::Three => {
|
||||
// The stream reads all of its data when it is made, so the data follows the
|
||||
// procedure that makes it.
|
||||
let intent = if self.op == "imagemask" { 1 } else { 0 };
|
||||
let _ = writeln!(
|
||||
s,
|
||||
"{{ /VCsrc currentfile /ASCII85Decode filter def\n/VCim{i} VCsrc << /Intent {intent} /AsyncRead false /CloseSource false >> /ReusableStreamDecode filter def\nVCsrc flushfile }} exec"
|
||||
);
|
||||
s.push_str(&self.ascii);
|
||||
}
|
||||
Level::Two => {
|
||||
let _ = writeln!(s, "/VCim{i} [");
|
||||
for chunk in self.data.chunks(IMAGE_CHUNK) {
|
||||
s.push_str("<~");
|
||||
s.push_str(&ps::ascii85(chunk));
|
||||
}
|
||||
s.push_str("] def\n");
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// What the walk wrote: definitions for the setup, the page, the spot colours it uses (name and
|
||||
/// CMYK equivalent) and the warnings.
|
||||
@@ -157,10 +248,18 @@ pub(crate) struct Scene<'a> {
|
||||
device_n: Vec<String>,
|
||||
warnings: Vec<String>,
|
||||
brushes: Option<Vec<vectorcraft_brush::Brush>>,
|
||||
/// Image keys → what draws them (`None`: left out).
|
||||
images: HashMap<String, Option<Arc<String>>>,
|
||||
/// Image keys → the index in `codes` of what draws them (`None`: left out).
|
||||
images: HashMap<String, Option<usize>>,
|
||||
/// The source key and solid paint together identify a colorized encoding.
|
||||
colorized_images: HashMap<(String, String), Option<Arc<String>>>,
|
||||
colorized_images: HashMap<(String, String), Option<usize>>,
|
||||
/// The encoded images.
|
||||
codes: Vec<ImageCode>,
|
||||
/// Where in `body` each placement of an encoded image goes (in order) and the index of its code.
|
||||
placements: Vec<(usize, usize)>,
|
||||
/// What the placements in `placements` add to `body`'s length when the page is finished.
|
||||
pending: usize,
|
||||
/// The most the page body may grow to ([`MAX_BODY`]).
|
||||
max_body: usize,
|
||||
/// Symbols and brush art being written inside one another.
|
||||
nest: u32,
|
||||
}
|
||||
@@ -181,10 +280,21 @@ impl<'a> Scene<'a> {
|
||||
brushes: None,
|
||||
images: HashMap::new(),
|
||||
colorized_images: HashMap::new(),
|
||||
codes: vec![],
|
||||
placements: vec![],
|
||||
pending: 0,
|
||||
max_body: MAX_BODY,
|
||||
nest: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// This scene with a page body of at most `max` bytes.
|
||||
#[cfg(test)]
|
||||
pub fn with_max_body(mut self, max: usize) -> Self {
|
||||
self.max_body = max;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn run(mut self) -> Page {
|
||||
let doc = self.doc;
|
||||
for l in &doc.layers {
|
||||
@@ -199,7 +309,27 @@ impl<'a> Scene<'a> {
|
||||
self.page()
|
||||
}
|
||||
|
||||
fn page(self) -> Page {
|
||||
fn page(mut self) -> Page {
|
||||
if !self.placements.is_empty() {
|
||||
let level = self.o.level;
|
||||
let mut body = String::with_capacity(self.body.len().saturating_add(self.pending));
|
||||
let mut at = 0;
|
||||
for &(offset, i) in &self.placements {
|
||||
body.push_str(self.body.get(at..offset).unwrap_or_default());
|
||||
at = offset;
|
||||
let Some(code) = self.codes.get(i) else { continue };
|
||||
if code.uses > 1 {
|
||||
body.push_str(&code.reference(i, level));
|
||||
} else {
|
||||
code.push_inline(&mut body);
|
||||
}
|
||||
}
|
||||
body.push_str(self.body.get(at..).unwrap_or_default());
|
||||
self.body = body;
|
||||
for (i, code) in self.codes.iter().enumerate().filter(|(_, c)| c.uses > 1) {
|
||||
self.setup.push_str(&code.resource(i, level));
|
||||
}
|
||||
}
|
||||
let custom = self
|
||||
.spots
|
||||
.iter()
|
||||
@@ -337,7 +467,7 @@ impl<'a> Scene<'a> {
|
||||
if let NodeKind::Layer { template: true, .. } = n.kind {
|
||||
return;
|
||||
}
|
||||
if self.body.len() >= MAX_BODY {
|
||||
if self.size() >= self.max_body {
|
||||
self.warn(TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
@@ -347,7 +477,7 @@ impl<'a> Scene<'a> {
|
||||
_ => {}
|
||||
}
|
||||
self.note_losses(n);
|
||||
let was = self.body.len();
|
||||
let (was, placed) = (self.body.len(), self.placements.len());
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => {
|
||||
children.iter().for_each(|c| self.node(c, false));
|
||||
@@ -402,12 +532,29 @@ impl<'a> Scene<'a> {
|
||||
// Ruler guides draw on screen only.
|
||||
NodeKind::RulerGuide { .. } => {}
|
||||
}
|
||||
if self.body.len() > MAX_BODY {
|
||||
if self.size() > self.max_body {
|
||||
self.body.truncate(was);
|
||||
self.unplace(placed);
|
||||
self.warn(TOO_LARGE);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long the page body will be: what is written and what its image placements add.
|
||||
fn size(&self) -> usize {
|
||||
self.body.len().saturating_add(self.pending)
|
||||
}
|
||||
|
||||
/// Take back the image placements after the first `n`, last first.
|
||||
fn unplace(&mut self, n: usize) {
|
||||
while self.placements.len() > n {
|
||||
let Some((_, i)) = self.placements.pop() else { break };
|
||||
let Some(code) = self.codes.get_mut(i) else { continue };
|
||||
code.uses = code.uses.saturating_sub(1);
|
||||
let cost = if code.uses == 0 { code.inline_len } else { code.ref_len };
|
||||
self.pending = self.pending.saturating_sub(cost);
|
||||
}
|
||||
}
|
||||
|
||||
/// A clipping group: the art inside its first child's outline. The clipping path's fills
|
||||
/// paint behind the art (clipped) and its strokes over it (not clipped).
|
||||
fn clip_group(&mut self, children: &[Arc<Node>]) {
|
||||
@@ -1229,7 +1376,7 @@ impl<'a> Scene<'a> {
|
||||
};
|
||||
let place = Affine::translate(area.origin().to_vec2()) * Affine::scale_non_uniform(area.width(), area.height());
|
||||
if let Some(image) = image {
|
||||
self.place_image(&image, place);
|
||||
self.place_inline(&image, place);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1241,18 +1388,29 @@ impl<'a> Scene<'a> {
|
||||
return;
|
||||
}
|
||||
let encoded = match self.images.get(key) {
|
||||
Some(e) => e.clone(),
|
||||
Some(e) => *e,
|
||||
None => {
|
||||
let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(Arc::new);
|
||||
self.images.insert(key.to_string(), e.clone());
|
||||
let e = self.decode_image(blob).and_then(|img| self.encode_image(img.as_raw(), img.width(), img.height())).map(|c| self.add_code(c));
|
||||
self.images.insert(key.to_string(), e);
|
||||
e
|
||||
}
|
||||
};
|
||||
if let Some(e) = encoded {
|
||||
self.place_image(&e, place);
|
||||
if let Some(i) = encoded {
|
||||
self.place_image(i, place);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep `code` for the placements that draw it: its index in `codes`.
|
||||
fn add_code(&mut self, mut code: ImageCode) -> usize {
|
||||
let i = self.codes.len();
|
||||
if self.o.level == Level::Three {
|
||||
code.data = vec![];
|
||||
}
|
||||
code.ref_len = code.reference(i, self.o.level).len();
|
||||
self.codes.push(code);
|
||||
i
|
||||
}
|
||||
|
||||
/// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil;
|
||||
/// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2.
|
||||
fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) {
|
||||
@@ -1262,19 +1420,19 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
let cache = (key.to_string(), format!("{paint:?}"));
|
||||
let encoded = match self.colorized_images.get(&cache) {
|
||||
Some(e) => e.clone(),
|
||||
Some(e) => *e,
|
||||
None => {
|
||||
let e = self.encode_colorized(blob, paint).map(Arc::new);
|
||||
self.colorized_images.insert(cache, e.clone());
|
||||
let e = self.encode_colorized(blob, paint).map(|c| self.add_code(c));
|
||||
self.colorized_images.insert(cache, e);
|
||||
e
|
||||
}
|
||||
};
|
||||
if let Some(e) = encoded {
|
||||
self.place_image(&e, place);
|
||||
if let Some(i) = encoded {
|
||||
self.place_image(i, place);
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option<String> {
|
||||
fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option<ImageCode> {
|
||||
let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else {
|
||||
self.warn(UNDECODED);
|
||||
return None;
|
||||
@@ -1355,17 +1513,17 @@ impl<'a> Scene<'a> {
|
||||
("/RunLengthDecode", rl)
|
||||
}
|
||||
};
|
||||
let mut out = String::new();
|
||||
let mut prelude = String::new();
|
||||
if binary {
|
||||
// imagemask takes its current ink from the graphics state.
|
||||
out.push_str(&self.ink_code(ink));
|
||||
prelude.push_str(&self.ink_code(ink));
|
||||
} else {
|
||||
match ink {
|
||||
Ink::Spot { space, .. } => {
|
||||
let _ = writeln!(out, "VCsp{space} setcolorspace");
|
||||
let _ = writeln!(prelude, "VCsp{space} setcolorspace");
|
||||
}
|
||||
Ink::Process(space, ..) => {
|
||||
let _ = writeln!(out, "{} setcolorspace", space.name());
|
||||
let _ = writeln!(prelude, "{} setcolorspace", space.name());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1374,19 +1532,16 @@ impl<'a> Scene<'a> {
|
||||
Ink::Process(space, ..) => space.n(),
|
||||
};
|
||||
let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() };
|
||||
let _ = write!(
|
||||
out,
|
||||
"{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]",
|
||||
let mut dict = format!(
|
||||
"<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]",
|
||||
if keyed { 4 } else { 1 },
|
||||
if binary { 1 } else { 8 },
|
||||
);
|
||||
if keyed {
|
||||
let mask: Vec<String> = key.iter().take(n).map(|v| format!("{v} {v}")).collect();
|
||||
let _ = write!(out, " /MaskColor [{}]", mask.join(" "));
|
||||
let _ = write!(dict, " /MaskColor [{}]", mask.join(" "));
|
||||
}
|
||||
let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> {}\nVCsrc flushfile }} exec", if binary { "imagemask" } else { "image" });
|
||||
out.push_str(&ps::ascii85(&encoded));
|
||||
Some(out)
|
||||
Some(image_code(prelude, dict, filter, if binary { "imagemask" } else { "image" }, encoded))
|
||||
}
|
||||
|
||||
/// Ink-setting operators in the cached stencil body, built with the same path as solid fills.
|
||||
@@ -1409,18 +1564,40 @@ impl<'a> Scene<'a> {
|
||||
Some(img.to_rgba8())
|
||||
}
|
||||
|
||||
/// Draw an image of [`Self::encode_image`] on the unit square mapped by `place`.
|
||||
fn place_image(&mut self, encoded: &str, place: Affine) {
|
||||
/// Draw the image of `codes[i]` on the unit square mapped by `place`. Its operators go in when
|
||||
/// the page is finished ([`Self::page`]), once it is known how many placements draw it.
|
||||
fn place_image(&mut self, i: usize, place: Affine) {
|
||||
if !invertible(place) {
|
||||
return;
|
||||
}
|
||||
if self.body.len().saturating_add(encoded.len()).saturating_add(64) > MAX_BODY {
|
||||
let Some(code) = self.codes.get(i) else { return };
|
||||
let cost = if code.uses == 0 { code.inline_len } else { code.ref_len };
|
||||
if self.size().saturating_add(cost).saturating_add(64) > self.max_body {
|
||||
self.warn(TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
self.line("q");
|
||||
let _ = writeln!(self.body, "{} cm", ps::matrix(place));
|
||||
self.body.push_str(encoded);
|
||||
self.placements.push((self.body.len(), i));
|
||||
self.pending = self.pending.saturating_add(cost);
|
||||
if let Some(code) = self.codes.get_mut(i) {
|
||||
code.uses += 1;
|
||||
}
|
||||
self.line("Q");
|
||||
}
|
||||
|
||||
/// Draw `code`, an image drawn nowhere else, on the unit square mapped by `place`.
|
||||
fn place_inline(&mut self, code: &ImageCode, place: Affine) {
|
||||
if !invertible(place) {
|
||||
return;
|
||||
}
|
||||
if self.size().saturating_add(code.inline_len).saturating_add(64) > self.max_body {
|
||||
self.warn(TOO_LARGE);
|
||||
return;
|
||||
}
|
||||
self.line("q");
|
||||
let _ = writeln!(self.body, "{} cm", ps::matrix(place));
|
||||
code.push_inline(&mut self.body);
|
||||
self.line("Q");
|
||||
}
|
||||
|
||||
@@ -1428,7 +1605,7 @@ impl<'a> Scene<'a> {
|
||||
/// them on the unit square: in the process colour space, transparent pixels masked out at
|
||||
/// Level 3 (a key colour no opaque pixel has), white at Level 2; partly transparent ones over
|
||||
/// white. `None` for an empty image.
|
||||
fn encode_image(&mut self, rgba: &[u8], w: u32, h: u32) -> Option<String> {
|
||||
fn encode_image(&mut self, rgba: &[u8], w: u32, h: u32) -> Option<ImageCode> {
|
||||
let space = if self.cmyk { Space::Cmyk } else { Space::Rgb };
|
||||
let mut cache: HashMap<[u8; 3], [u8; 4]> = HashMap::new();
|
||||
let cms = self.cms.clone();
|
||||
@@ -1447,7 +1624,7 @@ impl<'a> Scene<'a> {
|
||||
/// Straight CMYK pixels with opacity (five bytes a pixel, `w` × `h`, rows from the top), drawn
|
||||
/// as [`Self::encode_image`] draws its pixels and keeping their ink amounts: partly
|
||||
/// transparent pixels lay down that share of each ink.
|
||||
fn encode_inks(&mut self, cmyka: &[u8], w: u32, h: u32) -> Option<String> {
|
||||
fn encode_inks(&mut self, cmyka: &[u8], w: u32, h: u32) -> Option<ImageCode> {
|
||||
self.encode_samples(cmyka.as_chunks::<5>().0, w, h, Space::Cmyk, |p: &[u8; 5], al| {
|
||||
[0, 1, 2, 3].map(|i| ((u32::from(p[i]) * al + 127) / 255) as u8)
|
||||
})
|
||||
@@ -1463,7 +1640,7 @@ impl<'a> Scene<'a> {
|
||||
h: u32,
|
||||
space: Space,
|
||||
mut sample: impl FnMut(&[u8; N], u32) -> [u8; 4],
|
||||
) -> Option<String> {
|
||||
) -> Option<ImageCode> {
|
||||
if w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -1503,27 +1680,29 @@ impl<'a> Scene<'a> {
|
||||
("/RunLengthDecode", rl)
|
||||
}
|
||||
};
|
||||
let mut out = String::with_capacity(encoded.len() * 5 / 4 + 400);
|
||||
let _ = writeln!(out, "{} setcolorspace", space.name());
|
||||
let prelude = format!("{} setcolorspace\n", space.name());
|
||||
let decode = "0 1 ".repeat(n);
|
||||
let _ = write!(
|
||||
out,
|
||||
"{{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent 8 /Decode [{}] /ImageMatrix [{w} 0 0 {h} 0 0]",
|
||||
let mut dict = format!(
|
||||
"<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent 8 /Decode [{}] /ImageMatrix [{w} 0 0 {h} 0 0]",
|
||||
if keyed { 4 } else { 1 },
|
||||
decode.trim_end()
|
||||
);
|
||||
if keyed {
|
||||
let mask: Vec<String> = key.iter().take(n).map(|v| format!("{v} {v}")).collect();
|
||||
let _ = write!(out, " /MaskColor [{}]", mask.join(" "));
|
||||
let _ = write!(dict, " /MaskColor [{}]", mask.join(" "));
|
||||
}
|
||||
// The procedure is read whole before it runs: the image data follows it, and flushing the
|
||||
// ASCII85 filter afterwards reads past its end marker.
|
||||
let _ = writeln!(out, "\n/DataSource VCsrc {filter} filter >> image\nVCsrc flushfile }} exec");
|
||||
out.push_str(&ps::ascii85(&encoded));
|
||||
Some(out)
|
||||
Some(image_code(prelude, dict, filter, "image", encoded))
|
||||
}
|
||||
}
|
||||
|
||||
/// An image of `prelude`, `dict`, `filter` and `op` (see [`ImageCode`]) with compressed samples
|
||||
/// `data`, not yet placed.
|
||||
fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static str, data: Vec<u8>) -> ImageCode {
|
||||
let mut code = ImageCode { prelude, dict, filter, op, ascii: ps::ascii85(&data), data, uses: 0, inline_len: 0, ref_len: 0 };
|
||||
code.inline_len = code.prelude.len() + INLINE_SOURCE.len() + code.dict.len() + code.inline_read().len() + code.ascii.len();
|
||||
code
|
||||
}
|
||||
|
||||
/// `a` to `b` at `t`.
|
||||
fn mix(a: &[f32], b: &[f32], t: f32) -> Vec<f32> {
|
||||
a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect()
|
||||
|
||||
+232
-3
@@ -82,6 +82,17 @@ fn checked_page(ps: &str) -> String {
|
||||
}
|
||||
}
|
||||
'{' | '[' => stack.push(c),
|
||||
// An ASCII85 string: its digits are data.
|
||||
'<' if chars.peek() == Some(&'~') => {
|
||||
let mut last = ' ';
|
||||
loop {
|
||||
let c = chars.next().expect("ASCII85 string closes");
|
||||
if last == '~' && c == '>' {
|
||||
break;
|
||||
}
|
||||
last = c;
|
||||
}
|
||||
}
|
||||
'<' if chars.peek() == Some(&'<') => {
|
||||
chars.next();
|
||||
stack.push('<');
|
||||
@@ -679,15 +690,20 @@ fn png_doc() -> Document {
|
||||
for (x, _, p) in img.enumerate_pixels_mut() {
|
||||
*p = if x < 2 { image::Rgba([0, 200, 0, 255]) } else { image::Rgba([0, 0, 0, 0]) };
|
||||
}
|
||||
image_doc(&img, 10.0)
|
||||
}
|
||||
|
||||
/// A 200 × 200 pt document holding `img` as a PNG, its pixels `scale` points wide, at (10, 10).
|
||||
fn image_doc(img: &image::RgbaImage, scale: f64) -> Document {
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut d = Document::new(200.0, 200.0);
|
||||
d.images.insert("pic".into(), ImageBlob::new("image/png", png));
|
||||
let im = ImageObject {
|
||||
key: "pic".into(),
|
||||
width: 4,
|
||||
height: 2,
|
||||
xf: Affine::translate((10.0, 10.0)) * Affine::scale(10.0),
|
||||
width: img.width(),
|
||||
height: img.height(),
|
||||
xf: Affine::translate((10.0, 10.0)) * Affine::scale(scale),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
@@ -988,6 +1004,219 @@ fn uncolorized_image_stays_on_original_eps_path() {
|
||||
assert_eq!(page_of(&color, &opts(&color)), original);
|
||||
}
|
||||
|
||||
/// A copy of the first layer's object `i`, moved by `xf`, added on top.
|
||||
fn place_again(d: &mut Document, i: usize, xf: Affine) {
|
||||
let mut n = (*d.layers[0].children().unwrap()[i]).clone();
|
||||
n.id = d.alloc_id();
|
||||
if let NodeKind::Image(im) = &mut n.kind {
|
||||
im.xf = xf * im.xf;
|
||||
}
|
||||
d.insert(d.default_layer(), usize::MAX, n).unwrap();
|
||||
}
|
||||
|
||||
/// Pixels of noise, opaque.
|
||||
fn noise(w: u32, h: u32) -> image::RgbaImage {
|
||||
let mut seed = 1u32;
|
||||
image::RgbaImage::from_fn(w, h, |_, _| {
|
||||
let mut px = [255u8; 4];
|
||||
for v in &mut px[..3] {
|
||||
seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
|
||||
*v = (seed >> 16) as u8;
|
||||
}
|
||||
image::Rgba(px)
|
||||
})
|
||||
}
|
||||
|
||||
/// The pixels of each image an EPS file's page draws, read back from the page.
|
||||
fn imported_images(bytes: &[u8]) -> Vec<Vec<u8>> {
|
||||
fn walk(n: &Node, d: &Document, out: &mut Vec<Vec<u8>>) {
|
||||
if let NodeKind::Image(im) = &n.kind {
|
||||
out.push(image::load_from_memory(&d.images[&im.key].bytes).unwrap().to_rgba8().into_raw());
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(c, d, out);
|
||||
}
|
||||
}
|
||||
let r = import_with(bytes, false).unwrap();
|
||||
assert!(!r.preview, "{:?}", r.warnings);
|
||||
let mut out = vec![];
|
||||
for l in &r.document.layers {
|
||||
walk(l, &r.document, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The samples of an image placed more than once, from the setup that defines them: inflated at
|
||||
/// Level 3, each string run-length decoded in turn at Level 2.
|
||||
fn reused_samples(ps: &str, level: Level) -> Vec<u8> {
|
||||
let setup = &ps[ps.find("%%BeginSetup").unwrap()..ps.find("%%EndSetup").unwrap()];
|
||||
match level {
|
||||
Level::Three => ps::inflate(&image_data(setup), 1 << 28).unwrap(),
|
||||
Level::Two => {
|
||||
let mut data = vec![];
|
||||
for s in setup.split("<~").skip(1) {
|
||||
let chunk = ps::ascii85_decode(&s[..s.find("~>").unwrap() + 2]).unwrap();
|
||||
assert!(chunk.len() <= 65_535, "a string holds at most 65,535 bytes: {}", chunk.len());
|
||||
data.extend(chunk);
|
||||
}
|
||||
unpack(&data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The samples of a single image written where it is drawn.
|
||||
fn inline_samples(ps: &str, level: Level) -> Vec<u8> {
|
||||
match level {
|
||||
Level::Three => ps::inflate(&image_data(ps), 1 << 28).unwrap(),
|
||||
Level::Two => unpack(&image_data(ps)),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many placements draw the image the setup defines as `VCim<i>`.
|
||||
fn reuses(ps: &str, i: usize, level: Level) -> usize {
|
||||
match level {
|
||||
Level::Three => ps.matches(&format!("VCim{i} resetfile\n")).count(),
|
||||
Level::Two => ps.matches(&format!("{{VCi VCim{i} length lt")).count(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_placed_twice_writes_its_samples_once_at_both_levels() {
|
||||
let single = png_doc();
|
||||
let mut d = single.clone();
|
||||
place_again(&mut d, 0, Affine::translate((60.0, 80.0)) * Affine::rotate(0.5));
|
||||
for level in Level::ALL {
|
||||
let one = export(&single, &EpsOptions { level, ..opts(&single) }, None, None).unwrap();
|
||||
let one_ps = text(&one);
|
||||
assert!(!one_ps.contains("VCim"), "an image placed once is written where it is drawn: {one_ps}");
|
||||
let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap();
|
||||
let ps = text(&out);
|
||||
checked_page(&ps);
|
||||
assert_eq!(reuses(&ps, 0, level), 2, "{ps}");
|
||||
assert!(!ps.contains("VCim1"), "{ps}");
|
||||
let body = &ps[ps.find("%%EndSetup").unwrap()..];
|
||||
assert!(!body.contains("currentfile") && !body.contains("~>"), "no samples in the page: {ps}");
|
||||
match level {
|
||||
Level::Three => {
|
||||
assert_eq!(ps.matches("/ReusableStreamDecode filter def").count(), 1, "{ps}");
|
||||
assert!(ps.contains("/Intent 0 /AsyncRead false /CloseSource false"), "{ps}");
|
||||
assert!(body.contains("/DataSource VCim0 /FlateDecode filter >> image\n"), "{ps}");
|
||||
}
|
||||
Level::Two => {
|
||||
assert!(ps.contains("/VCim0 [\n<~") && !ps.contains("ReusableStreamDecode"), "{ps}");
|
||||
assert!(body.contains("/VCi 0 def\n") && body.contains("/RunLengthDecode filter >> image\n"), "{ps}");
|
||||
}
|
||||
}
|
||||
assert_eq!(reused_samples(&ps, level), inline_samples(&one_ps, level));
|
||||
assert_eq!(out.warnings, one.warnings);
|
||||
// Read back, each placement draws the image the single placement draws.
|
||||
let once = imported_images(&one.bytes);
|
||||
assert_eq!(once.len(), 1);
|
||||
assert_eq!(imported_images(&out.bytes), vec![once[0].clone(); 2], "{level:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An image in an envelope is drawn as clipped pieces, all from one copy of its samples, which the
|
||||
/// image placed beside the envelope also draws.
|
||||
#[test]
|
||||
fn an_envelopes_image_pieces_draw_one_copy_of_its_samples() {
|
||||
let mut d = png_doc();
|
||||
let mut content = (*d.layers[0].children().unwrap()[0]).clone();
|
||||
content.id = d.alloc_id();
|
||||
let kind = vectorcraft_doc::EnvelopeKind::Warp { style: "arc".into(), bend: 50.0, h: 0.0, v: 0.0, horizontal: true, version: 0 };
|
||||
let envelope = Node::new(
|
||||
d.alloc_id(),
|
||||
NodeKind::Envelope {
|
||||
content: vec![Arc::new(content)],
|
||||
kind: Box::new(kind),
|
||||
fidelity: 50.0,
|
||||
editing: false,
|
||||
options: Default::default(),
|
||||
frame: Box::new(Affine::IDENTITY),
|
||||
},
|
||||
);
|
||||
d.insert(d.default_layer(), usize::MAX, envelope).unwrap();
|
||||
for level in Level::ALL {
|
||||
let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap();
|
||||
let ps = text(&out);
|
||||
checked_page(&ps);
|
||||
// The plain image and 200 pieces: 10 × 10 cells of two triangles.
|
||||
assert_eq!(reuses(&ps, 0, level), 201, "{ps}");
|
||||
assert!(!ps.contains("VCim1"), "{ps}");
|
||||
assert_eq!(ps.matches(if level == Level::Three { "/ReusableStreamDecode" } else { "<~" }).count(), 1, "{ps}");
|
||||
assert!(!out.warnings.iter().any(|w| w.contains("too large")), "{:?}", out.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_ink_of_a_colorized_image_placed_twice_is_written_once() {
|
||||
let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
|
||||
let mut d = colorized_doc(vec![0, 255, 0], Some(first));
|
||||
let mut n = (*d.layers[0].children().unwrap()[0]).clone();
|
||||
n.id = d.alloc_id();
|
||||
n.extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::rgb8(255, 128, 128), swatch: Some("Ink".into()), tint: 0.5 }));
|
||||
d.insert(d.default_layer(), usize::MAX, n).unwrap();
|
||||
place_again(&mut d, 0, Affine::translate((0.0, 50.0)));
|
||||
place_again(&mut d, 1, Affine::translate((0.0, 100.0)));
|
||||
for level in Level::ALL {
|
||||
let ps = page_of(&d, &EpsOptions { level, ..opts(&d) });
|
||||
assert_eq!((reuses(&ps, 0, level), reuses(&ps, 1, level)), (2, 2), "{ps}");
|
||||
assert_eq!(ps.matches("VCsp0 setcolorspace 1 setcolor\n").count(), 2, "{ps}");
|
||||
assert_eq!(ps.matches("VCsp0 setcolorspace 0.5 setcolor\n").count(), 2, "{ps}");
|
||||
assert_eq!(ps.matches("imagemask").count(), 4, "{ps}");
|
||||
if level == Level::Three {
|
||||
assert_eq!(ps.matches("/Intent 1 ").count(), 2, "image masks: {ps}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples longer than PostScript's longest string: one stream at Level 3, several strings at
|
||||
/// Level 2, each placement reading all of them.
|
||||
#[test]
|
||||
fn samples_longer_than_a_string_are_reused_at_both_levels() {
|
||||
let single = image_doc(&noise(160, 160), 1.0);
|
||||
let mut d = single.clone();
|
||||
place_again(&mut d, 0, Affine::translate((20.0, 0.0)));
|
||||
for level in Level::ALL {
|
||||
let one = export(&single, &EpsOptions { level, ..opts(&single) }, None, None).unwrap();
|
||||
let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap();
|
||||
let ps = text(&out);
|
||||
checked_page(&ps);
|
||||
assert_eq!(reuses(&ps, 0, level), 2);
|
||||
if level == Level::Two {
|
||||
assert_eq!(ps.matches("<~").count(), 2, "160 × 160 × 3 run-length bytes take two strings");
|
||||
}
|
||||
let samples = reused_samples(&ps, level);
|
||||
assert_eq!(samples.len(), 160 * 160 * 3);
|
||||
assert_eq!(samples, inline_samples(&text(&one), level));
|
||||
let once = imported_images(&one.bytes);
|
||||
assert_eq!(imported_images(&out.bytes), vec![once[0].clone(); 2], "{level:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The limit on the page body counts the samples of an image placed many times once. Art taken
|
||||
/// back for passing the limit takes its image placements with it.
|
||||
#[test]
|
||||
fn the_page_limit_counts_a_repeated_images_samples_once() {
|
||||
let single = image_doc(&noise(40, 40), 1.0);
|
||||
let o = opts(&single);
|
||||
let inline = crate::scene::Scene::new(&single, &o).run().body.len();
|
||||
let mut d = single.clone();
|
||||
for k in 1..20 {
|
||||
place_again(&mut d, 0, Affine::translate((f64::from(k), 0.0)));
|
||||
}
|
||||
let page = crate::scene::Scene::new(&d, &o).with_max_body(inline * 3).run();
|
||||
assert!(page.warnings.is_empty(), "{:?}", page.warnings);
|
||||
assert_eq!(reuses(&page.body, 0, Level::Three), 20);
|
||||
assert!(page.setup.contains("/VCim0 VCsrc"));
|
||||
// Past the limit, the placements that don't fit are left out with a warning.
|
||||
let page = crate::scene::Scene::new(&d, &o).with_max_body(inline + 1000).run();
|
||||
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{:?}", page.warnings);
|
||||
let placed = reuses(&page.body, 0, Level::Three);
|
||||
assert!((2..20).contains(&placed), "{placed}");
|
||||
assert!(page.body.len() + page.setup.len() <= inline + 1000 + 400, "{}", page.body.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_length_and_ascii85_round_trip() {
|
||||
let cycle: Vec<u8> = (0..=255u8).cycle().take(1000).collect();
|
||||
|
||||
+20
-2
@@ -688,7 +688,8 @@ fn box_gap(c: &CubicBez, p: Point) -> Option<f64> {
|
||||
const MEASURE_LIMIT: f64 = 1e9;
|
||||
|
||||
/// The length of `seg` to `accuracy`; 0 for a segment whose control points are not finite or past
|
||||
/// [`MEASURE_LIMIT`].
|
||||
/// [`MEASURE_LIMIT`], and 0 when the measurement is not finite (kurbo gives NaN for a quadratic
|
||||
/// segment whose three points coincide).
|
||||
pub fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 {
|
||||
let ok = |p: Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MEASURE_LIMIT && p.y.abs() <= MEASURE_LIMIT;
|
||||
let fits = match seg {
|
||||
@@ -696,7 +697,11 @@ pub fn measured_arclen(seg: &PathSeg, accuracy: f64) -> f64 {
|
||||
PathSeg::Quad(q) => ok(q.p0) && ok(q.p1) && ok(q.p2),
|
||||
PathSeg::Cubic(c) => ok(c.p0) && ok(c.p1) && ok(c.p2) && ok(c.p3),
|
||||
};
|
||||
if fits { kurbo::ParamCurveArclen::arclen(seg, accuracy) } else { 0.0 }
|
||||
if !fits {
|
||||
return 0.0;
|
||||
}
|
||||
let len = kurbo::ParamCurveArclen::arclen(seg, accuracy);
|
||||
if len.is_finite() { len } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The largest x or y, in size, of a segment's control points for which [`segment_bounds`]
|
||||
@@ -1056,6 +1061,19 @@ mod tests {
|
||||
assert!((square().length() - 40.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// A quadratic segment whose three points coincide measures 0, not NaN; quadratic segments
|
||||
/// with only two points together, and an ordinary one, keep kurbo's length.
|
||||
#[test]
|
||||
fn measured_arclen_of_a_quad_whose_points_coincide_is_zero() {
|
||||
let quad = |a: (f64, f64), b: (f64, f64), c: (f64, f64)| PathSeg::Quad(kurbo::QuadBez::new(a, b, c));
|
||||
assert_eq!(measured_arclen(&quad((5.0, 5.0), (5.0, 5.0), (5.0, 5.0)), 1e-6), 0.0);
|
||||
assert_eq!(measured_arclen(&quad((0.0, 0.0), (0.0, 0.0), (0.0, 0.0)), 1e-3), 0.0);
|
||||
assert!((measured_arclen(&quad((0.0, 0.0), (0.0, 0.0), (10.0, 0.0)), 1e-6) - 10.0).abs() < 1e-6);
|
||||
assert!((measured_arclen(&quad((0.0, 0.0), (10.0, 0.0), (0.0, 0.0)), 1e-6) - 10.0).abs() < 1e-6);
|
||||
let ordinary = quad((0.0, 0.0), (10.0, 0.0), (10.0, 10.0));
|
||||
assert_eq!(measured_arclen(&ordinary, 1e-6), kurbo::ParamCurveArclen::arclen(&ordinary, 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_roundtrip() {
|
||||
let p = square();
|
||||
|
||||
+56
-2
@@ -74,6 +74,21 @@ pub enum HostError {
|
||||
/// A function the host gives a script, with its arguments converted.
|
||||
pub type HostFunction = Rc<dyn Fn(Vec<Data>) -> Result<Data, HostError>>;
|
||||
|
||||
/// The place in the script's code that reads a [`HostItem::SiteGetter`] property: the source tag
|
||||
/// of that code, as [`crate::Realm::error_tag`] gives one, and the line and column there, counted
|
||||
/// from 1. A function an earlier script defined keeps its script's tag; code that `eval` or
|
||||
/// `Function` compiled has [`crate::UNKNOWN_SOURCE`]. A read with none of the script's code
|
||||
/// running has [`crate::UNKNOWN_SOURCE`] and line and column 0.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct CallSite {
|
||||
pub source: u32,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
}
|
||||
|
||||
/// A getter the host gives a script that is told where the code reading it is.
|
||||
pub type SiteFunction = Rc<dyn Fn(CallSite) -> Result<Data, HostError>>;
|
||||
|
||||
/// How one argument of a [`HostItem::Converted`] function is read.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Arg {
|
||||
@@ -96,6 +111,8 @@ pub(crate) enum ArgRead {
|
||||
Text,
|
||||
/// One by one as the list says; those past its end are not read.
|
||||
Each(Rc<[Arg]>),
|
||||
/// None: the function is given the [`CallSite`] of the code that calls it, as three numbers.
|
||||
Site,
|
||||
}
|
||||
|
||||
/// A member of an object the host adds to the global environment.
|
||||
@@ -114,6 +131,9 @@ pub enum HostItem {
|
||||
/// A property whose value the function gives each time it is read, frozen as
|
||||
/// [`HostItem::Value`] gives its value.
|
||||
FrozenGetter(HostFunction),
|
||||
/// A property whose value the function gives each time it is read, given the [`CallSite`] of
|
||||
/// the code that reads it.
|
||||
SiteGetter(SiteFunction),
|
||||
/// A property whose value `get` gives each time it is read, and that `set` is given each value
|
||||
/// assigned to it, as its one argument; an error from `set` is thrown to the script.
|
||||
Property {
|
||||
@@ -357,7 +377,10 @@ impl Interp {
|
||||
/// Calls host function `f`: reads its arguments as `how` says, runs it, and gives its result to
|
||||
/// the script.
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, args: &[Value], how: &ArgRead) -> JsResult<Value> {
|
||||
let data = self.read_args(name, args, how)?;
|
||||
let data = match how {
|
||||
ArgRead::Site => site_data(self.call_site()),
|
||||
_ => self.read_args(name, args, how)?,
|
||||
};
|
||||
// Only the script's own code, in a run that can pause, can wait for a result.
|
||||
let can_wait = self.in_slice && self.reentry == 0;
|
||||
self.can_wait.set(can_wait);
|
||||
@@ -375,6 +398,18 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the innermost frame of the script's code is: its source's tag and the line and column
|
||||
/// of the instruction it is running.
|
||||
fn call_site(&self) -> CallSite {
|
||||
match self.script_frames().last() {
|
||||
Some((code, pc, _)) => {
|
||||
let (line, column) = code.line_column(pc.saturating_sub(1));
|
||||
CallSite { source: code.source.tag, line, column }
|
||||
}
|
||||
None => CallSite { source: crate::UNKNOWN_SOURCE, line: 0, column: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls evaluator `f` ([`HostItem::Evaluator`]): reads its arguments, runs it, and runs the
|
||||
/// source it gives as global code, as an indirect `eval` does, giving that code's completion
|
||||
/// value. A result that is not a string is given to the script as it is. `end` is called once
|
||||
@@ -442,7 +477,7 @@ impl Interp {
|
||||
for (i, a) in args.iter().enumerate() {
|
||||
reading.path.push(Step::Index(u32::try_from(i).unwrap_or(u32::MAX)));
|
||||
let d = match how {
|
||||
ArgRead::Data | ArgRead::Frozen => self.read_data(a, &mut reading),
|
||||
ArgRead::Data | ArgRead::Frozen | ArgRead::Site => self.read_data(a, &mut reading),
|
||||
ArgRead::Text => self.read_text(a, &mut reading),
|
||||
ArgRead::Each(list) => match list.get(i) {
|
||||
Some(Arg::TextOrUndefined) if matches!(a, Value::Undefined) => Ok(Data::Undefined),
|
||||
@@ -531,6 +566,10 @@ impl Interp {
|
||||
HostItem::Value(d) => Prop::Data { value: self.write_data(d, 0, true)?, flags: ENUMERABLE },
|
||||
HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Data)), set: None, flags: ENUMERABLE },
|
||||
HostItem::FrozenGetter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, ArgRead::Frozen)), set: None, flags: ENUMERABLE },
|
||||
HostItem::SiteGetter(f) => {
|
||||
let get: HostFunction = Rc::new(move |data| f(read_site(&data)));
|
||||
Prop::Accessor { get: Some(self.host_function(get, &full, ArgRead::Site)), set: None, flags: ENUMERABLE }
|
||||
}
|
||||
HostItem::Property { get, set } => Prop::Accessor {
|
||||
get: Some(self.host_function(get, &full, ArgRead::Data)),
|
||||
set: Some(self.host_function(set, &full, ArgRead::Data)),
|
||||
@@ -577,3 +616,18 @@ enum Slot {
|
||||
Index(usize),
|
||||
Name(String),
|
||||
}
|
||||
|
||||
/// `site` as the three numbers [`ArgRead::Site`] gives its function.
|
||||
fn site_data(site: CallSite) -> Vec<Data> {
|
||||
vec![Data::Number(f64::from(site.source)), Data::Number(f64::from(site.line)), Data::Number(f64::from(site.column))]
|
||||
}
|
||||
|
||||
/// The [`CallSite`] that [`site_data`] gave as `data`.
|
||||
fn read_site(data: &[Data]) -> CallSite {
|
||||
let at = |i: usize, missing: u32| match data.get(i) {
|
||||
// Each number is a `u32` that `site_data` gave, so the conversion is exact.
|
||||
Some(Data::Number(n)) => *n as u32,
|
||||
_ => missing,
|
||||
};
|
||||
CallSite { source: at(0, crate::UNKNOWN_SOURCE), line: at(1, 0), column: at(2, 0) }
|
||||
}
|
||||
@@ -271,6 +271,41 @@ fn a_frozen_getter_gives_a_frozen_value_each_time() {
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("true,true,true,1,false,false".into()));
|
||||
}
|
||||
|
||||
/// A site getter is told the source tag, line and column of the code that reads it: a function an
|
||||
/// earlier script or an evaluator's source defined keeps that source's tag, and code that `eval`
|
||||
/// compiled has none.
|
||||
#[test]
|
||||
fn a_site_getter_is_told_where_the_code_that_reads_it_is() {
|
||||
let mut r = realm(10_000_000);
|
||||
let seen: Rc<RefCell<Vec<CallSite>>> = Rc::default();
|
||||
let log = seen.clone();
|
||||
let site: SiteFunction = Rc::new(move |s| {
|
||||
log.borrow_mut().push(s);
|
||||
Ok(Data::Number(f64::from(s.line)))
|
||||
});
|
||||
let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into())));
|
||||
let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) };
|
||||
r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap();
|
||||
r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap();
|
||||
let first = r.script_tag();
|
||||
assert_eq!(r.run("\n\n\n\nhost.site + early() + inEval() + eval('host.site')").unwrap(), JsValue::Number(5.0 + 2.0 + 3.0 + 1.0));
|
||||
let second = r.script_tag();
|
||||
let sites = seen.borrow().clone();
|
||||
assert_eq!(
|
||||
sites,
|
||||
vec![
|
||||
CallSite { source: second, line: 5, column: 1 },
|
||||
CallSite { source: first, line: 2, column: 11 },
|
||||
CallSite { source: first + 1, line: 3, column: 28 },
|
||||
CallSite { source: UNKNOWN_SOURCE, line: 1, column: 1 },
|
||||
]
|
||||
);
|
||||
seen.borrow_mut().clear();
|
||||
// A getter a built-in calls is at the place of the code that called the built-in.
|
||||
assert_eq!(r.run("\nObject.getOwnPropertyDescriptor(host, 'site').get.call(host)").unwrap(), JsValue::Number(2.0));
|
||||
assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_function_takes_each_argument_as_string_gives_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
@@ -80,7 +80,7 @@ pub use ast::{
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use host::{Arg, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem};
|
||||
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, UNKNOWN_SOURCE};
|
||||
|
||||
+303
-168
@@ -7,6 +7,7 @@
|
||||
//! each new node, name, reference or output unit is charged to the heap before it is made.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::LimitKind;
|
||||
@@ -18,7 +19,7 @@ use crate::heap::{
|
||||
XmlListData, XmlName, XmlNode, XmlNs, key, string_bytes,
|
||||
};
|
||||
use crate::interp::{Abrupt, ErrorType, HeldBytes, Interp, JsResult};
|
||||
use crate::string_builtins::{UNITS_PER_FUEL, flat_charged};
|
||||
use crate::string_builtins::{UNITS_PER_FUEL, flat_charged, push_held, reserve_units};
|
||||
use crate::value::{Str, Value, index_key};
|
||||
|
||||
fn parser_units(s: &str) -> Vec<u16> {
|
||||
@@ -295,26 +296,40 @@ fn name_bytes(n: &XmlName) -> usize {
|
||||
string_bytes(n.local.len()) + n.uri.as_ref().map_or(0, |u| string_bytes(u.len())) + n.prefix.as_ref().map_or(0, |p| string_bytes(p.len()))
|
||||
}
|
||||
|
||||
/// The namespace `stack` declares for `uri`, nearest first, skipping prefixes redeclared nearer.
|
||||
/// `prefer` picks that prefix when several match; `need_prefix` rejects the default namespace.
|
||||
fn ns_lookup(stack: &[XmlNs], uri: &Key, prefer: Option<&Key>, need_prefix: bool) -> Option<XmlNs> {
|
||||
let mut seen: HashSet<&[u16]> = HashSet::new();
|
||||
let mut best = None;
|
||||
for ns in stack.iter().rev() {
|
||||
let Some(p) = &ns.prefix else { continue };
|
||||
if !seen.insert(p) {
|
||||
continue;
|
||||
}
|
||||
if ns.uri == *uri && !(need_prefix && p.is_empty()) {
|
||||
if prefer == Some(p) {
|
||||
return Some(ns.clone());
|
||||
}
|
||||
if best.is_none() {
|
||||
best = Some(ns.clone());
|
||||
}
|
||||
}
|
||||
/// Inserts `item` into `set`, first holding an upper estimate of the bytes of the set's new table
|
||||
/// when it must grow. Returns whether `item` was new.
|
||||
fn insert_held<T: Eq + Hash>(interp: &mut Interp, held: &mut HeldBytes, set: &mut HashSet<T>, item: T) -> JsResult<bool> {
|
||||
if set.len() == set.capacity() && !set.contains(&item) {
|
||||
let more = set.capacity().max(4);
|
||||
held.add(interp, more.saturating_mul(size_of::<T>() + 1).saturating_mul(16) / 7)?;
|
||||
set.reserve(more);
|
||||
}
|
||||
best
|
||||
Ok(set.insert(item))
|
||||
}
|
||||
|
||||
/// Makes room in `list` for `more` items, first holding the bytes of its new capacity when it must
|
||||
/// grow. The capacity at least doubles, as a push's would.
|
||||
fn reserve_held<T>(interp: &mut Interp, held: &mut HeldBytes, list: &mut Vec<T>, more: usize) -> JsResult<()> {
|
||||
if list.capacity() - list.len() < more {
|
||||
let cap = list.len().saturating_add(more).max(list.capacity().saturating_mul(2));
|
||||
held.add(interp, (cap - list.capacity()).saturating_mul(size_of::<T>()))?;
|
||||
list.reserve_exact(cap - list.len());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The number `n` of a prefix written `ns<n>` in decimal without leading zeros, as
|
||||
/// [`Interp::fresh_prefix`] makes them.
|
||||
fn prefix_number(prefix: &[u16]) -> Option<usize> {
|
||||
let digits = prefix.strip_prefix(&[u16::from(b'n'), u16::from(b's')])?;
|
||||
let (&first, _) = digits.split_first()?;
|
||||
if digits.len() > 9 || (first == u16::from(b'0') && digits.len() > 1) {
|
||||
return None;
|
||||
}
|
||||
digits.iter().try_fold(0usize, |n, &c| {
|
||||
let d = c.checked_sub(u16::from(b'0')).filter(|d| *d < 10)?;
|
||||
Some(n * 10 + usize::from(d))
|
||||
})
|
||||
}
|
||||
|
||||
fn prefix_in_scope<'a>(stack: &'a [XmlNs], prefix: &[u16]) -> Option<&'a XmlNs> {
|
||||
@@ -345,18 +360,6 @@ fn units_are(units: &[u16], text: &str) -> bool {
|
||||
units.iter().copied().eq(text.encode_utf16())
|
||||
}
|
||||
|
||||
/// A prefix no entry of `stack` uses.
|
||||
fn fresh_prefix(stack: &[XmlNs]) -> Key {
|
||||
let mut n = 0u32;
|
||||
loop {
|
||||
let candidate = key(&format!("ns{n}"));
|
||||
if prefix_in_scope(stack, &candidate).is_none() {
|
||||
return candidate;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// One open element while serializing.
|
||||
struct OutFrame {
|
||||
node: ObjId,
|
||||
@@ -579,13 +582,16 @@ impl Interp {
|
||||
|
||||
// ---- names ----
|
||||
|
||||
fn name_from_string(&mut self, s: &[u16]) -> JsResult<NameRef> {
|
||||
/// The name `s` gives: an attribute name after `@`, which is copied after its units are
|
||||
/// reserved, and otherwise an element name that shares `s`.
|
||||
fn name_from_string(&mut self, s: &Key) -> JsResult<NameRef> {
|
||||
if let Some((&0x40, rest)) = s.split_first() {
|
||||
let uri = if rest == STAR { None } else { Some(Rc::from(Vec::new())) };
|
||||
reserve_units(self, rest.len())?;
|
||||
return Ok(NameRef { uri, local: Rc::from(rest), attribute: true });
|
||||
}
|
||||
let uri = if s == STAR { None } else { Some(self.xml_default_uri()?) };
|
||||
Ok(NameRef { uri, local: Rc::from(s), attribute: false })
|
||||
let uri = if **s == *STAR { None } else { Some(self.xml_default_uri()?) };
|
||||
Ok(NameRef { uri, local: s.clone(), attribute: false })
|
||||
}
|
||||
|
||||
/// ToXMLName, with a canonical array index read as a position (ECMA-357 section 10.6).
|
||||
@@ -593,7 +599,7 @@ impl Interp {
|
||||
match k {
|
||||
Value::Number(n) if *n >= 0.0 && n.fract() == 0.0 && *n < 4_294_967_295.0 => Ok(Access::Index(*n as u32)),
|
||||
Value::String(s) => {
|
||||
let flat = s.flat();
|
||||
let flat = flat_charged(self, s)?;
|
||||
if let Some(i) = canonical_index(&flat) {
|
||||
return Ok(Access::Index(i));
|
||||
}
|
||||
@@ -603,7 +609,8 @@ impl Interp {
|
||||
if let Some(Class::QName { name, attribute, .. }) = self.heap.object(*o).map(|ob| &ob.class) {
|
||||
return Ok(Access::Name(NameRef { uri: name.uri.clone(), local: name.local.clone(), attribute: *attribute }));
|
||||
}
|
||||
let s = self.to_str(k)?.flat();
|
||||
let s = self.to_str(k)?;
|
||||
let s = flat_charged(self, &s)?;
|
||||
if let Some(i) = canonical_index(&s) {
|
||||
return Ok(Access::Index(i));
|
||||
}
|
||||
@@ -787,31 +794,33 @@ impl Interp {
|
||||
if n.attribute {
|
||||
let count = self.xml_node(x)?.attrs.len();
|
||||
self.xml_take_fuel(count)?;
|
||||
let attrs = std::mem::take(&mut self.xml_node_mut(x)?.attrs);
|
||||
let mut kept = Vec::with_capacity(attrs.len());
|
||||
for a in attrs {
|
||||
let mut kept = 0;
|
||||
for k in 0..count {
|
||||
let Some(a) = self.xml_node(x)?.attrs.get(k).copied() else { break };
|
||||
let hit = self.xml_node(a)?.name.as_ref().is_some_and(|q| n.matches(q));
|
||||
if hit {
|
||||
self.xml_node_mut(a)?.parent = None;
|
||||
} else {
|
||||
kept.push(a);
|
||||
self.xml_node_mut(x)?.attrs.swap(kept, k);
|
||||
kept += 1;
|
||||
}
|
||||
}
|
||||
self.xml_node_mut(x)?.attrs = kept;
|
||||
self.xml_node_mut(x)?.attrs.truncate(kept);
|
||||
return Ok(());
|
||||
}
|
||||
let count = self.children_len(x)?;
|
||||
self.xml_take_fuel(count)?;
|
||||
let children = std::mem::take(&mut self.xml_node_mut(x)?.children);
|
||||
let mut kept = Vec::with_capacity(children.len());
|
||||
for c in children {
|
||||
let mut kept = 0;
|
||||
for k in 0..count {
|
||||
let Some(c) = self.child_at(x, k)? else { break };
|
||||
if n.matches_child(self.xml_node(c)?) {
|
||||
self.xml_node_mut(c)?.parent = None;
|
||||
} else {
|
||||
kept.push(c);
|
||||
self.xml_node_mut(x)?.children.swap(kept, k);
|
||||
kept += 1;
|
||||
}
|
||||
}
|
||||
self.xml_node_mut(x)?.children = kept;
|
||||
self.xml_node_mut(x)?.children.truncate(kept);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -939,7 +948,7 @@ impl Interp {
|
||||
self.use_fuel()?;
|
||||
cur = self.xml_node(a)?.parent;
|
||||
}
|
||||
let height = self.node_height(v)?;
|
||||
let height = self.rooted(&[Value::Object(x), Value::Object(v)], |i| i.node_height(v))?;
|
||||
if depth.saturating_add(height) > self.options.max_depth {
|
||||
return Err(Abrupt::Limit(LimitKind::Heap));
|
||||
}
|
||||
@@ -971,7 +980,9 @@ impl Interp {
|
||||
|
||||
/// The levels of the tree at `root`, counting it.
|
||||
fn node_height(&mut self, root: ObjId) -> JsResult<usize> {
|
||||
let mut stack = vec![(root, 0usize)];
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut stack = Vec::new();
|
||||
push_held(self, &mut held, &mut stack, (root, 0usize))?;
|
||||
let mut height = 1;
|
||||
while let Some(&(node, next)) = stack.last() {
|
||||
self.use_fuel()?;
|
||||
@@ -980,7 +991,7 @@ impl Interp {
|
||||
if let Some(top) = stack.last_mut() {
|
||||
top.1 += 1;
|
||||
}
|
||||
stack.push((c, 0));
|
||||
push_held(self, &mut held, &mut stack, (c, 0))?;
|
||||
height = height.max(stack.len());
|
||||
}
|
||||
None => {
|
||||
@@ -1049,19 +1060,22 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// Takes the fuel and heap to put every item of `l` under `x` and returns the nodes to place,
|
||||
/// from [`Self::child_for_item`]. The tree does not change here, so a limit leaves it as it
|
||||
/// was.
|
||||
fn reserve_list_insert(&mut self, x: ObjId, l: ObjId) -> JsResult<Vec<ObjId>> {
|
||||
/// from [`Self::child_for_item`], with the hold on the list of them, which the caller keeps
|
||||
/// until they are placed. The tree does not change here, so a limit leaves it as it was.
|
||||
fn reserve_list_insert(&mut self, x: ObjId, l: ObjId) -> JsResult<(Vec<ObjId>, HeldBytes)> {
|
||||
let count = self.list_len(l)?;
|
||||
let roots = [Value::Object(x), Value::Object(l)];
|
||||
let mut held = HeldBytes::new(self);
|
||||
self.rooted(&roots, |i| held.add(i, size_of::<ObjId>().saturating_mul(count)))?;
|
||||
let mut items = self.xml_list(l)?.items.clone();
|
||||
let bytes = XML_REF_BYTES.saturating_mul(items.len());
|
||||
let roots = [Value::Object(x), Value::Object(l)];
|
||||
self.rooted(&roots, |i| i.xml_charge(bytes))?;
|
||||
let len = self.children_len(x)?;
|
||||
for (j, item) in items.iter_mut().enumerate() {
|
||||
*item = self.child_for_item(*item, &roots)?;
|
||||
self.place_fuel(len + j, *item)?;
|
||||
}
|
||||
Ok(items)
|
||||
Ok((items, held))
|
||||
}
|
||||
|
||||
/// Puts `items` at `at` in order, after [`Self::reserve_list_insert`].
|
||||
@@ -1100,7 +1114,7 @@ impl Interp {
|
||||
self.insert_node(x, at, *v)?;
|
||||
}
|
||||
Content::List(l) => {
|
||||
let items = self.reserve_list_insert(x, *l)?;
|
||||
let (items, _held) = self.reserve_list_insert(x, *l)?;
|
||||
self.place_children(x, at, &items)?;
|
||||
}
|
||||
}
|
||||
@@ -1152,7 +1166,7 @@ impl Interp {
|
||||
}
|
||||
Content::List(l) => {
|
||||
self.check_attach(x, c)?;
|
||||
let items = self.reserve_list_insert(x, *l)?;
|
||||
let (items, _held) = self.reserve_list_insert(x, *l)?;
|
||||
let len = self.children_len(x)?;
|
||||
self.xml_text_fuel(len)?;
|
||||
if at < len {
|
||||
@@ -1229,7 +1243,8 @@ impl Interp {
|
||||
s.push_units(self, &[SPACE])?;
|
||||
}
|
||||
let Some(item) = self.list_at(*l, i)? else { break };
|
||||
let text = self.node_to_str(item)?.flat();
|
||||
let text = self.node_to_str(item)?;
|
||||
let text = flat_charged(self, &text)?;
|
||||
s.push_units(self, &text)?;
|
||||
}
|
||||
let Value::String(s) = s.finish(self) else { return Err(Abrupt::Internal("not a string".into())) };
|
||||
@@ -1240,9 +1255,9 @@ impl Interp {
|
||||
let mut found = None;
|
||||
let count = self.xml_node(x)?.attrs.len();
|
||||
self.xml_take_fuel(count)?;
|
||||
let attrs = std::mem::take(&mut self.xml_node_mut(x)?.attrs);
|
||||
let mut kept = Vec::with_capacity(attrs.len());
|
||||
for a in attrs {
|
||||
let mut kept = 0;
|
||||
for k in 0..count {
|
||||
let Some(a) = self.xml_node(x)?.attrs.get(k).copied() else { break };
|
||||
let hit = self.xml_node(a)?.name.as_ref().is_some_and(|q| n.matches(q));
|
||||
if hit && found.is_some() {
|
||||
self.xml_node_mut(a)?.parent = None;
|
||||
@@ -1250,10 +1265,11 @@ impl Interp {
|
||||
if hit {
|
||||
found = Some(a);
|
||||
}
|
||||
kept.push(a);
|
||||
self.xml_node_mut(x)?.attrs.swap(kept, k);
|
||||
kept += 1;
|
||||
}
|
||||
}
|
||||
self.xml_node_mut(x)?.attrs = kept;
|
||||
self.xml_node_mut(x)?.attrs.truncate(kept);
|
||||
if let Some(a) = found {
|
||||
self.xml_node_mut(a)?.value = value;
|
||||
return Ok(());
|
||||
@@ -1280,11 +1296,13 @@ impl Interp {
|
||||
}
|
||||
let len = self.children_len(x)?;
|
||||
self.xml_take_fuel(len)?;
|
||||
self.xml_keep(x);
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut matches = Vec::new();
|
||||
for k in 0..len {
|
||||
let Some(child) = self.child_at(x, k)? else { break };
|
||||
if n.matches_child(self.xml_node(child)?) {
|
||||
matches.push(child);
|
||||
push_held(self, &mut held, &mut matches, child)?;
|
||||
}
|
||||
}
|
||||
match c {
|
||||
@@ -1378,6 +1396,8 @@ impl Interp {
|
||||
|
||||
/// The steps of [`Self::resolve_value`], setting `created` to the first element they add.
|
||||
fn resolve_value_adding(&mut self, x: ObjId, created: &mut Option<ObjId>) -> JsResult<Option<ObjId>> {
|
||||
self.xml_keep(x);
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut chain = Vec::new();
|
||||
let mut cur = x;
|
||||
let base = loop {
|
||||
@@ -1391,7 +1411,7 @@ impl Interp {
|
||||
if *name.local == *STAR {
|
||||
return Ok(None);
|
||||
}
|
||||
chain.push(l);
|
||||
push_held(self, &mut held, &mut chain, l)?;
|
||||
cur = target;
|
||||
};
|
||||
let mut base = base;
|
||||
@@ -1615,6 +1635,9 @@ impl Interp {
|
||||
Some(parent) => self.index_in_parent(parent, item)?.map(|q| (parent, q)),
|
||||
None => None,
|
||||
};
|
||||
let count = self.list_len(c)?;
|
||||
let mut held = HeldBytes::new(self);
|
||||
self.rooted(&[Value::Object(x), Value::Object(c)], |i| held.add(i, size_of::<ObjId>().saturating_mul(count)))?;
|
||||
let mut items = self.xml_list(c)?.items.clone();
|
||||
if place.is_some() {
|
||||
let roots = [Value::Object(x), Value::Object(c)];
|
||||
@@ -1682,6 +1705,8 @@ impl Interp {
|
||||
// ---- copies ----
|
||||
|
||||
fn copy_shallow(&mut self, src: ObjId, parent: Option<ObjId>) -> JsResult<ObjId> {
|
||||
let declared = self.xml_node(src)?.ns.len();
|
||||
self.xml_charge(XML_NS_BYTES.saturating_mul(declared))?;
|
||||
let node = self.xml_node(src)?;
|
||||
let copy = XmlNode {
|
||||
kind: node.kind,
|
||||
@@ -1692,11 +1717,11 @@ impl Interp {
|
||||
children: Vec::new(),
|
||||
ns: node.ns.clone(),
|
||||
};
|
||||
let attrs = node.attrs.clone();
|
||||
self.xml_charge(XML_NS_BYTES.saturating_mul(copy.ns.len()))?;
|
||||
let c = self.new_xml_node(copy)?;
|
||||
self.xml_keep(c);
|
||||
for a in attrs {
|
||||
let mut k = 0;
|
||||
while let Some(a) = self.xml_node(src)?.attrs.get(k).copied() {
|
||||
k += 1;
|
||||
self.use_fuel()?;
|
||||
let n = self.xml_node(a)?;
|
||||
let attr = XmlNode {
|
||||
@@ -1721,7 +1746,9 @@ impl Interp {
|
||||
let top = i.copy_shallow(root, None)?;
|
||||
i.xml_keep(top);
|
||||
let mark = i.temp_roots.len();
|
||||
let mut stack = vec![(root, top, 0usize)];
|
||||
let mut held = HeldBytes::new(i);
|
||||
let mut stack = Vec::new();
|
||||
push_held(i, &mut held, &mut stack, (root, top, 0usize))?;
|
||||
while let Some(&(src, dst, next)) = stack.last() {
|
||||
i.use_fuel()?;
|
||||
i.temp_roots.truncate(mark);
|
||||
@@ -1733,7 +1760,7 @@ impl Interp {
|
||||
let c = i.copy_shallow(child, Some(dst))?;
|
||||
i.xml_charge_link(c)?;
|
||||
i.xml_node_mut(dst)?.children.push(c);
|
||||
stack.push((child, c, 0));
|
||||
push_held(i, &mut held, &mut stack, (child, c, 0))?;
|
||||
}
|
||||
None => {
|
||||
stack.pop();
|
||||
@@ -1778,9 +1805,18 @@ impl Interp {
|
||||
|
||||
// ---- comparison ----
|
||||
|
||||
/// The namespace, local name and value of the attribute `id`, flattening a value that is a
|
||||
/// rope with [`flat_charged`].
|
||||
fn attr_key(&mut self, id: ObjId) -> JsResult<(Option<Key>, Key, Key)> {
|
||||
let n = self.xml_node(id)?;
|
||||
let name = n.name.as_ref().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?;
|
||||
let (uri, local, value) = (name.uri.clone(), name.local.clone(), n.value.clone());
|
||||
Ok((uri, local, flat_charged(self, &value)?))
|
||||
}
|
||||
|
||||
fn same_shallow(&mut self, a: ObjId, b: ObjId) -> JsResult<bool> {
|
||||
let (x, y) = (self.xml_node(a)?, self.xml_node(b)?);
|
||||
if x.kind != y.kind || x.attrs.len() != y.attrs.len() || x.children.len() != y.children.len() || x.value.flat() != y.value.flat() {
|
||||
if x.kind != y.kind || x.attrs.len() != y.attrs.len() || x.children.len() != y.children.len() || x.value.len() != y.value.len() {
|
||||
return Ok(false);
|
||||
}
|
||||
match (&x.name, &y.name) {
|
||||
@@ -1788,26 +1824,25 @@ impl Interp {
|
||||
(Some(p), Some(q)) if p.local == q.local && p.uri == q.uri => {}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
if x.attrs.is_empty() {
|
||||
let (xv, yv) = (x.value.clone(), y.value.clone());
|
||||
if flat_charged(self, &xv)? != flat_charged(self, &yv)? {
|
||||
return Ok(false);
|
||||
}
|
||||
let count = self.xml_node(a)?.attrs.len();
|
||||
if count == 0 {
|
||||
return Ok(true);
|
||||
}
|
||||
let count = x.attrs.len();
|
||||
self.xml_take_fuel(count)?;
|
||||
let mut held = HeldBytes::new(self);
|
||||
held.add(self, ATTR_COUNT_BYTES.saturating_mul(count))?;
|
||||
let (x, y) = (self.xml_node(a)?, self.xml_node(b)?);
|
||||
let (xa, ya) = (x.attrs.clone(), y.attrs.clone());
|
||||
let mut counts: HashMap<(Option<Key>, Key, Key), usize> = HashMap::new();
|
||||
let attr_key = |i: &Self, id: ObjId| -> JsResult<(Option<Key>, Key, Key)> {
|
||||
let n = i.xml_node(id)?;
|
||||
let name = n.name.as_ref().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?;
|
||||
Ok((name.uri.clone(), name.local.clone(), n.value.flat()))
|
||||
};
|
||||
for a in xa {
|
||||
*counts.entry(attr_key(self, a)?).or_default() += 1;
|
||||
for k in 0..count {
|
||||
let Some(id) = self.xml_node(a)?.attrs.get(k).copied() else { break };
|
||||
*counts.entry(self.attr_key(id)?).or_default() += 1;
|
||||
}
|
||||
for b in ya {
|
||||
match counts.get_mut(&attr_key(self, b)?) {
|
||||
for k in 0..count {
|
||||
let Some(id) = self.xml_node(b)?.attrs.get(k).copied() else { break };
|
||||
match counts.get_mut(&self.attr_key(id)?) {
|
||||
Some(n) if *n > 0 => *n -= 1,
|
||||
_ => return Ok(false),
|
||||
}
|
||||
@@ -1884,7 +1919,8 @@ impl Interp {
|
||||
let (xk, yk) = (self.xml_kind(x)?, self.xml_kind(y)?);
|
||||
let textual = |k| matches!(k, XmlKind::Text | XmlKind::Attribute);
|
||||
if (textual(xk) && self.node_simple(y)?) || (textual(yk) && self.node_simple(x)?) {
|
||||
return Ok(Some(self.node_to_str(x)?.flat() == self.node_to_str(y)?.flat()));
|
||||
let (s, other) = (self.node_to_str(x)?, self.node_to_str(y)?);
|
||||
return Ok(Some(flat_charged(self, &s)? == flat_charged(self, &other)?));
|
||||
}
|
||||
return self.node_equals(x, y).map(Some);
|
||||
}
|
||||
@@ -1900,9 +1936,9 @@ impl Interp {
|
||||
if let Xv::Node(n) = self.classify(x)
|
||||
&& self.node_simple(n)?
|
||||
{
|
||||
let s = self.node_to_str(n)?.flat();
|
||||
let other = self.to_str(y)?.flat();
|
||||
return Ok(Some(s == other));
|
||||
let s = self.node_to_str(n)?;
|
||||
let other = self.to_str(y)?;
|
||||
return Ok(Some(flat_charged(self, &s)? == flat_charged(self, &other)?));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
@@ -1951,7 +1987,9 @@ impl Interp {
|
||||
|
||||
/// The nodes under `x` matching `n`, in document order ([[Descendants]], section 9.1.1.8).
|
||||
pub(crate) fn node_descendants(&mut self, x: ObjId, n: &NameRef, out: ObjId) -> JsResult<()> {
|
||||
let mut stack = vec![(x, 0usize)];
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut stack = Vec::new();
|
||||
push_held(self, &mut held, &mut stack, (x, 0usize))?;
|
||||
if n.attribute {
|
||||
self.collect_matching(x, n, out)?;
|
||||
}
|
||||
@@ -1969,14 +2007,16 @@ impl Interp {
|
||||
} else if n.matches_child(self.xml_node(child)?) {
|
||||
self.list_push(out, child)?;
|
||||
}
|
||||
stack.push((child, 0));
|
||||
push_held(self, &mut held, &mut stack, (child, 0))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Merges adjacent text and removes empty text under `root` (ECMA-357 section 13.4.4.26).
|
||||
pub(crate) fn node_normalize(&mut self, root: ObjId) -> JsResult<()> {
|
||||
let mut stack = vec![(root, 0usize)];
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut stack = Vec::new();
|
||||
push_held(self, &mut held, &mut stack, (root, 0usize))?;
|
||||
while let Some(&(x, mut i)) = stack.last() {
|
||||
self.use_fuel()?;
|
||||
let Some(child) = self.child_at(x, i)? else {
|
||||
@@ -2010,7 +2050,7 @@ impl Interp {
|
||||
frame.1 = i + 1;
|
||||
}
|
||||
if kind == XmlKind::Element {
|
||||
stack.push((child, 0));
|
||||
push_held(self, &mut held, &mut stack, (child, 0))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -2032,7 +2072,8 @@ impl Interp {
|
||||
let Some(c) = self.child_at(x, i)? else { break };
|
||||
let node = self.xml_node(c)?;
|
||||
if !matches!(node.kind, XmlKind::Comment | XmlKind::Pi) {
|
||||
let text = node.value.flat();
|
||||
let text = node.value.clone();
|
||||
let text = flat_charged(self, &text)?;
|
||||
out.push_units(self, &text)?;
|
||||
}
|
||||
}
|
||||
@@ -2069,7 +2110,8 @@ impl Interp {
|
||||
self.use_fuel()?;
|
||||
let Some(item) = self.list_at(l, i)? else { break };
|
||||
if !matches!(self.xml_kind(item)?, XmlKind::Comment | XmlKind::Pi) {
|
||||
let text = self.node_to_str(item)?.flat();
|
||||
let text = self.node_to_str(item)?;
|
||||
let text = flat_charged(self, &text)?;
|
||||
out.push_units(self, &text)?;
|
||||
}
|
||||
}
|
||||
@@ -2107,6 +2149,46 @@ impl Interp {
|
||||
out.push_units(self, text.get(from..).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The namespace `stack` declares for `uri`, nearest first, skipping prefixes redeclared nearer.
|
||||
/// `prefer` picks that prefix when several match; `need_prefix` rejects the default namespace.
|
||||
/// The set of prefixes it has passed is held against the heap limit.
|
||||
fn ns_lookup(&mut self, stack: &[XmlNs], uri: &Key, prefer: Option<&Key>, need_prefix: bool) -> JsResult<Option<XmlNs>> {
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut seen: HashSet<&[u16]> = HashSet::new();
|
||||
let mut best = None;
|
||||
for ns in stack.iter().rev() {
|
||||
let Some(p) = &ns.prefix else { continue };
|
||||
if !insert_held(self, &mut held, &mut seen, &p[..])? {
|
||||
continue;
|
||||
}
|
||||
if ns.uri == *uri && !(need_prefix && p.is_empty()) {
|
||||
if prefer == Some(p) {
|
||||
return Ok(Some(ns.clone()));
|
||||
}
|
||||
if best.is_none() {
|
||||
best = Some(ns.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(best)
|
||||
}
|
||||
|
||||
/// The first of `ns0`, `ns1`, ... that no entry of `stack` uses. One of the first
|
||||
/// `stack.len() + 1` is free, so one pass over `stack` marks the used ones.
|
||||
fn fresh_prefix(&mut self, stack: &[XmlNs]) -> JsResult<Key> {
|
||||
self.xml_take_fuel(stack.len() + 1)?;
|
||||
let mut held = HeldBytes::new(self);
|
||||
held.add(self, stack.len() + 1)?;
|
||||
let mut used = vec![false; stack.len() + 1];
|
||||
for ns in stack {
|
||||
if let Some(slot) = ns.prefix.as_deref().and_then(prefix_number).and_then(|n| used.get_mut(n)) {
|
||||
*slot = true;
|
||||
}
|
||||
}
|
||||
let n = used.iter().position(|u| !u).unwrap_or(stack.len());
|
||||
Ok(key(&format!("ns{n}")))
|
||||
}
|
||||
|
||||
/// Picks the prefix of a name in `scope`, adding a declaration to `scope` when none is there.
|
||||
fn out_prefix(&mut self, name: &XmlName, scope: &mut Vec<XmlNs>, attribute: bool) -> JsResult<Key> {
|
||||
self.xml_take_fuel(scope.len() + 1)?;
|
||||
@@ -2122,13 +2204,13 @@ impl Interp {
|
||||
if *uri == *key(XML_URI) {
|
||||
return Ok(key("xml"));
|
||||
}
|
||||
if let Some(ns) = ns_lookup(scope, &uri, name.prefix.as_ref(), attribute) {
|
||||
if let Some(ns) = self.ns_lookup(scope, &uri, name.prefix.as_ref(), attribute)? {
|
||||
return Ok(ns.prefix.unwrap_or(empty));
|
||||
}
|
||||
let prefix = match &name.prefix {
|
||||
Some(p) if !(attribute && p.is_empty()) && prefix_in_scope(scope, p).is_none() => p.clone(),
|
||||
_ if !attribute && prefix_in_scope(scope, &empty).is_none() => empty,
|
||||
_ => fresh_prefix(scope),
|
||||
_ => self.fresh_prefix(scope)?,
|
||||
};
|
||||
self.xml_charge(XML_NS_BYTES)?;
|
||||
scope.push(XmlNs { prefix: Some(prefix.clone()), uri });
|
||||
@@ -2143,8 +2225,7 @@ impl Interp {
|
||||
out.push_units(self, local)
|
||||
}
|
||||
|
||||
/// Writes `x`; an element with children is left open on `stack`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// Writes `x`, and returns the frame of an element with children, which is left open.
|
||||
fn write_enter(
|
||||
&mut self,
|
||||
out: &mut Builder,
|
||||
@@ -2153,11 +2234,11 @@ impl Interp {
|
||||
settings: &Settings,
|
||||
pretty: bool,
|
||||
scope: &mut Vec<XmlNs>,
|
||||
stack: &mut Vec<OutFrame>,
|
||||
) -> JsResult<()> {
|
||||
) -> JsResult<Option<OutFrame>> {
|
||||
self.use_fuel()?;
|
||||
let node = self.xml_node(x)?;
|
||||
let (kind, value) = (node.kind, node.value.flat());
|
||||
let (kind, value) = (node.kind, node.value.clone());
|
||||
let value = flat_charged(self, &value)?;
|
||||
self.xml_text_fuel(value.len())?;
|
||||
if pretty {
|
||||
out.push_repeated(self, &[SPACE], indent)?;
|
||||
@@ -2165,13 +2246,18 @@ impl Interp {
|
||||
match kind {
|
||||
XmlKind::Text => {
|
||||
let trimmed: &[u16] = if pretty { trim_xml_space(&value) } else { &value };
|
||||
return self.write_escaped(out, trimmed, false);
|
||||
self.write_escaped(out, trimmed, false)?;
|
||||
return Ok(None);
|
||||
}
|
||||
XmlKind::Attribute => {
|
||||
self.write_escaped(out, &value, true)?;
|
||||
return Ok(None);
|
||||
}
|
||||
XmlKind::Attribute => return self.write_escaped(out, &value, true),
|
||||
XmlKind::Comment => {
|
||||
out.push_str(self, "<!--")?;
|
||||
out.push_units(self, &value)?;
|
||||
return out.push_str(self, "-->");
|
||||
out.push_str(self, "-->")?;
|
||||
return Ok(None);
|
||||
}
|
||||
XmlKind::Pi => {
|
||||
let target = self.xml_node(x)?.name.as_ref().map(|n| n.local.clone()).unwrap_or_else(|| Rc::from(Vec::new()));
|
||||
@@ -2179,47 +2265,46 @@ impl Interp {
|
||||
out.push_units(self, &target)?;
|
||||
out.push_units(self, &[SPACE])?;
|
||||
out.push_units(self, &value)?;
|
||||
return out.push_str(self, "?>");
|
||||
out.push_str(self, "?>")?;
|
||||
return Ok(None);
|
||||
}
|
||||
XmlKind::Element => {}
|
||||
}
|
||||
let ns_mark = scope.len();
|
||||
let node = self.xml_node(x)?;
|
||||
let declared = node.ns.clone();
|
||||
let attrs = node.attrs.clone();
|
||||
let declared = node.ns.len();
|
||||
let name = node.name.clone().ok_or_else(|| Abrupt::Internal("element without a name".into()))?;
|
||||
self.xml_take_fuel(declared.len().saturating_mul(scope.len() + 1))?;
|
||||
let mut unnamed = Vec::new();
|
||||
for ns in declared {
|
||||
if ns.prefix.is_none() {
|
||||
unnamed.push(ns);
|
||||
} else if !scope.iter().any(|a| a.uri == ns.uri && a.prefix == ns.prefix) {
|
||||
self.xml_charge(XML_NS_BYTES)?;
|
||||
scope.push(ns);
|
||||
}
|
||||
}
|
||||
for ns in unnamed {
|
||||
if !scope.iter().any(|a| a.uri == ns.uri) {
|
||||
let prefix = fresh_prefix(scope);
|
||||
self.xml_charge(XML_NS_BYTES)?;
|
||||
scope.push(XmlNs { prefix: Some(prefix), uri: ns.uri });
|
||||
self.xml_take_fuel(declared.saturating_mul(scope.len() + 1))?;
|
||||
for unnamed in [false, true] {
|
||||
let mut k = 0;
|
||||
while let Some(ns) = self.xml_node(x)?.ns.get(k).cloned() {
|
||||
k += 1;
|
||||
if ns.prefix.is_none() != unnamed {
|
||||
continue;
|
||||
}
|
||||
if !unnamed && !scope.iter().any(|a| a.uri == ns.uri && a.prefix == ns.prefix) {
|
||||
self.xml_charge(XML_NS_BYTES)?;
|
||||
scope.push(ns);
|
||||
} else if unnamed && !scope.iter().any(|a| a.uri == ns.uri) {
|
||||
let prefix = self.fresh_prefix(scope)?;
|
||||
self.xml_charge(XML_NS_BYTES)?;
|
||||
scope.push(XmlNs { prefix: Some(prefix), uri: ns.uri });
|
||||
}
|
||||
}
|
||||
}
|
||||
let prefix = self.out_prefix(&name, scope, false)?;
|
||||
let mut attr_prefixes = Vec::new();
|
||||
for &a in &attrs {
|
||||
self.use_fuel()?;
|
||||
let an = self.xml_node(a)?.name.clone().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?;
|
||||
attr_prefixes.push(self.out_prefix(&an, scope, true)?);
|
||||
}
|
||||
out.push_units(self, &[LT])?;
|
||||
self.write_name(out, &prefix, &name.local)?;
|
||||
for (&a, attr_prefix) in attrs.iter().zip(&attr_prefixes) {
|
||||
let an = self.xml_node(a)?;
|
||||
let local = an.name.as_ref().map(|q| q.local.clone()).unwrap_or_else(|| Rc::from(Vec::new()));
|
||||
let value = an.value.flat();
|
||||
let mut k = 0;
|
||||
while let Some(a) = self.xml_node(x)?.attrs.get(k).copied() {
|
||||
k += 1;
|
||||
self.use_fuel()?;
|
||||
let an = self.xml_node(a)?.name.clone().ok_or_else(|| Abrupt::Internal("attribute without a name".into()))?;
|
||||
let attr_prefix = self.out_prefix(&an, scope, true)?;
|
||||
let value = self.xml_node(a)?.value.clone();
|
||||
let value = flat_charged(self, &value)?;
|
||||
out.push_units(self, &[SPACE])?;
|
||||
self.write_name(out, attr_prefix, &local)?;
|
||||
self.write_name(out, &attr_prefix, &an.local)?;
|
||||
out.push_units(self, &[EQ, DQUOTE])?;
|
||||
self.write_escaped(out, &value, true)?;
|
||||
out.push_units(self, &[DQUOTE])?;
|
||||
@@ -2239,7 +2324,8 @@ impl Interp {
|
||||
let count = self.children_len(x)?;
|
||||
if count == 0 {
|
||||
scope.truncate(ns_mark);
|
||||
return out.push_str(self, "/>");
|
||||
out.push_str(self, "/>")?;
|
||||
return Ok(None);
|
||||
}
|
||||
out.push_units(self, &[GT])?;
|
||||
let first_is_text = match self.child_at(x, 0)? {
|
||||
@@ -2248,14 +2334,17 @@ impl Interp {
|
||||
};
|
||||
let pretty_children = pretty && (count > 1 || !first_is_text);
|
||||
let child_indent = if pretty_children { indent.saturating_add(u64::from(settings.indent)) } else { 0 };
|
||||
stack.push(OutFrame { node: x, next: 0, indent, child_indent, pretty_children, ns_mark, prefix, local: name.local });
|
||||
Ok(())
|
||||
Ok(Some(OutFrame { node: x, next: 0, indent, child_indent, pretty_children, ns_mark, prefix, local: name.local }))
|
||||
}
|
||||
|
||||
/// Writes the tree at `root`. Its open elements are held against the heap limit.
|
||||
fn write_node(&mut self, out: &mut Builder, root: ObjId, indent: u64, settings: &Settings, pretty: bool) -> JsResult<()> {
|
||||
let mut scope: Vec<XmlNs> = Vec::new();
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut stack: Vec<OutFrame> = Vec::new();
|
||||
self.write_enter(out, root, indent, settings, pretty, &mut scope, &mut stack)?;
|
||||
if let Some(frame) = self.write_enter(out, root, indent, settings, pretty, &mut scope)? {
|
||||
push_held(self, &mut held, &mut stack, frame)?;
|
||||
}
|
||||
while let Some(frame) = stack.last_mut() {
|
||||
let (node, next, child_indent, pretty_children) = (frame.node, frame.next, frame.child_indent, frame.pretty_children);
|
||||
frame.next += 1;
|
||||
@@ -2264,7 +2353,9 @@ impl Interp {
|
||||
if pretty_children {
|
||||
out.push_units(self, &[LF])?;
|
||||
}
|
||||
self.write_enter(out, child, child_indent, settings, pretty && pretty_children, &mut scope, &mut stack)?;
|
||||
if let Some(frame) = self.write_enter(out, child, child_indent, settings, pretty && pretty_children, &mut scope)? {
|
||||
push_held(self, &mut held, &mut stack, frame)?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let Some(frame) = stack.pop() else { break };
|
||||
@@ -2311,8 +2402,11 @@ impl Interp {
|
||||
self.throw(ErrorType::Syntax, message)
|
||||
}
|
||||
|
||||
fn decode_into(&mut self, src: &[u16], from: usize, to: usize, out: &mut Vec<u16>, attribute: bool) -> JsResult<()> {
|
||||
/// Decodes `src[from..to]` onto `out`, holding the room it takes in `out` with `held` first. The
|
||||
/// decoded text is never longer than the source.
|
||||
fn decode_into(&mut self, src: &[u16], from: usize, to: usize, out: &mut Vec<u16>, attribute: bool, held: &mut HeldBytes) -> JsResult<()> {
|
||||
self.xml_text_fuel(to.saturating_sub(from))?;
|
||||
reserve_held(self, held, out, to.saturating_sub(from))?;
|
||||
let mut pos = from;
|
||||
while pos < to {
|
||||
let Some(&c) = src.get(pos) else { break };
|
||||
@@ -2427,7 +2521,16 @@ impl Interp {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn flush_text(&mut self, text: &mut Vec<u16>, ignore_whitespace: bool, open: &[ObjId], roots: &mut Vec<ObjId>) -> JsResult<()> {
|
||||
/// Makes a text node of `text`, unless it is empty or ignored white space. Taking the buffer
|
||||
/// releases `text_held`, its hold.
|
||||
fn flush_text(
|
||||
&mut self,
|
||||
text: &mut Vec<u16>,
|
||||
text_held: &mut HeldBytes,
|
||||
ignore_whitespace: bool,
|
||||
open: &[ObjId],
|
||||
roots: &mut Vec<ObjId>,
|
||||
) -> JsResult<()> {
|
||||
if text.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -2435,16 +2538,22 @@ impl Interp {
|
||||
text.clear();
|
||||
return Ok(());
|
||||
}
|
||||
let t = self.new_text_node(Str::from_units(std::mem::take(text)), None)?;
|
||||
let value = Str::from_units(std::mem::take(text));
|
||||
*text_held = HeldBytes::new(self);
|
||||
let t = self.new_text_node(value, None)?;
|
||||
self.place_parsed(t, open, roots)
|
||||
}
|
||||
|
||||
/// Parses the open tag at `src[pos]` and returns the offset after it. An element left open is
|
||||
/// pushed onto `open` and its name onto `names`, both held with `stack_held`. The attributes,
|
||||
/// sets and copies it works with are held until it returns.
|
||||
fn parse_open_tag(
|
||||
&mut self,
|
||||
src: &[u16],
|
||||
pos: usize,
|
||||
open: &mut Vec<ObjId>,
|
||||
names: &mut Vec<(usize, usize)>,
|
||||
stack_held: &mut HeldBytes,
|
||||
roots: &mut Vec<ObjId>,
|
||||
) -> JsResult<usize> {
|
||||
if open.len() >= self.options.max_depth {
|
||||
@@ -2455,6 +2564,7 @@ impl Interp {
|
||||
let raw_name = src.get(name_start..name_end).unwrap_or_default();
|
||||
let (elem_prefix, elem_local) = self.split_name(raw_name)?;
|
||||
let mut at = name_end;
|
||||
let mut held = HeldBytes::new(self);
|
||||
let mut raw_attrs: Vec<(usize, usize, Vec<u16>)> = Vec::new();
|
||||
let closes = loop {
|
||||
let before = at;
|
||||
@@ -2492,27 +2602,31 @@ impl Interp {
|
||||
return Err(self.syntax("'<' cannot appear in an attribute value"));
|
||||
}
|
||||
let mut value = Vec::new();
|
||||
self.decode_into(src, value_start, value_end, &mut value, true)?;
|
||||
raw_attrs.push((at, end, value));
|
||||
self.decode_into(src, value_start, value_end, &mut value, true, &mut held)?;
|
||||
push_held(self, &mut held, &mut raw_attrs, (at, end, value))?;
|
||||
at = value_end + 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
self.xml_charge(XML_NS_BYTES.saturating_mul(raw_attrs.len()))?;
|
||||
let mut ns: Vec<XmlNs> = Vec::new();
|
||||
let mut seen_decl: HashSet<Vec<u16>> = HashSet::new();
|
||||
let xmlns = key("xmlns");
|
||||
let declares = |raw: &[u16]| raw == &xmlns[..] || raw.strip_prefix(&xmlns[..]).is_some_and(|rest| rest.first() == Some(&COLON));
|
||||
let decls = raw_attrs.iter().filter(|(start, end, _)| declares(src.get(*start..*end).unwrap_or_default())).count();
|
||||
let mut ns: Vec<XmlNs> = Vec::with_capacity(decls);
|
||||
let mut seen_decl: HashSet<&[u16]> = HashSet::new();
|
||||
for (start, end, value) in &raw_attrs {
|
||||
let raw = src.get(*start..*end).unwrap_or_default();
|
||||
if raw == key("xmlns").as_ref() {
|
||||
if raw == &xmlns[..] {
|
||||
if !ns_binding_allowed(&[], value) {
|
||||
return Err(self.syntax(RESERVED_NS_BINDING));
|
||||
}
|
||||
if !seen_decl.insert(Vec::new()) {
|
||||
if !insert_held(self, &mut held, &mut seen_decl, &[] as &[u16])? {
|
||||
return Err(self.syntax("a namespace is declared twice"));
|
||||
}
|
||||
self.xml_charge(string_bytes(0).saturating_add(string_bytes(value.len())))?;
|
||||
ns.push(XmlNs { prefix: Some(Rc::from(Vec::new())), uri: Rc::from(value.as_slice()) });
|
||||
} else if let (Some(p), local) = self.split_name(raw)?
|
||||
&& p == key("xmlns").as_ref()
|
||||
&& p == &xmlns[..]
|
||||
{
|
||||
if value.is_empty() {
|
||||
return Err(self.syntax("a namespace prefix cannot be declared with an empty URI"));
|
||||
@@ -2520,9 +2634,10 @@ impl Interp {
|
||||
if !ns_binding_allowed(local, value) {
|
||||
return Err(self.syntax(RESERVED_NS_BINDING));
|
||||
}
|
||||
if !seen_decl.insert(local.to_vec()) {
|
||||
if !insert_held(self, &mut held, &mut seen_decl, local)? {
|
||||
return Err(self.syntax("a namespace is declared twice"));
|
||||
}
|
||||
self.xml_charge(string_bytes(local.len()).saturating_add(string_bytes(value.len())))?;
|
||||
ns.push(XmlNs { prefix: Some(Rc::from(local)), uri: Rc::from(value.as_slice()) });
|
||||
}
|
||||
}
|
||||
@@ -2547,7 +2662,8 @@ impl Interp {
|
||||
ns,
|
||||
})?;
|
||||
self.place_parsed(element, open, roots)?;
|
||||
let mut unique: HashSet<(Key, Vec<u16>)> = HashSet::new();
|
||||
let mut unique: HashSet<(Key, &[u16])> = HashSet::new();
|
||||
let mut own: Option<Vec<XmlNs>> = None;
|
||||
for (start, end, value) in raw_attrs {
|
||||
self.use_fuel()?;
|
||||
let raw = src.get(start..end).unwrap_or_default();
|
||||
@@ -2557,15 +2673,19 @@ impl Interp {
|
||||
}
|
||||
let (auri, stored_prefix): (Key, Key) = match prefix {
|
||||
Some(p) => {
|
||||
let own = self.xml_node(element)?.ns.clone();
|
||||
match self.resolve_prefix(p, &own, open)? {
|
||||
if own.is_none() {
|
||||
let count = self.xml_node(element)?.ns.len();
|
||||
held.add(self, size_of::<XmlNs>().saturating_mul(count))?;
|
||||
own = Some(self.xml_node(element)?.ns.clone());
|
||||
}
|
||||
match self.resolve_prefix(p, own.as_deref().unwrap_or_default(), open)? {
|
||||
Some(u) => (u, Rc::from(p)),
|
||||
None => return Err(self.syntax("an XML name uses an undeclared namespace prefix")),
|
||||
}
|
||||
}
|
||||
None => (Rc::from(Vec::new()), Rc::from(Vec::new())),
|
||||
};
|
||||
if !unique.insert((auri.clone(), local.to_vec())) {
|
||||
if !insert_held(self, &mut held, &mut unique, (auri.clone(), local))? {
|
||||
return Err(self.type_error("an XML element has two attributes with the same name"));
|
||||
}
|
||||
let a = self.new_xml_node(XmlNode {
|
||||
@@ -2581,8 +2701,8 @@ impl Interp {
|
||||
self.xml_node_mut(element)?.attrs.push(a);
|
||||
}
|
||||
if !closes {
|
||||
open.push(element);
|
||||
names.push((name_start, name_end));
|
||||
push_held(self, stack_held, open, element)?;
|
||||
push_held(self, stack_held, names, (name_start, name_end))?;
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
@@ -2605,10 +2725,14 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// Parses XML text into nodes, kept reachable through the temporary roots until the caller's
|
||||
/// scope ends.
|
||||
/// scope ends. The open elements and their names, the text being gathered and each tag's
|
||||
/// attributes are held as they grow. The allowance held from the source's length covers the
|
||||
/// copy a value's units take as it becomes a string, before the node that holds it is charged.
|
||||
pub(crate) fn xml_parse(&mut self, source: &[u16]) -> JsResult<Vec<ObjId>> {
|
||||
let mut held = HeldBytes::new(self);
|
||||
held.add(self, string_bytes(source.len()).saturating_mul(2))?;
|
||||
let mut stack_held = HeldBytes::new(self);
|
||||
let mut text_held = HeldBytes::new(self);
|
||||
let settings = self.xml_settings()?;
|
||||
let mut src = source;
|
||||
let offset_start = skip_xml_space(src, 0);
|
||||
@@ -2638,7 +2762,7 @@ impl Interp {
|
||||
self.xml_text_fuel(end - pos)?;
|
||||
return Err(self.syntax("']]>' cannot appear in XML text"));
|
||||
}
|
||||
self.decode_into(src, pos, end, &mut text, false)?;
|
||||
self.decode_into(src, pos, end, &mut text, false, &mut text_held)?;
|
||||
pos = end;
|
||||
continue;
|
||||
}
|
||||
@@ -2650,11 +2774,13 @@ impl Interp {
|
||||
};
|
||||
self.xml_text_fuel(end - pos)?;
|
||||
self.check_units(src, pos + 9, end)?;
|
||||
text.extend_from_slice(src.get(pos + 9..end).unwrap_or_default());
|
||||
let section = src.get(pos + 9..end).unwrap_or_default();
|
||||
reserve_held(self, &mut text_held, &mut text, section.len())?;
|
||||
text.extend_from_slice(section);
|
||||
pos = end + 3;
|
||||
continue;
|
||||
}
|
||||
self.flush_text(&mut text, settings.ignore_whitespace, &open, &mut roots)?;
|
||||
self.flush_text(&mut text, &mut text_held, settings.ignore_whitespace, &open, &mut roots)?;
|
||||
if rest.starts_with(&parser_units("<!--")) {
|
||||
let Some(end) = Self::find_from(src, pos + 4, &parser_units("--")) else {
|
||||
self.xml_text_fuel(src.len() - pos)?;
|
||||
@@ -2666,7 +2792,7 @@ impl Interp {
|
||||
}
|
||||
self.check_units(src, pos + 4, end)?;
|
||||
if !settings.ignore_comments {
|
||||
let value = Str::from_units(src.get(pos + 4..end).unwrap_or_default().to_vec());
|
||||
let value = Str::from_rc(Rc::from(src.get(pos + 4..end).unwrap_or_default()));
|
||||
let n = self.new_xml_node(XmlNode {
|
||||
kind: XmlKind::Comment,
|
||||
name: None,
|
||||
@@ -2698,7 +2824,7 @@ impl Interp {
|
||||
while from < end && src.get(from).copied().is_some_and(is_xml_space) {
|
||||
from += 1;
|
||||
}
|
||||
let value = Str::from_units(src.get(from..end).unwrap_or_default().to_vec());
|
||||
let value = Str::from_rc(Rc::from(src.get(from..end).unwrap_or_default()));
|
||||
let name = XmlName { uri: Some(Rc::from(Vec::new())), local: Rc::from(target), prefix: None };
|
||||
let n = self.new_xml_node(XmlNode {
|
||||
kind: XmlKind::Pi,
|
||||
@@ -2715,13 +2841,13 @@ impl Interp {
|
||||
} else if rest.get(1) == Some(&SLASH) {
|
||||
pos = self.parse_close_tag(src, pos, &mut open, &mut names)?;
|
||||
} else {
|
||||
pos = self.parse_open_tag(src, pos, &mut open, &mut names, &mut roots)?;
|
||||
pos = self.parse_open_tag(src, pos, &mut open, &mut names, &mut stack_held, &mut roots)?;
|
||||
}
|
||||
}
|
||||
if !open.is_empty() {
|
||||
return Err(self.syntax("an XML element is not closed"));
|
||||
}
|
||||
self.flush_text(&mut text, settings.ignore_whitespace, &open, &mut roots)?;
|
||||
self.flush_text(&mut text, &mut text_held, settings.ignore_whitespace, &open, &mut roots)?;
|
||||
Ok(roots)
|
||||
}
|
||||
|
||||
@@ -2752,7 +2878,8 @@ impl Interp {
|
||||
(name.uri.clone(), name.local.clone())
|
||||
}
|
||||
v => {
|
||||
let local = self.to_str(v)?.flat();
|
||||
let local = self.to_str(v)?;
|
||||
let local = flat_charged(self, &local)?;
|
||||
let uri = if *local == *STAR {
|
||||
None
|
||||
} else if attribute {
|
||||
@@ -2770,9 +2897,15 @@ impl Interp {
|
||||
Value::Object(o) => match self.heap.object(*o).map(|ob| &ob.class) {
|
||||
Some(Class::Namespace(ns)) => Some(ns.uri.clone()),
|
||||
Some(Class::QName { name, .. }) => name.uri.clone(),
|
||||
_ => Some(self.to_str(&q)?.flat()),
|
||||
_ => {
|
||||
let s = self.to_str(&q)?;
|
||||
Some(flat_charged(self, &s)?)
|
||||
}
|
||||
},
|
||||
_ => Some(self.to_str(&q)?.flat()),
|
||||
_ => {
|
||||
let s = self.to_str(&q)?;
|
||||
Some(flat_charged(self, &s)?)
|
||||
}
|
||||
};
|
||||
}
|
||||
let id = self.new_reference_name(XmlName { uri, local, prefix: None }, attribute)?;
|
||||
@@ -2816,7 +2949,8 @@ impl Interp {
|
||||
let result = match kind {
|
||||
0 if self.is_xml(&v) => self.xml_string_of(&v, Some(false))?,
|
||||
0 | 1 => {
|
||||
let text = self.to_str(&v)?.flat();
|
||||
let text = self.to_str(&v)?;
|
||||
let text = flat_charged(self, &text)?;
|
||||
let mut out = Builder::new();
|
||||
self.write_escaped(&mut out, &text, kind == 1)?;
|
||||
let Value::String(s) = out.finish(self) else { return Err(Abrupt::Internal("not a string".into())) };
|
||||
@@ -2991,7 +3125,8 @@ impl Interp {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(self.to_str(v)?.flat())
|
||||
let s = self.to_str(v)?;
|
||||
flat_charged(self, &s)
|
||||
}
|
||||
|
||||
pub(crate) fn op_set_default_namespace(&mut self) -> JsResult<()> {
|
||||
|
||||
@@ -1185,6 +1185,251 @@ fn a_limit_during_normalize_does_not_repeat_text() {
|
||||
assert!(fuel_stops(setup, "x.normalize()", check) > 0);
|
||||
}
|
||||
|
||||
/// A realm whose trees may be 100,000 levels deep, with `squeeze`, after `setup` ran with no limit.
|
||||
fn deep_realm(setup: &str) -> Realm {
|
||||
let mut r = Realm::with_options(Options { max_depth: 100_000, ..e4x() }, Limits::default());
|
||||
let interp = r.interp();
|
||||
let global = interp.global;
|
||||
assert!(crate::builtins::method(interp, global, "squeeze", squeeze, 1).is_ok());
|
||||
r.run(setup).unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
/// How `action` ends after `setup` in a [`deep_realm`], asserting that `check` is true after it
|
||||
/// with the limits lifted.
|
||||
fn squeezed(setup: &str, action: &str, check: &str) -> Result<JsValue, RunErrorKind> {
|
||||
let mut r = deep_realm(setup);
|
||||
let got = r.run(action).map_err(|e| e.kind);
|
||||
r.set_limits(Limits::default());
|
||||
assert_eq!(r.run(check), Ok(JsValue::Bool(true)), "{action}: {got:?}");
|
||||
got
|
||||
}
|
||||
|
||||
/// The least spare heap, found by bisection, at which `action` ends without the heap limit after
|
||||
/// `setup` in a [`deep_realm`].
|
||||
fn least_room(setup: &str, action: &str) -> usize {
|
||||
let ends = |spare: usize| match deep_realm(setup).run(&format!("squeeze({spare}); {action}")) {
|
||||
Ok(_) => true,
|
||||
Err(e) if e.kind == RunErrorKind::Limit(LimitKind::Heap) => false,
|
||||
Err(e) => panic!("{action}: {e:?}"),
|
||||
};
|
||||
let (mut lo, mut hi) = (0usize, 1usize << 22);
|
||||
assert!(ends(hi), "{action}");
|
||||
while lo < hi {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
if ends(mid) {
|
||||
hi = mid;
|
||||
} else {
|
||||
lo = mid + 1;
|
||||
}
|
||||
}
|
||||
lo
|
||||
}
|
||||
|
||||
/// Scripts that make `x`, an `r` element over 2,000 elements named `d`, nested in the first and
|
||||
/// side by side, named `wide_name`, in the second. Both also make `t`, an empty element, and turn
|
||||
/// pretty printing off.
|
||||
fn deep_and_wide(wide_name: &str) -> (String, String) {
|
||||
let common = "XML.prettyPrinting = false; var t = <t/>; var s = '';";
|
||||
let deep = format!(
|
||||
"{common} for (var i = 0; i < 2000; i++) s += '<d>'; for (var i = 0; i < 2000; i++) s += '</d>'; var x = new XML('<r>' + s + '</r>');"
|
||||
);
|
||||
let wide = format!("{common} for (var i = 0; i < 2000; i++) s += '<{wide_name}/>'; var x = new XML('<r>' + s + '</r>');");
|
||||
(deep, wide)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_walks_hold_their_stacks_against_the_heap_limit() {
|
||||
// A walk keeps a frame for each open level, so the deep tree needs room for 2,000 frames that
|
||||
// the wide tree, with as many nodes and the same markup length, does not.
|
||||
let mut wrong = Vec::new();
|
||||
for (action, wide_name, frame) in [
|
||||
("x.copy(); 1", "d", 8),
|
||||
("x..z.length()", "d", 8),
|
||||
("x.normalize(); 1", "d", 8),
|
||||
("t.appendChild(x); 1", "d", 8),
|
||||
("x.toXMLString().length", "dddd", 32),
|
||||
] {
|
||||
let (deep, wide) = deep_and_wide(wide_name);
|
||||
let (d, w) = (least_room(&deep, action), least_room(&wide, action));
|
||||
if d < w + 2000 * frame {
|
||||
wrong.push(format!("{action}: deep {d}, wide {w}"));
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
let (deep, _) = deep_and_wide("d");
|
||||
let same = "var y = x.copy(); var a = x, b = y, n = 0; while (a.d.length()) { a = a.d[0]; b = b.d[0]; n++; if (b.parent().d[0] !== b) break; } \
|
||||
n === 2000 && y.parent() === null && y == x && y.toXMLString() === x.toXMLString()";
|
||||
assert_eq!(squeezed(&deep, same, "true"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assignments_hold_the_matches_and_targets_they_collect() {
|
||||
let heap = Err(RunErrorKind::Limit(LimitKind::Heap));
|
||||
let wide = "var x = <r/>; for (var i = 0; i < 4000; i++) x.appendChild(<b/>);";
|
||||
let kept = "x.*.length() === 4000 && x.b[3999].parent() === x";
|
||||
assert_eq!(squeezed(wide, "squeeze(4096); x.b = 'v'; 1", kept), heap);
|
||||
let first = "var old = x.b[0]; x.b = 'v'; x.*.length() === 1 && x.b[0] === old && x.b == 'v'";
|
||||
assert_eq!(squeezed(wide, first, "x.b[0].parent() === x"), Ok(JsValue::Bool(true)));
|
||||
// `l` is an empty list 4,000 `.b` steps below `x.a`, which holds two elements, so the
|
||||
// assignment adds nothing.
|
||||
let chain = "var x = <r><a/><a/></r>; var l = x.a; for (var i = 0; i < 4000; i++) l = l.b;";
|
||||
let same = "x.*.length() === 2 && x.a.*.length() === 0";
|
||||
assert_eq!(squeezed(chain, "squeeze(4096); l.c = 'v'; 1", same), heap);
|
||||
assert_eq!(squeezed(chain, "l.c = 'v'; 1", same), Ok(JsValue::Number(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializing_charges_the_text_it_flattens() {
|
||||
// `k` is a rope of 32,768 units. Both trees hold the same 65,536 units of text, as a rope in the
|
||||
// first and as flat text in the second.
|
||||
let k = "var k = 'x'; for (var i = 0; i < 15; i++) k += k; XML.prettyPrinting = false;";
|
||||
let rope = format!("{k} var x = <r/>; x.appendChild(k); x.appendChild(k); x.normalize();");
|
||||
let flat = format!("{k} var x = new XML('<r>' + k + k + '</r>');");
|
||||
let action = "x.toXMLString().length";
|
||||
let (r, f) = (least_room(&rope, action), least_room(&flat, action));
|
||||
assert!(r >= f + 100_000, "rope {r}, flat {f}");
|
||||
let attr = format!("{k} var x = <r/>; x.@a = k + k;");
|
||||
let same = "var s = x.toXMLString(); s.length > 65536 && s.indexOf(k + k) > 0 && new XML(s).toXMLString() === s";
|
||||
for setup in [rope, attr] {
|
||||
assert_eq!(squeezed(&setup, same, "true"), Ok(JsValue::Bool(true)), "{setup}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A script that makes `x`, a `r:r` element over 2,000 nested `r:d` elements in the same
|
||||
/// namespace, each of which declares one more prefix: a new one each time, or `q10000` each time.
|
||||
fn nested_prefixes(same: bool) -> String {
|
||||
let prefix = if same { "10000" } else { "' + (10000 + i) + '" };
|
||||
format!(
|
||||
"XML.prettyPrinting = false; var s = ''; for (var i = 0; i < 2000; i++) s += '<r:d xmlns:q{prefix}=\"u' + (10000 + i) + '\">'; \
|
||||
for (var i = 0; i < 2000; i++) s += '</r:d>'; var x = new XML('<r:r xmlns:r=\"R\">' + s + '</r:r>');"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializing_holds_the_prefixes_a_lookup_passes() {
|
||||
// Finding the `r` prefix from the deepest element passes 2,000 prefixes when each level
|
||||
// declares a new one, and one when they all declare `q10000`.
|
||||
let action = "x.toXMLString().length";
|
||||
let (new, same) = (least_room(&nested_prefixes(false), action), least_room(&nested_prefixes(true), action));
|
||||
assert!(new >= same + 2000 * 16, "new {new}, same {same}");
|
||||
let check = "var s = x.toXMLString(); s.indexOf('<r:r xmlns:r=\"R\"><r:d xmlns:q10000=\"u10000\"><r:d xmlns:q10001=\"u10001\">') === 0 && new XML(s).toXMLString() === s";
|
||||
assert_eq!(squeezed(&nested_prefixes(false), check, "true"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_prefix_is_the_first_free_ns_number() {
|
||||
let setup = "XML.prettyPrinting = false; var n = new Namespace('urn:z');";
|
||||
for (decls, prefix) in [
|
||||
("", "ns0"),
|
||||
(" xmlns:ns0=\"a\" xmlns:ns1=\"b\" xmlns:ns3=\"c\" xmlns:ns02=\"d\"", "ns2"),
|
||||
(" xmlns:ns0=\"a\" xmlns:ns1=\"b\" xmlns:nsx=\"c\" xmlns:ns2=\"d\"", "ns3"),
|
||||
] {
|
||||
truth(&format!(
|
||||
"{setup} var x = <r{decls}/>; x.@n::a = 'v'; var s = x.toXMLString(); \
|
||||
s.indexOf(' {prefix}:a=\"v\"') > 0 && s.indexOf(' xmlns:{prefix}=\"urn:z\"') > 0 && new XML(s).@n::a == 'v'"
|
||||
));
|
||||
}
|
||||
truth(&format!(
|
||||
"{setup} var s = ''; for (var i = 0; i < 500; i++) s += ' xmlns:ns' + i + '=\"u' + i + '\"'; var x = new XML('<r' + s + '/>'); x.@n::a = 'v'; \
|
||||
x.toXMLString().indexOf(' ns500:a=\"v\"') > 0"
|
||||
));
|
||||
}
|
||||
|
||||
/// A script that makes `x`, an `r` element over 4,000 `b` elements, `l`, the list of them, and
|
||||
/// `t`, an empty element.
|
||||
const MANY_B: &str = "XML.prettyPrinting = false; var x = <r/>; for (var i = 0; i < 4000; i++) x.appendChild(<b/>); var l = x.b; var t = <t/>;";
|
||||
|
||||
#[test]
|
||||
fn inserting_a_list_holds_its_copy_of_the_items() {
|
||||
// Both actions move the same 4,000 elements under `t`. The first charges the links, 8 bytes
|
||||
// each, before any element leaves `x`, and holds its copy of the list's items, 4 bytes each;
|
||||
// the second moves them one at a time.
|
||||
let list = least_room(MANY_B, "t.prependChild(l); 1");
|
||||
let one_by_one = least_room(MANY_B, "for (var i = 0; i < 4000; i++) t.prependChild(l[i]); 1");
|
||||
assert!(list >= one_by_one + 4000 * (8 + 2), "list {list}, one by one {one_by_one}");
|
||||
let moved = "t.prependChild(l); t.*.length() === 4000 && x.*.length() === 0 && t.b[3999].parent() === t";
|
||||
assert_eq!(squeezed(MANY_B, moved, "true"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_a_list_to_a_list_item_holds_its_copy_of_the_items() {
|
||||
// Both actions put the 4,000 elements of `l` under `m`. The first, through the list `m.a`,
|
||||
// also makes a list of them, 8 bytes each, and holds a copy of its items, 4 bytes each.
|
||||
let setup = format!("{MANY_B} var m = <m><a/></m>; var la = m.a;");
|
||||
let through_list = least_room(&setup, "la[0] = l; 1");
|
||||
let direct = least_room(&setup, "m.prependChild(l); 1");
|
||||
assert!(through_list >= direct + 4000 * 10, "through the list {through_list}, direct {direct}");
|
||||
let placed = "la[0] = l; m.*.length() === 4000 && la.length() === 4000 && la[3999] === m.b[3999] && x.*.length() === 0";
|
||||
assert_eq!(squeezed(&setup, placed, "true"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsing_holds_its_open_elements_and_attribute_scratch() {
|
||||
// The deep markup leaves 2,000 elements open at once and the wide markup, of the same
|
||||
// length, leaves none. The open elements and their names take 2,048 times 20 bytes, and the
|
||||
// longer names of the wide markup take 2,000 times 6 bytes more.
|
||||
let (deep, wide) = deep_and_wide("dddd");
|
||||
let action = "new XML('<r>' + s + '</r>'); 1";
|
||||
let (d, w) = (least_room(&deep, action), least_room(&wide, action));
|
||||
// Both elements declare 2,001 namespaces and have one attribute. Resolving the prefix of the
|
||||
// attribute in the first reads a copy of the element's namespaces.
|
||||
let decls = "var d = ''; for (var i = 10000; i < 12000; i++) d += ' xmlns:n' + i + '=\"u\"';";
|
||||
let prefixed = least_room(decls, "new XML('<r' + d + ' xmlns:p=\"P\" p:a=\"v\"/>'); 1");
|
||||
let plain = least_room(decls, "new XML('<r' + d + ' xmlns:p=\"P\" pa=\"v\"/>'); 1");
|
||||
assert!(d >= w + 2000 * 8 && prefixed >= plain + 2000 * 32, "deep {d}, wide {w}, prefixed {prefixed}, plain {plain}");
|
||||
truth(&format!(
|
||||
"{decls} var x = new XML('<r' + d + ' xmlns:p=\"P\" p:a=\"v\" b=\"w\"/>'); x.@b == 'w' && x.namespaceDeclarations().length == 2001"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flattening_a_rope_in_xml_code_is_charged() {
|
||||
let k = "var k = 'x'; for (var i = 0; i < 15; i++) k += k; XML.prettyPrinting = false; var x = <r/>, y = <r/>;";
|
||||
// Each pair holds the same 65,536 units as ropes in the first script and as flat text in the
|
||||
// second: the text of `x` and `y`, an attribute of `x` and `y`, and the string `s2`.
|
||||
let text = (
|
||||
format!("{k} for each (var e in [x, y]) {{ e.appendChild(k); e.appendChild(k); e.normalize(); }}"),
|
||||
format!("{k} x = new XML('<r>' + k + k + '</r>'); y = new XML('<r>' + k + k + '</r>');"),
|
||||
);
|
||||
let attr = (format!("{k} x.@a = k + k; y.@a = k + k;"), format!("{k} x = new XML('<r a=\"' + k + k + '\"/>'); y = new XML(x.toXMLString());"));
|
||||
let o = "var o = { toString: function () { return s2; } };";
|
||||
let string = (format!("{k} var s2 = k + k; {o}"), format!("{k} var s2 = new XML('<r>' + k + k + '</r>').toString(); {o}"));
|
||||
let mut wrong = Vec::new();
|
||||
for ((rope, flat), action) in [
|
||||
(&text, "x == y"),
|
||||
(&attr, "x == y"),
|
||||
(&text, "x.text()[0] == y.text()[0]"),
|
||||
(&text, "x.text()[0] == 'z'"),
|
||||
(&string, "<e/> == s2"),
|
||||
(&text, "x.toString().length"),
|
||||
(&text, "x.text().toString().length"),
|
||||
(&string, "x.@[s2].length()"),
|
||||
(&string, "x.s2::b.length()"),
|
||||
(&string, "x.o::b.length()"),
|
||||
(&string, "default xml namespace = s2; 1"),
|
||||
(&string, "x[s2].length()"),
|
||||
(&string, "x[o].length()"),
|
||||
] {
|
||||
let (r, f) = (least_room(rope, action), least_room(flat, action));
|
||||
if r < f + 100_000 {
|
||||
wrong.push(format!("{action}: rope {r}, flat {f}"));
|
||||
}
|
||||
}
|
||||
// A name read from a flat string is a copy of its units after `@` for an attribute, and shares
|
||||
// the string for an element.
|
||||
let names = format!("{} var at = new XML('<r>@' + k + k + '</r>').toString();", string.1);
|
||||
let (a, e) = (least_room(&names, "x[at].length()"), least_room(&names, "x[s2].length()"));
|
||||
if a < e + 100_000 {
|
||||
wrong.push(format!("names: attribute {a}, element {e}"));
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
let same = "x == y && x.text()[0] == y.text()[0] && x.toString() === s && x.text().toString() === s && !(x.text()[0] == 'z')";
|
||||
for setup in [&text.0, &text.1] {
|
||||
assert_eq!(squeezed(&format!("{setup} var s = k + k;"), same, "true"), Ok(JsValue::Bool(true)), "{setup}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `action` as [`heap_stops`] does, and asserts that every run completes or stops at the heap
|
||||
/// limit and that `check` is true after it. Returns how many runs stopped.
|
||||
fn heap_stops_only(setup: &str, action: &str, check: &str) -> usize {
|
||||
|
||||
@@ -646,6 +646,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{} the Learn panel's skills in the order its Skills tab lists them: {skills: [{id, title, tutorials: [{id, title, steps: number of steps}]}]}",
|
||||
),
|
||||
(
|
||||
"learn.skills",
|
||||
"Back to Skills",
|
||||
"",
|
||||
"{} show the Learn panel on its Skills tab with the list of skills, with no skill and no tutorial open, as Back to skills after a skill's last tutorial and the Quick skill guide card do; returns what learn.list returns",
|
||||
),
|
||||
(
|
||||
"learn.show",
|
||||
"Show Tutorial",
|
||||
@@ -658,6 +664,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"",
|
||||
"{tool: a tool id, as tool.select takes} mark where that tool is for 3 seconds without choosing it, as the link on a tool's name in a Learn tutorial step does: its toolbar button, a row of its collapsed group's flyout (which opens), its group's torn-off strip (which comes to the front), or, when no shown toolbar holds it, its row in the All Tools drawer (which opens); a Tools panel hidden with Window › Tools shows again; Escape or the next locate removes the mark; a missing, non-string or unknown id is an error and changes nothing; returns {tool, location: toolbar|flyout|strip|allTools|unavailable, toolbar: the name of the toolbar made with New Toolbar that holds it, or null}, with reason when Presentation Mode or Tab hides the toolbars",
|
||||
),
|
||||
(
|
||||
"learn.openSample",
|
||||
"Open Tutorial Sample",
|
||||
"",
|
||||
"{tutorial: id (see learn.list)} open that tutorial's practice sample as a new untitled document, which becomes the active one, and move the Learn view to the tutorial, as its View more button does; each call opens another copy and open documents stay as they are; a missing, non-string or unknown id is an error and changes nothing; returns {tutorial, index, title} of the new document",
|
||||
),
|
||||
(
|
||||
"learn.finish",
|
||||
"Finish Tutorial",
|
||||
"",
|
||||
"{tutorial: id (see learn.list)} mark a tutorial whose sample learn.openSample opened as finished, as its Finish tutorial button does; finishing it again keeps one entry; a missing, non-string or unknown id, or a tutorial whose sample was not opened, is an error and changes nothing; returns {tutorial, finished: true, next: id of the next tutorial in its skill, or null after the skill's last one}",
|
||||
),
|
||||
(
|
||||
"learn.next",
|
||||
"Next Tutorial",
|
||||
"",
|
||||
"{tutorial: id (see learn.list)} show the Learn panel on the tutorial after a finished one in the same skill, as its Next Up button does, without opening a sample; a missing, non-string or unknown id, a tutorial not finished, or a skill's last tutorial is an error and changes nothing; returns {skill, tutorial, title} of the next tutorial",
|
||||
),
|
||||
("window.brightness", "UI Brightness", "", "{brightness: dark|mediumDark|mediumLight|light}"),
|
||||
(
|
||||
"window.workspace",
|
||||
|
||||
+111
-5
@@ -22,14 +22,23 @@ pub struct SimplifyOptions {
|
||||
/// How far (points, the spread of a Gaussian along the path) the path is smoothed before it is
|
||||
/// refitted, so that bumps and jags come out as one curve ([`smooth_level`]); 0 for none.
|
||||
pub smooth: f64,
|
||||
/// With [`smooth`](Self::smooth), refit each stretch fitted as one piece (between corners) within
|
||||
/// twice the farthest the smoothing moved any of its points when that is less than `tolerance`, and
|
||||
/// never within less than a tenth of `tolerance`. A stretch that smoothing barely moves anywhere
|
||||
/// keeps its shape. The limit is the same along the whole stretch, so where smoothing moves some of
|
||||
/// its points far, all of it is refitted within up to `tolerance`, as without this option.
|
||||
pub smooth_moved_only: bool,
|
||||
}
|
||||
|
||||
impl Default for SimplifyOptions {
|
||||
fn default() -> Self {
|
||||
Self { tolerance: 0.5, corner_angle_deg: 30.0, straight_lines: false, smooth: 0.0 }
|
||||
Self { tolerance: 0.5, corner_angle_deg: 30.0, straight_lines: false, smooth: 0.0, smooth_moved_only: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// The least share of the tolerance that [`SimplifyOptions::smooth_moved_only`] refits within.
|
||||
const SMOOTH_MOVED_FLOOR: f64 = 0.1;
|
||||
|
||||
/// Simplify with the default corner threshold (30°).
|
||||
pub fn simplify(path: &PathData, tolerance: f64) -> PathData {
|
||||
simplify_with(path, &SimplifyOptions { tolerance, ..Default::default() })
|
||||
@@ -310,16 +319,27 @@ pub(crate) fn simplify_run_within(run: &[Seg], opts: &SimplifyOptions, mut budge
|
||||
}
|
||||
|
||||
/// Adds the refit of `part`, consecutive segments with no corner between them and the steps to
|
||||
/// sample each one with, to `result`. `ends` is the direction it leaves and arrives along, when not
|
||||
/// those of its first and last segments.
|
||||
fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, ends: Option<Vec2>, result: &mut Vec<Seg>) {
|
||||
/// sample each one with, to `result`. `ends`, given only when `part` is a whole closed loop, is the
|
||||
/// direction it leaves and arrives along; when the loop is smoothed, the smoothing runs across its
|
||||
/// start and the direction comes from the smoothed samples there.
|
||||
fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, mut ends: Option<Vec2>, result: &mut Vec<Seg>) {
|
||||
let (Some((first, _)), Some((last, _))) = (part.first(), part.last()) else { return };
|
||||
let mut pts = Vec::new();
|
||||
for (k, (s, steps)) in part.iter().enumerate() {
|
||||
sample(&s.c, *steps, &mut pts, k == 0);
|
||||
}
|
||||
let mut tol = tol;
|
||||
if opts.smooth > 0.0 {
|
||||
pts = smooth_points(&pts, opts.smooth);
|
||||
let smoothed = if ends.is_some() { smooth_loop_points(&pts, opts.smooth) } else { smooth_points(&pts, opts.smooth) };
|
||||
if ends.is_some()
|
||||
&& let (Some(&next), Some(&prev)) = (smoothed.get(1), smoothed.len().checked_sub(2).and_then(|i| smoothed.get(i)))
|
||||
{
|
||||
ends = unit(next - prev).or(ends);
|
||||
}
|
||||
if opts.smooth_moved_only {
|
||||
tol = tol.min((2.0 * smoothing_moved(&pts, &smoothed)).max(tol * SMOOTH_MOVED_FLOOR));
|
||||
}
|
||||
pts = smoothed;
|
||||
}
|
||||
if opts.straight_lines {
|
||||
let keep = rdp(&pts, tol * (1.0 - SAMPLE_GAP));
|
||||
@@ -346,6 +366,66 @@ fn smooth_points(pts: &[Point], sigma: f64) -> Vec<Point> {
|
||||
smooth_points_counted(pts, sigma, &mut 0)
|
||||
}
|
||||
|
||||
/// [`smooth_points`] for the samples `pts` of a whole closed loop, whose last sample is its first:
|
||||
/// the samples at its start are smoothed like the others, and the first and last ones move together.
|
||||
/// The loop is smoothed twice as an open run of the same samples, once from its start and once from
|
||||
/// the sample nearest halfway round by length, where [`smooth_points`] keeps each run's ends in place.
|
||||
/// Each sample takes a blend of the two that runs smoothly round the loop, with weights
|
||||
/// `(1 ± cos θ) / 2`: `θ` goes from 0 at the start to π at the halfway sample and on to 2π at the end,
|
||||
/// in proportion to length, so the start takes only the second run and the halfway sample only the
|
||||
/// first, and no sample takes any of a run's fixed ends.
|
||||
fn smooth_loop_points(pts: &[Point], sigma: f64) -> Vec<Point> {
|
||||
let Some(m) = pts.len().checked_sub(1).filter(|&m| m >= 3) else { return smooth_points(pts, sigma) };
|
||||
let mut along = Vec::with_capacity(pts.len());
|
||||
let mut total = 0.0;
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
if let Some(prev) = i.checked_sub(1).and_then(|j| pts.get(j)) {
|
||||
total += prev.distance(*p);
|
||||
}
|
||||
along.push(total);
|
||||
}
|
||||
if !(total.is_finite() && total > 0.0) {
|
||||
return smooth_points(pts, sigma);
|
||||
}
|
||||
let half = (1..m).min_by(|&a, &b| (along[a] - total / 2.0).abs().total_cmp(&(along[b] - total / 2.0).abs())).unwrap_or(m / 2);
|
||||
let mid = along[half];
|
||||
if !(mid > 0.0 && mid < total) {
|
||||
return smooth_points(pts, sigma);
|
||||
}
|
||||
let ring = &pts[..m];
|
||||
let turned: Vec<Point> = ring[half..].iter().chain(&ring[..=half]).copied().collect();
|
||||
let from_half = smooth_points(&turned, sigma);
|
||||
let mut out = smooth_points(pts, sigma);
|
||||
for (i, (p, &s)) in out.iter_mut().zip(&along).enumerate() {
|
||||
// Sample `i` of the loop is sample `i - half` of `turned`, round the loop.
|
||||
let Some(&q) = from_half.get((i + m - half) % m) else { continue };
|
||||
let theta = if s <= mid { s / mid } else { 1.0 + (s - mid) / (total - mid) } * std::f64::consts::PI;
|
||||
let w = 0.5 * (1.0 + theta.cos());
|
||||
*p = p.lerp(q, w);
|
||||
}
|
||||
if let Some(&start) = out.first()
|
||||
&& let Some(end) = out.last_mut()
|
||||
{
|
||||
*end = start;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How far [`smooth_points`] moved the samples `pts` to `smoothed` (the same number of points, in
|
||||
/// order) across the path: the largest distance from a smoothed point to the lines between the
|
||||
/// samples up to two on either side of the one it came from.
|
||||
fn smoothing_moved(pts: &[Point], smoothed: &[Point]) -> f64 {
|
||||
smoothed
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &q)| {
|
||||
let own = pts.get(i).map_or(f64::INFINITY, |p| p.distance(q));
|
||||
let (lo, hi) = (i.saturating_sub(2), (i + 2).min(pts.len().saturating_sub(1)));
|
||||
(lo..hi).filter_map(|j| Some(Line::new(*pts.get(j)?, *pts.get(j + 1)?).nearest(q, 1e-9).distance_sq.sqrt())).fold(own, f64::min)
|
||||
})
|
||||
.fold(0.0, f64::max)
|
||||
}
|
||||
|
||||
/// How many groups of samples a spread holds at most in [`smooth_points`]. Weighing them in groups
|
||||
/// leaves each smoothed point within a thousandth of a spread of the mean of its samples weighed one
|
||||
/// by one.
|
||||
@@ -678,6 +758,7 @@ pub fn smooth_options(path: &PathData, level: f64) -> SimplifyOptions {
|
||||
corner_angle_deg: SMOOTH_CORNER_DEG,
|
||||
straight_lines: false,
|
||||
smooth: size * 0.05 * level / 100.0,
|
||||
smooth_moved_only: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1182,6 +1263,31 @@ mod tests {
|
||||
assert!(work <= 400 * pts.len(), "{work} steps for {} samples", pts.len());
|
||||
}
|
||||
|
||||
/// A spike on a closed loop whose samples are ten times denser on one half than on the other is
|
||||
/// smoothed out wherever it is, including at the sample halfway through the list, which is only
|
||||
/// about a quarter of the way round by length.
|
||||
#[test]
|
||||
fn loop_smoothing_smooths_a_spike_on_unevenly_sampled_loops() {
|
||||
let c = Point::new(300.0, 300.0);
|
||||
let on = |a: f64, r: f64| c + r * Vec2::from_angle(a);
|
||||
let mut pts: Vec<Point> = (0..300).map(|i| on(f64::from(i) / 300.0 * std::f64::consts::PI, 100.0)).collect();
|
||||
pts.extend((0..30).map(|i| on(std::f64::consts::PI * (1.0 + f64::from(i) / 30.0), 100.0)));
|
||||
let m = pts.len();
|
||||
pts.push(pts[0]);
|
||||
for spike in [m / 2, 0, 100] {
|
||||
let mut p = pts.clone();
|
||||
p[spike] = on(std::f64::consts::PI * spike as f64 / 300.0, 105.0);
|
||||
if spike == 0 {
|
||||
p[m] = p[0];
|
||||
}
|
||||
let out = smooth_loop_points(&p, 10.0);
|
||||
assert_eq!(out.len(), p.len());
|
||||
assert_eq!(out[0], out[m], "spike at {spike}: the loop stays closed");
|
||||
let left = out[spike].distance(c) - 100.0;
|
||||
assert!(left < 1.0, "spike at {spike}: {left} pt of 5 pt left");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_samples_of_a_flat_loop_and_its_line_segments_stay_within_the_result_limit() {
|
||||
for (curved, kept) in [(1, 0), (32, 1), (40, 1_000_000), (1_000, MAX_RUN_RESULT - 1_000), (3, MAX_RUN_RESULT - 7)] {
|
||||
|
||||
@@ -183,10 +183,18 @@ fn offset_region(
|
||||
} else {
|
||||
BezPath::new()
|
||||
};
|
||||
let arr = Arrangement::new_budgeted(
|
||||
vec![(fill, FillRule::NonZero), (ring, FillRule::NonZero), (open_bp, FillRule::NonZero)],
|
||||
MAX_OFFSET_SEGMENT_PAIRS,
|
||||
)?;
|
||||
let parts = vec![fill, ring, open_bp];
|
||||
match crate::sweep_axis::turned_outlines(&parts) {
|
||||
Some(turned) => offset_faces(turned, delta, |p, r| within(crate::sweep_axis::unturn_point(p), r)).map(crate::sweep_axis::unturn),
|
||||
None => offset_faces(parts, delta, within),
|
||||
}
|
||||
}
|
||||
|
||||
/// The faces of the offset by `delta` from `parts` (the closed fill, the ring stroked around it and
|
||||
/// the stroke of the open subpaths, in that order), less the spurious ones that `within` finds.
|
||||
fn offset_faces(parts: Vec<BezPath>, delta: f64, within: impl Fn(kurbo::Point, f64) -> bool) -> Result<PathData, PathOpsError> {
|
||||
let d = delta.abs();
|
||||
let arr = Arrangement::new_budgeted(parts.into_iter().map(|p| (p, FillRule::NonZero)).collect(), MAX_OFFSET_SEGMENT_PAIRS)?;
|
||||
let c = if delta >= 0.0 { arr.contours_covering(|c| !c.is_empty()) } else { arr.contours_covering(|c| c.contains(&0) && !c.contains(&1)) };
|
||||
// When `d` exceeds a curvature radius the stroker's inner offset inverts and its loops cancel
|
||||
// winding, leaving faces uncovered that are really within `d` of the path. Every face of the
|
||||
|
||||
@@ -149,6 +149,11 @@ pub(crate) fn unturn(mut path: PathData) -> PathData {
|
||||
path
|
||||
}
|
||||
|
||||
/// A point of turned input, turned back.
|
||||
pub(crate) fn unturn_point(p: kurbo::Point) -> kurbo::Point {
|
||||
UNTURN * p
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use kurbo::{Join, Stroke, StrokeOpts};
|
||||
@@ -251,6 +256,39 @@ mod tests {
|
||||
assert_eq!(turns_during(|| drop(stroke_region(std::slice::from_ref(&short)))), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end() {
|
||||
let mut rng = Rng(17);
|
||||
// Grown past the zigzag's bends, where the stroker leaves loops whose faces are dropped by
|
||||
// the distance test; grown a little; and inset.
|
||||
for (closed, delta) in [(false, 1.5), (true, 0.5), (true, -0.3)] {
|
||||
let what = format!("closed {closed}, offset {delta}");
|
||||
let low = zigzag(3, 300, 0.4, &mut rng, closed);
|
||||
let tall = upright(&low);
|
||||
let offset = |p: &PathData| crate::try_offset_path(p, delta, Join::Round, 4.0).unwrap();
|
||||
let mut turned = PathData::default();
|
||||
assert_eq!(turns_during(|| turned = offset(&low)), 1, "{what}: low");
|
||||
let mut on_end = PathData::default();
|
||||
assert_eq!(turns_during(|| on_end = offset(&tall)), 0, "{what}: tall");
|
||||
assert!(!turned.is_empty(), "{what}: empty");
|
||||
assert_same_region(&turned, &upright(&on_end), &what);
|
||||
}
|
||||
// A long plate with a row of round holes: growing it by 1 closes the narrow holes, which
|
||||
// the distance test drops, and keeps the wide ones.
|
||||
use kurbo::Shape;
|
||||
let mut plate = kurbo::Rect::new(0.0, 0.0, 4000.0, 20.0).to_path(0.1);
|
||||
for i in 0..200u32 {
|
||||
let r = if i % 2 == 0 { 0.8 } else { 4.0 };
|
||||
plate.extend(kurbo::Circle::new((10.0 + 20.0 * f64::from(i), 10.0), r).to_path(0.01).reverse_subpaths());
|
||||
}
|
||||
let plate = PathData::from_bezpath(&plate);
|
||||
let grow = |p: &PathData| crate::try_offset_path(p, 1.0, Join::Round, 4.0).unwrap();
|
||||
let mut grown = PathData::default();
|
||||
assert_eq!(turns_during(|| grown = grow(&plate)), 1, "plate");
|
||||
assert_eq!(grown.subpaths.len(), 1 + 100, "plate");
|
||||
assert_same_region(&grown, &upright(&grow(&upright(&plate))), "plate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeating_path_is_measured_at_every_position() {
|
||||
// Short segments in a row along the bottom, with a long one stacked above the row after
|
||||
|
||||
@@ -82,6 +82,57 @@ pub fn install(mut plugin: Plugin) -> Result<Arc<Plugin>> {
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// What [`install_checked`] does to the grant recorded for the plug-in's id.
|
||||
pub enum GrantUpdate {
|
||||
/// Records this grant, replacing an earlier one for the id ([`grant`]).
|
||||
Record(GrantToken),
|
||||
/// Forgets the grant for the id ([`revoke`]).
|
||||
Revoke,
|
||||
}
|
||||
|
||||
/// Installs `plugin` and updates the grant for its id as one step. While it holds the plug-ins and
|
||||
/// then the grants, `check` is given the plug-in installed under the id and the grant recorded for
|
||||
/// it. When `check` returns an error, nothing changes and that error is returned. A plug-in that
|
||||
/// lists permissions the grant `update` records doesn't give this very module is refused the same
|
||||
/// way, with [`Error::NeedsApproval`] passed through `refused`. Otherwise `attach` runs, the grant
|
||||
/// is updated and the plug-in is installed, replacing one with the same id. `check` and `attach`
|
||||
/// must not call the other functions of this module, which wait for the locks held here.
|
||||
pub fn install_checked<E>(
|
||||
mut plugin: Plugin,
|
||||
update: GrantUpdate,
|
||||
check: impl FnOnce(Option<&Plugin>, Option<&Grant>) -> std::result::Result<(), E>,
|
||||
attach: impl FnOnce(),
|
||||
refused: impl FnOnce(Error) -> E,
|
||||
) -> std::result::Result<Arc<Plugin>, E> {
|
||||
// The same order as `install`, which reads the grants while it holds the plug-ins.
|
||||
let mut plugins = PLUGINS.write().unwrap_or_else(|e| e.into_inner());
|
||||
let mut grants = GRANTS.write().unwrap_or_else(|e| e.into_inner());
|
||||
let id = plugin.id().to_string();
|
||||
check(plugins.get(&id).map(|p| &**p), grants.get(&id))?;
|
||||
let m = plugin.manifest();
|
||||
let granted = match &update {
|
||||
GrantUpdate::Record(token) => Some(token.grant()),
|
||||
GrantUpdate::Revoke => None,
|
||||
};
|
||||
if m.asks_permissions() && !granted.is_some_and(|g| g.covers(&m.id, plugin.hash(), &m.permissions())) {
|
||||
return Err(refused(Error::NeedsApproval(crate::permissions::names(&m.permissions()).join(", "))));
|
||||
}
|
||||
attach();
|
||||
match update {
|
||||
GrantUpdate::Record(token) => {
|
||||
let g = token.grant().clone();
|
||||
grants.insert(g.id.clone(), g);
|
||||
}
|
||||
GrantUpdate::Revoke => {
|
||||
grants.remove(&id);
|
||||
}
|
||||
}
|
||||
plugin.set_serial(REVISION.fetch_add(1, Ordering::Relaxed) + 1);
|
||||
let p = Arc::new(plugin);
|
||||
plugins.insert(id, p.clone());
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Loads `bytes` with the default limits and installs the plug-in ([`install`]: one that lists
|
||||
/// permissions installs only when they were granted to this very module).
|
||||
pub fn install_bytes(bytes: &[u8]) -> Result<Arc<Plugin>> {
|
||||
@@ -345,4 +396,61 @@ mod tests {
|
||||
assert!(granted(id).is_none() && remove(id), "{listed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `install_checked` gives `check` the plug-in and grant held for the id. When `check` refuses,
|
||||
/// or the grant it would record doesn't approve the module, the plug-in, the grant and the
|
||||
/// revision stay as they were and `attach` doesn't run; otherwise it records the grant (or
|
||||
/// forgets it) and installs the module.
|
||||
#[test]
|
||||
fn install_checked_changes_nothing_when_refused() {
|
||||
use crate::permissions::Permission::DocRead;
|
||||
let _lock = crate::safe_mode::TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let id = "test.registry.checked";
|
||||
let old = module(id, Some(r#"["doc.read"]"#), 8);
|
||||
let new = module(id, Some(r#"["doc.read"]"#), 9);
|
||||
grant(GrantToken::after_engine_approval(grant_for(id, &old, vec![DocRead])));
|
||||
install_bytes(&old).unwrap();
|
||||
let load = |bytes: &[u8]| Plugin::load(bytes, Limits::default()).unwrap();
|
||||
let record = |bytes: &[u8]| GrantUpdate::Record(GrantToken::after_engine_approval(grant_for(id, bytes, vec![DocRead])));
|
||||
let unchanged = |why: &str| {
|
||||
assert_eq!(get(id).map(|p| p.hash().to_string()), Some(crate::permissions::sha256_hex(&old)), "{why}");
|
||||
assert_eq!(granted(id), Some(grant_for(id, &old, vec![DocRead])), "{why}");
|
||||
};
|
||||
let attached = std::cell::Cell::new(false);
|
||||
let before = revision();
|
||||
|
||||
let seen = std::cell::RefCell::new(None);
|
||||
let e = install_checked(
|
||||
load(&new),
|
||||
record(&new),
|
||||
|p, g| {
|
||||
*seen.borrow_mut() = Some((p.map(|p| p.hash().to_string()), g.cloned()));
|
||||
Err("refused")
|
||||
},
|
||||
|| attached.set(true),
|
||||
|_| "not approved",
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(e, "refused");
|
||||
assert_eq!(seen.take(), Some((Some(crate::permissions::sha256_hex(&old)), Some(grant_for(id, &old, vec![DocRead])))));
|
||||
unchanged("check refused");
|
||||
|
||||
let same = std::convert::identity::<Error>;
|
||||
let e = install_checked(load(&new), record(&old), |_, _| Ok(()), || attached.set(true), same).unwrap_err();
|
||||
assert_eq!(e, Error::NeedsApproval("doc.read".into()));
|
||||
unchanged("a grant for other bytes");
|
||||
let e = install_checked(load(&new), GrantUpdate::Revoke, |_, _| Ok(()), || attached.set(true), same).unwrap_err();
|
||||
assert_eq!(e, Error::NeedsApproval("doc.read".into()));
|
||||
unchanged("no grant");
|
||||
assert!(!attached.get() && revision() == before, "nothing ran or moved");
|
||||
|
||||
let p = install_checked(load(&new), record(&new), |_, _| Ok(()), || attached.set(true), same).unwrap();
|
||||
assert!(attached.get() && revision() > before);
|
||||
assert_eq!(get(id).map(|p| p.hash().to_string()), Some(p.hash().to_string()));
|
||||
assert_eq!(granted(id), Some(grant_for(id, &new, vec![DocRead])));
|
||||
let plain = module(id, Some("[]"), 10);
|
||||
install_checked(load(&plain), GrantUpdate::Revoke, |_, _| Ok(()), || {}, same).unwrap();
|
||||
assert!(granted(id).is_none(), "a module without permissions forgets the grant");
|
||||
assert!(remove(id));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The shipped code that records a plug-in grant: only the engine's install approval and its load
|
||||
//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant`. A new call
|
||||
//! site fails this test until it is added to the list. It checks the source, not what native code
|
||||
//! can do at run time.
|
||||
//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant` or
|
||||
//! `registry::install_checked`. A new call site fails this test until it is added to the list. It
|
||||
//! checks the source, not what native code can do at run time.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
@@ -11,10 +11,13 @@ use std::path::{Path, PathBuf};
|
||||
const EXPECTED: &[(&str, &str, usize)] = &[
|
||||
("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2),
|
||||
("registry::grant", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
("registry::grant", "crates/engine/src/store.rs", 2),
|
||||
("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1),
|
||||
];
|
||||
|
||||
/// The names the audit counts.
|
||||
const NAMES: [&str; 4] = ["GrantToken::after_engine_approval", "GrantToken::from_engine_grants_file", "registry::grant", "registry::install_checked"];
|
||||
|
||||
/// Every `.rs` file under `dir`, without test files and folders.
|
||||
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
@@ -61,7 +64,7 @@ fn grant_token_call_sites_are_limited() {
|
||||
let text = std::fs::read_to_string(file).unwrap();
|
||||
let rel = file.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/");
|
||||
for line in shipped(&text) {
|
||||
for name in ["GrantToken::after_engine_approval", "GrantToken::from_engine_grants_file", "registry::grant"] {
|
||||
for name in NAMES {
|
||||
let n = count(line, name);
|
||||
if n > 0 {
|
||||
*found.entry((name, rel.clone())).or_default() += n;
|
||||
|
||||
@@ -125,9 +125,15 @@ impl BrushCache {
|
||||
}
|
||||
|
||||
/// Cull bounds that allow for brush art reaching past the stroke (scatter, wide nibs), symbol
|
||||
/// instances measured by their art from `symbols`, with the brushed strokes in that art.
|
||||
/// instances measured by their art from `symbols`, with the brushed strokes in that art. A path
|
||||
/// whose live-effect plug-ins paint their pieces leaves that room past each piece
|
||||
/// ([`crate::fx::painted_cull_bounds`]). A group or layer leaves that room past each of its
|
||||
/// members, as the renderer measures a group by its members (`Renderer::bounds_of`).
|
||||
pub(crate) fn cull_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let b = crate::fx::cull_bounds(symbols, n)?;
|
||||
if let Some(b) = crate::fx::painted_cull_bounds(symbols, n) {
|
||||
return b;
|
||||
}
|
||||
let b = crate::fx::brushed_cull_bounds(symbols, n)?;
|
||||
let pad = pad(symbols, n);
|
||||
Some(b.inflate(pad, pad))
|
||||
}
|
||||
@@ -145,12 +151,15 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO
|
||||
/// How far brush art can paint past `n`'s brushed strokes, or past the brushed strokes in the art
|
||||
/// of symbol instance `n`: `16 × w + 8`, where `w` is the widest stroke (at least 1) of `n` when it
|
||||
/// has a visible brushed stroke and of the objects in that art that have one
|
||||
/// ([`SymbolBoxes::brush_width`]), and 0 when neither has one.
|
||||
/// ([`SymbolBoxes::brush_width`]) or the pieces live-effect plug-ins paint for them
|
||||
/// ([`crate::fx::painted_brush_width`]), and 0 when neither has one.
|
||||
pub(crate) fn pad(symbols: &SymbolBoxes, n: &Node) -> f64 {
|
||||
let own = vectorcraft_brush::has_brush(n)
|
||||
.then(|| n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max));
|
||||
let art = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => symbols.brush_width(symbol).map(|w| w.max(1.0)),
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
symbols.brush_width(symbol).into_iter().chain(crate::fx::painted_brush_width(symbols, symbol)).reduce(f64::max).map(|w| w.max(1.0))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
own.into_iter().chain(art).reduce(f64::max).map_or(0.0, |w| 16.0 * w + 8.0)
|
||||
|
||||
@@ -70,7 +70,10 @@ mod renderer;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use bounds::visual_bounds;
|
||||
pub(crate) use bounds::{cull_bounds, drawn_outline, drawn_outlines, painted_reach, path_cull_bounds, three_d_art_bounds, with_own_raster_reach};
|
||||
pub(crate) use bounds::{
|
||||
brushed_cull_bounds, cull_bounds, drawn_outline, drawn_outlines, painted_brush_width, painted_cull_bounds, painted_reach, path_cull_bounds,
|
||||
three_d_art_bounds, with_own_raster_reach,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use entries::Drawn;
|
||||
pub(crate) use entries::{DocInputs, FxGeom, Inputs, Reads, ShadowEntry};
|
||||
|
||||
+125
-16
@@ -99,6 +99,72 @@ fn painted_art(symbols: &SymbolBoxes, n: &Node) -> Option<Node> {
|
||||
effects::has_painted_effects(n).then(|| effects::reshape(Some(symbols.document()), n, None)).flatten()
|
||||
}
|
||||
|
||||
/// Calls `f` on each object in `art`, the art [`painted_art`] makes, that has a visible brushed
|
||||
/// stroke, looking into the visible members of its groups. Hidden objects are left out.
|
||||
fn each_brushed_piece(art: &Node, f: &mut impl FnMut(&Node)) {
|
||||
if !art.visible {
|
||||
return;
|
||||
}
|
||||
match &art.kind {
|
||||
NodeKind::Group { children, .. } => children.iter().for_each(|c| each_brushed_piece(c, f)),
|
||||
_ if vectorcraft_brush::has_brush(art) => f(art),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`cull_bounds`] of path or compound path `n` whose live-effect plug-ins paint their pieces
|
||||
/// ([`painted_art`]), with room for brush art past each piece's brushed strokes
|
||||
/// ([`crate::brush_fx::pad`] of that piece, from the piece's own stroke widths) and the reach of
|
||||
/// `n`'s raster effects past them. `None` when the renderer measures `n` otherwise: it has no such
|
||||
/// pieces, or has Crop Marks, Vector Halftone or a 3D effect.
|
||||
pub(crate) fn painted_cull_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Option<Rect>> {
|
||||
if !effects::has_painted_effects(n)
|
||||
|| effects::has_crop_marks(n)
|
||||
|| effects::addons::halftone::has_halftone(n)
|
||||
|| effects::has_revolve(n)
|
||||
|| effects::has_solid(n)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let art = painted_art(symbols, n)?;
|
||||
let mut b = art.visual_bounds_with(symbols);
|
||||
each_brushed_piece(&art, &mut |p| {
|
||||
let pad = crate::brush_fx::pad(symbols, p);
|
||||
b = vectorcraft_geom::union_opt(b, p.visual_bounds_with(symbols).map(|r| r.inflate(pad, pad)));
|
||||
});
|
||||
Some(b.map(|b| with_raster_reach(symbols, n, b)))
|
||||
}
|
||||
|
||||
/// The widest stroke of the pieces with a visible brushed stroke that live-effect plug-ins paint
|
||||
/// ([`painted_art`]) for the paths in the art of the symbol named `symbol`, and in the art of the
|
||||
/// symbols the instances in it show, each symbol measured once for `symbols`
|
||||
/// ([`SymbolBoxes::measured_width`]). `None` when no such piece has one; symbols whose art has no
|
||||
/// visible effect ([`SymbolBoxes::has_effects`]) are not looked at.
|
||||
pub(crate) fn painted_brush_width(symbols: &SymbolBoxes, symbol: &str) -> Option<f64> {
|
||||
symbols.measured_width("painted brush", symbol, || {
|
||||
if !symbols.has_effects(symbol) {
|
||||
return None;
|
||||
}
|
||||
let mut width: Option<f64> = None;
|
||||
symbols.measure_art(symbol, |art| {
|
||||
art.walk(&mut |n| {
|
||||
let nested = match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => painted_brush_width(symbols, symbol),
|
||||
_ => None,
|
||||
};
|
||||
width = width.into_iter().chain(nested).reduce(f64::max);
|
||||
if let Some(pieces) = painted_art(symbols, n) {
|
||||
each_brushed_piece(&pieces, &mut |p| {
|
||||
let widths = p.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None });
|
||||
width = Some(widths.fold(width.unwrap_or(0.0), f64::max));
|
||||
});
|
||||
}
|
||||
})
|
||||
});
|
||||
width
|
||||
})
|
||||
}
|
||||
|
||||
/// Does `item` paint (as [`Renderer::paint_items`] draws it)?
|
||||
fn paints(item: &AppearanceItem) -> bool {
|
||||
item.visible() && !item.paint().is_none()
|
||||
@@ -152,8 +218,18 @@ fn spread(symbols: &SymbolBoxes, fx: &[Effect], b: Rect) -> Rect {
|
||||
}
|
||||
|
||||
/// [`drawn_bounds`] before the raster effects of `n`'s fills and strokes: its art, and the art of
|
||||
/// its brushed strokes (a symbol's brushed art as far as [`crate::brush_fx::pad`] reaches).
|
||||
/// its brushed strokes (a symbol's brushed art as far as [`crate::brush_fx::pad`] reaches). A path
|
||||
/// whose live-effect plug-ins paint their pieces is measured by those pieces, each with the art
|
||||
/// its brushed strokes draw along it.
|
||||
fn art_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
if let Some(art) = painted_art(symbols, n) {
|
||||
let mut b = art.visual_bounds_with(symbols);
|
||||
each_brushed_piece(&art, &mut |p| {
|
||||
let brushed = vectorcraft_brush::expand(symbols.document(), p).and_then(|a| a.visual_bounds_with(symbols));
|
||||
b = vectorcraft_geom::union_opt(b, brushed);
|
||||
});
|
||||
return b;
|
||||
}
|
||||
let b = shape_bounds(symbols, n);
|
||||
let brushed = vectorcraft_brush::has_brush(n)
|
||||
.then(|| vectorcraft_brush::expand(symbols.document(), n))
|
||||
@@ -180,9 +256,6 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
}
|
||||
NodeKind::Layer { clip: false, .. } | NodeKind::Group { clip: false, .. } => union(n),
|
||||
_ if has_fx(n) => {
|
||||
if let Some(art) = painted_art(symbols, n) {
|
||||
return art.visual_bounds_with(symbols);
|
||||
}
|
||||
let g = effected_path(symbols.document(), n, &node_bezpath(n)?);
|
||||
// The path as the fills and strokes without geometry effects of their own paint it
|
||||
// (as every fill and stroke would when none paints).
|
||||
@@ -396,7 +469,28 @@ fn outset(symbols: &SymbolBoxes, fx: &[Effect], b: Rect) -> f64 {
|
||||
/// the subtree (a shadow can reach the view while its object is outside it). Symbol instances are
|
||||
/// measured by their art from `symbols`.
|
||||
pub(crate) fn cull_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
cull_bounds_in(symbols, n, true)
|
||||
cull_bounds_in(symbols, n, true, false)
|
||||
}
|
||||
|
||||
/// [`cull_bounds`] with room for the brush art of the members of the groups and layers in `n`, each
|
||||
/// member measured as [`crate::brush_fx::cull_bounds`] measures it. The room for `n`'s own brushed
|
||||
/// strokes is left to the caller.
|
||||
pub(crate) fn brushed_cull_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
cull_bounds_in(symbols, n, true, true)
|
||||
}
|
||||
|
||||
/// [`cull_bounds_in`] of `c`, a member of a group or layer; with `brush`, grown by the room its
|
||||
/// brushed strokes leave for brush art, as [`crate::brush_fx::cull_bounds`] measures it.
|
||||
fn member_cull_bounds(symbols: &SymbolBoxes, c: &Node, after_reshape: bool, brush: bool) -> Option<Rect> {
|
||||
if !brush {
|
||||
return cull_bounds_in(symbols, c, after_reshape, false);
|
||||
}
|
||||
if let Some(b) = painted_cull_bounds(symbols, c) {
|
||||
return b;
|
||||
}
|
||||
let b = cull_bounds_in(symbols, c, after_reshape, true)?;
|
||||
let pad = crate::brush_fx::pad(symbols, c);
|
||||
Some(b.inflate(pad, pad))
|
||||
}
|
||||
|
||||
/// [`cull_bounds`] of path or compound path `n` made from `visual`, its visual bounds as
|
||||
@@ -420,16 +514,21 @@ pub(crate) fn path_cull_bounds(symbols: &SymbolBoxes, n: &Node, visual: impl FnO
|
||||
/// with geometry effects of its own are measured on the art as those effects reshape it
|
||||
/// ([`reshaped_art_effects_reach`]). With `after_reshape` false, they are measured on the art
|
||||
/// before those effects run ([`art_effects_reach`]), which `symbols` keeps for each symbol and
|
||||
/// linear part.
|
||||
fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Option<Rect> {
|
||||
let inner = |c: &Node| cull_bounds_in(symbols, c, after_reshape);
|
||||
/// linear part. With `brush` true, the members of a group or layer are measured with the room
|
||||
/// their brushed strokes leave for brush art ([`member_cull_bounds`]).
|
||||
fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: bool) -> Option<Rect> {
|
||||
let inner = |c: &Node| cull_bounds_in(symbols, c, after_reshape, false);
|
||||
let member = |c: &Node| member_cull_bounds(symbols, c, after_reshape, brush);
|
||||
// The art that a group's or layer's crop marks or Vector Halftone draw holds its members. The
|
||||
// caller leaves the room for an object's own brushed strokes.
|
||||
let held = |art: &Node| cull_bounds_in(symbols, art, after_reshape, brush && is_container(n));
|
||||
match &n.kind {
|
||||
// The object and its crop marks.
|
||||
_ if effects::has_crop_marks(n) => effects::crop_marks_art(n).and_then(|art| inner(&art)),
|
||||
_ if effects::has_crop_marks(n) => effects::crop_marks_art(n).and_then(|art| held(&art)),
|
||||
// The object Vector Halftone samples, and as far as its dots reach past it.
|
||||
_ if effects::addons::halftone::has_halftone(n) => {
|
||||
let reach = effects::addons::halftone::reach(n);
|
||||
inner(&effects::addons::halftone::split(n).0).map(|b| b.inflate(reach, reach))
|
||||
held(&effects::addons::halftone::split(n).0).map(|b| b.inflate(reach, reach))
|
||||
}
|
||||
// A 3D effect's art, as the renderer draws it, and the raster effects' reach: the solid of
|
||||
// type or of a group's members reaches past the letters or members the arms below measure.
|
||||
@@ -445,12 +544,12 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Optio
|
||||
let b = if art.clips() {
|
||||
art.visual_bounds_with(symbols)
|
||||
} else {
|
||||
art.children()?.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, inner(c)))
|
||||
art.children()?.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, member(c)))
|
||||
}?;
|
||||
Some(with_own_raster_reach(symbols, n, b))
|
||||
}
|
||||
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => {
|
||||
children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, inner(c)))
|
||||
children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, member(c)))
|
||||
}
|
||||
_ if has_fx(n) => visual_bounds(symbols, n),
|
||||
// The reshaped art (a symbol instance's reshaped art is made from its symbol's art; type's
|
||||
@@ -568,14 +667,24 @@ fn glyphs_box(t: &vectorcraft_doc::TextObject, outset: f64) -> Option<Rect> {
|
||||
/// How far the content of live object `n` (a blend, envelope or repeat) can paint past its visual
|
||||
/// bounds: for each object in it, how far the effects in a symbol instance's art paint past that
|
||||
/// art ([`art_effects_reach`]), how far brush art can paint ([`crate::brush_fx::pad`]) and how far
|
||||
/// a path's own effects paint past it ([`path_effects_reach`]), on the farthest side. 0 for any
|
||||
/// other kind of object.
|
||||
/// a path's own effects paint past it ([`path_effects_reach`]), on the farthest side; for a path
|
||||
/// whose live-effect plug-ins paint their pieces, how far its pieces and their brush art reach past
|
||||
/// it ([`painted_cull_bounds`]). 0 for any other kind of object.
|
||||
fn live_content_reach(symbols: &SymbolBoxes, n: &Node) -> f64 {
|
||||
if !vectorcraft_doc::live::is_live(n) {
|
||||
return 0.0;
|
||||
}
|
||||
let mut reach = 0.0f64;
|
||||
n.walk(&mut |c| reach = reach.max(art_effects_reach(symbols, c).max(path_effects_reach(symbols, c)) + crate::brush_fx::pad(symbols, c)));
|
||||
n.walk(&mut |c| {
|
||||
let own = match painted_cull_bounds(symbols, c) {
|
||||
Some(b) => match (b, c.visual_bounds_with(symbols)) {
|
||||
(Some(b), Some(v)) => [v.x0 - b.x0, v.y0 - b.y0, b.x1 - v.x1, b.y1 - v.y1].into_iter().fold(0.0, f64::max),
|
||||
_ => 0.0,
|
||||
},
|
||||
None => art_effects_reach(symbols, c).max(path_effects_reach(symbols, c)) + crate::brush_fx::pad(symbols, c),
|
||||
};
|
||||
reach = reach.max(own);
|
||||
});
|
||||
reach
|
||||
}
|
||||
|
||||
@@ -628,7 +737,7 @@ fn reshaped_art_effects_reach(symbols: &SymbolBoxes, n: &Node, r: &Node) -> f64
|
||||
if !symbols.has_effects(symbol) {
|
||||
return 0.0;
|
||||
}
|
||||
let art = r.children().into_iter().flatten().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, cull_bounds_in(symbols, c, false)));
|
||||
let art = r.children().into_iter().flatten().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, cull_bounds_in(symbols, c, false, false)));
|
||||
match (art, r.visual_bounds_with(symbols)) {
|
||||
(Some(c), Some(v)) => [v.x0 - c.x0, v.y0 - c.y0, c.x1 - v.x1, c.y1 - v.y1].into_iter().fold(0.0, f64::max),
|
||||
_ => 0.0,
|
||||
|
||||
@@ -123,7 +123,7 @@ impl Renderer {
|
||||
/// ([`effects::plugin_revision`]), drop what the caches keep from plug-in effects: the effect
|
||||
/// geometry of paths with a plug-in effect, the cull bounds of objects that have one or hold one,
|
||||
/// of symbol instances and of the objects that hold them, and the art drawn for the effects of
|
||||
/// objects with a plug-in effect. Rasters of raster effects and evaluations of live objects hold
|
||||
/// objects that have a plug-in effect or hold one. Rasters of raster effects and evaluations of live objects hold
|
||||
/// the revision in their keys when what they draw has a plug-in effect (`fx::Inputs`,
|
||||
/// `live::resources_key`).
|
||||
///
|
||||
@@ -146,7 +146,8 @@ impl Renderer {
|
||||
if stale {
|
||||
self.fx_geom.retain(|_, e| !effects::has_plugin_effect(&e.node));
|
||||
self.geom.retain(|_, e| !holds_plugin_effect(&e.node) && !holds_instance(&e.node));
|
||||
self.fx_arts.retain(|(node, ..)| !effects::has_plugin_effect(node));
|
||||
// The art of a group holds what its members' plug-in effects draw.
|
||||
self.fx_arts.retain(|(node, ..)| !holds_plugin_effect(node));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ mod longstroke;
|
||||
mod memory;
|
||||
mod movedstroke;
|
||||
mod objectfx;
|
||||
mod paintedbrush;
|
||||
mod placed_document;
|
||||
mod rasterize;
|
||||
mod setup;
|
||||
|
||||
@@ -1716,7 +1716,8 @@ fn installing_a_plugin_keeps_what_is_kept_for_other_objects() {
|
||||
}
|
||||
|
||||
/// The art drawn for an object's effects follows the plug-ins installed: in the next frame, a group
|
||||
/// with a plug-in effect, the same group feathered (Feather clips to the art's outline), an
|
||||
/// with a plug-in effect, the same group feathered (Feather clips to the art's outline), a group
|
||||
/// with a Transform effect holding a square with a plug-in effect, an
|
||||
/// instance of symbol `S` ([`symbol_art`]) and type, each with a plug-in effect, are drawn as the
|
||||
/// plug-in installed again with another shape draws them.
|
||||
#[test]
|
||||
@@ -1738,6 +1739,13 @@ fn effect_art_follows_the_plugins_installed() {
|
||||
plugin_change_draws_as_new(group(vec![]), ID, small.clone(), big.clone());
|
||||
let feather = effect("stylize.feather", serde_json::json!({"radius": 2.0}));
|
||||
plugin_change_draws_as_new(group(vec![feather]), ID, small.clone(), big.clone());
|
||||
// A group with a Transform effect holding a square with the plug-in effect: the group's art
|
||||
// holds what the plug-in draws for the square.
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
let square = filled(&mut d, rectangle(Rect::new(20.0, 30.0, 60.0, 70.0)), Paint::solid(Color::BLACK), vec![plugin()]);
|
||||
let mut moved = Node::group(d.alloc_id(), vec![Arc::new(square)]);
|
||||
moved.appearance.effects.push(effect("distort.transform", serde_json::json!({"moveH": 10.0})));
|
||||
plugin_change_draws_as_new(with_art(d, vec![moved]), ID, small.clone(), big.clone());
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
let art = symbol_art(&mut d);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "S".into(), art: Arc::new(art) });
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//! A path whose live-effect plug-in paints its pieces draws each piece's brushed stroke along that
|
||||
//! piece, at the piece's stroke width. Culling leaves room for that brush art past each piece, in a
|
||||
//! symbol instance and a live object too, and Object › Rasterize measures it.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeKind, Symbol};
|
||||
use vectorcraft_geom::{Affine, PathData, Point, SubPath};
|
||||
|
||||
use crate::{RenderOptions, Renderer};
|
||||
|
||||
const BRUSH: &str = "3 pt. Round";
|
||||
|
||||
/// A 20 × 20 square at `x`, 40.
|
||||
fn square_at(x: f64) -> PathData {
|
||||
PathData::single(SubPath::polyline(&[Point::new(x, 40.0), Point::new(x + 20.0, 40.0), Point::new(x + 20.0, 60.0), Point::new(x, 60.0)], true))
|
||||
}
|
||||
|
||||
/// Installs live-effect plug-in `id`, which declares `paintOutput` and returns one piece: the
|
||||
/// square at 120, 40 with a black stroke 10 pt wide.
|
||||
fn install(id: &str) {
|
||||
use vectorcraft_plugins::wat as tpl;
|
||||
let paint = serde_json::to_value(Paint::solid(Color::BLACK)).unwrap();
|
||||
let output = json!({"objects": [{"path": square_at(120.0), "strokes": [{"paint": paint, "width": 10.0}]}]}).to_string();
|
||||
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":2,"paintOutput":true,"params":{{}}}}"#);
|
||||
let module = wat::parse_str(tpl::returning(&manifest, &output)).unwrap();
|
||||
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
|
||||
}
|
||||
|
||||
/// A document whose brush `3 pt. Round` paints a round nib 10 pt across for each point of stroke
|
||||
/// weight: 100 pt across on a piece's 10 pt stroke, reaching from 70 to 190 across the piece.
|
||||
fn document() -> Document {
|
||||
let mut d = Document::new(300.0, 100.0);
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
let Some(vectorcraft_brush::BrushKind::Calligraphic(c)) = lib.iter_mut().find(|b| b.name == BRUSH).map(|b| &mut b.kind) else {
|
||||
panic!("the {BRUSH} brush")
|
||||
};
|
||||
c.size = 10.0;
|
||||
vectorcraft_brush::store(&mut d, &lib);
|
||||
d
|
||||
}
|
||||
|
||||
/// The square at 0, 40 with a black 1 pt stroke, painted by the brush when `brushed`, with
|
||||
/// live-effect plug-in `plugin` as its own effect, or as its stroke's when `on_stroke`.
|
||||
fn source(d: &mut Document, plugin: &str, on_stroke: bool, brushed: bool) -> Node {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
let effect = Effect { id: format!("plugin.{plugin}"), params: json!({}), visible: true };
|
||||
let stroke = ap.stroke_mut().unwrap();
|
||||
stroke.brush = brushed.then(|| BRUSH.to_string());
|
||||
if on_stroke {
|
||||
stroke.effects = vec![effect];
|
||||
} else {
|
||||
ap.effects = vec![effect];
|
||||
}
|
||||
Node::path(d.alloc_id(), square_at(0.0), ap)
|
||||
}
|
||||
|
||||
/// `d` with `n` added to its first layer.
|
||||
fn with(mut d: Document, n: Node) -> Document {
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Does a new renderer draw `d` dark at (`x` + 5, 50), in a view of 10 × 20 pt from (`x`, 40)?
|
||||
fn dark_at(d: &Document, x: f64) -> bool {
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let img = Renderer::new().render(d, 10, 20, Affine::translate((-x, -40.0)), &opts);
|
||||
let p = img.pixel(5, 10);
|
||||
(p[0] as u32 + p[1] as u32 + p[2] as u32) < 200
|
||||
}
|
||||
|
||||
/// The brush art of the piece reaches 50 pt past it, to 190; the room left for the source's 1 pt
|
||||
/// brushed stroke ends at 169. A view from 175 shows that art whether the plug-in is the path's own
|
||||
/// effect or its stroke's, and culling leaves `16 × 10 + 8` pt past the piece's 10 pt stroke. A
|
||||
/// renderer that draws the whole document draws it there too.
|
||||
#[test]
|
||||
fn a_painted_piece_is_culled_by_its_own_brush_art() {
|
||||
for (id, on_stroke) in [("test.render.paintedbrush.object", false), ("test.render.paintedbrush.stroke", true)] {
|
||||
install(id);
|
||||
let mut d = document();
|
||||
let n = source(&mut d, id, on_stroke, true);
|
||||
let d = with(d, n.clone());
|
||||
assert!(dark_at(&d, 175.0), "on the stroke: {on_stroke}; the brush art past the source's room is drawn");
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let whole = Renderer::new().render(&d, 300, 100, Affine::IDENTITY, &opts).pixel(180, 50);
|
||||
assert!((whole[0] as u32 + whole[1] as u32 + whole[2] as u32) < 200, "on the stroke: {on_stroke}; {whole:?}");
|
||||
let b = crate::brush_fx::cull_bounds(&d.symbol_boxes(), &n).unwrap();
|
||||
assert!(b.x0 <= -52.9 && b.x1 >= 312.9 && b.y0 <= -132.9 && b.y1 >= 232.9, "on the stroke: {on_stroke}; {b:?}");
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Object › Rasterize measures the brush art drawn along the piece, from 70 to 190, and not the
|
||||
/// brush art of the source, which is not drawn.
|
||||
#[test]
|
||||
fn a_painted_piece_s_brush_art_is_in_its_drawn_bounds() {
|
||||
const ID: &str = "test.render.paintedbrush.crop";
|
||||
install(ID);
|
||||
let mut d = document();
|
||||
let n = source(&mut d, ID, false, true);
|
||||
let d = with(d, n.clone());
|
||||
let b = crate::drawn_bounds(&d, &n).unwrap();
|
||||
assert!(b.x0 > 65.0 && b.x0 < 75.0 && b.x1 > 185.0 && b.x1 < 195.0, "{b:?}");
|
||||
vectorcraft_plugins::registry::remove(ID);
|
||||
}
|
||||
|
||||
/// An instance of a symbol whose art is the path, and a one-by-one grid repeat of it, are drawn
|
||||
/// where the piece's brush art reaches.
|
||||
#[test]
|
||||
fn a_symbol_and_a_repeat_holding_a_painted_path_are_culled_by_its_pieces_brush_art() {
|
||||
const ID: &str = "test.render.paintedbrush.held";
|
||||
install(ID);
|
||||
let mut d = document();
|
||||
let art = source(&mut d, ID, false, true);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) });
|
||||
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Painted".into(), xf: Affine::IDENTITY });
|
||||
let d = with(d, instance);
|
||||
assert!(dark_at(&d, 175.0), "an instance");
|
||||
let mut d = document();
|
||||
let held = source(&mut d, ID, false, true);
|
||||
let kind = vectorcraft_doc::RepeatKind::Grid {
|
||||
h_spacing: 0.0,
|
||||
v_spacing: 0.0,
|
||||
rows: 1,
|
||||
cols: 1,
|
||||
grid_type: vectorcraft_doc::TileType::Grid,
|
||||
flip_rows: false,
|
||||
flip_cols: false,
|
||||
};
|
||||
let repeat = Node::new(d.alloc_id(), NodeKind::Repeat(vectorcraft_doc::RepeatSpec { kind, source: vec![Arc::new(held)] }));
|
||||
let d = with(d, repeat);
|
||||
assert!(dark_at(&d, 175.0), "a repeat");
|
||||
vectorcraft_plugins::registry::remove(ID);
|
||||
}
|
||||
|
||||
/// The room an instance leaves for the pieces' brush art is measured once for a symbol's art: the
|
||||
/// second instance measured with the same boxes measures no art.
|
||||
#[test]
|
||||
fn the_pieces_brush_width_is_measured_once_for_a_symbol() {
|
||||
const ID: &str = "test.render.paintedbrush.once";
|
||||
install(ID);
|
||||
let mut d = document();
|
||||
let art = source(&mut d, ID, false, true);
|
||||
d.symbols.push(Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) });
|
||||
let instance =
|
||||
|d: &mut Document, x: f64| Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Painted".into(), xf: Affine::translate((x, 0.0)) });
|
||||
let (a, b) = (instance(&mut d, 0.0), instance(&mut d, 30.0));
|
||||
let symbols = d.symbol_boxes();
|
||||
assert_eq!(crate::brush_fx::pad(&symbols, &a), 168.0, "16 × the piece's 10 pt + 8");
|
||||
let measured = symbols.art_measured();
|
||||
assert_eq!(crate::brush_fx::pad(&symbols, &b), 168.0);
|
||||
assert_eq!(symbols.art_measured(), measured);
|
||||
vectorcraft_plugins::registry::remove(ID);
|
||||
}
|
||||
|
||||
/// The square at 0, 40 with a black 1 pt stroke painted by the brush, without effects.
|
||||
fn brushed_path(d: &mut Document) -> Node {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
ap.stroke_mut().unwrap().brush = Some(BRUSH.to_string());
|
||||
Node::path(d.alloc_id(), square_at(0.0), ap)
|
||||
}
|
||||
|
||||
/// A group leaves the room each member's brushed strokes leave for brush art, as the renderer
|
||||
/// measures the group by its members: a plain brushed path (`16 × 1 + 8` pt past its 1 pt stroke),
|
||||
/// a painted path (the room past its piece), and the brushed path in a group with an effect of its
|
||||
/// own.
|
||||
#[test]
|
||||
fn a_group_is_culled_by_its_members_brush_art() {
|
||||
const ID: &str = "test.render.paintedbrush.group";
|
||||
install(ID);
|
||||
for painted in [false, true] {
|
||||
let mut d = document();
|
||||
let member = if painted { source(&mut d, ID, false, true) } else { brushed_path(&mut d) };
|
||||
let g = Node::group(d.alloc_id(), vec![Arc::new(member.clone())]);
|
||||
let d = with(d, g);
|
||||
let g = d.layers[0].children().unwrap()[0].clone();
|
||||
let symbols = d.symbol_boxes();
|
||||
let own = crate::brush_fx::cull_bounds(&symbols, &member);
|
||||
assert!(own.is_some_and(|b| b.x0 < -24.0), "painted: {painted}; {own:?}");
|
||||
assert_eq!(crate::brush_fx::cull_bounds(&symbols, &g), own, "painted: {painted}");
|
||||
assert_eq!(crate::painted_bounds(&d, &g), own, "painted: {painted}");
|
||||
assert_eq!(Renderer::new().bounds_of(&symbols, &g), own, "painted: {painted}");
|
||||
}
|
||||
vectorcraft_plugins::registry::remove(ID);
|
||||
// A 4 pt stroke leaves `16 × 4 + 8` pt, past the crop marks. An empty effect id stands for a
|
||||
// stroke of the group's own.
|
||||
for effect in ["adjust.hueSaturation", "cropMarks", ""] {
|
||||
let mut d = document();
|
||||
let mut member = brushed_path(&mut d);
|
||||
member.appearance.stroke_mut().unwrap().width = 4.0;
|
||||
let mut g = Node::group(d.alloc_id(), vec![Arc::new(member.clone())]);
|
||||
if effect.is_empty() {
|
||||
g.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
|
||||
} else {
|
||||
g.appearance.effects = vec![Effect { id: effect.into(), params: json!({}), visible: true }];
|
||||
}
|
||||
let d = with(d, g);
|
||||
let g = d.layers[0].children().unwrap()[0].clone();
|
||||
assert!(crate::fx::has_object_fx(&g), "{effect}: an effect of the group's own");
|
||||
let own = crate::brush_fx::cull_bounds(&d.symbol_boxes(), &member).unwrap();
|
||||
assert!(own.x0 <= -73.9, "{own:?}");
|
||||
let b = crate::painted_bounds(&d, &g);
|
||||
assert!(b.is_some_and(|b| b.union(own) == b), "{effect}: {b:?} holds {own:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer leaves the room its members' brushed strokes leave for brush art.
|
||||
#[test]
|
||||
fn a_layer_is_culled_by_its_members_brush_art() {
|
||||
let mut d = document();
|
||||
let member = brushed_path(&mut d);
|
||||
let d = with(d, member.clone());
|
||||
let layer = d.layers[0].clone();
|
||||
let symbols = d.symbol_boxes();
|
||||
let own = crate::brush_fx::cull_bounds(&symbols, &member);
|
||||
assert!(own.is_some_and(|b| b.x0 <= -24.4 && b.x1 >= 44.4), "{own:?}");
|
||||
assert_eq!(crate::brush_fx::cull_bounds(&symbols, &layer), own);
|
||||
assert_eq!(crate::painted_bounds(&d, &layer), own);
|
||||
assert_eq!(Renderer::new().bounds_of(&symbols, &layer), own);
|
||||
}
|
||||
|
||||
/// Pieces without a brushed stroke are culled by the pieces alone, as before.
|
||||
#[test]
|
||||
fn painted_pieces_without_a_brush_take_no_room_for_one() {
|
||||
const ID: &str = "test.render.paintedbrush.plain";
|
||||
install(ID);
|
||||
let mut d = document();
|
||||
let n = source(&mut d, ID, false, false);
|
||||
let d = with(d, n.clone());
|
||||
let symbols = d.symbol_boxes();
|
||||
let b = crate::brush_fx::cull_bounds(&symbols, &n);
|
||||
assert_eq!(b, crate::fx::cull_bounds(&symbols, &n));
|
||||
assert!(b.is_some_and(|b| b.x0 > 100.0 && b.x1 < 150.0), "{b:?}");
|
||||
vectorcraft_plugins::registry::remove(ID);
|
||||
}
|
||||
@@ -1236,12 +1236,6 @@ impl Ctx {
|
||||
.collect();
|
||||
let under = stroke_under(&mut cells, label, warnings);
|
||||
|
||||
let anchor_of = |i: usize| match cs.chars.get(i).and_then(|c| self.prop(c.1, "text-anchor")).as_deref() {
|
||||
Some("middle") => 0.5,
|
||||
Some("end") => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
let anchor = anchor_of(0);
|
||||
let path = cs.path.and_then(|tp| match self.text_path(xml, tp) {
|
||||
Some(p) => Some((tp, p)),
|
||||
None => {
|
||||
@@ -1250,6 +1244,23 @@ impl Ctx {
|
||||
}
|
||||
});
|
||||
let vertical = self.prop(t, "writing-mode").is_some_and(|m| m.starts_with("tb") || m.starts_with("vertical"));
|
||||
let rtl = self.prop(t, "direction").is_some_and(|d| d.trim() == "rtl");
|
||||
// Where the chunk starting at character `i` sits on its anchor: 0 its left (or top) edge,
|
||||
// 0.5 its middle, 1 its right (or bottom) edge; on a path, its edge toward the path's
|
||||
// start, its middle or its edge toward the path's end. In horizontal type `start` and
|
||||
// `end` follow the `direction` of the element holding that character: right-to-left text
|
||||
// starts at its right edge, and on a path at the edge toward the path's end (type on a
|
||||
// path lays its glyphs out in visual order from its start).
|
||||
let anchor_of = |i: usize| {
|
||||
let Some(&(_, el)) = cs.chars.get(i) else { return 0.0 };
|
||||
let a = match self.prop(el, "text-anchor").as_deref() {
|
||||
Some("middle") => 0.5,
|
||||
Some("end") => 1.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
if !vertical && self.prop(el, "direction").is_some_and(|d| d.trim() == "rtl") { 1.0 - a } else { a }
|
||||
};
|
||||
let anchor = anchor_of(0);
|
||||
self.fit_lengths(&cs.spans, &mut cells, vertical, label, warnings);
|
||||
let mut obj = TextObject::point(Point::ZERO, "", CharStyle::default());
|
||||
let mut breaks: Vec<Break> = vec![];
|
||||
@@ -1268,6 +1279,8 @@ impl Ctx {
|
||||
let em = self.font_size(tp);
|
||||
let offset = tp.attribute("startOffset").and_then(|v| self.length(v, em, len)).unwrap_or(0.0) + dx[0];
|
||||
let width = if anchor > 0.0 { advance(&point_text(&cells)) } else { 0.0 };
|
||||
// Text that would start before the path's beginning starts at it, with all its glyphs
|
||||
// on the path (SVG does not draw the glyphs that fall off it).
|
||||
let start = Some((offset - anchor * width) / len).filter(|s| s.is_finite()).map_or(0.0, |s| s.clamp(0.0, 1.0));
|
||||
obj.kind = TextKind::OnPath { path: PathData::from_bezpath(&bp), start, end: None };
|
||||
obj.xf = Affine::IDENTITY;
|
||||
@@ -1293,14 +1306,14 @@ impl Ctx {
|
||||
obj.xf = Affine::IDENTITY;
|
||||
} else {
|
||||
let origin = Point::new(x[0].unwrap_or(0.0) + dx[0], y[0].unwrap_or(0.0) + dy[0]);
|
||||
let (justify, left, starts) = lines(&mut cells, &x, &y, &dx, &dy, anchor, origin.x, &mut breaks);
|
||||
let (justify, left, starts) = lines(&mut cells, &x, &y, &dx, &dy, &anchor_of, rtl, origin.x, &mut breaks);
|
||||
obj.para.justify = justify;
|
||||
obj.xf = Affine::translate((finite(left), finite(origin.y)));
|
||||
// Lines anchored differently (paragraphs aligned differently): each line's paragraph
|
||||
// takes its alignment, and indents that put it where it was.
|
||||
if let Some(starts) = starts.filter(|st| st.iter().any(|(i, _)| anchor_of(*i) != anchor)) {
|
||||
for (k, &(i, ax)) in starts.iter().enumerate() {
|
||||
let a = anchor_of(i);
|
||||
// Lines anchored differently or at different x (paragraphs aligned or indented
|
||||
// differently): each line's paragraph takes its alignment, and indents that put it
|
||||
// where it was.
|
||||
if starts.iter().any(|&(_, a, ax)| a != starts[0].1 || ax != starts[0].2) {
|
||||
for (k, &(_, a, ax)) in starts.iter().enumerate() {
|
||||
let d = finite(ax - left);
|
||||
let mut pa = ParaStyle { justify: justify_of(a), ..ParaStyle::default() };
|
||||
match pa.justify {
|
||||
@@ -1319,13 +1332,7 @@ impl Ctx {
|
||||
if !para_styles.is_empty() {
|
||||
obj.set_paragraph_styles(para_styles);
|
||||
}
|
||||
// SVG text runs left to right unless `direction: rtl` says otherwise, whatever its first
|
||||
// strong character: pinned (on every paragraph) when that would read as right to left.
|
||||
if self.prop(t, "direction").is_some_and(|d| d.trim() == "rtl") {
|
||||
obj.edit_paras(None, |pa| pa.direction = Some(ParaDirection::RightToLeft));
|
||||
} else if obj.plain_text().split('\n').any(|p| vectorcraft_text::paragraph_is_rtl(p, None)) {
|
||||
obj.edit_paras(None, |pa| pa.direction = Some(ParaDirection::LeftToRight));
|
||||
}
|
||||
pin_direction(&mut obj, rtl);
|
||||
keep_reader_anchors(&mut obj);
|
||||
// The placeholder covers the text (laid out when a paint server needs its bounding box).
|
||||
let b = if paints.is_empty() { obj.bounds() } else { Some(obj.xf.transform_rect_bbox(measure(&obj).bounds)) }.unwrap_or_default();
|
||||
@@ -1412,7 +1419,7 @@ fn finite(v: f64) -> f64 {
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
}
|
||||
|
||||
/// The alignment of an SVG text chunk anchored at `anchor` (0 start, 0.5 middle, 1 end).
|
||||
/// The alignment of an SVG text chunk anchored at `anchor` (0 left edge, 0.5 middle, 1 right edge).
|
||||
fn justify_of(anchor: f64) -> Justify {
|
||||
match anchor {
|
||||
a if a >= 1.0 => Justify::Right,
|
||||
@@ -1428,8 +1435,11 @@ fn leading_tolerance(spacing: f64) -> f64 {
|
||||
}
|
||||
|
||||
/// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the
|
||||
/// justification, the x of the first line's left (or anchor) edge and, when no character is
|
||||
/// placed on its own, each line's first character and anchor x.
|
||||
/// justification, the x of the first line's left (or anchor) edge and each line's first
|
||||
/// character, alignment (as for [`justify_of`]) and anchor x. `anchor_of` gives where the chunk
|
||||
/// starting at a character sits on its anchor, and `rtl` whether the text's `direction` is `rtl`
|
||||
/// ([`pin_direction`]). When characters are placed on their own, every line is left-aligned and
|
||||
/// its anchor x is its left edge.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn lines(
|
||||
cells: &mut [Cell],
|
||||
@@ -1437,10 +1447,11 @@ fn lines(
|
||||
y: &[Option<f64>],
|
||||
dx: &[f64],
|
||||
dy: &[f64],
|
||||
anchor: f64,
|
||||
anchor_of: &dyn Fn(usize) -> f64,
|
||||
rtl: bool,
|
||||
x0: f64,
|
||||
breaks: &mut Vec<Break>,
|
||||
) -> (Justify, f64, Option<Vec<(usize, f64)>>) {
|
||||
) -> (Justify, f64, Vec<(usize, f64, f64)>) {
|
||||
let n = cells.len();
|
||||
let y0 = y[0].unwrap_or(0.0) + dy[0];
|
||||
let (mut base, mut cur) = (y0, y0);
|
||||
@@ -1482,53 +1493,59 @@ fn lines(
|
||||
}
|
||||
}
|
||||
if targets.is_empty() {
|
||||
return (justify_of(anchor), x0, Some(lines));
|
||||
let starts = lines.iter().map(|&(s, lx)| (s, anchor_of(s), lx)).collect();
|
||||
return (justify_of(anchor_of(0)), x0, starts);
|
||||
}
|
||||
// Absolutely placed characters: lay the text out left-aligned and kern each one onto its x.
|
||||
// SVG anchors every absolutely placed chunk on its own, so with a middle/end anchor each
|
||||
// chunk's target moves back by its share of the chunk's width.
|
||||
// SVG anchors every absolutely placed chunk on its own, so a chunk not anchored at its left
|
||||
// edge moves back by its share of its own width. A chunk's edges are those of its glyphs as
|
||||
// they are drawn: the first character of a right-to-left chunk is at its right.
|
||||
let line_of = |i: usize| lines.partition_point(|(s, _)| *s <= i) - 1;
|
||||
let mut left = x0;
|
||||
let mut wants: Vec<(usize, f64)> = targets.clone();
|
||||
if anchor > 0.0 {
|
||||
let (runs, bytes) = assemble(cells, breaks);
|
||||
let lay = measure(&with_runs(runs.0));
|
||||
let (pens, ends) = pens(&lay, &bytes);
|
||||
// Chunk starts in order: line starts and absolutely placed characters.
|
||||
let mut starts: Vec<usize> = lines.iter().map(|l| l.0).chain(targets.iter().map(|t| t.0)).collect();
|
||||
starts.sort_unstable();
|
||||
let width = |s: usize| {
|
||||
let k = starts.partition_point(|&c| c <= s);
|
||||
let e = starts.get(k).copied().unwrap_or(n);
|
||||
let end = (s..e).filter_map(|j| ends[j]).fold(f64::NEG_INFINITY, f64::max);
|
||||
match pens[s] {
|
||||
Some(p) if end.is_finite() => end - p,
|
||||
_ => 0.0,
|
||||
}
|
||||
};
|
||||
let line_left: Vec<f64> = lines.iter().map(|&(s, lx)| lx - anchor * width(s)).collect();
|
||||
left = line_left[0];
|
||||
for w in &mut wants {
|
||||
w.1 -= anchor * width(w.0) + line_left[line_of(w.0)];
|
||||
}
|
||||
} else {
|
||||
for w in &mut wants {
|
||||
w.1 -= lines[line_of(w.0)].1;
|
||||
}
|
||||
}
|
||||
// Chunk starts in order: line starts and absolutely placed characters.
|
||||
let mut starts: Vec<usize> = lines.iter().map(|l| l.0).chain(targets.iter().map(|t| t.0)).collect();
|
||||
starts.sort_unstable();
|
||||
// The left and right edges of the chunk starting at character `s`, from each character's pen and end.
|
||||
let edges = |s: usize, pens: &[Option<f64>], ends: &[Option<f64>]| {
|
||||
let e = starts.get(starts.partition_point(|&c| c <= s)).copied().unwrap_or(n);
|
||||
let left = (s..e).filter_map(|j| pens[j]).fold(f64::INFINITY, f64::min);
|
||||
let right = (s..e).filter_map(|j| ends[j]).fold(f64::NEG_INFINITY, f64::max);
|
||||
(left.is_finite() && right.is_finite()).then_some((left, right))
|
||||
};
|
||||
let mut line_left: Vec<f64> = lines.iter().map(|l| l.1).collect();
|
||||
// Where each absolutely placed character's pen goes, from the left edge of its line's first chunk.
|
||||
let mut wants: Vec<(usize, f64)> = vec![];
|
||||
// Kerning changes shaping (pair kerning is off for manually kerned characters): repeat until
|
||||
// every character sits on its x.
|
||||
for _ in 0..4 {
|
||||
for round in 0..4 {
|
||||
let (runs, bytes) = assemble(cells, breaks);
|
||||
let lay = measure(&with_runs(runs.0));
|
||||
let (pens, _) = pens(&lay, &bytes);
|
||||
let mut text = with_runs(runs.0);
|
||||
pin_direction(&mut text, rtl);
|
||||
let (pens, ends) = pens(&measure(&text), &bytes);
|
||||
// The edges of each line's first chunk, found once a round.
|
||||
let first: Vec<Option<(f64, f64)>> = lines.iter().map(|&(s, _)| edges(s, &pens, &ends)).collect();
|
||||
if round == 0 {
|
||||
// The chunks as they lie before any is moved: each one's left edge on its anchor.
|
||||
let left_at = |s: usize, x: f64, chunk: Option<(f64, f64)>| chunk.map_or(x, |(left, right)| x - anchor_of(s) * (right - left));
|
||||
let first_left: Vec<f64> = lines.iter().zip(&first).map(|(&(s, lx), &chunk)| left_at(s, lx, chunk)).collect();
|
||||
wants = targets
|
||||
.iter()
|
||||
.map(|&(i, x)| {
|
||||
let chunk = edges(i, &pens, &ends);
|
||||
// The pen of a right-to-left chunk's first character is right of the chunk's left edge.
|
||||
let pen = pens[i].zip(chunk).map_or(0.0, |(p, (left, _))| p - left);
|
||||
(i, left_at(i, x, chunk) + pen - first_left[line_of(i)])
|
||||
})
|
||||
.collect();
|
||||
// A line's layout starts at the line's left edge, and its first chunk's left edge is `left` from there.
|
||||
line_left = first_left.iter().zip(&first).map(|(&x, chunk)| x - chunk.map_or(0.0, |(left, _)| left)).collect();
|
||||
}
|
||||
let (mut line, mut moved, mut worst) = (usize::MAX, 0.0, 0.0f64);
|
||||
for &(i, want) in &wants {
|
||||
let l = line_of(i);
|
||||
if l != line {
|
||||
(line, moved) = (l, 0.0);
|
||||
}
|
||||
let (Some(p), Some(p0)) = (pens[i], pens[lines[l].0]) else { continue };
|
||||
let (Some(p), Some((p0, _))) = (pens[i], first[l]) else { continue };
|
||||
let d = want - (p - p0 + moved);
|
||||
cells[i - 1].kern += d;
|
||||
moved += d;
|
||||
@@ -1538,7 +1555,8 @@ fn lines(
|
||||
break;
|
||||
}
|
||||
}
|
||||
(Justify::Left, left, None)
|
||||
let starts = lines.iter().zip(&line_left).map(|(&(s, _), &lx)| (s, 0.0, lx)).collect();
|
||||
(Justify::Left, line_left[0], starts)
|
||||
}
|
||||
|
||||
/// Centred and right-aligned lines of point type `obj` where a reader draws them. `text-anchor`
|
||||
@@ -1546,7 +1564,9 @@ fn lines(
|
||||
/// export anchors lines so); VectorCraft aligns a line without that tracking
|
||||
/// ([`vectorcraft_text::LineInfo::trailing`]). Each such line moves back by its share of it: the
|
||||
/// type moves when every line moves alike, otherwise each paragraph's right indent takes the
|
||||
/// tracking (a line of imported point type is a paragraph). Browsers add that letter spacing
|
||||
/// tracking (a line of imported point type is a paragraph). A right-to-left paragraph's lines
|
||||
/// keep all their tracking in the layout (`trailing` is 0), so they stay where they are and their
|
||||
/// whole advance sits on the anchor. Browsers add that letter spacing
|
||||
/// today; CSS WG issue 1518 and Firefox bugs 1907305 and 1913554 may drop it at a line's end.
|
||||
fn keep_reader_anchors(obj: &mut TextObject) {
|
||||
let share = |j: Justify| match j {
|
||||
@@ -1590,6 +1610,17 @@ fn keep_reader_anchors(obj: &mut TextObject) {
|
||||
obj.set_paragraph_styles(styles);
|
||||
}
|
||||
|
||||
/// SVG text runs left to right unless `direction: rtl` on the `<text>` says otherwise (`rtl`),
|
||||
/// whatever its first strong character: pinned (on every paragraph of `obj`) when that would read
|
||||
/// as right to left.
|
||||
fn pin_direction(obj: &mut TextObject, rtl: bool) {
|
||||
if rtl {
|
||||
obj.edit_paras(None, |pa| pa.direction = Some(ParaDirection::RightToLeft));
|
||||
} else if obj.plain_text().split('\n').any(|p| vectorcraft_text::paragraph_is_rtl(p, None)) {
|
||||
obj.edit_paras(None, |pa| pa.direction = Some(ParaDirection::LeftToRight));
|
||||
}
|
||||
}
|
||||
|
||||
/// A left-aligned point text of `runs` at the origin (for measuring).
|
||||
fn with_runs(runs: Vec<TextRun>) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "", CharStyle::default());
|
||||
|
||||
@@ -360,6 +360,197 @@ fn anchored_letter_spaced_lines_stay_where_a_reader_draws_them() {
|
||||
assert!(close(s[0], 200.0 - a[0] / 2.0, 1e-6) && close(s[1], 200.0 - a[1], 1e-6), "{s:?} {a:?}");
|
||||
}
|
||||
|
||||
/// Document-space left and right edges of the advance of each laid-out line.
|
||||
fn line_edges(t: &TextObject) -> Vec<(f64, f64)> {
|
||||
let lay = layout(FontDb::global(), t);
|
||||
lay.lines
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let g = &lay.glyphs[l.glyph_start..l.glyph_end];
|
||||
let left = g.iter().map(|g| (t.xf * g.origin).x).fold(f64::INFINITY, f64::min);
|
||||
let right = g.iter().map(|g| (t.xf * g.origin).x + g.advance).fold(f64::NEG_INFINITY, f64::max);
|
||||
(left, right)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// SVG 2 §11.10.1.1 (https://www.w3.org/TR/SVG2/text.html#TextAnchoringProperties): with
|
||||
/// `direction: rtl`, `start` puts the right side of the text at its position and `end` puts the
|
||||
/// left side there; `middle` centers it either way. The direction is the effective one of the element that
|
||||
/// holds the chunk's first character.
|
||||
#[test]
|
||||
fn rtl_point_text_start_and_end_use_directional_edges() {
|
||||
// (markup, share of the advance left of x = 200)
|
||||
for (body, share) in [
|
||||
(r#"<text x="200" y="60" direction="rtl" font-size="20">Wave</text>"#, 1.0),
|
||||
(r#"<text x="200" y="60" direction="rtl" text-anchor="start" font-size="20">Wave</text>"#, 1.0),
|
||||
(r#"<text x="200" y="60" direction="rtl" text-anchor="middle" font-size="20">Wave</text>"#, 0.5),
|
||||
(r#"<text x="200" y="60" direction="rtl" text-anchor="end" font-size="20">Wave</text>"#, 0.0),
|
||||
(r#"<g direction="rtl"><text x="200" y="60" font-size="20">Wave</text></g>"#, 1.0),
|
||||
(r#"<g direction="rtl" text-anchor="end"><text x="200" y="60" font-size="20">Wave</text></g>"#, 0.0),
|
||||
(r#"<text x="200" y="60" direction="rtl" font-size="20"><tspan direction="ltr">Wave</tspan></text>"#, 0.0),
|
||||
(r#"<text x="200" y="60" text-anchor="start" font-size="20">Wave</text>"#, 0.0),
|
||||
(r#"<text x="200" y="60" direction="ltr" text-anchor="end" font-size="20">Wave</text>"#, 1.0),
|
||||
] {
|
||||
let d = open(body);
|
||||
let (left, right) = line_edges(only_text(&d))[0];
|
||||
let want = 200.0 - share * (right - left);
|
||||
assert!(close(left, want, 1e-6), "{body}: the advance spans {left}..{right}, so it does not start at {want}");
|
||||
}
|
||||
}
|
||||
|
||||
/// On a path, right-to-left text anchored by `start` ends at `startOffset` and one anchored by
|
||||
/// `end` begins there (its glyphs run from the path's start in visual order); `middle` centers it.
|
||||
#[test]
|
||||
fn rtl_type_on_a_path_starts_at_its_directional_edge() {
|
||||
// (anchor, direction, share of the advance before the offset)
|
||||
for (anchor, direction, share) in [("start", "rtl", 1.0), ("middle", "rtl", 0.5), ("end", "rtl", 0.0), ("start", "ltr", 0.0), ("end", "ltr", 1.0)]
|
||||
{
|
||||
let d = open(&format!(
|
||||
r##"<path id="p" d="M0 100 L400 100" fill="none"/>
|
||||
<text font-size="20" text-anchor="{anchor}" direction="{direction}"><textPath href="#p" startOffset="200">Wave</textPath></text>"##
|
||||
));
|
||||
let t = only_text(&d);
|
||||
assert!(matches!(t.kind, TextKind::OnPath { .. }), "{:?}", t.kind);
|
||||
let lay = layout(FontDb::global(), t);
|
||||
let left = lay.glyphs.iter().map(|g| (t.xf * g.origin).x).fold(f64::INFINITY, f64::min);
|
||||
let width: f64 = lay.glyphs.iter().map(|g| g.advance).sum();
|
||||
let want = 200.0 - share * width;
|
||||
assert!(close(left, want, 0.05), "{anchor} {direction}: the text starts at {left}, not {want}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Letter-spaced right-to-left lines: a line keeps the tracking after each of its characters, and
|
||||
/// its whole advance sits on its anchor as `start`, `middle` and `end` place it.
|
||||
#[test]
|
||||
fn rtl_letter_spaced_lines_stay_on_their_anchor() {
|
||||
for (anchor, share) in [("start", 1.0), ("middle", 0.5), ("end", 0.0)] {
|
||||
let d = open(&format!(r#"<text x="200" y="100" direction="rtl" text-anchor="{anchor}" letter-spacing="8" font-size="40">WAVE</text>"#));
|
||||
let t = only_text(&d);
|
||||
let (left, right) = line_edges(t)[0];
|
||||
let want = 200.0 - share * (right - left);
|
||||
assert!(close(left, want, 1e-6), "{anchor}: the advance spans {left}..{right}, so it does not start at {want}");
|
||||
let natural = {
|
||||
let d = open(&format!(r#"<text x="200" y="100" direction="rtl" text-anchor="{anchor}" font-size="40">WAVE</text>"#));
|
||||
let (l, r) = line_edges(only_text(&d))[0];
|
||||
r - l
|
||||
};
|
||||
assert!(close(right - left, natural + 4.0 * 8.0, 1e-6), "{anchor}: the advance {} holds the tracking of all 4 letters", right - left);
|
||||
}
|
||||
// A right-to-left line anchored by `start` beside a left-to-right `middle` line: each keeps its own anchor.
|
||||
let d = open(
|
||||
r#"<text y="100" font-size="20" letter-spacing="4"><tspan x="200" direction="rtl">Wave</tspan><tspan x="200" dy="30" text-anchor="middle">Line</tspan></text>"#,
|
||||
);
|
||||
let t = only_text(&d);
|
||||
let e = line_edges(t);
|
||||
assert_eq!(e.len(), 2, "{e:?}");
|
||||
assert!(close(e[0].1, 200.0, 1e-6), "the right-to-left line ends at 200: {e:?}");
|
||||
let lay = layout(FontDb::global(), t);
|
||||
let a: f64 = lay.glyphs[lay.lines[1].glyph_start..lay.lines[1].glyph_end].iter().map(|g| g.advance).sum();
|
||||
assert!(close(e[1].0, 200.0 - a / 2.0, 1e-6), "the middle line is centered on 200 with its tracking: {e:?}");
|
||||
}
|
||||
|
||||
/// Each line is a chunk anchored by the `text-anchor` and `direction` of its first character.
|
||||
#[test]
|
||||
fn rtl_lines_use_each_chunk_first_character_direction_and_anchor() {
|
||||
let d = open(
|
||||
r#"<text y="60" font-size="20"><tspan x="200" direction="rtl">Wave</tspan><tspan x="200" dy="30">Line</tspan><tspan x="200" dy="30" direction="rtl" text-anchor="end">Last</tspan><tspan x="200" dy="30" direction="rtl" text-anchor="middle">Mid</tspan></text>"#,
|
||||
);
|
||||
let e = line_edges(only_text(&d));
|
||||
assert_eq!(e.len(), 4, "{e:?}");
|
||||
assert!(close(e[0].1, 200.0, 1e-6), "a right-to-left start line ends at 200: {e:?}");
|
||||
assert!(close(e[1].0, 200.0, 1e-6), "a left-to-right start line starts at 200: {e:?}");
|
||||
assert!(close(e[2].0, 200.0, 1e-6), "a right-to-left end line starts at 200: {e:?}");
|
||||
assert!(close((e[3].0 + e[3].1) / 2.0, 200.0, 1e-6), "a middle line is centered on 200: {e:?}");
|
||||
}
|
||||
|
||||
/// A line starts at its own x, also when it is anchored as the line before it is and when another
|
||||
/// line holds absolutely placed characters.
|
||||
#[test]
|
||||
fn each_line_starts_at_its_own_x() {
|
||||
let d = open(r#"<text y="40" font-size="20"><tspan x="50">Wave</tspan><tspan x="120" dy="30">Line</tspan></text>"#);
|
||||
let e = line_edges(only_text(&d));
|
||||
assert!(close(e[0].0, 50.0, 1e-6) && close(e[1].0, 120.0, 1e-6), "{e:?}");
|
||||
let d = open(r#"<text y="40" font-size="20" text-anchor="end"><tspan x="150">Wave</tspan><tspan x="100" dy="30">Line</tspan></text>"#);
|
||||
let e = line_edges(only_text(&d));
|
||||
assert!(close(e[0].1, 150.0, 1e-6) && close(e[1].1, 100.0, 1e-6), "{e:?}");
|
||||
let d = open(r#"<text y="40" font-size="20"><tspan x="50 100">ab</tspan><tspan x="200" dy="30" direction="rtl">Line</tspan></text>"#);
|
||||
let t = only_text(&d);
|
||||
let e = line_edges(t);
|
||||
assert_eq!(e.len(), 2, "{e:?}");
|
||||
assert!(close(e[0].0, 50.0, 0.05) && close(e[1].1, 200.0, 0.05), "{e:?}");
|
||||
let b = (t.xf * layout(FontDb::global(), t).glyphs[1].origin).x;
|
||||
assert!(close(b, 100.0, 0.05), "b starts at {b}");
|
||||
}
|
||||
|
||||
/// Absolutely placed chunks are anchored on their own, each by the `text-anchor` and `direction`
|
||||
/// of its first character, whatever the first chunk's anchor.
|
||||
#[test]
|
||||
fn absolutely_placed_chunks_use_their_own_rtl_anchor() {
|
||||
// (markup, share of each chunk's advance left of its x)
|
||||
for (body, shares) in [
|
||||
(r#"<text x="80 200" y="40" font-size="20">a<tspan direction="rtl">b</tspan></text>"#, [0.0, 1.0]),
|
||||
(r#"<text x="80 200" y="40" font-size="20">a<tspan direction="rtl" text-anchor="end">b</tspan></text>"#, [0.0, 0.0]),
|
||||
(r#"<text y="40" font-size="20"><tspan x="80">a</tspan><tspan x="200" direction="rtl">b</tspan></text>"#, [0.0, 1.0]),
|
||||
(r#"<text x="80 200" y="40" text-anchor="middle" font-size="20">a<tspan direction="rtl" text-anchor="end">b</tspan></text>"#, [0.5, 0.0]),
|
||||
(r#"<text x="80 200" y="40" text-anchor="middle" font-size="20">a<tspan direction="rtl" text-anchor="start">b</tspan></text>"#, [0.5, 1.0]),
|
||||
(r#"<text x="80 200" y="40" text-anchor="middle" font-size="20">a<tspan direction="rtl">b</tspan></text>"#, [0.5, 0.5]),
|
||||
(r#"<text x="80 200" y="40" direction="rtl" font-size="20">ab</text>"#, [1.0, 1.0]),
|
||||
] {
|
||||
let d = open(body);
|
||||
let t = only_text(&d);
|
||||
let lay = layout(FontDb::global(), t);
|
||||
assert_eq!(lay.glyphs.len(), 2, "{body}");
|
||||
// Natural advance: the kerning that moves `b` onto its x is added after `a`.
|
||||
let style = |i: usize| t.runs.iter().flat_map(|r| r.text.chars().map(move |_| &r.style)).nth(i).unwrap();
|
||||
let natural = |i: usize| lay.glyphs[i].advance - style(i).kerning.unwrap_or(0.0) / 1000.0 * style(i).size;
|
||||
for (i, (x, share)) in [80.0, 200.0].into_iter().zip(shares).enumerate() {
|
||||
let left = (t.xf * lay.glyphs[i].origin).x;
|
||||
let want = x - share * natural(i);
|
||||
assert!(close(left, want, 0.05), "{body}: chunk {i} starts at {left}, not {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A right-to-left chunk of several characters is anchored by its visual edges: its first
|
||||
/// character is drawn at its right, so the chunk runs left from that character's right edge.
|
||||
#[test]
|
||||
fn absolutely_placed_rtl_chunks_of_several_characters_anchor_by_their_visual_edges() {
|
||||
// (markup, share of the right-to-left chunk's advance left of x = 200)
|
||||
for (body, share) in [
|
||||
(r#"<text x="80 200" y="40" font-size="20">a<tspan direction="rtl">אב</tspan></text>"#, 1.0),
|
||||
(r#"<text x="80 200" y="40" font-size="20">a<tspan direction="rtl" text-anchor="middle">אב</tspan></text>"#, 0.5),
|
||||
(r#"<text x="80 200" y="40" font-size="20">a<tspan direction="rtl" text-anchor="end">אב</tspan></text>"#, 0.0),
|
||||
(r#"<text x="80 200" y="40" font-size="20">a<tspan text-anchor="end">אב</tspan></text>"#, 1.0),
|
||||
// A digit is not a strong character: the text still runs left to right.
|
||||
(r#"<text x="80 200" y="40" font-size="20">1<tspan direction="rtl" text-anchor="end">אב</tspan></text>"#, 0.0),
|
||||
// The chunk starts a line, and another line holds absolutely placed characters.
|
||||
(r#"<text y="40" font-size="20"><tspan x="200" direction="rtl">אב</tspan><tspan x="50 100" dy="30">ab</tspan></text>"#, 1.0),
|
||||
(
|
||||
r#"<text y="40" font-size="20"><tspan x="200" direction="rtl" text-anchor="middle">אב</tspan><tspan x="50 100" dy="30">ab</tspan></text>"#,
|
||||
0.5,
|
||||
),
|
||||
(
|
||||
r#"<text y="40" font-size="20"><tspan x="200" direction="rtl" text-anchor="end">אב</tspan><tspan x="50 100" dy="30">ab</tspan></text>"#,
|
||||
0.0,
|
||||
),
|
||||
] {
|
||||
let d = open(body);
|
||||
let t = only_text(&d);
|
||||
let lay = layout(FontDb::global(), t);
|
||||
let chunk: Vec<_> = lay.glyphs.iter().filter(|g| g.rtl).collect();
|
||||
assert_eq!(chunk.len(), 2, "{body}");
|
||||
assert!(chunk.iter().all(|g| g.advance > 1.0), "{body}: both letters have an advance");
|
||||
let left = chunk.iter().map(|g| (t.xf * g.origin).x).fold(f64::INFINITY, f64::min);
|
||||
let right = chunk.iter().map(|g| (t.xf * g.origin).x + g.advance).fold(f64::NEG_INFINITY, f64::max);
|
||||
let want = 200.0 - share * (right - left);
|
||||
assert!(close(left, want, 0.05), "{body}: the chunk spans {left}..{right}, so it does not start at {want}");
|
||||
// The first character is the right one of the two.
|
||||
let first = lay.glyphs.iter().filter(|g| g.rtl).min_by_key(|g| g.byte).map(|g| (t.xf * g.origin).x);
|
||||
assert!(first.is_some_and(|x| x > left + 1.0), "{body}: the first character starts at {first:?}, the chunk at {left}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_line_gap_in_tiny_type_keeps_its_leading() {
|
||||
// 0.0085 against an auto leading of 0.006 differs by less than 0.01 but is not a whole multiple of it.
|
||||
|
||||
+82
-17
@@ -61,10 +61,51 @@ pub(crate) struct Params {
|
||||
pub hyphen_limit: usize,
|
||||
}
|
||||
|
||||
struct Node {
|
||||
/// The search gave up: it ran past its budget ([`Measure::line`]).
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Exhausted;
|
||||
|
||||
/// Where each line of a paragraph goes and how wide it is: the measure a line gets may depend on
|
||||
/// the lines set above it (their heights move it down a shaped frame, or past a wrap object).
|
||||
pub(crate) trait Measure {
|
||||
/// What the measure of the next line depends on; breaks reached with equal states are
|
||||
/// interchangeable from there on.
|
||||
type State: Clone + PartialEq;
|
||||
/// The state of the paragraph's first line.
|
||||
fn first(&mut self) -> Self::State;
|
||||
/// The width of the line of glyphs `pos..end` set from `state`, and the state of the line
|
||||
/// after it; `Ok(None)` when the line can't be set (the frame is full), and [`Exhausted`] when
|
||||
/// the search is to stop.
|
||||
fn line(&mut self, state: &Self::State, pos: usize, end: usize) -> Result<Option<(f64, Self::State)>, Exhausted>;
|
||||
/// Whether a line from `state` longer than `pos..end`, which [`Measure::line`] just measured,
|
||||
/// may get more room than it. While it may, a line from `state` that is too long, or that
|
||||
/// can't be set, does not end the reach of `state`. Lines from a state are all as wide by
|
||||
/// default.
|
||||
fn may_widen(&mut self, _state: &Self::State, _pos: usize, _end: usize) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Line widths by line number: `width(k)` for line `k`, lines from `uniform_from` on all as wide.
|
||||
struct ByLine<'a> {
|
||||
width: &'a dyn Fn(usize) -> f64,
|
||||
uniform_from: usize,
|
||||
}
|
||||
|
||||
impl Measure for ByLine<'_> {
|
||||
type State = usize;
|
||||
fn first(&mut self) -> usize {
|
||||
0
|
||||
}
|
||||
fn line(&mut self, &line: &usize, _: usize, _: usize) -> Result<Option<(f64, usize)>, Exhausted> {
|
||||
Ok(Some(((self.width)(line), (line + 1).min(self.uniform_from))))
|
||||
}
|
||||
}
|
||||
|
||||
struct Node<S> {
|
||||
pos: usize,
|
||||
/// Line number of the next line, clamped to `uniform_from`.
|
||||
line: usize,
|
||||
/// The measure of the next line (its line number, clamped to `uniform_from`, for [`compose`]).
|
||||
state: S,
|
||||
fitness: u8,
|
||||
demerits: f64,
|
||||
/// Lines in a row ending with a hyphen up to this break (at most `hyphen_limit`, or 1 with no
|
||||
@@ -131,6 +172,19 @@ pub(crate) fn compose(
|
||||
cands: &[Breakpoint],
|
||||
flex: &[Flex],
|
||||
p: &Params,
|
||||
) -> Option<Vec<(usize, bool)>> {
|
||||
compose_with(g, &mut ByLine { width, uniform_from: p.uniform_from }, start_credit, end_credit, cands, flex, p)
|
||||
}
|
||||
|
||||
/// [`compose`] with each line's width from `measure`, which follows where the lines above it went.
|
||||
pub(crate) fn compose_with<M: Measure>(
|
||||
g: &[SGlyph],
|
||||
measure: &mut M,
|
||||
start_credit: &dyn Fn(usize) -> f64,
|
||||
end_credit: &dyn Fn(usize) -> f64,
|
||||
cands: &[Breakpoint],
|
||||
flex: &[Flex],
|
||||
p: &Params,
|
||||
) -> Option<Vec<(usize, bool)>> {
|
||||
let n = g.len();
|
||||
if n == 0 {
|
||||
@@ -165,14 +219,14 @@ pub(crate) fn compose(
|
||||
all.push(Breakpoint { end: n, hyphen: 0.0 });
|
||||
let (adj_demerits, hyphen_penalty) =
|
||||
if p.ragged { (ADJ_DEMERITS_RAGGED, HYPHEN_PENALTY_RAGGED) } else { (ADJ_DEMERITS_JUSTIFIED, HYPHEN_PENALTY) };
|
||||
let mut nodes = vec![Node { pos: 0, line: 0, fitness: 1, demerits: 0.0, hyphens: 0, prev: None }];
|
||||
let mut nodes = vec![Node { pos: 0, state: measure.first(), fitness: 1, demerits: 0.0, hyphens: 0, prev: None }];
|
||||
let mut active: Vec<usize> = vec![0];
|
||||
for bp in &all {
|
||||
let last = bp.end == n;
|
||||
let hyphen = bp.hyphen > 0.0;
|
||||
// `automatic` is true for a hyphenation point and false for a soft hyphen typed in the text.
|
||||
let automatic = hyphen && !bp.end.checked_sub(1).and_then(|k| g.get(k)).is_some_and(SGlyph::is_soft_hyphen);
|
||||
let mut best: Vec<(usize, u8, usize, f64, usize)> = vec![]; // (line, fitness, hyphens, demerits, from)
|
||||
let mut best: Vec<(M::State, u8, usize, f64, usize)> = vec![]; // (state, fitness, hyphens, demerits, from)
|
||||
let mut keep = Vec::with_capacity(active.len());
|
||||
for &ai in &active {
|
||||
let Some(a) = nodes.get(ai) else { continue };
|
||||
@@ -182,13 +236,25 @@ pub(crate) fn compose(
|
||||
// last glyph's advance, so a longer line from the same node is never narrower.
|
||||
let end = if hyphen || t <= a.pos { 0.0 } else { line_end_credit(t) };
|
||||
let natural = w[t] - w[a.pos] - credit - end + bp.hyphen;
|
||||
let lw = width(a.line);
|
||||
// Adjustment ratio, badness and whether the line ends the active node's reach.
|
||||
let Some(ratio) = adjustment_ratio(natural, lw, st[t] - st[a.pos], sh[t] - sh[a.pos], last, p) else { continue };
|
||||
if ratio < -1.0 {
|
||||
// Too long already; longer lines from this node only get worse.
|
||||
// A line that can't be set (no room left in the frame) ends this node's reach, unless a
|
||||
// longer line may be placed elsewhere (a taller line steps down the frame by its own
|
||||
// leading).
|
||||
let Some((lw, next)) = measure.line(&a.state, a.pos, bp.end).ok()? else {
|
||||
if measure.may_widen(&a.state, a.pos, bp.end) {
|
||||
keep.push(ai);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// Adjustment ratio, badness and whether the line ends the active node's reach.
|
||||
let ratio = adjustment_ratio(natural, lw, st[t] - st[a.pos], sh[t] - sh[a.pos], last, p);
|
||||
let Some(ratio) = ratio.filter(|&r| r >= -1.0 || r.is_nan()) else {
|
||||
// Too long already; longer lines from this node only get worse, unless they may
|
||||
// get more room (a taller line set lower down a shaped frame).
|
||||
if measure.may_widen(&a.state, a.pos, bp.end) {
|
||||
keep.push(ai);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
keep.push(ai);
|
||||
if automatic && p.hyphen_limit > 0 && a.hyphens >= p.hyphen_limit {
|
||||
continue;
|
||||
@@ -214,22 +280,21 @@ pub(crate) fn compose(
|
||||
d += adj_demerits;
|
||||
}
|
||||
let total = a.demerits + d;
|
||||
let line = (a.line + 1).min(p.uniform_from);
|
||||
// With a limit, breaks reached with different runs of hyphenated lines stay apart.
|
||||
let hyphens = match (hyphen, p.hyphen_limit) {
|
||||
(false, _) => 0,
|
||||
(true, 0) => 1,
|
||||
(true, limit) => (a.hyphens + 1).min(limit),
|
||||
};
|
||||
match best.iter_mut().find(|b| b.0 == line && b.1 == fit && b.2 == hyphens) {
|
||||
match best.iter_mut().find(|b| b.0 == next && b.1 == fit && b.2 == hyphens) {
|
||||
Some(b) if b.3 <= total => {}
|
||||
Some(b) => *b = (line, fit, hyphens, total, ai),
|
||||
None => best.push((line, fit, hyphens, total, ai)),
|
||||
Some(b) => *b = (next, fit, hyphens, total, ai),
|
||||
None => best.push((next, fit, hyphens, total, ai)),
|
||||
}
|
||||
}
|
||||
active = keep;
|
||||
for (line, fitness, hyphens, demerits, from) in best {
|
||||
nodes.push(Node { pos: bp.end, line, fitness, demerits, hyphens, prev: Some(from) });
|
||||
for (state, fitness, hyphens, demerits, from) in best {
|
||||
nodes.push(Node { pos: bp.end, state, fitness, demerits, hyphens, prev: Some(from) });
|
||||
active.push(nodes.len() - 1);
|
||||
}
|
||||
if active.is_empty() || active.len() > MAX_ACTIVE {
|
||||
|
||||
@@ -31,6 +31,7 @@ mod flow;
|
||||
mod on_path;
|
||||
mod region;
|
||||
mod ruby;
|
||||
mod shaped;
|
||||
mod vertical;
|
||||
|
||||
pub(crate) use bidi::{is_rtl, para_bidi};
|
||||
|
||||
@@ -26,14 +26,18 @@ impl Metrics {
|
||||
pub(super) fn max(g: &[SGlyph]) -> Option<Self> {
|
||||
let mut it = g.iter();
|
||||
let first = Self::of(it.next()?);
|
||||
Some(it.fold(first, |m, g| Self {
|
||||
asc: m.asc.max(g.ascent),
|
||||
desc: m.desc.max(g.descent),
|
||||
lead: m.lead.max(g.leading),
|
||||
cap: m.cap.max(g.cap),
|
||||
xh: m.xh.max(g.xh),
|
||||
top: m.top.max(Self::of(g).top),
|
||||
}))
|
||||
Some(it.fold(first, |m, g| m.union(Self::of(g))))
|
||||
}
|
||||
/// The larger of each of the metrics of `self` and `o`: those of a line holding both.
|
||||
pub(super) fn union(self, o: Self) -> Self {
|
||||
Self {
|
||||
asc: self.asc.max(o.asc),
|
||||
desc: self.desc.max(o.desc),
|
||||
lead: self.lead.max(o.lead),
|
||||
cap: self.cap.max(o.cap),
|
||||
xh: self.xh.max(o.xh),
|
||||
top: self.top.max(o.top),
|
||||
}
|
||||
}
|
||||
/// Distance from the frame top to the first baseline.
|
||||
pub(super) fn first_baseline(&self, fb: FirstBaseline, min: f64) -> f64 {
|
||||
@@ -67,6 +71,9 @@ pub(super) struct Pen<'r> {
|
||||
/// Baseline steps still allowed over all the frame's cells and placements (shared by this pen's
|
||||
/// copies): see [`MAX_TOTAL_STEPS`].
|
||||
pub(super) steps_left: std::rc::Rc<std::cell::Cell<usize>>,
|
||||
/// What is left of the every-line composer's search over the frame's paragraphs (shared by
|
||||
/// this pen's copies): see [`super::shaped::Budget`].
|
||||
pub(super) search: std::rc::Rc<super::shaped::Budget>,
|
||||
}
|
||||
|
||||
/// The largest number of steps layout takes to move a line down a frame cell to find room for it:
|
||||
@@ -103,9 +110,24 @@ impl Pen<'_> {
|
||||
let b = self.prev.map_or(0.0, |b| self.next_baseline(b, est));
|
||||
return Some((b, f64::NEG_INFINITY, f64::INFINITY, false));
|
||||
};
|
||||
if !self.queued.is_empty() {
|
||||
// A further span was measured across the height of the line set before it on its baseline.
|
||||
// This line gets the part of it that is free across its own height: a taller line can
|
||||
// reach a wrap object the line before it stayed clear of. A span with no such part is
|
||||
// left empty, and so is a part the line's height made narrower than `min`.
|
||||
while !self.queued.is_empty() {
|
||||
let (b, x0, x1) = self.queued.remove(0);
|
||||
return Some((b, x0, x1, true));
|
||||
let Some(r) = regions.get(self.ri) else { return Some((b, x0, x1, true)) };
|
||||
let mut free = r.spans(b - est.asc, b + est.desc).into_iter().filter_map(|(s, e)| {
|
||||
let (s, e) = (s.max(x0), e.min(x1));
|
||||
let room = e - s - ind_l - ind_r;
|
||||
let narrowed = s > x0 + EPS || e < x1 - EPS;
|
||||
(room > est.asc.max(1.0) && (!narrowed || room + EPS >= min)).then_some((s, e))
|
||||
});
|
||||
let Some((s, e)) = free.next() else { continue };
|
||||
// An object inside the span splits it: the parts after the first stay queued.
|
||||
let rest: Vec<_> = free.map(|(s, e)| (b, s, e)).collect();
|
||||
self.queued.splice(0..0, rest);
|
||||
return Some((b, s, e, true));
|
||||
}
|
||||
loop {
|
||||
let r = regions.get(self.ri)?;
|
||||
@@ -841,6 +863,7 @@ fn a_pen_out_of_baseline_steps_finds_no_room() {
|
||||
next_top: None,
|
||||
no_room_for: f64::INFINITY,
|
||||
steps_left: std::rc::Rc::new(std::cell::Cell::new(steps)),
|
||||
search: Default::default(),
|
||||
};
|
||||
assert!(pen(MAX_TOTAL_STEPS).place(est, 0.0, 0.0, 0.0).is_some());
|
||||
assert!(pen(0).place(est, 0.0, 0.0, 0.0).is_none());
|
||||
|
||||
@@ -24,9 +24,15 @@ fn pushes_in(para: &ParaStyle) -> bool {
|
||||
/// Paragraphs longer than this (glyphs) are always broken line by line.
|
||||
const MAX_COMPOSE_GLYPHS: usize = 200_000;
|
||||
|
||||
/// Whether every line of area type in `regions` is as wide however tall it is and wherever it is set:
|
||||
/// rectangular cells without text wrap.
|
||||
fn constant_width(regions: Option<&[Region]>) -> bool {
|
||||
regions.is_some_and(|r| r.iter().all(|r| (r.rect || r.polys.is_empty()) && r.wraps.is_empty()))
|
||||
}
|
||||
|
||||
/// Every-line composition of paragraph glyphs `sg` if applicable (area text, justified or ragged,
|
||||
/// with uniform line metrics or in rectangular cells without text wrap); `None` falls back to the
|
||||
/// greedy single-line composer. With `continued`, the paragraph continues from the frame before,
|
||||
/// in any frame shape, with or without text wrap); `None` falls back to the greedy single-line
|
||||
/// composer. With `continued`, the paragraph continues from the frame before,
|
||||
/// and its first composed line is not its first line. `line_end` is how much narrower a line
|
||||
/// ending with each glyph is set ([`ParagraphData::line_end`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -66,14 +72,11 @@ fn compose_para(
|
||||
let m = Metrics::of(&sg[0]);
|
||||
// Line widths are independent of the breaks when every line has the same metrics, or when
|
||||
// a line's width does not depend on how far down the frame it is set: rectangular cells
|
||||
// without text wrap. Then a paragraph whose characters differ in line metrics (type size,
|
||||
// font, leading, vertical scale, an inline graphic taller than the text) is composed too. In
|
||||
// other shapes, or with text wrap, a taller line can move the lines below it to where the
|
||||
// frame is narrower, so such a paragraph is broken line by line.
|
||||
let plain = pen.regions.is_some_and(|r| r.iter().all(|r| (r.rect || r.polys.is_empty()) && r.wraps.is_empty()));
|
||||
if !plain && sg.iter().any(|g| Metrics::of(g) != m) {
|
||||
return None;
|
||||
}
|
||||
// without text wrap. In other shapes, or with text wrap, a paragraph whose characters differ
|
||||
// in line metrics (type size, font, leading, vertical scale, an inline graphic taller than
|
||||
// the text) can have a taller line move the lines below it to where the frame is narrower:
|
||||
// each line the composer tries is then placed after the lines it follows (`shaped::Shaped`).
|
||||
let shaped = !constant_width(pen.regions) && sg.iter().any(|g| Metrics::of(g) != m);
|
||||
let total: f64 = sg.iter().map(|g| g.adv).sum();
|
||||
// The same rule as the line loop below: an opening bracket starting a wrapped line gives up
|
||||
// the space before it.
|
||||
@@ -86,7 +89,7 @@ fn compose_para(
|
||||
let mut acc = 0.0;
|
||||
// A line's width and placement depend on the sum of its indents alone, which the mirrored
|
||||
// indents of a right-to-left list ([`line_indents`]) keep.
|
||||
while widths.len() < sg.len() {
|
||||
while !shaped && widths.len() < sg.len() {
|
||||
let first = widths.is_empty();
|
||||
let ind_l = para.laid_out_left_indent() + if first && !continued { para.first_line_indent } else { 0.0 };
|
||||
// Only the first line's first word is known here. Later lines are placed as the composed
|
||||
@@ -103,7 +106,11 @@ fn compose_para(
|
||||
break;
|
||||
}
|
||||
}
|
||||
let last = *widths.last()?;
|
||||
let last = match widths.last() {
|
||||
Some(&last) => last,
|
||||
None if shaped => 0.0,
|
||||
None => return None,
|
||||
};
|
||||
let width = |k: usize| widths.get(k).copied().unwrap_or(last);
|
||||
// Lines from `uniform_from` on are interchangeable (same width).
|
||||
let uniform_from = widths.iter().rposition(|&w| (w - last).abs() > EPS).map_or(0, |k| k + 1);
|
||||
@@ -119,6 +126,14 @@ fn compose_para(
|
||||
let (strict, loose) = (1.0, f64::INFINITY);
|
||||
// A line's last character is set narrower, as the line loop sets it.
|
||||
let end_credit = |end: usize| end.checked_sub(1).and_then(|k| line_end.get(k)).copied().unwrap_or(0.0);
|
||||
if shaped {
|
||||
// Both passes share the placements tried and one search budget.
|
||||
let mirror = mirrors_indents(para, rtl, cx.vertical);
|
||||
let mut measure = super::shaped::Shaped::new(sg, line_end, para, &start_credit, continued, mirror, pen);
|
||||
let mut pass = |p: &Params| crate::composer::compose_with(sg, &mut measure, &start_credit, &end_credit, &cands, flex, p);
|
||||
let lines = pass(¶ms(strict));
|
||||
return lines.or_else(|| pass(¶ms(loose)));
|
||||
}
|
||||
let pass = |p: &Params| compose(sg, &width, &start_credit, &end_credit, &cands, flex, p);
|
||||
pass(¶ms(strict)).or_else(|| pass(¶ms(loose)))
|
||||
}
|
||||
@@ -142,7 +157,7 @@ fn mirrors_indents(para: &ParaStyle, rtl: bool, vertical: bool) -> bool {
|
||||
/// the right and the right indent from the left: the bullet of a right-to-left list hangs at the
|
||||
/// right, and the lines it wraps to line up with the text after the bullet. A list level past the
|
||||
/// first adds to the left indent ([`ParaStyle::laid_out_left_indent`]), mirrored with it.
|
||||
fn line_indents(para: &ParaStyle, first: bool, mirror: bool) -> (f64, f64) {
|
||||
pub(super) fn line_indents(para: &ParaStyle, first: bool, mirror: bool) -> (f64, f64) {
|
||||
let start = para.laid_out_left_indent() + if first { para.first_line_indent } else { 0.0 };
|
||||
if mirror { (para.right_indent, start) } else { (start, para.right_indent) }
|
||||
}
|
||||
@@ -162,6 +177,7 @@ pub(super) fn flow(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject, reg
|
||||
next_top: None,
|
||||
no_room_for: f64::INFINITY,
|
||||
steps_left: std::rc::Rc::new(std::cell::Cell::new(super::breaking::MAX_TOTAL_STEPS)),
|
||||
search: Default::default(),
|
||||
};
|
||||
let markers = list_markers(t, paras);
|
||||
for (pi, pr) in paras.iter().enumerate() {
|
||||
@@ -392,6 +408,12 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
|
||||
}
|
||||
// The line's first word, as narrow as the line sets it at both ends.
|
||||
let word = word_width(sg, *i, line_end, para.kinsoku);
|
||||
// A composed line in a frame whose lines are not all as wide is placed at its own tallest
|
||||
// metrics, as the composer placed it (`shaped::Shaped`): its room is the room across its height.
|
||||
let est = match composed.as_ref().and_then(|lines| lines.get(*para_line)) {
|
||||
Some(&(end, _)) if end > *i && !constant_width(pen.regions) => sg.get(*i..end).and_then(Metrics::max).unwrap_or(est),
|
||||
_ => est,
|
||||
};
|
||||
// Place, break, then settle the baseline on the line's real metrics (moving on to the
|
||||
// next row/column if it no longer fits).
|
||||
loop {
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
//! Every-line composition where a line's width depends on the lines above it: area type in a
|
||||
//! shape other than a rectangle, or with text wrap, whose characters differ in line metrics (type
|
||||
//! size, font, leading, vertical scale, an inline graphic taller than the text). A taller line
|
||||
//! moves the lines below it down, to where the frame may be narrower or a wrap object splits the
|
||||
//! line. Each line the composer tries is placed from where the lines above it left the pen, at its
|
||||
//! own tallest metrics, as the line loop in [`super::flow`] places a composed line: the span it
|
||||
//! gets is the room across its whole height.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::breaking::{Metrics, Pen, word_width};
|
||||
use super::flow::line_indents;
|
||||
use super::{ParaStyle, SGlyph};
|
||||
use crate::composer::{Exhausted, Measure};
|
||||
|
||||
/// The most lines the composer tries to place for one paragraph before it stops and the paragraph
|
||||
/// is broken line by line.
|
||||
const MAX_PROBES: usize = 1_000_000;
|
||||
|
||||
/// The most baseline steps placing those lines takes in all (see [`super::breaking::MAX_TOTAL_STEPS`]).
|
||||
const MAX_STEPS: usize = 2_000_000;
|
||||
|
||||
/// The most lines the composer tries to place for all the paragraphs of one frame's layout.
|
||||
const MAX_LAYOUT_PROBES: usize = 2 * MAX_PROBES;
|
||||
|
||||
/// The most baseline steps placing them takes over all the paragraphs of one frame's layout.
|
||||
const MAX_LAYOUT_STEPS: usize = 2 * MAX_STEPS;
|
||||
|
||||
/// What is left of the composer's search over one frame's layout: the lines it may still try to
|
||||
/// place and the baseline steps placing them may still take. Every paragraph's search takes what
|
||||
/// it spends from it, and stops when it runs out, or at its own limits of [`MAX_PROBES`] and
|
||||
/// [`MAX_STEPS`]. It is separate from the layout's own steps ([`Pen::steps_left`]), which the
|
||||
/// search leaves to the line loop.
|
||||
pub(super) struct Budget {
|
||||
probes: Cell<usize>,
|
||||
steps: Cell<usize>,
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
/// A budget of `probes` lines to try and `steps` baseline steps.
|
||||
pub(super) fn new(probes: usize, steps: usize) -> Self {
|
||||
Self { probes: Cell::new(probes), steps: Cell::new(steps) }
|
||||
}
|
||||
|
||||
/// The lines left to try and the baseline steps left.
|
||||
#[cfg(test)]
|
||||
pub(super) fn left(&self) -> (usize, usize) {
|
||||
(self.probes.get(), self.steps.get())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Budget {
|
||||
fn default() -> Self {
|
||||
Self::new(MAX_LAYOUT_PROBES, MAX_LAYOUT_STEPS)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a line starts: glyph `pos`, with the pen where the lines above it left it.
|
||||
struct Start<'r> {
|
||||
pos: usize,
|
||||
/// The paragraph's first line (it takes the first-line indent).
|
||||
first: bool,
|
||||
pen: Pen<'r>,
|
||||
/// The line placed at each of the metrics it was tried with: its width and the pen after it,
|
||||
/// or `None` when the frame has no room for it.
|
||||
placed: Vec<(Metrics, Option<(f64, Pen<'r>)>)>,
|
||||
/// The metrics of glyphs `pos..to`, measured so far.
|
||||
to: usize,
|
||||
m: Option<Metrics>,
|
||||
}
|
||||
|
||||
/// What a line's placement depends on: its first glyph, whether it is the paragraph's first line,
|
||||
/// and the pen's cell, baselines, pending space, narrowest word without room and further spans.
|
||||
type Key = (usize, bool, usize, Option<u64>, Option<u64>, u64, u64, Vec<[u64; 3]>);
|
||||
|
||||
fn key(pos: usize, first: bool, pen: &Pen<'_>) -> Key {
|
||||
(
|
||||
pos,
|
||||
first,
|
||||
pen.ri,
|
||||
pen.prev.map(f64::to_bits),
|
||||
pen.next_top.map(f64::to_bits),
|
||||
pen.pending.to_bits(),
|
||||
pen.no_room_for.to_bits(),
|
||||
pen.queued.iter().map(|&(b, x0, x1)| [b.to_bits(), x0.to_bits(), x1.to_bits()]).collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// What placing a line reads from the paragraph.
|
||||
struct Para<'a> {
|
||||
sg: &'a [SGlyph],
|
||||
/// How much narrower a line ending with each glyph is set (`ParagraphData::line_end`).
|
||||
line_end: &'a [f64],
|
||||
para: &'a ParaStyle,
|
||||
/// The width a line starting with each glyph gives back (Mojikumi's flush opening bracket).
|
||||
start_credit: &'a dyn Fn(usize) -> f64,
|
||||
mirror: bool,
|
||||
/// The baseline steps left to the search.
|
||||
steps: Rc<Cell<usize>>,
|
||||
}
|
||||
|
||||
/// The measures of a paragraph's lines in a frame where they depend on the lines above.
|
||||
pub(super) struct Shaped<'a, 'r> {
|
||||
para: Para<'a>,
|
||||
continued: bool,
|
||||
pen: Pen<'r>,
|
||||
starts: Vec<Start<'r>>,
|
||||
known: HashMap<Key, usize>,
|
||||
/// The lines tried so far, and the most this search may try.
|
||||
probes: usize,
|
||||
max_probes: usize,
|
||||
/// The baseline steps this search started with.
|
||||
max_steps: usize,
|
||||
/// The layout's budget, which takes what the search spent when it ends.
|
||||
budget: Rc<Budget>,
|
||||
/// The tallest metrics of glyphs `k..` for each `k`, `None` past the last glyph.
|
||||
rest: Vec<Option<Metrics>>,
|
||||
}
|
||||
|
||||
impl<'a, 'r> Shaped<'a, 'r> {
|
||||
/// The measures of the lines of glyphs `sg` of paragraph `para`, set from `pen`. `line_end`
|
||||
/// and `start_credit` are how much narrower a line ending with each glyph is set and how much
|
||||
/// a line starting with it gives back; `continued`: the paragraph's first line is in the
|
||||
/// frame before; `mirror`: its indents are mirrored. The search places its lines with a copy
|
||||
/// of `pen` and takes its baseline steps from the layout's search budget ([`Pen::search`]),
|
||||
/// so the frame's layout keeps its own steps.
|
||||
pub(super) fn new(
|
||||
sg: &'a [SGlyph],
|
||||
line_end: &'a [f64],
|
||||
para: &'a ParaStyle,
|
||||
start_credit: &'a dyn Fn(usize) -> f64,
|
||||
continued: bool,
|
||||
mirror: bool,
|
||||
pen: &Pen<'r>,
|
||||
) -> Self {
|
||||
let mut pen = pen.clone();
|
||||
let budget = Rc::clone(&pen.search);
|
||||
let max_steps = budget.steps.get().min(pen.steps_left.get()).min(MAX_STEPS);
|
||||
let steps = Rc::new(Cell::new(max_steps));
|
||||
pen.steps_left = Rc::clone(&steps);
|
||||
let mut rest = vec![None; sg.len() + 1];
|
||||
for (k, g) in sg.iter().enumerate().rev() {
|
||||
let m = Metrics::of(g);
|
||||
rest[k] = Some(rest[k + 1].map_or(m, |r: Metrics| r.union(m)));
|
||||
}
|
||||
Self {
|
||||
para: Para { sg, line_end, para, start_credit, mirror, steps },
|
||||
continued,
|
||||
pen,
|
||||
starts: vec![],
|
||||
known: HashMap::new(),
|
||||
probes: 0,
|
||||
max_probes: budget.probes.get().min(MAX_PROBES),
|
||||
max_steps,
|
||||
budget,
|
||||
rest,
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of a line at glyph `pos` with `pen`: an existing one when its placement is the same.
|
||||
fn start(&mut self, pos: usize, first: bool, pen: Pen<'r>) -> usize {
|
||||
let k = key(pos, first, &pen);
|
||||
if let Some(&id) = self.known.get(&k) {
|
||||
return id;
|
||||
}
|
||||
self.starts.push(Start { pos, first, pen, placed: vec![], to: pos, m: None });
|
||||
let id = self.starts.len() - 1;
|
||||
self.known.insert(k, id);
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
impl Measure for Shaped<'_, '_> {
|
||||
type State = usize;
|
||||
|
||||
fn first(&mut self) -> usize {
|
||||
let pen = self.pen.clone();
|
||||
self.start(0, !self.continued, pen)
|
||||
}
|
||||
|
||||
fn line(&mut self, &id: &usize, pos: usize, end: usize) -> Result<Option<(f64, usize)>, Exhausted> {
|
||||
if self.probes >= self.max_probes {
|
||||
return Err(Exhausted);
|
||||
}
|
||||
self.probes += 1;
|
||||
let Some(start) = self.starts.get_mut(id) else { return Ok(None) };
|
||||
let Some((width, pen)) = line(&self.para, start, pos, end)? else { return Ok(None) };
|
||||
Ok(Some((width, self.start(end, false, pen))))
|
||||
}
|
||||
|
||||
/// A longer line is placed as this one is, and gets the same room, unless a glyph after it
|
||||
/// changes the line's tallest metrics.
|
||||
fn may_widen(&mut self, &id: &usize, pos: usize, end: usize) -> bool {
|
||||
let Some(start) = self.starts.get(id) else { return false };
|
||||
let m = if start.pos == pos && start.to == end { start.m } else { self.para.sg.get(pos..end).and_then(Metrics::max) };
|
||||
match (m, self.rest.get(end).copied().flatten()) {
|
||||
(Some(m), Some(rest)) => m.union(rest) != m,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The search's lines tried and baseline steps spent come off the layout's budget, so the
|
||||
/// paragraphs of one frame share it.
|
||||
impl Drop for Shaped<'_, '_> {
|
||||
fn drop(&mut self) {
|
||||
let spent = self.max_steps.saturating_sub(self.para.steps.get());
|
||||
self.budget.steps.set(self.budget.steps.get().saturating_sub(spent));
|
||||
self.budget.probes.set(self.budget.probes.get().saturating_sub(self.probes));
|
||||
}
|
||||
}
|
||||
|
||||
/// The width of the line of glyphs `pos..end` from `start`, and the pen after it; `None` when
|
||||
/// the frame has no room for it.
|
||||
fn line<'r>(p: &Para<'_>, start: &mut Start<'r>, pos: usize, end: usize) -> Result<Option<(f64, Pen<'r>)>, Exhausted> {
|
||||
if start.pos != pos || end <= pos {
|
||||
return Ok(None);
|
||||
}
|
||||
// The line's tallest metrics, measured on from the glyphs already measured.
|
||||
if end < start.to {
|
||||
start.m = p.sg.get(pos..end).and_then(Metrics::max);
|
||||
start.to = end;
|
||||
} else if end > start.to {
|
||||
let more = p.sg.get(start.to..end).and_then(Metrics::max);
|
||||
start.m = match (start.m, more) {
|
||||
(Some(m), Some(more)) => Some(m.union(more)),
|
||||
(m, more) => m.or(more),
|
||||
};
|
||||
start.to = end;
|
||||
}
|
||||
let Some(m) = start.m else { return Ok(None) };
|
||||
if let Some((_, placed)) = start.placed.iter().find(|(at, _)| *at == m) {
|
||||
return Ok(placed.clone());
|
||||
}
|
||||
let placed = place(p, start, m)?;
|
||||
start.placed.push((m, placed.clone()));
|
||||
Ok(placed)
|
||||
}
|
||||
|
||||
/// The line from `start` placed with metrics `m`: its width and the pen after it, as the line loop
|
||||
/// places and settles it; `None` when no frame cell has room for it.
|
||||
fn place<'r>(p: &Para<'_>, start: &Start<'r>, m: Metrics) -> Result<Option<(f64, Pen<'r>)>, Exhausted> {
|
||||
let (ind_l, ind_r) = line_indents(p.para, start.first, p.mirror);
|
||||
let word = word_width(p.sg, start.pos, p.line_end, p.para.kinsoku) - (p.start_credit)(start.pos);
|
||||
let mut pen = start.pen.clone();
|
||||
loop {
|
||||
match pen.place(m, ind_l, ind_r, word) {
|
||||
Some((baseline, x0, x1, _)) if baseline.is_finite() && (x1 - x0).is_finite() => {
|
||||
if baseline + m.desc > pen.bottom() + 0.01 {
|
||||
// A further span of the line above, too low for this line: the next row or column.
|
||||
pen.ri += 1;
|
||||
pen.prev = None;
|
||||
pen.pending = 0.0;
|
||||
pen.queued.clear();
|
||||
continue;
|
||||
}
|
||||
pen.pending = 0.0;
|
||||
pen.settled(baseline, m);
|
||||
// Further spans of this line band share the settled baseline.
|
||||
for queued in &mut pen.queued {
|
||||
queued.0 = baseline;
|
||||
}
|
||||
return Ok(Some((x1 - x0 - ind_l - ind_r, pen)));
|
||||
}
|
||||
Some(_) => return Ok(None),
|
||||
// Out of steps: the frame may still have room further down.
|
||||
None if p.steps.get() == 0 => return Err(Exhausted),
|
||||
None => return Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -533,6 +533,241 @@ fn composition_counts_the_narrower_line_end() {
|
||||
assert_eq!(lines(38.0, &half, &[Breakpoint { end: 4, hyphen: 0.0 }]), Some(vec![(4, false), (7, false)]));
|
||||
}
|
||||
|
||||
/// A line measure for `compose_with`: every line is `width` wide, its state is the glyph it starts
|
||||
/// at, and the search stops once `calls` lines were measured.
|
||||
struct Measured {
|
||||
width: f64,
|
||||
calls: usize,
|
||||
/// A line from a start past this one finds the frame full.
|
||||
full_after: usize,
|
||||
}
|
||||
|
||||
impl crate::composer::Measure for Measured {
|
||||
type State = usize;
|
||||
fn first(&mut self) -> usize {
|
||||
0
|
||||
}
|
||||
fn line(&mut self, &start: &usize, _: usize, end: usize) -> Result<Option<(f64, usize)>, crate::composer::Exhausted> {
|
||||
if self.calls == 0 {
|
||||
return Err(crate::composer::Exhausted);
|
||||
}
|
||||
self.calls -= 1;
|
||||
Ok((start <= self.full_after).then_some((self.width, end)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The every-line composer with a line measure that follows the lines above: it breaks as with
|
||||
/// fixed widths when the widths are the same, finds no composition when the frame is full before
|
||||
/// the paragraph ends, and gives up when the measure's search stops.
|
||||
#[test]
|
||||
fn composition_with_a_measure_from_the_lines_above() {
|
||||
let text = "가나다 라마바";
|
||||
let glyphs = korean(text, false);
|
||||
let cands = candidates(text, &glyphs, None, Kinsoku::Hard);
|
||||
let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 };
|
||||
let with = |calls: usize, full_after: usize| {
|
||||
let mut measure = Measured { width: 50.0, calls, full_after };
|
||||
crate::composer::compose_with(&glyphs, &mut measure, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms)
|
||||
};
|
||||
let fixed = compose(&glyphs, &|_| 50.0, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms);
|
||||
assert_eq!(fixed, Some(vec![(4, false), (7, false)]));
|
||||
assert_eq!(with(usize::MAX, usize::MAX), fixed);
|
||||
assert_eq!(with(usize::MAX, 0), None, "no room for a second line");
|
||||
assert_eq!(with(1, usize::MAX), None, "the search stopped");
|
||||
}
|
||||
|
||||
/// A line measure for `compose_with` whose lines are `narrow` wide, and `wide` wide when they reach
|
||||
/// past glyph `from` (a line made taller there, and set lower in a frame that widens).
|
||||
struct Widening {
|
||||
narrow: f64,
|
||||
wide: f64,
|
||||
from: usize,
|
||||
}
|
||||
|
||||
impl crate::composer::Measure for Widening {
|
||||
type State = usize;
|
||||
fn first(&mut self) -> usize {
|
||||
0
|
||||
}
|
||||
fn line(&mut self, _: &usize, _: usize, end: usize) -> Result<Option<(f64, usize)>, crate::composer::Exhausted> {
|
||||
Ok(Some((if end > self.from { self.wide } else { self.narrow }, end)))
|
||||
}
|
||||
fn may_widen(&mut self, _: &usize, _: usize, end: usize) -> bool {
|
||||
end <= self.from
|
||||
}
|
||||
}
|
||||
|
||||
/// A line too long for its room does not end the composer's search from its start while a longer
|
||||
/// line may get more room: the longer line is tried and set.
|
||||
#[test]
|
||||
fn composition_tries_a_longer_line_that_gets_more_room() {
|
||||
let text = "가나다 라마바";
|
||||
let glyphs = korean(text, false);
|
||||
let cands = candidates(text, &glyphs, None, Kinsoku::Hard);
|
||||
let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 };
|
||||
// "가나다" is 30 wide and does not fit 25; the whole paragraph reaches past glyph 4 and fits 100.
|
||||
let mut measure = Widening { narrow: 25.0, wide: 100.0, from: 4 };
|
||||
let lines = crate::composer::compose_with(&glyphs, &mut measure, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms);
|
||||
assert_eq!(lines, Some(vec![(7, false)]));
|
||||
}
|
||||
|
||||
/// A line measure for `compose_with` whose lines can't be set until they reach past glyph `from`
|
||||
/// (a line made taller there steps down the frame by its own leading, to a band the shorter
|
||||
/// line's steps miss), and are `wide` wide from there.
|
||||
struct Unplaced {
|
||||
wide: f64,
|
||||
from: usize,
|
||||
}
|
||||
|
||||
impl crate::composer::Measure for Unplaced {
|
||||
type State = usize;
|
||||
fn first(&mut self) -> usize {
|
||||
0
|
||||
}
|
||||
fn line(&mut self, _: &usize, _: usize, end: usize) -> Result<Option<(f64, usize)>, crate::composer::Exhausted> {
|
||||
Ok((end > self.from).then_some((self.wide, end)))
|
||||
}
|
||||
fn may_widen(&mut self, _: &usize, _: usize, end: usize) -> bool {
|
||||
end <= self.from
|
||||
}
|
||||
}
|
||||
|
||||
/// A line that can't be set does not end the composer's search from its start while a longer line
|
||||
/// may be placed elsewhere: the longer line is tried and set.
|
||||
#[test]
|
||||
fn composition_tries_a_longer_line_after_one_that_cannot_be_set() {
|
||||
let text = "가나다 라마바";
|
||||
let glyphs = korean(text, false);
|
||||
let cands = candidates(text, &glyphs, None, Kinsoku::Hard);
|
||||
let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 };
|
||||
// "가나다" finds no room; the whole paragraph reaches past glyph 4 and fits 100.
|
||||
let mut measure = Unplaced { wide: 100.0, from: 4 };
|
||||
let lines = crate::composer::compose_with(&glyphs, &mut measure, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms);
|
||||
assert_eq!(lines, Some(vec![(7, false)]));
|
||||
}
|
||||
|
||||
/// A further span beside a wrap object goes to the line set in it with the room across that line's
|
||||
/// own height. A line taller than the one before it on the baseline keeps clear of an object the
|
||||
/// shorter line did not reach, and moves down when the span has no room for it.
|
||||
#[test]
|
||||
fn a_further_span_is_measured_across_the_height_of_its_line() {
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
let frame = Rect::new(0.0, 0.0, 400.0, 400.0).to_path(0.1);
|
||||
let wrap = |r: Rect| vectorcraft_doc::WrapShape {
|
||||
path: PathData::from_bezpath(&r.to_path(0.1)),
|
||||
wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false },
|
||||
};
|
||||
let small = breaking::Metrics { asc: 10.0, desc: 3.0, lead: 14.0, cap: 7.0, xh: 5.0, top: 10.0 };
|
||||
let tall = breaking::Metrics { asc: 30.0, desc: 9.0, lead: 42.0, cap: 21.0, xh: 15.0, top: 30.0 };
|
||||
// An object down the middle of the frame splits every line in two, and `above` lies right of
|
||||
// it over y 20 to 40. A small line after a baseline of 50 is set at 64, over y 54 to 67, clear
|
||||
// of `above`; a tall line in the span right of it on that baseline covers y 34 to 73.
|
||||
// The tall line starts with a word `word` wide.
|
||||
let set = |above: Rect, word: f64| {
|
||||
let regions = region::Region::cells(&frame, &LayoutOptions::default(), &[wrap(Rect::new(180.0, 0.0, 220.0, 400.0)), wrap(above)]);
|
||||
let mut pen = breaking::Pen {
|
||||
regions: Some(®ions),
|
||||
ri: 0,
|
||||
prev: Some(50.0),
|
||||
pending: 0.0,
|
||||
fb: FirstBaseline::Ascent,
|
||||
fb_min: 0.0,
|
||||
queued: vec![],
|
||||
model: LeadingModel::RomanBaseline,
|
||||
next_top: None,
|
||||
no_room_for: f64::INFINITY,
|
||||
steps_left: Rc::new(Cell::new(breaking::MAX_TOTAL_STEPS)),
|
||||
search: Default::default(),
|
||||
};
|
||||
let left = pen.place(small, 0.0, 0.0, 0.0);
|
||||
pen.settled(64.0, small);
|
||||
let right = pen.place(tall, 0.0, 0.0, word);
|
||||
(left, right)
|
||||
};
|
||||
let near = |got: Option<(f64, f64, f64, bool)>, want: (f64, f64, f64, bool)| {
|
||||
got.is_some_and(|g| (g.0 - want.0).abs() < 0.01 && (g.1 - want.1).abs() < 0.01 && (g.2 - want.2).abs() < 0.01 && g.3 == want.3)
|
||||
};
|
||||
// `above` covers the right end of the span: the tall line gets the part left of it.
|
||||
let (left, right) = set(Rect::new(300.0, 20.0, 400.0, 40.0), 0.0);
|
||||
assert!(near(left, (64.0, 0.0, 180.0, false)), "{left:?}");
|
||||
assert!(near(right, (64.0, 220.0, 300.0, true)), "{right:?}");
|
||||
// That part is 80 wide: a tall line that starts with a wider word goes on the next baseline.
|
||||
let (_, right) = set(Rect::new(300.0, 20.0, 400.0, 40.0), 100.0);
|
||||
assert!(near(right, (106.0, 0.0, 180.0, false)), "{right:?}");
|
||||
// `above` covers the whole span: the tall line goes on the next baseline, left of the object.
|
||||
let (left, right) = set(Rect::new(220.0, 20.0, 400.0, 40.0), 0.0);
|
||||
assert!(near(left, (64.0, 0.0, 180.0, false)), "{left:?}");
|
||||
assert!(near(right, (106.0, 0.0, 180.0, false)), "{right:?}");
|
||||
// `above` lies below the tall line: the span is as wide for it as for the small line, and it
|
||||
// takes the span whatever its first word, as a further span always did.
|
||||
let (_, right) = set(Rect::new(300.0, 300.0, 400.0, 320.0), 200.0);
|
||||
assert!(near(right, (64.0, 220.0, 400.0, true)), "{right:?}");
|
||||
}
|
||||
|
||||
/// The every-line composer's searches for the paragraphs of one frame share one budget: each takes
|
||||
/// the lines it tried and the baseline steps it spent from it, the layout's own steps stay as they
|
||||
/// were, and once the budget runs out the next paragraph's search stops (it is broken line by line).
|
||||
#[test]
|
||||
fn shaped_composition_searches_share_the_frame_budget() {
|
||||
use super::shaped::{Budget, Shaped};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
let text = "aa bb cc dd ee ff gg hh ii jj";
|
||||
let mut glyphs = full_width(text);
|
||||
glyphs[3].ascent = 30.0;
|
||||
let cands = candidates(text, &glyphs, None, Kinsoku::Hard);
|
||||
// 60 pt wide down to 40 pt, and 30 pt wide below.
|
||||
let frame = BezPath::from_vec(vec![
|
||||
PathEl::MoveTo((0.0, 0.0).into()),
|
||||
PathEl::LineTo((60.0, 0.0).into()),
|
||||
PathEl::LineTo((60.0, 40.0).into()),
|
||||
PathEl::LineTo((30.0, 40.0).into()),
|
||||
PathEl::LineTo((30.0, 400.0).into()),
|
||||
PathEl::LineTo((0.0, 400.0).into()),
|
||||
PathEl::ClosePath,
|
||||
]);
|
||||
let regions = region::Region::cells(&frame, &LayoutOptions::default(), &[]);
|
||||
let para = ParaStyle::default();
|
||||
let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 };
|
||||
let pen = |search: Rc<Budget>| breaking::Pen {
|
||||
regions: Some(®ions),
|
||||
ri: 0,
|
||||
prev: None,
|
||||
pending: 0.0,
|
||||
fb: FirstBaseline::Ascent,
|
||||
fb_min: 0.0,
|
||||
queued: vec![],
|
||||
model: LeadingModel::default(),
|
||||
next_top: None,
|
||||
no_room_for: f64::INFINITY,
|
||||
steps_left: Rc::new(Cell::new(breaking::MAX_TOTAL_STEPS)),
|
||||
search,
|
||||
};
|
||||
let compose = |pen: &breaking::Pen<'_>| {
|
||||
let mut measure = Shaped::new(&glyphs, &[], ¶, &|_| 0.0, false, false, pen);
|
||||
crate::composer::compose_with(&glyphs, &mut measure, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms)
|
||||
};
|
||||
// One paragraph's search, with room to spare.
|
||||
let one = pen(Rc::new(Budget::default()));
|
||||
let before = one.search.left();
|
||||
let lines = compose(&one);
|
||||
assert!(lines.is_some());
|
||||
let after = one.search.left();
|
||||
let (probes, steps) = (before.0 - after.0, before.1 - after.1);
|
||||
assert!(probes > 0 && steps > 0, "{probes} lines tried, {steps} steps");
|
||||
assert_eq!(one.steps_left.get(), breaking::MAX_TOTAL_STEPS, "the layout's own steps");
|
||||
// A budget of three such searches: three paragraphs are composed, the fourth is not.
|
||||
let three = pen(Rc::new(Budget::new(3 * probes, 3 * steps)));
|
||||
for k in 0..3 {
|
||||
assert_eq!(compose(&three), lines, "paragraph {k}");
|
||||
}
|
||||
assert_eq!(three.search.left(), (0, 0));
|
||||
assert_eq!(compose(&three), None, "the budget ran out");
|
||||
assert_eq!(three.search.left(), (0, 0));
|
||||
assert_eq!(three.steps_left.get(), breaking::MAX_TOTAL_STEPS, "the layout's own steps");
|
||||
}
|
||||
|
||||
/// The glyphs of `text`, each 10 pt wide, with Korean words kept whole unless `anywhere` (Korean
|
||||
/// Line Break Anywhere on).
|
||||
fn korean(text: &str, anywhere: bool) -> Vec<SGlyph> {
|
||||
|
||||
@@ -334,14 +334,14 @@ fn composer_x_mixed_sizes() {
|
||||
assert_eq!(x.line, 0);
|
||||
assert!(l.lines[0].ascent > l.lines[1].ascent + 1.0, "{:?}", l.lines);
|
||||
// A rectangle that wraps around an object, and a frame that isn't a rectangle (a corner cut),
|
||||
// both far below the text, break mixed sizes line by line and still break uniform sizes with
|
||||
// the every-line composer.
|
||||
// both far below the text, break mixed sizes and uniform sizes alike with the every-line
|
||||
// composer.
|
||||
let below = PathData::from_bezpath(&Rect::new(0.0, 180.0, 20.0, 190.0).to_path(0.1));
|
||||
for (x, want) in [(&wide, every), (&big, greedy)] {
|
||||
for x in [&wide, &big] {
|
||||
let mut t = area(runs(x.clone()), Rect::new(0.0, 0.0, w, 200.0));
|
||||
t.wrap = vec![vectorcraft_doc::WrapShape { path: below.clone(), wrap: Default::default() }];
|
||||
t.para.composer = Composer::EveryLine;
|
||||
assert_eq!(line_texts(&t, &layout(db(), &t)), want, "wrap, {}", x.size);
|
||||
assert_eq!(line_texts(&t, &layout(db(), &t)), every, "wrap, {}", x.size);
|
||||
}
|
||||
let cut = kurbo::BezPath::from_vec(vec![
|
||||
kurbo::PathEl::MoveTo((0.0, 0.0).into()),
|
||||
@@ -351,14 +351,176 @@ fn composer_x_mixed_sizes() {
|
||||
kurbo::PathEl::LineTo((0.0, 200.0).into()),
|
||||
kurbo::PathEl::ClosePath,
|
||||
]);
|
||||
for (x, want) in [(&wide, every), (&big, greedy)] {
|
||||
for x in [&wide, &big] {
|
||||
let mut t = area(runs(x.clone()), Rect::ZERO);
|
||||
t.kind = TextKind::Area { frame: PathData::from_bezpath(&cut) };
|
||||
t.para.composer = Composer::EveryLine;
|
||||
assert_eq!(line_texts(&t, &layout(db(), &t)), want, "cut corner, {}", x.size);
|
||||
assert_eq!(line_texts(&t, &layout(db(), &t)), every, "cut corner, {}", x.size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Text with the word `X` set in `x` and the rest in 12 pt.
|
||||
fn with_x(x: CharStyle) -> Vec<TextRun> {
|
||||
let st = sans(12.0);
|
||||
vec![
|
||||
run("Destroy all creatures with toughness ", st.clone()),
|
||||
run("X", x),
|
||||
run(" or less. Then draw a card for each creature destroyed this way.", st),
|
||||
]
|
||||
}
|
||||
|
||||
/// The width the text of [`with_x`] is set in.
|
||||
fn x_width() -> f64 {
|
||||
natural_width("Destroy all creatures with toughness X or", 12.0) + 2.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_x_mixed_sizes_in_a_stepped_frame() {
|
||||
// A frame as wide as the first line down to 40 pt and half as wide below. A 36 pt word makes
|
||||
// the line it is on reach below the step, where the frame is narrow: the every-line composer
|
||||
// breaks the paragraph with each line's measure where its height sets it, not as the
|
||||
// single-line composer does, and every line keeps within its room.
|
||||
let w = x_width();
|
||||
let set = |x: CharStyle, composer: Composer| {
|
||||
let mut t = stepped(w, w * 0.5, 40.0, 300.0);
|
||||
t.runs = with_x(x);
|
||||
t.para.composer = composer;
|
||||
let l = layout(db(), &t);
|
||||
assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{composer:?}: {:?}", l.lines);
|
||||
(line_texts(&t, &l), l)
|
||||
};
|
||||
let (every, l) = set(sans(36.0), Composer::EveryLine);
|
||||
assert_eq!(every, ["Destroy all creatures with toughness", "X or less. Then", "draw a card for each", "creature destroyed", "this way."]);
|
||||
// The 36 pt line reaches below the step and is set at the narrow measure.
|
||||
let tall = &l.lines[1];
|
||||
assert!(tall.ascent > 30.0 && tall.baseline + tall.descent > 40.0 && tall.avail.1 < w * 0.5 + 0.01, "{:?}", l.lines);
|
||||
let (greedy, _) = set(sans(36.0), Composer::SingleLine);
|
||||
assert_ne!(every, greedy);
|
||||
// Uniform sizes keep the breaks they had.
|
||||
let (uniform, _) = set(sans(12.0), Composer::EveryLine);
|
||||
assert_eq!(uniform, ["Destroy all creatures with toughness X or", "less. Then draw a card for each creature", "destroyed this way."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_x_mixed_sizes_around_text_wrap() {
|
||||
// A wrap object across the middle of the frame from 40 pt down splits the lines beside it in
|
||||
// two. The line of the 36 pt word, which starts with a 12 pt word, falls beside it, and the
|
||||
// every-line composer measures each of the two spans across the line's whole height: no
|
||||
// glyph runs into the object.
|
||||
let w = x_width();
|
||||
let object = Rect::new(w * 0.4, 40.0, w * 0.6, 70.0);
|
||||
let set = |composer: Composer| {
|
||||
let mut runs = with_x(sans(36.0));
|
||||
// A no-break space keeps the 36 pt word on the line of the 12 pt word before it.
|
||||
runs[0] = run("Destroy all creatures with toughness\u{a0}", sans(12.0));
|
||||
let mut t = area(runs, Rect::new(0.0, 0.0, w, 300.0));
|
||||
t.wrap = vec![vectorcraft_doc::WrapShape { path: PathData::from_bezpath(&object.to_path(0.1)), wrap: Default::default() }];
|
||||
t.para.composer = composer;
|
||||
let l = layout(db(), &t);
|
||||
(line_texts(&t, &l), l, t)
|
||||
};
|
||||
let (every, l, t) = set(Composer::EveryLine);
|
||||
assert_eq!(
|
||||
every,
|
||||
["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."]
|
||||
);
|
||||
assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{:?}", l.lines);
|
||||
// Two spans share each baseline beside the object.
|
||||
assert_eq!(l.lines[1].baseline, l.lines[2].baseline);
|
||||
assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{:?}", l.lines);
|
||||
let text = t.plain_text();
|
||||
let hits = l.glyphs.iter().filter(|g| {
|
||||
let li = &l.lines[g.line];
|
||||
let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0;
|
||||
across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0
|
||||
});
|
||||
assert_eq!(hits.count(), 0, "{:?}", l.lines);
|
||||
let (greedy, _, _) = set(Composer::SingleLine);
|
||||
assert_ne!(every, greedy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_x_mixed_sizes_in_a_frame_that_widens() {
|
||||
// A frame as wide as "Destroy all" down to 20 pt and as wide as the first line of
|
||||
// `composer_x_mixed_sizes_in_a_stepped_frame` below. The second line is too long for the narrow
|
||||
// part until it takes in the 48 pt word, which sets it lower, where the frame is wide: the
|
||||
// every-line composer tries that longer line and sets it there.
|
||||
let w = x_width();
|
||||
let narrow = natural_width("Destroy all", 12.0) + 2.0;
|
||||
let set = |composer: Composer| {
|
||||
let mut t = stepped(narrow, w, 20.0, 300.0);
|
||||
t.runs = with_x(sans(48.0));
|
||||
t.para.composer = composer;
|
||||
let l = layout(db(), &t);
|
||||
assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{composer:?}: {:?}", l.lines);
|
||||
(line_texts(&t, &l), l)
|
||||
};
|
||||
let (every, l) = set(Composer::EveryLine);
|
||||
assert_eq!(every, ["Destroy all", "creatures with toughness X or less.", "Then draw a card for each creature", "destroyed this way."]);
|
||||
let tall = &l.lines[1];
|
||||
assert!(tall.ascent > 40.0 && tall.baseline - tall.ascent > 20.0 && tall.avail.1 > narrow + 1.0, "{:?}", l.lines);
|
||||
let (greedy, _) = set(Composer::SingleLine);
|
||||
assert_eq!(greedy, ["Destroy all", "creatures", "with toughness X or less. Then draw", "a card for each creature destroyed this", "way."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_x_mixed_sizes_overflow_a_shaped_frame() {
|
||||
// A stepped frame too short for the paragraph: the lines that fit are set, in order, each once
|
||||
// and within its room, and the frame overflows.
|
||||
let w = x_width();
|
||||
let mut t = stepped(w, w * 0.5, 40.0, 75.0);
|
||||
t.runs = with_x(sans(36.0));
|
||||
t.para.composer = Composer::EveryLine;
|
||||
let l = layout(db(), &t);
|
||||
assert!(l.overflow && l.lines.len() >= 2, "{:?}", l.lines);
|
||||
assert_eq!(l.lines[0].start, 0);
|
||||
assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{:?}", l.lines);
|
||||
assert!(past_their_room(&t, &l).is_empty(), "{:?}", l.lines);
|
||||
assert!(l.lines.iter().all(|li| li.baseline + li.descent <= 75.0 + 0.01), "{:?}", l.lines);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_x_mixed_sizes_long_paragraph_in_a_shaped_frame() {
|
||||
// A long paragraph of mixed sizes in a stepped frame is laid out whole, its lines in order and
|
||||
// each within its room, whether the composer's search finishes or stops at its limits.
|
||||
let w = x_width();
|
||||
let mut t = stepped(w, w * 0.5, 40.0, 100_000.0);
|
||||
t.runs = (0..150).flat_map(|_| with_x(sans(36.0))).collect();
|
||||
t.para.composer = Composer::EveryLine;
|
||||
let l = layout(db(), &t);
|
||||
assert!(!l.overflow, "{} lines", l.lines.len());
|
||||
assert_eq!(l.lines.last().map(|li| li.end), Some(t.plain_text().len()));
|
||||
assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start), "lines out of order");
|
||||
assert!(past_their_room(&t, &l).is_empty());
|
||||
}
|
||||
|
||||
/// A frame `w` wide down to `y`, and `narrow` wide below it.
|
||||
fn stepped(w: f64, narrow: f64, y: f64, bottom: f64) -> TextObject {
|
||||
let frame = kurbo::BezPath::from_vec(vec![
|
||||
kurbo::PathEl::MoveTo((0.0, 0.0).into()),
|
||||
kurbo::PathEl::LineTo((w, 0.0).into()),
|
||||
kurbo::PathEl::LineTo((w, y).into()),
|
||||
kurbo::PathEl::LineTo((narrow, y).into()),
|
||||
kurbo::PathEl::LineTo((narrow, bottom).into()),
|
||||
kurbo::PathEl::LineTo((0.0, bottom).into()),
|
||||
kurbo::PathEl::ClosePath,
|
||||
]);
|
||||
let mut t = area(vec![], Rect::ZERO);
|
||||
t.kind = TextKind::Area { frame: PathData::from_bezpath(&frame) };
|
||||
t
|
||||
}
|
||||
|
||||
/// The lines of `l` whose glyphs reach past either end of the room they were set in.
|
||||
fn past_their_room(t: &TextObject, l: &TextLayout) -> Vec<usize> {
|
||||
let text = t.plain_text();
|
||||
let past = |i: usize| {
|
||||
let (a, b) = l.lines[i].avail;
|
||||
let mut glyphs = l.glyphs.iter().filter(|g| g.line == i && !text[g.byte..].starts_with(char::is_whitespace));
|
||||
glyphs.any(|g| g.origin.x < a - 0.01 || g.origin.x + g.advance > b + 0.01)
|
||||
};
|
||||
(0..l.lines.len()).filter(|&i| past(i)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composer_x_mixed_line_metrics() {
|
||||
// In a rectangle the every-line composer also breaks a paragraph whose characters differ in
|
||||
|
||||
@@ -23,16 +23,26 @@ pub fn story(frames: &[&TextObject]) -> Vec<TextRun> {
|
||||
/// the earlier frame's part of the paragraph is empty (its slice ends with a paragraph break).
|
||||
/// An empty frame that was just restyled keeps its style against unedited empty frames after it.
|
||||
pub fn story_paras(frames: &[&TextObject], later_wins: &[bool]) -> Vec<ParaStyle> {
|
||||
story_paras_restyled(frames, later_wins, &[])
|
||||
}
|
||||
|
||||
/// [`story_paras`] that also knows which frames' last paragraph was just restyled
|
||||
/// (`earlier_wins[k]`, read for frames with text). Such a frame's last paragraph keeps its style
|
||||
/// against the unedited first paragraph of the frame after it, and of frames after unedited empty
|
||||
/// frames, even when the frame ends with a paragraph break. When the later frame's first paragraph
|
||||
/// was restyled too (`later_wins`), the later frame's style wins.
|
||||
pub fn story_paras_restyled(frames: &[&TextObject], later_wins: &[bool], earlier_wins: &[bool]) -> Vec<ParaStyle> {
|
||||
let mut out: Vec<ParaStyle> = vec![];
|
||||
let mut prev_empty_tail = true;
|
||||
let mut empty_tail_restyled = false;
|
||||
let mut tail_restyled = false;
|
||||
for (k, f) in frames.iter().enumerate() {
|
||||
let text = f.plain_text();
|
||||
let restyled = later_wins.get(k).copied().unwrap_or(false);
|
||||
let mut styles = f.paragraph_styles().into_iter();
|
||||
if k > 0
|
||||
&& let Some(first) = styles.next()
|
||||
&& (restyled || (prev_empty_tail && !(text.is_empty() && empty_tail_restyled)))
|
||||
&& (restyled || (prev_empty_tail && !tail_restyled && !(text.is_empty() && empty_tail_restyled)))
|
||||
&& let Some(last) = out.last_mut()
|
||||
{
|
||||
*last = first;
|
||||
@@ -43,6 +53,7 @@ pub fn story_paras(frames: &[&TextObject], later_wins: &[bool]) -> Vec<ParaStyle
|
||||
if !text.is_empty() {
|
||||
prev_empty_tail = text.ends_with('\n') || out.is_empty();
|
||||
empty_tail_restyled = false;
|
||||
tail_restyled = earlier_wins.get(k).copied().unwrap_or(false);
|
||||
} else if restyled {
|
||||
empty_tail_restyled = true;
|
||||
}
|
||||
|
||||
@@ -196,6 +196,42 @@ fn a_restyled_empty_frame_keeps_its_style_after_a_paragraph_break() {
|
||||
assert_eq!(tail_style(&[&first, &restyled, &right], &[false, true, true]), Some(Justify::Right));
|
||||
}
|
||||
|
||||
/// A frame whose empty last paragraph (after a final paragraph break) was just restyled keeps that
|
||||
/// style against the unedited first paragraph of the next frame, empty or with text, and across an
|
||||
/// unedited empty frame. A restyled first paragraph in the next frame still wins.
|
||||
#[test]
|
||||
fn restyled_empty_last_paragraph_wins_over_unedited_next_frame() {
|
||||
let style = |j| ParaStyle { justify: j, ..Default::default() };
|
||||
let mut first = frame(0.0);
|
||||
first.runs = vec![TextRun { text: "a\n".into(), style: CharStyle::default(), inline: None }];
|
||||
first.set_paragraph_styles(vec![style(Justify::Left), style(Justify::Center)]);
|
||||
let empty = frame(200.0);
|
||||
let mut with_text = frame(400.0);
|
||||
with_text.runs = vec![TextRun { text: "def".into(), style: CharStyle::default(), inline: None }];
|
||||
let justify = |frames: &[&TextObject], later: &[bool], earlier: &[bool]| {
|
||||
story_paras_restyled(frames, later, earlier).iter().map(|p| p.justify).collect::<Vec<_>>()
|
||||
};
|
||||
use Justify::*;
|
||||
|
||||
assert_eq!(justify(&[&first, &empty], &[false, false], &[true, false]), [Left, Center]);
|
||||
assert_eq!(justify(&[&first, &with_text], &[false, false], &[true, false]), [Left, Center]);
|
||||
assert_eq!(justify(&[&first, &empty, &with_text], &[false, false, false], &[true, false, false]), [Left, Center]);
|
||||
assert_eq!(justify(&[&first, &empty, &empty], &[false, false, false], &[true, false, false]), [Left, Center]);
|
||||
// Without the edit, the next frame gives the paragraph its style, as before.
|
||||
assert_eq!(justify(&[&first, &empty], &[false, false], &[false, false]), [Left, Left]);
|
||||
assert_eq!(story_paras(&[&first, &with_text], &[]).iter().map(|p| p.justify).collect::<Vec<_>>(), [Left, Left]);
|
||||
// A restyled first paragraph in the next frame wins over the restyled tail.
|
||||
let mut right = with_text.clone();
|
||||
right.set_all_paras(style(Right));
|
||||
assert_eq!(justify(&[&first, &right], &[false, true], &[true, true]), [Left, Right]);
|
||||
assert_eq!(justify(&[&first, &empty, &right], &[false, false, true], &[true, false, true]), [Left, Right]);
|
||||
// A middle frame is the later side at one boundary and the earlier side at the next.
|
||||
let mut middle = frame(200.0);
|
||||
middle.runs = vec![TextRun { text: "b\n".into(), style: CharStyle::default(), inline: None }];
|
||||
middle.set_paragraph_styles(vec![style(Right), style(JustifyAll)]);
|
||||
assert_eq!(justify(&[&first, &middle, &with_text], &[false, true, false], &[false, true, false]), [Left, Right, JustifyAll]);
|
||||
}
|
||||
|
||||
/// Numbered list paragraphs count on from one frame to the next: the second frame's first
|
||||
/// whole paragraph takes the next number. A paragraph split between the frames has its number
|
||||
/// in the first frame only, and the paragraph after it takes the next number.
|
||||
|
||||
@@ -242,6 +242,8 @@ impl DimensionTool {
|
||||
/// a link to its path); else where Smart Guides put it (another object's anchor or centre, in
|
||||
/// line with one, or for the second point on a construction guide through the first), its
|
||||
/// guides showing; else on the closest point of the line under the pointer; else `p` itself.
|
||||
/// A point the guides leave where the pointer is (right on a guide line) stays there, and with
|
||||
/// Snap to Pixel or Snap to Grid on a point stays where they place it.
|
||||
fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option<PointRef>) {
|
||||
let leave = self.points.last().map(|(first, _)| crate::guides::Leave::segment(cx, *first, false));
|
||||
let guided = self.snap.hover(cx, p, &[], leave.as_ref());
|
||||
@@ -249,7 +251,7 @@ impl DimensionTool {
|
||||
self.snap.clear();
|
||||
return (point, Some(reference));
|
||||
}
|
||||
if guided.distance(p) > 1e-9 {
|
||||
if guided.distance(p) > 1e-9 || !self.snap.guides().is_empty() || cx.snap_to_pixel || cx.snap_to_grid {
|
||||
return (guided, None);
|
||||
}
|
||||
// Not on an anchor or a guide: snap to the closest point of the line (#2432).
|
||||
@@ -844,6 +846,54 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A point that Smart Guides leave where the pointer already is (the pointer right on a
|
||||
/// construction guide or in line with a target) stays on the guide the overlays show. It
|
||||
/// does not move to the nearest point of a segment within the pick's reach. Off the guides,
|
||||
/// a point near a segment still lands on it.
|
||||
#[test]
|
||||
fn a_point_on_a_guide_stays_on_the_guide() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let click = |t: &mut DimensionTool, x: f64, y: f64| {
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y));
|
||||
};
|
||||
let mut t = DimensionTool::default();
|
||||
// In line with the rectangle's center, 6 units right of its right edge.
|
||||
assert_eq!(t.snap_linear(&c, Point::new(206.0, 150.0)), (Point::new(206.0, 150.0), None));
|
||||
assert!(!t.snap.guides().is_empty());
|
||||
// Off the guides, beside the edge: the closest point of the edge.
|
||||
let (on_edge, reference) = t.snap_linear(&c, Point::new(206.0, 170.5));
|
||||
assert!(on_edge.distance(Point::new(200.0, 170.5)) < 1e-4 && reference.is_none(), "{on_edge:?}");
|
||||
// The first point, above the rectangle, then straight down along the vertical
|
||||
// construction guide through it, past the right edge.
|
||||
click(&mut t, 206.0, 50.0);
|
||||
assert_eq!(t.points, vec![(Point::new(206.0, 50.0), None)]);
|
||||
for y in [150.0, 170.5, 190.0] {
|
||||
assert_eq!(t.snap_linear(&c, Point::new(206.0, y)), (Point::new(206.0, y), None), "on the construction guide at y = {y}");
|
||||
assert!(!t.snap.guides().is_empty());
|
||||
}
|
||||
click(&mut t, 206.0, 170.5);
|
||||
let dim = t.pending.as_ref().expect("both points were picked");
|
||||
assert_eq!((dim.a, dim.b), (Point::new(206.0, 50.0), Point::new(206.0, 170.5)));
|
||||
// The second point, off the edge, is held against the rectangle's anchors.
|
||||
let Some(DimensionSource::Points { free_b: Some(free), .. }) = &dim.source else { panic!("{:?}", dim.source) };
|
||||
assert!(matches!(free, FreePoint::Anchors { .. }), "{free:?}");
|
||||
// A pointer already on a gridline crossing or on a whole pixel stays there too, and one
|
||||
// off the grid lands on the grid, not on the edge.
|
||||
let grid = ToolContext { snap_to_grid: true, ..cx(&d, &s, &p) };
|
||||
let step = grid.grid_step();
|
||||
let on_grid = Point::new((200.0 / step).ceil() * step, (170.0 / step).round() * step);
|
||||
assert!(on_grid.x > 200.0 + 1e-6 && on_grid.x - 200.0 < 8.0, "{on_grid:?} is off the edge, within the pick's reach");
|
||||
assert_eq!(DimensionTool::default().snap_linear(&grid, on_grid), (on_grid, None));
|
||||
let off_grid = on_grid + Vec2::new(-step * 0.3, 0.2);
|
||||
assert_eq!(DimensionTool::default().snap_linear(&grid, off_grid), (on_grid, None));
|
||||
let pixel = ToolContext { snap_to_pixel: true, ..cx(&d, &s, &p) };
|
||||
assert_eq!(DimensionTool::default().snap_linear(&pixel, Point::new(206.0, 170.0)), (Point::new(206.0, 170.0), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placement_press_previews_without_a_prior_move() {
|
||||
let (d, _) = doc_with_rect();
|
||||
|
||||
@@ -23,14 +23,24 @@ pub fn open(app: &mut VectorcraftApp, set: usize, action: usize) -> Result<Value
|
||||
if a.steps.iter().enumerate().all(|(i, _)| a.excluded_steps.contains(&i)) {
|
||||
return Err("the action has no included steps".into());
|
||||
}
|
||||
if crate::panels::actions::has_stop(&a.included_commands()) {
|
||||
return Err("Batch cannot play an action with a stop".into());
|
||||
}
|
||||
refuse_steps(&a.included_commands())?;
|
||||
let name = a.name.clone();
|
||||
app.ui.dialog = Some(Dialog::new(KIND, initial_fields(set, action, &name)));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Err when the included steps `commands` hold a step that Batch does not play: a stop, or a View
|
||||
/// menu step, which acts on a document window ([`crate::panels::actions::is_ui_step`]).
|
||||
fn refuse_steps(commands: &[Value]) -> Result<(), String> {
|
||||
if crate::panels::actions::has_stop(commands) {
|
||||
return Err("Batch cannot play an action with a stop".into());
|
||||
}
|
||||
if commands.iter().any(crate::panels::actions::is_ui_step) {
|
||||
return Err("Batch cannot play an action with a View menu step".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn initial_fields(set: usize, action: usize, name: &str) -> Value {
|
||||
json!({
|
||||
"set": set,
|
||||
@@ -119,9 +129,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
if commands.is_empty() {
|
||||
return Err("the action has no included steps".into());
|
||||
}
|
||||
if crate::panels::actions::has_stop(&commands) {
|
||||
return Err("Batch cannot play an action with a stop".into());
|
||||
}
|
||||
refuse_steps(&commands)?;
|
||||
let source = d.str("source");
|
||||
if source == "folder" && d.str("folder").trim().is_empty() {
|
||||
return Err("choose a source folder".into());
|
||||
|
||||
@@ -207,43 +207,86 @@ mod tests {
|
||||
assert_eq!((d.str("note"), d.str("command")), ("none".to_string(), "object.ungroup".to_string()), "a failed Find keeps the pick");
|
||||
}
|
||||
|
||||
/// The list holds the menu items that run an engine command without asking for values first,
|
||||
/// outside the application, File, Window and Help menus, and leaves out Undo, Redo, the Pastes,
|
||||
/// Object › Align, Image Trace's Make and Make and Expand, Pattern's Make and Edit Pattern and the
|
||||
/// saved-selection, saved-view and recent-font items.
|
||||
/// The list holds the menu items that run an engine command, and the View menu items that the
|
||||
/// app runs itself, without asking for values first, outside the application, File, Window and
|
||||
/// Help menus, and leaves out Undo, Redo, the Pastes, Image Trace's Make and Make and Expand,
|
||||
/// Pattern's Make and Edit Pattern and the saved-selection, saved-view and recent-font items.
|
||||
#[test]
|
||||
fn the_list_holds_only_menu_items_that_can_be_steps() {
|
||||
let items = menus::insertable_items(true);
|
||||
assert!(items.len() > 100, "only {} items", items.len());
|
||||
for item in &items {
|
||||
assert!(vectorcraft_engine::find_command(item.command).is_some(), "{item:?}");
|
||||
let in_app = menus::plays_in_app(item.command);
|
||||
assert!(vectorcraft_engine::find_command(item.command).is_some() != in_app, "{item:?}");
|
||||
assert!(!in_app || item.path[0] == "View", "{item:?}");
|
||||
assert!(!item.label.ends_with('…'), "{item:?}");
|
||||
assert!(!["VectorCraft", "File", "Window", "Help"].contains(&item.path[0]), "{item:?}");
|
||||
assert!(item.params.is_object(), "{item:?}");
|
||||
}
|
||||
let has = |command: &str| items.iter().any(|i| i.command == command);
|
||||
for command in ["object.group", "object.ungroup", "object.arrange.bringToFront"] {
|
||||
for command in [
|
||||
"object.group",
|
||||
"object.ungroup",
|
||||
"object.arrange.bringToFront",
|
||||
"object.align",
|
||||
"view.outline",
|
||||
"view.zoomIn",
|
||||
"view.fitArtboard",
|
||||
"view.rotate",
|
||||
"view.rulers",
|
||||
"view.snapToGrid",
|
||||
"view.guides.lock",
|
||||
] {
|
||||
assert!(has(command), "{command}");
|
||||
}
|
||||
let aligns = items.iter().filter(|i| i.command == "object.align").count();
|
||||
assert_eq!(aligns, 7, "each Object › Align item, by its params");
|
||||
for command in [
|
||||
"edit.undo",
|
||||
"edit.redo",
|
||||
"edit.paste",
|
||||
"edit.pasteInFront",
|
||||
"object.move",
|
||||
"object.align",
|
||||
"imageTrace.make",
|
||||
"imageTrace.makeAndExpand",
|
||||
"object.pattern.make",
|
||||
"object.pattern.edit",
|
||||
"file.save",
|
||||
"view.zoomIn",
|
||||
"window.panel",
|
||||
"view.goto1",
|
||||
"view.saved.new",
|
||||
"select.recall1",
|
||||
] {
|
||||
assert!(!has(command), "{command}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every View menu item that the app runs itself is listed, apart from the saved-view slots, the
|
||||
/// Perspective Grid presets (`ui.` commands, whose items follow the presets in the preferences)
|
||||
/// and the items that ask for values first.
|
||||
#[test]
|
||||
fn every_view_item_the_app_runs_is_listed() {
|
||||
let items = menus::insertable_items(true);
|
||||
let view = menus::menu_tree_named(true).into_iter().find(|(title, _)| *title == "View").map(|(_, items)| items).unwrap();
|
||||
fn walk(items: &[menus::Item], out: &mut Vec<(&'static str, &'static str)>) {
|
||||
for it in items {
|
||||
match it {
|
||||
menus::Item::Cmd(label, id, _) => out.push((label, id)),
|
||||
menus::Item::Sub(_, children) => walk(children, out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut all = vec![];
|
||||
walk(&view, &mut all);
|
||||
for (label, id) in all {
|
||||
let ui = vectorcraft_engine::find_command(id).is_none() && menus::UI_COMMANDS.iter().any(|c| c.0 == id);
|
||||
if ui && !label.ends_with('…') && !id.starts_with("view.goto") && !id.starts_with("ui.") {
|
||||
assert!(items.iter().any(|i| i.command == id), "{label} ({id})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows show their menu path in the UI language, and Find matches the English path, the shown
|
||||
/// one and the command id.
|
||||
#[test]
|
||||
|
||||
@@ -19,7 +19,13 @@
|
||||
//! show the new colors on the smooth wheel, on a segmented wheel (solid patches of 24 hues by 5
|
||||
//! saturations; its markers move as freely) or as color bars (one per new color, in row order: click
|
||||
//! one to select it for the sliders, drag one to move its row, which changes no color); the dialog
|
||||
//! opens on the smooth wheel. The preset menu sets up a 1, 2 or 3
|
||||
//! opens on the smooth wheel. With art, the Prominent Colors bar under the wheel shows the new
|
||||
//! colors, each part as wide as its row's share of the art's uses, the largest first; dragging the
|
||||
//! edge between two parts moves width between them, and when the drag ends the rows' current
|
||||
//! colors move toward those widths (`recolor.weigh`), and the art previews them. The New Color
|
||||
//! Group menu beside the link button saves the new colors (Save All Colors, in row order) or the
|
||||
//! bar's colors (Save Prominent Colors, in its order) as a color group right away, a step of its
|
||||
//! own. The preset menu sets up a 1, 2 or 3
|
||||
//! colour job or a library. Opened on a colour group (Edit or Apply Color Group), OK also rewrites
|
||||
//! the group with the new colours (renamed by `groupName`); without art only the group changes.
|
||||
//! Opened on colours alone (the Color Guide's Edit or Apply Colors without art), OK saves the new
|
||||
@@ -41,8 +47,9 @@
|
||||
//! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s
|
||||
//! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`;
|
||||
//! unset: `smooth`), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as
|
||||
//! `recolor.pickTheme`'s `picks`; a new list recolors the rows). Changing `colors`, a preserve
|
||||
//! flag or `limitTo` reduces the rows again.
|
||||
//! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as
|
||||
//! `recolor.weigh`'s; a new list moves the rows' current colors toward them). Changing `colors`, a
|
||||
//! preserve flag or `limitTo` reduces the rows again (and drops `weights`).
|
||||
|
||||
use egui::{Rect, Sense, Ui, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
@@ -81,6 +88,9 @@ const WHEEL: f32 = 220.0;
|
||||
/// Height of the Edit tab's color bars area (the wheel with its Brightness slider), and of a bar.
|
||||
const BARS_H: f32 = WHEEL + 31.0;
|
||||
const BAR_H: f32 = 22.0;
|
||||
/// Without the Prominent Colors bar, the Edit tab's gaps above the wheel and above the sliders.
|
||||
const WHEEL_GAP: f32 = 8.0;
|
||||
const SLIDERS_GAP: f32 = 6.0;
|
||||
/// Height of the rows table, and of either tab (so switching tabs doesn't resize the dialog).
|
||||
const TABLE_H: f32 = 182.0;
|
||||
const TAB_H: f32 = 400.0;
|
||||
@@ -151,7 +161,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
"preserveWhite": kept("preserveWhite", true), "preserveBlack": kept("preserveBlack", true),
|
||||
"preserveGrays": kept("preserveGrays", false), "limitTo": limit,
|
||||
"group": group, "groupName": if new_group { Some(NEW_GROUP) } else { group }, "tab": "assign", "rule": Harmony::Complementary.id(), "linked": true,
|
||||
"preview": true, THEME_PICKER: false, THEME_PICKS: [], "__art": art, "__assign": assign, "__newGroup": new_group,
|
||||
"preview": true, THEME_PICKER: false, THEME_PICKS: [], WEIGHTS: null, "__art": art, "__assign": assign, "__newGroup": new_group,
|
||||
});
|
||||
let mut d = Dialog::new(KIND, fields);
|
||||
// Without art the rows are there from the start: limit them now (art's rows snap as they reduce).
|
||||
@@ -214,6 +224,184 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) {
|
||||
d.fields.insert(DONE.into(), sig);
|
||||
// New rows take the colors picked with the Color Theme Picker again.
|
||||
d.fields.remove(THEME_DONE);
|
||||
// Weights given for the old rows don't apply to the new ones.
|
||||
d.fields.remove(WEIGHTS);
|
||||
d.fields.remove(WEIGHED);
|
||||
}
|
||||
|
||||
/// The fields of Prominent Colors: the weights the rows are to take (`recolor.weigh`'s `weights`,
|
||||
/// one per row; a new list moves the rows' current colors), the weights they last took, each row's
|
||||
/// share of the art's uses (`recolor.weigh`'s `shares`) and the rows' current colors, exclusions
|
||||
/// and whether each has a new color, which those were read for; a drag of a part's edge (each part's share of the bar while it lasts); and a request
|
||||
/// from the New Color Group menu (`all` or `prominent`).
|
||||
const WEIGHTS: &str = "weights";
|
||||
const WEIGHED: &str = "__weighed";
|
||||
const SHARES: &str = "__shares";
|
||||
const SHARES_OF: &str = "__sharesOf";
|
||||
const BAR_DRAG: &str = "__barDrag";
|
||||
const SAVE_GROUP: &str = "__saveGroup";
|
||||
/// Height of the Prominent Colors bar, and the smallest share of it a drag leaves a part. With the
|
||||
/// bar the Edit tab leaves out [`WHEEL_GAP`] and [`SLIDERS_GAP`], which keeps the tab's height.
|
||||
const PROMINENT_H: f32 = 10.0;
|
||||
const MIN_PART: f64 = 0.01;
|
||||
/// The ids of the bar's part `n` and of the edge after part `k`, with `n` or `k`.
|
||||
const PROMINENT_PART: &str = "recolor-prominent-part";
|
||||
const PROMINENT_EDGE: &str = "recolor-prominent-edge";
|
||||
|
||||
/// Cancel the preview, so commands read the art's own colors; it runs again afterwards.
|
||||
fn cancel_preview(app: &mut VectorcraftApp, d: &mut Dialog) {
|
||||
if d.fields.remove(super::form::PREVIEWED).is_some() {
|
||||
let _ = app.session.cancel_interaction();
|
||||
}
|
||||
}
|
||||
|
||||
/// With art: when `weights` changed, move the rows' current colors toward them
|
||||
/// (`recolor.weigh`); when the rows' current colors changed, read each row's share of the art's
|
||||
/// uses again.
|
||||
fn sync_weights(app: &mut VectorcraftApp, d: &mut Dialog) {
|
||||
if !d.bool("__art") {
|
||||
return;
|
||||
}
|
||||
if let Some(w) = d.fields.get(WEIGHTS).filter(|w| !w.is_null()).cloned()
|
||||
&& d.fields.get(WEIGHED) != Some(&w)
|
||||
{
|
||||
d.fields.insert(WEIGHED.into(), w.clone());
|
||||
cancel_preview(app, d);
|
||||
match app.session.execute("recolor.weigh", &json!({"map": rows(d), "weights": w})) {
|
||||
Ok(r) => {
|
||||
if let Some(m) = r["map"].as_array() {
|
||||
d.fields.insert("rows".into(), Value::Array(m.clone()));
|
||||
}
|
||||
}
|
||||
Err(e) => app.status(e.to_string()),
|
||||
}
|
||||
}
|
||||
let rs = rows(d);
|
||||
// A row with a new color takes a color before one without, so that changes the shares too.
|
||||
let of = Value::Array(rs.iter().map(|r| json!([r["from"], excluded(r), !r["to"].is_null()])).collect());
|
||||
if d.fields.get(SHARES_OF) == Some(&of) {
|
||||
return;
|
||||
}
|
||||
cancel_preview(app, d);
|
||||
let shares = match app.session.execute("recolor.weigh", &json!({"map": rs})) {
|
||||
Ok(r) => r["shares"].clone(),
|
||||
Err(e) => {
|
||||
app.status(e.to_string());
|
||||
json!([])
|
||||
}
|
||||
};
|
||||
d.fields.insert(SHARES.into(), shares);
|
||||
d.fields.insert(SHARES_OF.into(), of);
|
||||
}
|
||||
|
||||
/// The parts of the Prominent Colors bar: each row that isn't excluded and has a share of the
|
||||
/// art's uses, with that share in percent, the largest share first (on a tie, the first row).
|
||||
fn prominent_parts(d: &Dialog, rows: &[Value]) -> Vec<(usize, f64)> {
|
||||
let shares = d.fields.get(SHARES).and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
let mut parts: Vec<(usize, f64)> = shares
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| Some((i, s.as_f64().filter(|s| *s > 0.0)?)))
|
||||
.filter(|(i, _)| rows.get(*i).is_some_and(|r| !excluded(r)))
|
||||
.collect();
|
||||
parts.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
parts
|
||||
}
|
||||
|
||||
/// The Prominent Colors bar: a part per row of [`prominent_parts`] with the row's new color, as wide
|
||||
/// as its share of the art's uses. A drag of the edge between two parts moves width from one to
|
||||
/// the other (each keeps at least [`MIN_PART`] of the bar); when it ends, the parts' widths become
|
||||
/// the rows' `weights`.
|
||||
fn prominent_bar(ui: &mut Ui, d: &mut Dialog, rows: &[Value]) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let parts = prominent_parts(d, rows);
|
||||
let (bar, resp) = ui.allocate_exact_size(vec2(ui.available_width(), PROMINENT_H), Sense::hover());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, ui.is_enabled(), tl!("Prominent Colors")));
|
||||
if parts.is_empty() {
|
||||
ui.painter().rect_stroke(bar, 1.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
|
||||
return;
|
||||
}
|
||||
let total: f64 = parts.iter().map(|p| p.1).sum();
|
||||
let mut widths: Vec<f64> = match d.fields.get(BAR_DRAG).and_then(Value::as_array) {
|
||||
Some(w) if w.len() == parts.len() => w.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(),
|
||||
_ => parts.iter().map(|p| p.1 / total).collect(),
|
||||
};
|
||||
let w = f64::from(bar.width());
|
||||
let edge = |k: usize, widths: &[f64]| bar.left() + (widths[..=k].iter().sum::<f64>() * w) as f32;
|
||||
let mut left = bar.left();
|
||||
for (n, (i, _)) in parts.iter().enumerate() {
|
||||
let right = if n + 1 == parts.len() { bar.right() } else { edge(n, &widths) };
|
||||
let r = Rect::from_min_max(pos2(left, bar.top()), pos2(right, bar.bottom()));
|
||||
let c = to_color(&rows[*i]).or_else(|| from_colors(&rows[*i]).first().copied()).unwrap_or_default();
|
||||
chip(ui, r, c, false);
|
||||
let share = (widths[n] * 100.0).round();
|
||||
ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()).on_hover_text(format!("{} {}: {share}%", tl!("Color"), i + 1));
|
||||
left = right;
|
||||
}
|
||||
let mut ended = false;
|
||||
for k in 0..parts.len() - 1 {
|
||||
let x = edge(k, &widths);
|
||||
let handle = Rect::from_center_size(pos2(x, bar.center().y), vec2(8.0, PROMINENT_H));
|
||||
let h = ui.interact(handle, egui::Id::unique((PROMINENT_EDGE, k)), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal);
|
||||
if h.dragged() && w > 0.0 {
|
||||
// Each part keeps MIN_PART, or half of the two parts' width when they are narrower.
|
||||
let pair = widths[k] + widths[k + 1];
|
||||
let least = MIN_PART.min(pair / 2.0);
|
||||
let moved = (widths[k] + f64::from(h.drag_delta().x) / w).clamp(least, pair - least);
|
||||
widths[k] = moved;
|
||||
widths[k + 1] = pair - moved;
|
||||
d.fields.insert(BAR_DRAG.into(), json!(widths));
|
||||
}
|
||||
if h.hovered() || h.dragged() {
|
||||
ui.painter().vline(x, bar.y_range(), egui::Stroke::new(2.0, t.accent));
|
||||
}
|
||||
ended |= h.drag_stopped();
|
||||
}
|
||||
if ended && d.fields.remove(BAR_DRAG).is_some() {
|
||||
let mut weights = vec![0.0; rows.len()];
|
||||
for ((i, _), x) in parts.iter().zip(&widths) {
|
||||
weights[*i] = (x * 10_000.0).round() / 100.0;
|
||||
}
|
||||
d.fields.insert(WEIGHTS.into(), json!(weights));
|
||||
}
|
||||
}
|
||||
|
||||
/// The colors a new color group takes from rows `rs`: each row's new color with the Global Adjust,
|
||||
/// snapped to Limit to Library, as `recolor.apply` gives them to a group; a row without a new color
|
||||
/// gives its first current color, which the art keeps.
|
||||
fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator<Item = &'a Value>) -> Vec<Value> {
|
||||
let adjust = global_adjust(adjust_values(d));
|
||||
let limit = d.str("limitTo");
|
||||
let palette = Some(limit).filter(|l| !l.is_empty()).and_then(|l| swatchlib::limit_palette(&app.session, &l));
|
||||
rs.filter_map(|r| match to_color(r) {
|
||||
None => from_colors(r).first().map(key),
|
||||
Some(_) if adjust.is_identity() => Some(r["to"].clone()),
|
||||
Some(c) => {
|
||||
let c = adjust.apply(c);
|
||||
Some(key(&palette.as_ref().map_or(c, |p| p.nearest(c))))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The New Color Group menu's request: save the new colors of the rows that aren't excluded (Save
|
||||
/// All Colors, in row order; a row without one gives its first current color) or of the Prominent Colors bar (Save Prominent Colors, in its order)
|
||||
/// as a new color group, a step of its own (`swatch.newGroup`).
|
||||
fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) {
|
||||
let rs = rows(d);
|
||||
let order: Vec<usize> = match which {
|
||||
"prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(),
|
||||
_ => (0..rs.len()).filter(|&i| !excluded(&rs[i])).collect(),
|
||||
};
|
||||
let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i)));
|
||||
if colors.is_empty() {
|
||||
return;
|
||||
}
|
||||
// The group is added to the document itself, not to the preview, which runs again afterwards.
|
||||
cancel_preview(app, d);
|
||||
if let Err(e) = app.run("swatch.newGroup", json!({"colors": colors, "keepModel": true})) {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields of the Color Theme Picker: whether a click or drag on the canvas picks colors, and
|
||||
@@ -401,6 +589,7 @@ fn apply_params(d: &Dialog) -> Value {
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
sync(app, d);
|
||||
sync_theme(app, d);
|
||||
sync_weights(app, d);
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let picking = d.bool(THEME_PICKER);
|
||||
ui.horizontal(|ui| {
|
||||
@@ -444,6 +633,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
|
||||
}
|
||||
d.fields.insert("rows".into(), Value::Array(rs));
|
||||
}
|
||||
sync_weights(app, d);
|
||||
if let Some(which) = d.fields.remove(SAVE_GROUP) {
|
||||
save_group(app, d, which.as_str().unwrap_or_default());
|
||||
}
|
||||
if d.fields.get("group").is_some_and(Value::is_string) || d.bool("__newGroup") {
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal(|ui| {
|
||||
@@ -479,25 +672,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let mut d = d.clone();
|
||||
sync(app, &mut d);
|
||||
sync_theme(app, &mut d);
|
||||
sync_weights(app, &mut d);
|
||||
if d.bool("__newGroup") {
|
||||
// The new colors with the Global Adjust, snapped to Limit to Library, as `recolor.apply`
|
||||
// gives them to a group.
|
||||
let adjust = global_adjust(adjust_values(&d));
|
||||
let limit = d.str("limitTo");
|
||||
let palette = Some(limit).filter(|l| !l.is_empty()).and_then(|l| swatchlib::limit_palette(&app.session, &l));
|
||||
let colors: Vec<Value> = rows(&d)
|
||||
.into_iter()
|
||||
.filter(|r| !excluded(r))
|
||||
.map(|r| {
|
||||
to_color(&r).filter(|_| !adjust.is_identity()).map_or_else(
|
||||
|| r["to"].clone(),
|
||||
|c| {
|
||||
let c = adjust.apply(c);
|
||||
key(&palette.as_ref().map_or(c, |p| p.nearest(c)))
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let colors = group_colors(app, &d, rows(&d).iter().filter(|r| !excluded(r)));
|
||||
return form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true}));
|
||||
}
|
||||
let r = form::commit_preview(app, CMD, apply_params(&d))?;
|
||||
@@ -1091,13 +1268,30 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
|
||||
if widgets::icon_button(ui, if linked { "link" } else { "link-2-off" }, tip, linked, 24.0).clicked() {
|
||||
d.fields.insert("linked".into(), json!(!linked));
|
||||
}
|
||||
// New Color Group: save the wheel's colors or the Prominent Colors as a color group.
|
||||
let button = widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0);
|
||||
let prominent = d.bool("__art") && !prominent_parts(d, rows).is_empty();
|
||||
let saved = egui::Popup::menu(&button).show(|ui| {
|
||||
if widgets::menu_item_name(ui, tl!("Save All Colors"), rows.iter().any(|r| !excluded(r)), false) {
|
||||
return Some("all");
|
||||
}
|
||||
widgets::menu_item_name(ui, tl!("Save Prominent Colors"), prominent, false).then_some("prominent")
|
||||
});
|
||||
if let Some(which) = saved.and_then(|r| r.inner) {
|
||||
d.fields.insert(SAVE_GROUP.into(), json!(which));
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
// The mode of the color sliders under the wheel: the selected new color in a color
|
||||
// mode, or Global Adjust for all of them.
|
||||
mode_menu(ui, d, &target, true);
|
||||
});
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
// With art the Prominent Colors bar has the room of the two gaps, so the tab is no taller with
|
||||
// it: on a short screen all of the tab but the chips has to fit.
|
||||
let art = d.bool("__art");
|
||||
if !art {
|
||||
ui.add_space(WHEEL_GAP);
|
||||
}
|
||||
let colors: Vec<Color> = active.iter().filter_map(|&i| to_color(&rows[i])).collect();
|
||||
let marked = base.and_then(|b| active.iter().position(|&i| i == b));
|
||||
let display = d.str("display");
|
||||
@@ -1122,6 +1316,10 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
|
||||
_ => w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, marked),
|
||||
});
|
||||
});
|
||||
// Prominent Colors: the art's new colors, each as wide as its share of the art.
|
||||
if art {
|
||||
prominent_bar(ui, d, rows);
|
||||
}
|
||||
if let Some(k) = w.pressed {
|
||||
d.fields.insert("__sel".into(), json!([active[k]]));
|
||||
}
|
||||
@@ -1145,7 +1343,9 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
|
||||
if !ui.input(|i| i.pointer.any_down()) {
|
||||
d.fields.remove(DRAG);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
if !art {
|
||||
ui.add_space(SLIDERS_GAP);
|
||||
}
|
||||
if d.str("sliderMode") == GLOBAL {
|
||||
let sample = base.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25));
|
||||
global_sliders(ui, d, sample);
|
||||
@@ -1625,6 +1825,147 @@ mod tests {
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
}
|
||||
|
||||
const RED: &str = "rgb 255 0 0";
|
||||
const PURPLE: &str = "rgb 128 0 204";
|
||||
const BLUE: &str = "rgb 0 0 255";
|
||||
|
||||
/// Two red squares, a purple one and a blue one, selected; Recolor Artwork open on them on the
|
||||
/// Edit tab with the Exact method and the rows set: the blue to yellow, then the red and purple
|
||||
/// to green (the purple's square id last). One frame drawn.
|
||||
fn prominent_setup(app: &mut VectorcraftApp, ctx: &egui::Context) -> u64 {
|
||||
app.run("file.new", json!({"width": 300, "height": 100})).unwrap();
|
||||
let ids = [square(app, 10.0, "#ff0000"), square(app, 40.0, "#ff0000"), square(app, 70.0, "#8000cc"), square(app, 100.0, "#0000ff")];
|
||||
app.run("select.set", json!({"ids": ids})).unwrap();
|
||||
app.run("ui.recolorDialog", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
d.fields.insert("method".into(), json!(Method::Exact.id()));
|
||||
d.fields.insert("tab".into(), json!("edit"));
|
||||
crate::theme::install_fonts(ctx);
|
||||
frame(app, ctx, 0.0, vec![], 0);
|
||||
let rows = json!([{"from": [BLUE], "to": "rgb 255 255 0"}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}]);
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("rows".into(), rows);
|
||||
frame(app, ctx, 0.01, vec![], 0);
|
||||
ids[2]
|
||||
}
|
||||
|
||||
fn froms(app: &VectorcraftApp) -> Vec<Value> {
|
||||
super::rows(app.ui.dialog.as_ref().unwrap()).iter().map(|r| r["from"].clone()).collect()
|
||||
}
|
||||
|
||||
/// The Prominent Colors bar holds each row's share of the art's uses, the largest first; new
|
||||
/// `weights` move the rows' current colors toward them, the art previews the result, and only
|
||||
/// OK commits it, as one undo step.
|
||||
#[test]
|
||||
fn weights_move_the_rows_colors_and_the_art_previews_them() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
let purple = prominent_setup(&mut app, &ctx);
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(d.fields[SHARES], json!([25.0, 75.0]));
|
||||
assert_eq!(prominent_parts(d, &super::rows(d)), [(1, 75.0), (0, 25.0)], "the largest share first");
|
||||
assert_eq!(fill_hex(&app, purple), "#00ff00", "the art previews the rows");
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert(WEIGHTS.into(), json!([50, 50]));
|
||||
frame(&mut app, &ctx, 0.1, vec![], 0);
|
||||
assert_eq!(froms(&app), [json!([BLUE, PURPLE]), json!([RED])]);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields[SHARES], json!([50.0, 50.0]));
|
||||
assert_eq!(fill_hex(&app, purple), "#ffff00", "the moved color previews its new row's color");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "nothing is committed before OK");
|
||||
// A new count of Colors reduces the rows again and drops the weights.
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("colors".into(), json!(2));
|
||||
frame(&mut app, &ctx, 0.2, vec![], 0);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields.get(WEIGHTS), None);
|
||||
app.ui
|
||||
.dialog
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.fields
|
||||
.insert("rows".into(), json!([{"from": [BLUE, PURPLE], "to": "rgb 255 255 0"}, {"from": [RED], "to": "rgb 0 255 0"}]));
|
||||
crate::dialogs::confirm(&mut app).unwrap();
|
||||
assert_eq!(fill_hex(&app, purple), "#ffff00");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
}
|
||||
|
||||
/// A row that takes a new color takes the colors it shares with other rows, so the bar reads
|
||||
/// the shares again.
|
||||
#[test]
|
||||
fn a_new_color_for_a_row_reads_the_shares_again() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
prominent_setup(&mut app, &ctx);
|
||||
let rows = json!([{"from": [RED, PURPLE], "to": null}, {"from": [RED, BLUE], "to": "rgb 255 255 0"}]);
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("rows".into(), rows);
|
||||
frame(&mut app, &ctx, 0.1, vec![], 0);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields[SHARES], json!([25.0, 75.0]));
|
||||
let rows = json!([{"from": [RED, PURPLE], "to": "rgb 0 255 0"}, {"from": [RED, BLUE], "to": "rgb 255 255 0"}]);
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("rows".into(), rows);
|
||||
frame(&mut app, &ctx, 0.2, vec![], 0);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields[SHARES], json!([75.0, 25.0]));
|
||||
}
|
||||
|
||||
/// Dragging the edge between two parts of the bar to the left gives the right-hand part more
|
||||
/// weight; when the drag ends, the rows' current colors move.
|
||||
#[test]
|
||||
fn dragging_a_prominent_edge_moves_colors_between_rows() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
let purple = prominent_setup(&mut app, &ctx);
|
||||
let edge = |ctx: &egui::Context| ctx.read_response(egui::Id::unique((PROMINENT_EDGE, 0usize))).map(|r| r.rect);
|
||||
let mut last = None;
|
||||
for n in 0..10 {
|
||||
frame(&mut app, &ctx, 0.02 + f64::from(n) * 0.001, vec![], 0);
|
||||
let r = edge(&ctx);
|
||||
if r.is_some() && r == last {
|
||||
break;
|
||||
}
|
||||
last = r;
|
||||
}
|
||||
let at = edge(&ctx).expect("the edge between the two parts").center();
|
||||
let bar = ctx.read_response(egui::Id::unique((PROMINENT_PART, 0usize))).unwrap().rect;
|
||||
// From 75% to 50%: a quarter of the bar to the left.
|
||||
let to = at - vec2((bar.width() / 0.75) * 0.25, 0.0);
|
||||
let button =
|
||||
|pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
frame(&mut app, &ctx, 0.1, vec![egui::Event::PointerMoved(at), button(at, true)], 0);
|
||||
for k in 1..=5 {
|
||||
frame(&mut app, &ctx, 0.1 + f64::from(k) * 0.02, vec![egui::Event::PointerMoved(at + (to - at) * (k as f32 / 5.0))], 0);
|
||||
}
|
||||
assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key(BAR_DRAG), "the drag is under way");
|
||||
assert_eq!(froms(&app)[0], json!([BLUE]), "the rows wait for the drag to end");
|
||||
frame(&mut app, &ctx, 0.3, vec![button(to, false)], 0);
|
||||
frame(&mut app, &ctx, 0.32, vec![], 0);
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
let w = d.fields[WEIGHTS].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect::<Vec<_>>();
|
||||
assert!((w[0] - 50.0).abs() < 2.0 && (w[1] - 50.0).abs() < 2.0, "{w:?}");
|
||||
assert_eq!(froms(&app), [json!([BLUE, PURPLE]), json!([RED])]);
|
||||
assert_eq!(fill_hex(&app, purple), "#ffff00");
|
||||
}
|
||||
|
||||
/// The New Color Group menu's Save All Colors saves the new colors in row order and Save
|
||||
/// Prominent Colors the bar's colors, the largest share first, each as its own step; the
|
||||
/// preview of the recolor runs on.
|
||||
#[test]
|
||||
fn save_all_and_prominent_colors_make_color_groups() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
|
||||
let ctx = egui::Context::default();
|
||||
let purple = prominent_setup(&mut app, &ctx);
|
||||
let groups = |app: &VectorcraftApp| app.session.doc().unwrap().doc.swatch_groups.len();
|
||||
let last = |app: &VectorcraftApp| -> Vec<String> {
|
||||
let doc = &app.session.doc().unwrap().doc;
|
||||
doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect()
|
||||
};
|
||||
let (n, undo) = (groups(&app), app.session.doc().unwrap().history.undo.len());
|
||||
for (which, colors, t) in [("all", ["#ffff00", "#00ff00"], 0.1), ("prominent", ["#00ff00", "#ffff00"], 0.2)] {
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert(SAVE_GROUP.into(), json!(which));
|
||||
frame(&mut app, &ctx, t, vec![], 0);
|
||||
frame(&mut app, &ctx, t + 0.01, vec![], 0);
|
||||
assert_eq!(last(&app), colors, "{which}");
|
||||
assert_eq!(fill_hex(&app, purple), "#00ff00", "{which}: the art still previews the rows");
|
||||
}
|
||||
assert_eq!(groups(&app), n + 2);
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2, "a step for each group");
|
||||
}
|
||||
|
||||
/// One frame with `modifiers` held.
|
||||
fn frame_with(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec<egui::Event>, modifiers: egui::Modifiers) {
|
||||
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
|
||||
|
||||
@@ -296,7 +296,7 @@ pub static LANGUAGES: [LangInfo; 28] = [
|
||||
plural: plural_none,
|
||||
complete_menus: true,
|
||||
catalog: OnceLock::new(),
|
||||
}, // Dutch; every `nl-*` locale (`nl-NL`, `nl-BE`, `nl_NL.UTF-8`…) resolves here.
|
||||
}, // Dutch: the whole interface and the status and error messages; every `nl-*` locale (`nl-NL`, `nl-BE`, `nl_NL.UTF-8`…) resolves here.
|
||||
LangInfo {
|
||||
code: "nl",
|
||||
name: "Nederlands",
|
||||
|
||||
@@ -2834,6 +2834,9 @@ digits Malayalam Малаялам
|
||||
Reset the rows to the artwork's colors Нулиране на редовете към цветовете на илюстрацията
|
||||
Color Theme Picker Избор на цветова тема
|
||||
Click or drag across the art to pick its colors; Shift adds more Щракнете или плъзнете през илюстрацията, за да вземете цветовете ѝ; Shift добавя още
|
||||
Prominent Colors Преобладаващи цветове
|
||||
Save All Colors Запази всички цветове
|
||||
Save Prominent Colors Запази преобладаващите цветове
|
||||
Reset to Default Връщане към стандартните
|
||||
Reset to White, Black Нулиране към бяло, черно
|
||||
Reset with Mesh Нулиране с мрежа
|
||||
@@ -3492,6 +3495,8 @@ digits Malayalam Малаялам
|
||||
Rename Library Group Преименуване на библиотечна група
|
||||
Delete Library Group Изтриване на библиотечна група
|
||||
Move Library Item to Group Преместване на библиотечен елемент в група
|
||||
Rename Library Item Преименуване на елемент от библиотека
|
||||
Add to Character Styles Добавяне към стилове на знаци
|
||||
Library Библиотека
|
||||
Rename Library Преименуване на библиотека
|
||||
Show Library Показване на библиотека
|
||||
@@ -4065,6 +4070,7 @@ axis Both И двете
|
||||
Drag to the window's left or right edge to dock Плъзнете до левия или десния ръб на прозореца за закотвяне
|
||||
Float Tool Group Плаваща група инструменти
|
||||
@msg no library `{id}` няма библиотека `{id}`
|
||||
@msg the library has another item of that kind named `{name}` библиотеката вече има друг елемент от този вид с име `{name}`
|
||||
@msg select some type first първо изберете текст
|
||||
@msg kerning must be a number, "auto", or "optical" kerning трябва да е число, „auto“ или „optical“
|
||||
@msg {_1} has no {_2} style {_1} няма стил {_2}
|
||||
@@ -5996,6 +6002,7 @@ axis Y Axis Y ос
|
||||
@msg message must be text message трябва да бъде текст
|
||||
@msg allowContinue must be true or false allowContinue трябва да бъде true или false
|
||||
@msg Batch cannot play an action with a stop Пакет не може да изпълни действие със спиране
|
||||
@msg Batch cannot play an action with a View menu step Пакет не може да изпълни действие със стъпка от менюто Изглед
|
||||
Insert Menu Item… Вмъкване на елемент от меню…
|
||||
Insert Menu Item Вмъкване на елемент от меню
|
||||
Insert Select Path Вмъкване на избор на път
|
||||
@@ -6745,6 +6752,19 @@ breakText Glyphs Глифи
|
||||
Show where this tool is Показване къде е този инструмент
|
||||
@msg missing `tutorial` (see learn.list) липсва `tutorial` (вижте learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) непознат урок `{id}` (вижте learn.list)
|
||||
View more Вижте повече
|
||||
Finish tutorial Завършване на урока
|
||||
Next Up Следващ
|
||||
You finished the last tutorial in this skill. Завършихте последния урок в това умение.
|
||||
Back to skills Обратно към уменията
|
||||
Open Tutorial Sample Отваряне на примерния файл на урока
|
||||
Finish Tutorial Завършване на урок
|
||||
Next Tutorial Следващ урок
|
||||
Back to Skills Обратно към уменията
|
||||
@msg tutorial `{id}` has no practice sample урокът `{id}` няма примерен файл за упражнение
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) първо отворете примерния файл за упражнение на `{id}` (вижте learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) първо завършете `{id}` (вижте learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` е последният урок в своето умение
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Обновяване на отложените ефекти
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2855,6 +2855,9 @@ digits Malayalam Malajalam
|
||||
Reset the rows to the artwork's colors Vrati redove na boje crteža
|
||||
Color Theme Picker Birač teme boja
|
||||
Click or drag across the art to pick its colors; Shift adds more Kliknite ili prevucite preko crteža da uzmete njegove boje; Shift dodaje još
|
||||
Prominent Colors Istaknute boje
|
||||
Save All Colors Sačuvaj sve boje
|
||||
Save Prominent Colors Sačuvaj istaknute boje
|
||||
Separate colors into rows Razdvoji boje u redove
|
||||
Unlink harmony colors Prekini vezu boja harmonije
|
||||
1 Color Job Posao s 1 bojom
|
||||
@@ -3551,6 +3554,8 @@ theme Appearance Izgled
|
||||
Rename Library Group Preimenuj grupu biblioteke
|
||||
Delete Library Group Izbriši grupu biblioteke
|
||||
Move Library Item to Group Premjesti stavku biblioteke u grupu
|
||||
Rename Library Item Preimenuj stavku biblioteke
|
||||
Add to Character Styles Dodaj u stilove znakova
|
||||
Rename Library Preimenuj biblioteku
|
||||
Show Library Prikaži biblioteku
|
||||
Use Library Item Koristi stavku biblioteke
|
||||
@@ -4417,6 +4422,7 @@ imageTrace Outline Obris
|
||||
@plural {n} step|{n} steps {n} korak|{n} koraka|{n} koraka
|
||||
@plural {n} stroke|{n} strokes {n} potez|{n} poteza|{n} poteza
|
||||
@msg no library `{id}` nema biblioteke `{id}`
|
||||
@msg the library has another item of that kind named `{name}` biblioteka već ima drugu stavku te vrste s imenom `{name}`
|
||||
@msg select some type first prvo odaberite tekst
|
||||
@msg kerning must be a number, "auto", or "optical" kerning mora biti broj, „auto” ili „optical”
|
||||
@msg the selection has no gradient fill odabir nema ispunu gradijentom
|
||||
@@ -6038,6 +6044,7 @@ axis Y Axis Y osa
|
||||
@msg message must be text message mora biti tekst
|
||||
@msg allowContinue must be true or false allowContinue mora biti true ili false
|
||||
@msg Batch cannot play an action with a stop Paketna obrada ne može reprodukovati akciju sa zaustavljanjem
|
||||
@msg Batch cannot play an action with a View menu step Paketna obrada ne može reprodukovati akciju s korakom iz menija Prikaz
|
||||
Insert Menu Item… Umetni stavku menija…
|
||||
Insert Menu Item Umetni stavku menija
|
||||
Insert Select Path Umetni odabir putanje
|
||||
@@ -6799,6 +6806,19 @@ shape Open Otvoren
|
||||
Show where this tool is Prikaži gdje je ovaj alat
|
||||
@msg missing `tutorial` (see learn.list) nedostaje `tutorial` (vidi learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) nepoznat tutorijal `{id}` (vidi learn.list)
|
||||
View more Prikaži više
|
||||
Finish tutorial Završi tutorijal
|
||||
Next Up Sljedeće
|
||||
You finished the last tutorial in this skill. Završili ste posljednji tutorijal u ovoj vještini.
|
||||
Back to skills Nazad na vještine
|
||||
Open Tutorial Sample Otvori uzorak tutorijala
|
||||
Finish Tutorial Završi tutorijal
|
||||
Next Tutorial Sljedeći tutorijal
|
||||
Back to Skills Nazad na vještine
|
||||
@msg tutorial `{id}` has no practice sample tutorijal `{id}` nema uzorak za vježbu
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) prvo otvorite uzorak za vježbu tutorijala `{id}` (vidi learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) prvo završite `{id}` (vidi learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` je posljednji tutorijal u svojoj vještini
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Osvježi odgođene efekte
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2635,6 +2635,8 @@ digits Malayalam Malaiàlam
|
||||
Move in Perspective Mou en perspectiva
|
||||
Move Library Group Mou el grup de la biblioteca
|
||||
Move Library Item to Group Mou l’element de la biblioteca al grup
|
||||
Rename Library Item Canvia el nom de l’element de la biblioteca
|
||||
Add to Character Styles Afegeix als estils de caràcter
|
||||
Move Locked and Hidden Artwork with Artboard Mou la il·lustració bloquejada i oculta amb el tauler
|
||||
Move Mesh Point Mou el punt de malla
|
||||
Move Mesh Points Mou els punts de malla
|
||||
@@ -3616,6 +3618,9 @@ digits Malayalam Malaiàlam
|
||||
Reset the rows to the artwork's colors Restableix les files als colors de l’obra
|
||||
Color Theme Picker Selector de tema de colors
|
||||
Click or drag across the art to pick its colors; Shift adds more Feu clic o arrossegueu sobre l’obra per agafar-ne els colors; Maj n’afegeix més
|
||||
Prominent Colors Colors predominants
|
||||
Save All Colors Desa tots els colors
|
||||
Save Prominent Colors Desa els colors predominants
|
||||
Reset to Default Restableix el valor predeterminat
|
||||
Reset to default Restableix el valor predeterminat
|
||||
Reset to Defaults Restableix els valors predeterminats
|
||||
@@ -4050,6 +4055,7 @@ digits Malayalam Malaiàlam
|
||||
@msg message must be text message ha de ser text
|
||||
@msg allowContinue must be true or false allowContinue ha de ser true o false
|
||||
@msg Batch cannot play an action with a stop Lot no pot reproduir una acció amb una aturada
|
||||
@msg Batch cannot play an action with a View menu step Lot no pot reproduir una acció amb un pas del menú Visualitza
|
||||
Insert Menu Item… Insereix un element de menú…
|
||||
Insert Menu Item Insereix un element de menú
|
||||
Insert Select Path Insereix una selecció de traçat
|
||||
@@ -5731,6 +5737,7 @@ digits Malayalam Malaiàlam
|
||||
@msg no interaction in progress no hi ha cap interacció en curs
|
||||
@msg no key object no hi ha objecte clau
|
||||
@msg no library `{id}` no hi ha la biblioteca `{id}`
|
||||
@msg the library has another item of that kind named `{name}` la biblioteca ja té un altre element d’aquest tipus anomenat `{name}`
|
||||
@msg no library `{key}` (see {list}) no hi ha la biblioteca `{key}` (vegeu {list})
|
||||
@msg No linked files to look for No hi ha fitxers enllaçats per buscar
|
||||
@msg no Live Paint edge near that point no hi ha cap aresta de pintura interactiva a prop d’aquell punt
|
||||
@@ -7322,6 +7329,19 @@ breakText Glyphs Glifs
|
||||
Show where this tool is Mostra on és aquesta eina
|
||||
@msg missing `tutorial` (see learn.list) falta `tutorial` (vegeu learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) tutorial desconegut `{id}` (vegeu learn.list)
|
||||
View more Mostra’n més
|
||||
Finish tutorial Acaba el tutorial
|
||||
Next Up A continuació
|
||||
You finished the last tutorial in this skill. Heu acabat l’últim tutorial d’aquesta habilitat.
|
||||
Back to skills Torna a les habilitats
|
||||
Open Tutorial Sample Obre la mostra del tutorial
|
||||
Finish Tutorial Acaba el tutorial
|
||||
Next Tutorial Tutorial següent
|
||||
Back to Skills Torna a les habilitats
|
||||
@msg tutorial `{id}` has no practice sample el tutorial `{id}` no té cap mostra de pràctica
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) obriu primer la mostra de pràctica de `{id}` (vegeu learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) acabeu primer `{id}` (vegeu learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` és l’últim tutorial de la seva habilitat
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Actualitza els efectes ajornats
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2891,6 +2891,9 @@ digits Malayalam Malajálamské
|
||||
Reset the rows to the artwork's colors Obnovit řádky na barvy kresby
|
||||
Color Theme Picker Výběr barevného motivu
|
||||
Click or drag across the art to pick its colors; Shift adds more Klepnutím nebo tažením přes kresbu převezmete její barvy; Shift přidá další
|
||||
Prominent Colors Převládající barvy
|
||||
Save All Colors Uložit všechny barvy
|
||||
Save Prominent Colors Uložit převládající barvy
|
||||
Separate colors into rows Rozdělit barvy do řádků
|
||||
Unlink harmony colors Zrušit propojení barev harmonie
|
||||
1 Color Job Zakázka s 1 barvou
|
||||
@@ -3605,6 +3608,8 @@ theme Appearance Motiv
|
||||
Rename Library Group Přejmenovat skupinu knihovny
|
||||
Delete Library Group Odstranit skupinu knihovny
|
||||
Move Library Item to Group Přesunout položku knihovny do skupiny
|
||||
Rename Library Item Přejmenovat položku knihovny
|
||||
Add to Character Styles Přidat do stylů znaků
|
||||
Rename Library Přejmenovat knihovnu
|
||||
Show Library Zobrazit knihovnu
|
||||
Use Library Item Použít položku knihovny
|
||||
@@ -4478,6 +4483,7 @@ imageTrace Outline Obrys
|
||||
|
||||
# Status and error messages
|
||||
@msg no library `{id}` knihovna `{id}` neexistuje
|
||||
@msg the library has another item of that kind named `{name}` knihovna už má jinou položku tohoto druhu s názvem `{name}`
|
||||
@msg select some type first nejprve vyberte text
|
||||
@msg kerning must be a number, "auto", or "optical" kerning musí být číslo, „auto“ nebo „optical“
|
||||
@msg the selection has no gradient fill výběr nemá přechodovou výplň
|
||||
@@ -6531,6 +6537,7 @@ axis Y Axis osa Y
|
||||
@msg message must be text message musí být text
|
||||
@msg allowContinue must be true or false allowContinue musí být true nebo false
|
||||
@msg Batch cannot play an action with a stop Dávka nemůže přehrát akci se zastavením
|
||||
@msg Batch cannot play an action with a View menu step Dávka nemůže přehrát akci s krokem z nabídky Zobrazení
|
||||
Insert Menu Item… Vložit položku nabídky…
|
||||
Insert Menu Item Vložit položku nabídky
|
||||
Insert Select Path Vložit výběr cesty
|
||||
@@ -7341,6 +7348,19 @@ breakText Glyphs Glyfy
|
||||
Show where this tool is Zobrazit, kde je tento nástroj
|
||||
@msg missing `tutorial` (see learn.list) chybí `tutorial` (viz learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) neznámý výukový kurz `{id}` (viz learn.list)
|
||||
View more Zobrazit více
|
||||
Finish tutorial Dokončit výukový kurz
|
||||
Next Up Další
|
||||
You finished the last tutorial in this skill. Dokončili jste poslední výukový kurz této dovednosti.
|
||||
Back to skills Zpět na dovednosti
|
||||
Open Tutorial Sample Otevřít ukázku výukového kurzu
|
||||
Finish Tutorial Dokončit výukový kurz
|
||||
Next Tutorial Další výukový kurz
|
||||
Back to Skills Zpět na dovednosti
|
||||
@msg tutorial `{id}` has no practice sample výukový kurz `{id}` nemá cvičnou ukázku
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) nejprve otevřete cvičnou ukázku kurzu `{id}` (viz learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) nejprve dokončete `{id}` (viz learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` je poslední výukový kurz své dovednosti
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Obnovit odložené efekty
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2675,6 +2675,9 @@ digits Malayalam Malayalam
|
||||
Reset the rows to the artwork's colors Nulstil rækkerne til grafikkens farver
|
||||
Color Theme Picker Farvetemavælger
|
||||
Click or drag across the art to pick its colors; Shift adds more Klik eller træk hen over grafikken for at hente dens farver; Skift tilføjer flere
|
||||
Prominent Colors Fremtrædende farver
|
||||
Save All Colors Gem alle farver
|
||||
Save Prominent Colors Gem fremtrædende farver
|
||||
Separate colors into rows Opdel farver i rækker
|
||||
Unlink harmony colors Fjern sammenkædning af harmonifarver
|
||||
1 Color Job 1-farvejob
|
||||
@@ -3338,6 +3341,8 @@ theme Appearance Udseende
|
||||
Rename Library Group Omdøb biblioteksgruppe
|
||||
Delete Library Group Slet biblioteksgruppe
|
||||
Move Library Item to Group Flyt bibliotekselement til gruppe
|
||||
Rename Library Item Omdøb bibliotekselement
|
||||
Add to Character Styles Føj til tegnstile
|
||||
Rename Library Omdøb bibliotek
|
||||
Show Library Vis bibliotek
|
||||
Use Library Item Brug bibliotekselement
|
||||
@@ -4184,6 +4189,7 @@ imageTrace Outline Kontur
|
||||
@plural {n} step|{n} steps {n} trin|{n} trin
|
||||
@plural {n} stroke|{n} strokes {n} kontur|{n} konturer
|
||||
@msg no library `{id}` intet bibliotek `{id}`
|
||||
@msg the library has another item of that kind named `{name}` biblioteket har allerede et andet element af den type med navnet `{name}`
|
||||
@msg select some type first markér først noget tekst
|
||||
@msg kerning must be a number, "auto", or "optical" kerning skal være et tal, „auto“ eller „optical“
|
||||
@msg {_1} has no {_2} style {_1} har ingen {_2}-stil
|
||||
@@ -6013,6 +6019,7 @@ axis Y Axis Y-akse
|
||||
@msg message must be text message skal være tekst
|
||||
@msg allowContinue must be true or false allowContinue skal være true eller false
|
||||
@msg Batch cannot play an action with a stop Batch kan ikke afspille en handling med et stop
|
||||
@msg Batch cannot play an action with a View menu step Batch kan ikke afspille en handling med et trin fra menuen Vis
|
||||
Insert Menu Item… Indsæt menupunkt…
|
||||
Insert Menu Item Indsæt menupunkt
|
||||
Insert Select Path Indsæt kurvemarkering
|
||||
@@ -6761,6 +6768,19 @@ breakText Glyphs Glyffer
|
||||
Show where this tool is Vis, hvor dette værktøj er
|
||||
@msg missing `tutorial` (see learn.list) `tutorial` mangler (se learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) ukendt vejledning `{id}` (se learn.list)
|
||||
View more Vis mere
|
||||
Finish tutorial Afslut vejledning
|
||||
Next Up Næste
|
||||
You finished the last tutorial in this skill. Du har afsluttet den sidste vejledning i denne færdighed.
|
||||
Back to skills Tilbage til færdigheder
|
||||
Open Tutorial Sample Åbn eksempel til vejledning
|
||||
Finish Tutorial Afslut vejledning
|
||||
Next Tutorial Næste vejledning
|
||||
Back to Skills Tilbage til færdigheder
|
||||
@msg tutorial `{id}` has no practice sample vejledningen `{id}` har intet øvelseseksempel
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) åbn først øvelseseksemplet til `{id}` (se learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) afslut først `{id}` (se learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` er den sidste vejledning i sin færdighed
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Opdatér udskudte effekter
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2880,6 +2880,9 @@ digits Malayalam Malayalam
|
||||
Reset the rows to the artwork's colors Zeilen auf die Farben der Grafik zurücksetzen
|
||||
Color Theme Picker Farbthema-Auswahl
|
||||
Click or drag across the art to pick its colors; Shift adds more Klicken oder ziehen Sie über die Grafik, um ihre Farben aufzunehmen; Umschalt fügt weitere hinzu
|
||||
Prominent Colors Hervorstechende Farben
|
||||
Save All Colors Alle Farben speichern
|
||||
Save Prominent Colors Hervorstechende Farben speichern
|
||||
Reset to Default Auf Standard zurücksetzen
|
||||
Reset to White, Black Auf Weiß, Schwarz zurücksetzen
|
||||
Reset with Mesh Mit Gitter zurücksetzen
|
||||
@@ -4092,6 +4095,7 @@ theme Appearance Erscheinungsbild
|
||||
# (`untranslated_report` lists any that are missing). Command ids, parameter
|
||||
# names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are.
|
||||
@msg no library `{id}` keine Bibliothek `{id}`
|
||||
@msg the library has another item of that kind named `{name}` die Bibliothek hat bereits ein anderes Element dieser Art namens `{name}`
|
||||
@msg select some type first wählen Sie zuerst Text aus
|
||||
@msg kerning must be a number, "auto", or "optical" kerning muss eine Zahl, „auto“ oder „optical“ sein
|
||||
@msg the selection has no gradient fill die Auswahl hat keinen Flächenverlauf
|
||||
@@ -5125,6 +5129,8 @@ theme Appearance Erscheinungsbild
|
||||
Rename Library Group Bibliotheksgruppe umbenennen
|
||||
Delete Library Group Bibliotheksgruppe löschen
|
||||
Move Library Item to Group Bibliothekselement in Gruppe verschieben
|
||||
Rename Library Item Bibliothekselement umbenennen
|
||||
Add to Character Styles Zu Zeichenformaten hinzufügen
|
||||
Import Library Bibliothek importieren
|
||||
Export Library Bibliothek exportieren
|
||||
New Group Neue Gruppe
|
||||
@@ -6122,6 +6128,7 @@ axis Y Axis Y-Achse
|
||||
@msg message must be text message muss Text sein
|
||||
@msg allowContinue must be true or false allowContinue muss true oder false sein
|
||||
@msg Batch cannot play an action with a stop Die Stapelverarbeitung kann keine Aktion mit einem Stopp abspielen
|
||||
@msg Batch cannot play an action with a View menu step Die Stapelverarbeitung kann keine Aktion mit einem Schritt aus dem Menü Ansicht abspielen
|
||||
Insert Menu Item… Menübefehl einfügen…
|
||||
Insert Menu Item Menübefehl einfügen
|
||||
Insert Select Path Pfadauswahl einfügen
|
||||
@@ -6936,6 +6943,19 @@ breakText Glyphs Glyphen
|
||||
Show where this tool is Zeigen, wo sich dieses Werkzeug befindet
|
||||
@msg missing `tutorial` (see learn.list) `tutorial` fehlt (siehe learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) unbekanntes Lernprogramm `{id}` (siehe learn.list)
|
||||
View more Mehr anzeigen
|
||||
Finish tutorial Lernprogramm abschließen
|
||||
Next Up Als Nächstes
|
||||
You finished the last tutorial in this skill. Sie haben das letzte Lernprogramm dieser Fertigkeit abgeschlossen.
|
||||
Back to skills Zurück zu den Fertigkeiten
|
||||
Open Tutorial Sample Übungsdatei des Lernprogramms öffnen
|
||||
Finish Tutorial Lernprogramm abschließen
|
||||
Next Tutorial Nächstes Lernprogramm
|
||||
Back to Skills Zurück zu den Fertigkeiten
|
||||
@msg tutorial `{id}` has no practice sample das Lernprogramm `{id}` hat keine Übungsdatei
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) öffnen Sie zuerst die Übungsdatei von `{id}` (siehe learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) schließen Sie zuerst `{id}` ab (siehe learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` ist das letzte Lernprogramm seiner Fertigkeit
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Zurückgestellte Effekte aktualisieren
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2267,6 +2267,7 @@ axis Both Και τα δύο
|
||||
Document Options Επιλογές εγγράφου
|
||||
Dock Control Bar Αγκύρωση γραμμής ελέγχου
|
||||
@msg no library `{id}` Δεν υπάρχει βιβλιοθήκη με αναγνωριστικό `{id}`
|
||||
@msg the library has another item of that kind named `{name}` η βιβλιοθήκη έχει ήδη άλλο στοιχείο αυτού του είδους με όνομα `{name}`
|
||||
@msg select some type first Επιλέξτε πρώτα κάποιο κείμενο
|
||||
@msg kerning must be a number, "auto", or "optical" το kerning πρέπει να είναι αριθμός, «auto» ή «optical»
|
||||
@msg the selection has no gradient fill η επιλογή δεν έχει ντεγκραντέ γεμίσματος
|
||||
@@ -3598,6 +3599,9 @@ digits Malayalam Μαλαγιάλαμ
|
||||
Reset the rows to the artwork's colors Επαναφορά γραμμών στα χρώματα του σχεδίου
|
||||
Color Theme Picker Επιλογέας χρωματικού θέματος
|
||||
Click or drag across the art to pick its colors; Shift adds more Κάντε κλικ ή σύρετε πάνω στο σχέδιο για να πάρετε τα χρώματά του· το Shift προσθέτει κι άλλα
|
||||
Prominent Colors Κυρίαρχα χρώματα
|
||||
Save All Colors Αποθήκευση όλων των χρωμάτων
|
||||
Save Prominent Colors Αποθήκευση κυρίαρχων χρωμάτων
|
||||
Reset to White, Black Επαναφορά σε λευκό και μαύρο
|
||||
Reset with Mesh Επαναφορά με πλέγμα
|
||||
Reset with Mesh… Επαναφορά με πλέγμα…
|
||||
@@ -4052,6 +4056,8 @@ digits Malayalam Μαλαγιάλαμ
|
||||
Rename Library Group Μετονομασία ομάδας βιβλιοθήκης
|
||||
Delete Library Group Διαγραφή ομάδας βιβλιοθήκης
|
||||
Move Library Item to Group Μετακίνηση στοιχείου βιβλιοθήκης σε ομάδα
|
||||
Rename Library Item Μετονομασία στοιχείου βιβλιοθήκης
|
||||
Add to Character Styles Προσθήκη στα στυλ χαρακτήρων
|
||||
Rename Library Μετονομασία βιβλιοθήκης
|
||||
Show Library Εμφάνιση βιβλιοθήκης
|
||||
Use Library Item Χρήση στοιχείου βιβλιοθήκης
|
||||
@@ -6482,6 +6488,7 @@ axis Y Axis Άξονας Y
|
||||
@msg message must be text Το message πρέπει να είναι κείμενο
|
||||
@msg allowContinue must be true or false Το allowContinue πρέπει να είναι true ή false
|
||||
@msg Batch cannot play an action with a stop Η μαζική επεξεργασία δεν μπορεί να αναπαράγει ενέργεια με διακοπή
|
||||
@msg Batch cannot play an action with a View menu step Η μαζική επεξεργασία δεν μπορεί να αναπαράγει ενέργεια με βήμα από το μενού Προβολή
|
||||
Insert Menu Item… Εισαγωγή στοιχείου μενού…
|
||||
Insert Menu Item Εισαγωγή στοιχείου μενού
|
||||
Insert Select Path Εισαγωγή επιλογής διαδρομής
|
||||
@@ -7293,6 +7300,19 @@ breakText Glyphs Γλύφοι
|
||||
Show where this tool is Εμφάνιση της θέσης αυτού του εργαλείου
|
||||
@msg missing `tutorial` (see learn.list) λείπει το `tutorial` (δείτε learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) άγνωστος οδηγός εκμάθησης `{id}` (δείτε learn.list)
|
||||
View more Προβολή περισσότερων
|
||||
Finish tutorial Ολοκλήρωση οδηγού
|
||||
Next Up Επόμενο
|
||||
You finished the last tutorial in this skill. Ολοκληρώσατε τον τελευταίο οδηγό εκμάθησης αυτής της δεξιότητας.
|
||||
Back to skills Πίσω στις δεξιότητες
|
||||
Open Tutorial Sample Άνοιγμα δείγματος οδηγού εκμάθησης
|
||||
Finish Tutorial Ολοκλήρωση οδηγού εκμάθησης
|
||||
Next Tutorial Επόμενος οδηγός εκμάθησης
|
||||
Back to Skills Πίσω στις δεξιότητες
|
||||
@msg tutorial `{id}` has no practice sample ο οδηγός εκμάθησης `{id}` δεν έχει δείγμα εξάσκησης
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) ανοίξτε πρώτα το δείγμα εξάσκησης του `{id}` (δείτε learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) ολοκληρώστε πρώτα το `{id}` (δείτε learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill το `{id}` είναι ο τελευταίος οδηγός εκμάθησης της δεξιότητάς του
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Ανανέωση εφέ σε αναμονή
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2913,6 +2913,9 @@ digits Malayalam Malayálam
|
||||
Reset the rows to the artwork's colors Restablecer las filas a los colores de la ilustración
|
||||
Color Theme Picker Selector de tema de color
|
||||
Click or drag across the art to pick its colors; Shift adds more Haga clic o arrastre sobre la ilustración para tomar sus colores; Mayús añade más
|
||||
Prominent Colors Colores destacados
|
||||
Save All Colors Guardar todos los colores
|
||||
Save Prominent Colors Guardar colores destacados
|
||||
Reset to Default Restablecer valores predeterminados
|
||||
Reset to White, Black Restablecer a blanco, negro
|
||||
Reset with Mesh Restablecer con malla
|
||||
@@ -3584,6 +3587,8 @@ digits Malayalam Malayálam
|
||||
Rename Library Group Cambiar nombre del grupo de biblioteca
|
||||
Delete Library Group Eliminar grupo de biblioteca
|
||||
Move Library Item to Group Mover elemento de la biblioteca al grupo
|
||||
Rename Library Item Cambiar nombre del elemento de la biblioteca
|
||||
Add to Character Styles Agregar a estilos de carácter
|
||||
Library Biblioteca
|
||||
Rename Library Cambiar nombre de la biblioteca
|
||||
Show Library Mostrar biblioteca
|
||||
@@ -4168,6 +4173,7 @@ axis Both Ambos
|
||||
# (`untranslated_report` lists any that are missing). Command ids, parameter
|
||||
# names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are.
|
||||
@msg no library `{id}` no hay ninguna biblioteca `{id}`
|
||||
@msg the library has another item of that kind named `{name}` la biblioteca ya tiene otro elemento de ese tipo llamado `{name}`
|
||||
@msg select some type first selecciona primero algún texto
|
||||
@msg kerning must be a number, "auto", or "optical" kerning debe ser un número, «auto» u «optical»
|
||||
@msg the selection has no gradient fill la selección no tiene un degradado de relleno
|
||||
@@ -6473,6 +6479,7 @@ axis Y Axis Eje Y
|
||||
@msg message must be text message debe ser texto
|
||||
@msg allowContinue must be true or false allowContinue debe ser true o false
|
||||
@msg Batch cannot play an action with a stop Lote no puede reproducir una acción con una parada
|
||||
@msg Batch cannot play an action with a View menu step Lote no puede reproducir una acción con un paso del menú Ver
|
||||
Insert Menu Item… Insertar elemento de menú…
|
||||
Insert Menu Item Insertar elemento de menú
|
||||
Insert Select Path Insertar selección de trazado
|
||||
@@ -7284,6 +7291,19 @@ breakText Glyphs Glifos
|
||||
Show where this tool is Mostrar dónde está esta herramienta
|
||||
@msg missing `tutorial` (see learn.list) falta `tutorial` (consulta learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) tutorial desconocido `{id}` (consulta learn.list)
|
||||
View more Ver más
|
||||
Finish tutorial Terminar tutorial
|
||||
Next Up A continuación
|
||||
You finished the last tutorial in this skill. Has terminado el último tutorial de esta habilidad.
|
||||
Back to skills Volver a las habilidades
|
||||
Open Tutorial Sample Abrir muestra del tutorial
|
||||
Finish Tutorial Terminar tutorial
|
||||
Next Tutorial Tutorial siguiente
|
||||
Back to Skills Volver a las habilidades
|
||||
@msg tutorial `{id}` has no practice sample el tutorial `{id}` no tiene muestra de práctica
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) abre primero la muestra de práctica de `{id}` (consulta learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) termina primero `{id}` (consulta learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` es el último tutorial de su habilidad
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Actualizar efectos aplazados
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2835,6 +2835,9 @@ digits Malayalam Malajalam
|
||||
Reset the rows to the artwork's colors Palauta rivit kuvituksen väreihin
|
||||
Color Theme Picker Väriteeman valitsin
|
||||
Click or drag across the art to pick its colors; Shift adds more Napsauta tai vedä kuvituksen yli poimiaksesi sen värit; Vaihto lisää useampia
|
||||
Prominent Colors Hallitsevat värit
|
||||
Save All Colors Tallenna kaikki värit
|
||||
Save Prominent Colors Tallenna hallitsevat värit
|
||||
Separate colors into rows Erottele värit riveille
|
||||
Unlink harmony colors Poista harmoniavärien linkitys
|
||||
1 Color Job 1 värin työ
|
||||
@@ -3543,6 +3546,8 @@ theme Appearance Ulkoasu
|
||||
Rename Library Group Nimeä kirjastoryhmä uudelleen
|
||||
Delete Library Group Poista kirjastoryhmä
|
||||
Move Library Item to Group Siirrä kirjaston kohde ryhmään
|
||||
Rename Library Item Nimeä kirjaston kohde uudelleen
|
||||
Add to Character Styles Lisää merkkityyleihin
|
||||
Rename Library Nimeä kirjasto uudelleen
|
||||
Show Library Näytä kirjasto
|
||||
Use Library Item Käytä kirjaston kohdetta
|
||||
@@ -4393,6 +4398,7 @@ imageTrace Outline Ääriviiva
|
||||
@plural {n} step|{n} steps {n} vaihe|{n} vaihetta
|
||||
@plural {n} stroke|{n} strokes {n} viiva|{n} viivaa
|
||||
@msg no library `{id}` ei kirjastoa `{id}`
|
||||
@msg the library has another item of that kind named `{name}` kirjastossa on jo toinen samanlainen kohde nimeltä `{name}`
|
||||
@msg select some type first valitse ensin tekstiä
|
||||
@msg kerning must be a number, "auto", or "optical" kerning-arvon on oltava luku, ”auto” tai ”optical”
|
||||
@msg the selection has no gradient fill valinnalla ei ole liukuväritäyttöä
|
||||
@@ -6561,6 +6567,7 @@ axis Y Axis Y-akseli
|
||||
@msg message must be text message on oltava tekstiä
|
||||
@msg allowContinue must be true or false allowContinue on oltava true tai false
|
||||
@msg Batch cannot play an action with a stop Erä ei voi toistaa toimintoa, jossa on pysäytys
|
||||
@msg Batch cannot play an action with a View menu step Erä ei voi toistaa toimintoa, jossa on Näytä-valikon vaihe
|
||||
Insert Menu Item… Lisää valikkokohta…
|
||||
Insert Menu Item Lisää valikkokohta
|
||||
Insert Select Path Lisää polun valinta
|
||||
@@ -7376,6 +7383,19 @@ breakText Glyphs Merkit
|
||||
Show where this tool is Näytä, missä tämä työkalu on
|
||||
@msg missing `tutorial` (see learn.list) `tutorial` puuttuu (ks. learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) tuntematon opetusohjelma `{id}` (ks. learn.list)
|
||||
View more Näytä lisää
|
||||
Finish tutorial Viimeistele opetusohjelma
|
||||
Next Up Seuraavaksi
|
||||
You finished the last tutorial in this skill. Viimeistelit tämän taidon viimeisen opetusohjelman.
|
||||
Back to skills Takaisin taitoihin
|
||||
Open Tutorial Sample Avaa opetusohjelman harjoitustiedosto
|
||||
Finish Tutorial Viimeistele opetusohjelma
|
||||
Next Tutorial Seuraava opetusohjelma
|
||||
Back to Skills Takaisin taitoihin
|
||||
@msg tutorial `{id}` has no practice sample opetusohjelmalla `{id}` ei ole harjoitustiedostoa
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) avaa ensin opetusohjelman `{id}` harjoitustiedosto (ks. learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) viimeistele ensin `{id}` (ks. learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` on taitonsa viimeinen opetusohjelma
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Päivitä lykätyt tehosteet
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2905,6 +2905,9 @@ digits Malayalam Malayalam
|
||||
Reset the rows to the artwork's colors Réinitialiser les lignes avec les couleurs de l’illustration
|
||||
Color Theme Picker Sélecteur de thème de couleurs
|
||||
Click or drag across the art to pick its colors; Shift adds more Cliquez ou faites glisser sur l’illustration pour prélever ses couleurs ; Maj en ajoute d’autres
|
||||
Prominent Colors Couleurs dominantes
|
||||
Save All Colors Enregistrer toutes les couleurs
|
||||
Save Prominent Colors Enregistrer les couleurs dominantes
|
||||
Reset to Default Rétablir les valeurs par défaut
|
||||
Reset to White, Black Réinitialiser à blanc, noir
|
||||
Reset with Mesh Réinitialiser avec un filet
|
||||
@@ -3576,6 +3579,8 @@ digits Malayalam Malayalam
|
||||
Rename Library Group Renommer le groupe de bibliothèque
|
||||
Delete Library Group Supprimer le groupe de bibliothèque
|
||||
Move Library Item to Group Déplacer l’élément de la bibliothèque vers un groupe
|
||||
Rename Library Item Renommer l’élément de la bibliothèque
|
||||
Add to Character Styles Ajouter aux styles de caractère
|
||||
Library Bibliothèque
|
||||
Rename Library Renommer la bibliothèque
|
||||
Show Library Afficher la bibliothèque
|
||||
@@ -4157,6 +4162,7 @@ axis Both Les deux
|
||||
# (`untranslated_report` lists any that are missing). Command ids, parameter
|
||||
# names and values in backticks or code (`colorModel rgb`, `document.export`) stay as they are.
|
||||
@msg no library `{id}` aucune bibliothèque `{id}`
|
||||
@msg the library has another item of that kind named `{name}` la bibliothèque a déjà un autre élément de ce type nommé `{name}`
|
||||
@msg select some type first sélectionnez d’abord du texte
|
||||
@msg kerning must be a number, "auto", or "optical" kerning doit être un nombre, « auto » ou « optical »
|
||||
@msg the selection has no gradient fill la sélection n’a pas de dégradé de fond
|
||||
@@ -6526,6 +6532,7 @@ axis Y Axis Axe Y
|
||||
@msg message must be text message doit être du texte
|
||||
@msg allowContinue must be true or false allowContinue doit valoir true ou false
|
||||
@msg Batch cannot play an action with a stop Le traitement par lots ne peut pas exécuter un script comportant un arrêt
|
||||
@msg Batch cannot play an action with a View menu step Le traitement par lots ne peut pas exécuter un script comportant une étape du menu Affichage
|
||||
Insert Menu Item… Insérer une commande de menu…
|
||||
Insert Menu Item Insérer une commande de menu
|
||||
Insert Select Path Insérer une sélection de tracé
|
||||
@@ -7336,6 +7343,19 @@ breakText Glyphs Glyphes
|
||||
Show where this tool is Afficher l'emplacement de cet outil
|
||||
@msg missing `tutorial` (see learn.list) `tutorial` manquant (voir learn.list)
|
||||
@msg unknown tutorial `{id}` (see learn.list) tutoriel inconnu `{id}` (voir learn.list)
|
||||
View more Voir plus
|
||||
Finish tutorial Terminer le tutoriel
|
||||
Next Up À suivre
|
||||
You finished the last tutorial in this skill. Vous avez terminé le dernier tutoriel de cette compétence.
|
||||
Back to skills Retour aux compétences
|
||||
Open Tutorial Sample Ouvrir le fichier d’exercice du tutoriel
|
||||
Finish Tutorial Terminer le tutoriel
|
||||
Next Tutorial Tutoriel suivant
|
||||
Back to Skills Retour aux compétences
|
||||
@msg tutorial `{id}` has no practice sample le tutoriel `{id}` n’a pas de fichier d’exercice
|
||||
@msg open the practice sample of `{id}` first (see learn.openSample) ouvrez d’abord le fichier d’exercice de `{id}` (voir learn.openSample)
|
||||
@msg finish `{id}` first (see learn.finish) terminez d’abord `{id}` (voir learn.finish)
|
||||
@msg `{id}` is the last tutorial in its skill `{id}` est le dernier tutoriel de sa compétence
|
||||
|
||||
# Deferred plug-in effects
|
||||
Refresh Deferred Effects Actualiser les effets différés
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
+213
-193
File diff suppressed because it is too large.
Load diff
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user