mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 04:25:52 -05:00
Merge main into feat/scripts-api-d8b-tracing
This commit is contained in:
69 files changed
+2121
-308
No files matched your search
@@ -47,6 +47,9 @@ jobs:
|
||||
test-shards: 6
|
||||
shard-command: cargo xtask ci shard
|
||||
warm-command: cargo xtask ci warm
|
||||
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
|
||||
# its shard builds), and `cache warm` puts their files into the one entry it saves.
|
||||
warm-split: true
|
||||
# The dependency cache also keeps the compiled workspace crates and test executables, so a
|
||||
# pull request's shards rebuild only the crates its changes reach. Each main run's `cache
|
||||
# warm` leg saves a rolling entry of its own, every leg restores the newest one, and
|
||||
@@ -65,14 +68,17 @@ jobs:
|
||||
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
|
||||
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
|
||||
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
|
||||
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
|
||||
# script reports a leg that starts late with its own error before the job times out.
|
||||
# free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its
|
||||
# start deadline while any split leg is queued or running, then allows 180 minutes from the last
|
||||
# split completion for the saving leg to start. Without split legs, it allows 180 minutes from
|
||||
# the script's start. A failed split leg fails this job too. The script then waits up to 160
|
||||
# minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the
|
||||
# script's deadlines expire when split builds or runner waits take too long.
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 290
|
||||
timeout-minutes: 360
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! mark for [`STALL`] while inside a stage of its frame, the thread writes what the app knows to the
|
||||
//! log (`logs/vectorcraft.log`) and to `logs/hang-report-<process id>.txt`: the stage, a clipboard
|
||||
//! call in progress, the last commands, the last frames' times, the platform, the window system, the
|
||||
//! graphics processor and the present mode the app asked for, and how long the session has run with
|
||||
//! how many documents open. The process holds a lock on the file until the interface thread answers
|
||||
//! graphics processor, its driver when known, and the present mode the app asked for, and how long
|
||||
//! the session has run with how many documents open. The process holds a lock on the file until the interface thread answers
|
||||
//! again; then the log says after how long and the file is removed. A file nobody holds at a later
|
||||
//! launch was left by a session that was closed while it did not answer, and a locked one belongs to
|
||||
//! another instance that is stalled now and is left alone. That launch writes the report to the log,
|
||||
@@ -113,6 +113,8 @@ pub struct Facts {
|
||||
pub flatpak: bool,
|
||||
/// The graphics processor the window draws with.
|
||||
pub graphics: Option<String>,
|
||||
/// The active graphics driver's identity, when the backend reports it.
|
||||
graphics_driver: Option<String>,
|
||||
/// The present mode and frame queue the app asked the window surface for.
|
||||
pub surface: String,
|
||||
}
|
||||
@@ -128,14 +130,29 @@ impl Facts {
|
||||
session_type: value("XDG_SESSION_TYPE"),
|
||||
flatpak: flatpak_info || env("FLATPAK_ID").is_some_and(|v| !v.is_empty()),
|
||||
graphics,
|
||||
graphics_driver: None,
|
||||
surface,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "wgpu", test))]
|
||||
pub fn with_graphics_driver(mut self, driver: &str, info: &str) -> Facts {
|
||||
// D3D12 reports 0.0.0.0 when the driver version could not be read.
|
||||
let mut fields = [driver, info].map(clean).into_iter().filter(|value| !value.is_empty() && value != "0.0.0.0");
|
||||
self.graphics_driver = fields.next().map(|mut detail| {
|
||||
if let Some(info) = fields.next().filter(|info| info != &detail) {
|
||||
detail.push_str(" / ");
|
||||
detail.push_str(&info);
|
||||
}
|
||||
detail
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// The facts as report lines.
|
||||
pub fn lines(&self) -> String {
|
||||
let or_unknown = |v: &Option<String>| v.clone().unwrap_or_else(|| "unknown".to_string());
|
||||
format!(
|
||||
let mut lines = format!(
|
||||
"VectorCraft {} on {} {}\nWindow system: {}; desktop: {}; session type: {}; Flatpak: {}\nGraphics: {}; {}\n",
|
||||
vectorcraft_ui_egui::os_window::version(),
|
||||
std::env::consts::OS,
|
||||
@@ -146,7 +163,13 @@ impl Facts {
|
||||
if self.flatpak { "yes" } else { "no" },
|
||||
or_unknown(&self.graphics),
|
||||
self.surface,
|
||||
)
|
||||
);
|
||||
if let Some(driver) = &self.graphics_driver {
|
||||
lines.push_str("Graphics driver: ");
|
||||
lines.push_str(driver);
|
||||
lines.push('\n');
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -279,3 +279,22 @@ fn troubleshooting_info_holds_both_sessions_reports() {
|
||||
assert!(text.contains("(it was closed while it did not answer):\nVectorCraft hang report, last session\n"));
|
||||
assert!(text.contains("Recent commands, oldest first: none"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn troubleshooting_info_distinguishes_drivers_on_the_same_adapter() {
|
||||
let mut shared = shared(None);
|
||||
let beacon = Beacon::new();
|
||||
for (driver, info, expected) in [
|
||||
(" 32.0.16.1088 ", "", Some("32.0.16.1088")),
|
||||
("32.0.16.2124", "", Some("32.0.16.2124")),
|
||||
("Mesa\nRADV", "Mesa 25.2", Some("MesaRADV / Mesa 25.2")),
|
||||
("Mesa", "Mesa", Some("Mesa")),
|
||||
("0.0.0.0", "", None),
|
||||
("", "", None),
|
||||
] {
|
||||
shared.facts = facts().with_graphics_driver(driver, info);
|
||||
let text = troubleshooting(&shared, &beacon, UNIX_EPOCH);
|
||||
assert!(text.contains("Graphics: Test GPU"), "the adapter description is still in the report");
|
||||
assert_eq!(text.lines().find_map(|line| line.strip_prefix("Graphics driver: ")), expected);
|
||||
}
|
||||
}
|
||||
@@ -432,6 +432,12 @@ fn opens_through_xwayland(pref: Option<&str>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The docking runtime needs the backend the desktop window is opened on.
|
||||
fn desktop_shell_info(detected: Backend, forced_to_x11: bool) -> ShellInfo {
|
||||
let backend = if forced_to_x11 { Backend::X11 } else { detected };
|
||||
ShellInfo::current().backend(backend)
|
||||
}
|
||||
|
||||
/// The nightly channel this build is, as a string for the log.
|
||||
fn channel_name() -> &'static str {
|
||||
match build_flavor::COMPILED {
|
||||
@@ -718,10 +724,10 @@ fn main() -> std::process::ExitCode {
|
||||
// A window forced onto XWayland runs on X11, whose window manager draws the frame: the
|
||||
// framework decides the frame for that backend, from the platform, `VECTORCRAFT_TITLEBAR` and
|
||||
// Preferences › User Interface › System Title Bar.
|
||||
let shell_info = if forced_to_x11 { ShellInfo::current().backend(Backend::X11) } else { ShellInfo::current() };
|
||||
let shell_info = desktop_shell_info(Backend::from_env(), forced_to_x11);
|
||||
// On Wayland with no cursor theme, the system pointer stays and no tool cursor is painted
|
||||
// beside it (#2450, #5311).
|
||||
let wayland = !forced_to_x11 && Backend::from_env() == Backend::Wayland;
|
||||
let wayland = shell_info.backend == Backend::Wayland;
|
||||
let caps = cursor_theme::shell_caps(shell_info.caps, wayland, cursor_theme::theme_missing);
|
||||
let shell_info = shell_info.caps(caps);
|
||||
let titlebar_pref =
|
||||
@@ -981,14 +987,22 @@ fn main() -> std::process::ExitCode {
|
||||
.map(|_| (format!("{:?}", requested_surface.present_mode), requested_surface.desired_maximum_frame_latency));
|
||||
#[cfg(not(feature = "wgpu"))]
|
||||
let surface = None;
|
||||
let facts = hang_watch::Facts::new(
|
||||
|name| std::env::var(name).ok(),
|
||||
std::path::Path::new("/.flatpak-info").exists(),
|
||||
hang_watch::window_system(winit_window.as_deref()),
|
||||
app.graphics_adapter.clone(),
|
||||
hang_watch::surface(surface),
|
||||
);
|
||||
#[cfg(feature = "wgpu")]
|
||||
let facts = if let Some(rs) = &cc.wgpu_render_state {
|
||||
let info = rs.adapter.get_info();
|
||||
facts.with_graphics_driver(&info.driver, &info.driver_info)
|
||||
} else {
|
||||
facts
|
||||
};
|
||||
let hang = std::sync::Arc::new(hang_watch::Shared {
|
||||
facts: hang_watch::Facts::new(
|
||||
|name| std::env::var(name).ok(),
|
||||
std::path::Path::new("/.flatpak-info").exists(),
|
||||
hang_watch::window_system(winit_window.as_deref()),
|
||||
app.graphics_adapter.clone(),
|
||||
hang_watch::surface(surface),
|
||||
),
|
||||
facts,
|
||||
started: std::time::Instant::now(),
|
||||
last: std::sync::Mutex::new(None),
|
||||
previous: previous_hang.clone(),
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn desktop_shell_reports_the_backend_selected_for_docking() {
|
||||
let wayland = desktop_shell_info(Backend::Wayland, false);
|
||||
assert_eq!(wayland.backend, Backend::Wayland);
|
||||
assert!(!wayland.window_positions(), "native Wayland keeps palettes inside the window");
|
||||
|
||||
for (detected, force_x11) in [(Backend::Wayland, true), (Backend::X11, false)] {
|
||||
let x11 = desktop_shell_info(detected, force_x11);
|
||||
assert_eq!(x11.backend, Backend::X11);
|
||||
assert!(x11.window_positions(), "X11 and XWayland can place native palettes");
|
||||
}
|
||||
}
|
||||
|
||||
/// The saved UI state of an old `ui.json`, as the legacy import reads it.
|
||||
fn legacy_ui(bytes: &[u8]) -> Option<vectorcraft_ui_egui::UiState> {
|
||||
vectorcraft_ui_egui::parse_legacy(bytes).ok().map(|(settings, _)| settings.ui)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 4.8L18.7 1.4L22.6 21.6L4.8 18.2Z"/>
|
||||
<rect x="0.8" y="3.6" width="2.4" height="2.4" fill="currentColor"/>
|
||||
<rect x="17.5" y="0.2" width="2.4" height="2.4" fill="currentColor"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 525 B After Width: | Height: | Size: 527 B |
@@ -19,7 +19,7 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_doc::color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
|
||||
use vectorcraft_geom::hit::fill_contains;
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
|
||||
use vectorcraft_geom::{Affine, BezPath, CubicBez, FillRule, PathData, Point, Rect, shapes};
|
||||
use vectorcraft_pathops::{self as po, BoolOp};
|
||||
|
||||
use crate::catalog::{EffectInfo, Lengths};
|
||||
@@ -43,7 +43,7 @@ pub(crate) fn catalog() -> Vec<EffectInfo> {
|
||||
id: HALFTONE,
|
||||
label: "Vector Halftone…",
|
||||
menu: &["Effect", "Color Effects"],
|
||||
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
|
||||
params: "{shape: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency: lines per inch 1..300 (20), angle: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode: \"mono\"|\"cmyk\" (mono), color: mono dot colour (\"#000000\"), fromArt: bool (false; mono: each dot takes the art's colour under it), invert: bool (false; dots for light tones), clip: bool (true; the dots clipped to the art's outline)} draws the object as vector halftone dots sized by its tone, as object.vectorHalftone makes them (CMYK screens multiply); the object is sampled as drawn with its other effects; at most 100000 cells per screen, past that the object draws as it is",
|
||||
defaults: json!({"shape": "circle", "frequency": 20.0, "angle": 45.0, "mode": "mono", "color": "#000000", "fromArt": false, "invert": false, "clip": true}),
|
||||
raster: false,
|
||||
lengths: Lengths::default(),
|
||||
@@ -63,6 +63,12 @@ pub enum DotShape {
|
||||
Square,
|
||||
Diamond,
|
||||
Line,
|
||||
/// Round dots that grow into squares meeting corner to corner at 50% (a checkerboard), then
|
||||
/// round holes, as the Euclidean spot function draws them.
|
||||
Euclidean,
|
||||
/// Elongated dots that join along their long side at 40% into chains, along their short side
|
||||
/// at 60%, then elongated holes.
|
||||
Elliptical,
|
||||
}
|
||||
|
||||
impl DotShape {
|
||||
@@ -73,6 +79,8 @@ impl DotShape {
|
||||
"square" => DotShape::Square,
|
||||
"diamond" => DotShape::Diamond,
|
||||
"line" | "lines" => DotShape::Line,
|
||||
"euclidean" => DotShape::Euclidean,
|
||||
"elliptical" => DotShape::Elliptical,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -94,10 +102,227 @@ impl DotShape {
|
||||
DotShape::Diamond => square(s * t.sqrt()).transformed(Affine::rotate(std::f64::consts::FRAC_PI_4)),
|
||||
// Cells along a row join into a line as thick as the tone.
|
||||
DotShape::Line => shapes::rectangle(Rect::from_center_size(Point::ZERO, (s * 1.001, s * t))),
|
||||
DotShape::Euclidean => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Euclidean)),
|
||||
DotShape::Elliptical => PathData::from_bezpath(&spot(t, s / 2.0, SpotKind::Elliptical)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Elliptical dot's height over its width: a dot as wide as its cell covers 40% of it
|
||||
/// (π × ratio / 4 = 0.4 of a quadrant).
|
||||
const ELLIPTICAL_RATIO: f64 = 1.6 / std::f64::consts::PI;
|
||||
|
||||
/// The Elliptical dot's middle-tone cut in a quadrant of half side 1, the line
|
||||
/// `ELLIPTICAL_CUT.0 × x + y = ELLIPTICAL_CUT.1`. It meets the side x = 1 at y = 0.25 and the y
|
||||
/// axis at 0.75 and runs through the quadrant's center, so the dot it cuts at 50% is its own
|
||||
/// complement: the dark bridges across the x side from 40%, and the y side stays light until 60%.
|
||||
const ELLIPTICAL_CUT: (f64, f64) = (0.5, 0.75);
|
||||
|
||||
/// Steps of the table of dot sizes per tone ([`dot_sizes`]) over tones 0..0.5.
|
||||
const SIZE_STEPS: usize = 512;
|
||||
|
||||
static EUCLIDEAN: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
static ELLIPTICAL: OnceLock<Vec<f64>> = OnceLock::new();
|
||||
|
||||
/// The two spot-function dots.
|
||||
#[derive(Clone, Copy)]
|
||||
enum SpotKind {
|
||||
Euclidean,
|
||||
Elliptical,
|
||||
}
|
||||
|
||||
impl SpotKind {
|
||||
/// The first quadrant of the dot of width `a` in a quadrant of half side 1.
|
||||
fn quadrant(self, a: f64) -> Vec<CubicBez> {
|
||||
match self {
|
||||
SpotKind::Euclidean => quadrant(a, a, 1.0),
|
||||
SpotKind::Elliptical => elliptical_quadrant(a),
|
||||
}
|
||||
}
|
||||
|
||||
/// The width at which the dot covers half the cell.
|
||||
fn max_size(self) -> f64 {
|
||||
match self {
|
||||
SpotKind::Euclidean => 1.0,
|
||||
SpotKind::Elliptical => ELLIPTICAL_CUT.1 / ELLIPTICAL_RATIO,
|
||||
}
|
||||
}
|
||||
|
||||
fn table(self) -> &'static OnceLock<Vec<f64>> {
|
||||
match self {
|
||||
SpotKind::Euclidean => &EUCLIDEAN,
|
||||
SpotKind::Elliptical => &ELLIPTICAL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// For tones `k / SIZE_STEPS × 0.5`, the width `a` of the dot of `kind` that covers that tone of the
|
||||
/// cell [-1, 1]².
|
||||
fn dot_sizes(kind: SpotKind) -> Vec<f64> {
|
||||
(0..=SIZE_STEPS)
|
||||
.map(|k| {
|
||||
// A quadrant of the cell has area 1.
|
||||
let target = k as f64 / SIZE_STEPS as f64 * 0.5;
|
||||
let (mut lo, mut hi) = (0.0, kind.max_size());
|
||||
for _ in 0..50 {
|
||||
let mid = (lo + hi) / 2.0;
|
||||
if curves_area(&kind.quadrant(mid)) < target { lo = mid } else { hi = mid }
|
||||
}
|
||||
(lo + hi) / 2.0
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The area between the origin and `curves`, which run from the x axis to the y axis.
|
||||
fn curves_area(curves: &[CubicBez]) -> f64 {
|
||||
use vectorcraft_geom::kurbo::ParamCurveArea;
|
||||
curves.iter().map(|c| c.signed_area()).sum()
|
||||
}
|
||||
|
||||
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`.
|
||||
fn ellipse_arc(out: &mut Vec<CubicBez>, a: f64, b: f64, t0: f64, t1: f64) {
|
||||
if t1 <= t0 {
|
||||
return;
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0);
|
||||
let d = (t1 - t0) / n;
|
||||
let k = 4.0 / 3.0 * (d / 4.0).tan();
|
||||
for i in 0..n as usize {
|
||||
let (u0, u1) = (t0 + d * i as f64, t0 + d * (i as f64 + 1.0));
|
||||
let (p0, p3) = (at(u0), at(u1));
|
||||
let c1 = p0 + k * vectorcraft_geom::Vec2::new(-a * u0.sin(), b * u0.cos());
|
||||
let c2 = p3 - k * vectorcraft_geom::Vec2::new(-a * u1.sin(), b * u1.cos());
|
||||
out.push(CubicBez::new(p0, c1, c2, p3));
|
||||
}
|
||||
}
|
||||
|
||||
/// The straight segment from `p` to `q` as a cubic curve.
|
||||
fn segment(p: Point, q: Point) -> CubicBez {
|
||||
CubicBez::new(p, p.lerp(q, 1.0 / 3.0), p.lerp(q, 2.0 / 3.0), q)
|
||||
}
|
||||
|
||||
/// The first quadrant of the Elliptical dot of width `a` (height `ELLIPTICAL_RATIO × a`) in a
|
||||
/// quadrant of half side 1, from the x axis to the y axis. Up to width 1 (40%) it is the whole
|
||||
/// ellipse. Wider, the ellipse is clipped to the side x = 1, which makes a bridge to the next dot
|
||||
/// along x, and to the cut line [`ELLIPTICAL_CUT`], which keeps it off the y side.
|
||||
fn elliptical_quadrant(a: f64) -> Vec<CubicBez> {
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
let b = a * ELLIPTICAL_RATIO;
|
||||
let mut out = vec![];
|
||||
if a <= 1.0 {
|
||||
ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let (m, c) = ELLIPTICAL_CUT;
|
||||
// The ellipse crosses the side x = 1 at angle t0.
|
||||
let t0 = (1.0 / a).acos();
|
||||
// Between angles ts and te the ellipse lies beyond the cut line.
|
||||
let r = (m * a).hypot(b);
|
||||
let (ts, te) = if r > c {
|
||||
let (phi, alpha) = (b.atan2(m * a), (c / r).acos());
|
||||
(phi - alpha, phi + alpha)
|
||||
} else {
|
||||
(FRAC_PI_2, FRAC_PI_2)
|
||||
};
|
||||
let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, c) };
|
||||
out.push(segment(Point::new(1.0, 0.0), if t0 < ts || t0 >= te { at(t0) } else { Point::new(1.0, c - m) }));
|
||||
if t0 >= te {
|
||||
ellipse_arc(&mut out, a, b, t0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
if t0 < ts {
|
||||
ellipse_arc(&mut out, a, b, t0, ts.min(FRAC_PI_2));
|
||||
if ts >= FRAC_PI_2 {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
let from = out.last().map_or(Point::new(1.0, 0.0), |q| q.p3);
|
||||
out.push(segment(from, end));
|
||||
ellipse_arc(&mut out, a, b, te, FRAC_PI_2);
|
||||
out
|
||||
}
|
||||
|
||||
/// The first quadrant of the ellipse with semi-axes `a`, `b` clipped to the diamond side x + y ≤
|
||||
/// `h`, from its point on the x axis to its point on the y axis, as cubic curves.
|
||||
fn quadrant(a: f64, b: f64, h: f64) -> Vec<CubicBez> {
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let mut out = vec![];
|
||||
let r = a.hypot(b);
|
||||
if r <= h {
|
||||
ellipse_arc(&mut out, a, b, 0.0, FRAC_PI_2);
|
||||
return out;
|
||||
}
|
||||
let (phi, alpha) = (b.atan2(a), (h / r).acos());
|
||||
let (ts, te) = (phi - alpha, phi + alpha);
|
||||
let start = if ts > 0.0 {
|
||||
ellipse_arc(&mut out, a, b, 0.0, ts);
|
||||
at(ts)
|
||||
} else {
|
||||
Point::new(h, 0.0)
|
||||
};
|
||||
let end = if te < FRAC_PI_2 { at(te) } else { Point::new(0.0, h) };
|
||||
out.push(segment(start, end));
|
||||
ellipse_arc(&mut out, a, b, te, FRAC_PI_2);
|
||||
out
|
||||
}
|
||||
|
||||
/// `curves` reversed, each curve run backwards.
|
||||
fn reversed(curves: &[CubicBez]) -> Vec<CubicBez> {
|
||||
curves.iter().rev().map(|c| CubicBez::new(c.p3, c.p2, c.p1, c.p0)).collect()
|
||||
}
|
||||
|
||||
/// `curves` with each point mapped by `f`.
|
||||
fn mapped(curves: &[CubicBez], f: impl Fn(Point) -> Point) -> Vec<CubicBez> {
|
||||
curves.iter().map(|c| CubicBez::new(f(c.p0), f(c.p1), f(c.p2), f(c.p3))).collect()
|
||||
}
|
||||
|
||||
/// The quadrant of the `kind` spot for tone `u` (0..0.5) in a cell of half side `h`, its size from
|
||||
/// the kind's table ([`dot_sizes`]).
|
||||
fn spot_quadrant(u: f64, h: f64, kind: SpotKind) -> Vec<CubicBez> {
|
||||
let sizes = kind.table().get_or_init(|| dot_sizes(kind));
|
||||
let x = (u / 0.5).clamp(0.0, 1.0) * SIZE_STEPS as f64;
|
||||
let i = (x.floor() as usize).min(SIZE_STEPS - 1);
|
||||
let (lo, hi) = (sizes.get(i).copied().unwrap_or(0.0), sizes.get(i + 1).copied().unwrap_or(0.0));
|
||||
let a = lo + (hi - lo) * (x - i as f64);
|
||||
mapped(&kind.quadrant(a), |p| Point::new(p.x * h, p.y * h))
|
||||
}
|
||||
|
||||
/// A spot-function dot for tone `t` (0..1) in a cell of half side `h` centered on the origin: up to
|
||||
/// half tone, the `kind` dot with the tone's area (Euclidean: a circle clipped to the cell's
|
||||
/// diamond; Elliptical: an ellipse clipped to the cell's sides and its middle-tone cut); past half,
|
||||
/// the cell with the dot of the opposite tone cut out at each corner, so the dark joins up and the
|
||||
/// light becomes holes.
|
||||
fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
}
|
||||
};
|
||||
if t <= 0.5 {
|
||||
let q1 = spot_quadrant(t, h, kind);
|
||||
add(q1.clone(), true);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(-p.x, p.y))), false);
|
||||
add(mapped(&q1, |p| Point::new(-p.x, -p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x, -p.y))), false);
|
||||
} else {
|
||||
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
|
||||
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
|
||||
}
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
/// One screen: its ink and angle, and how to read its tone from a sampled pixel.
|
||||
struct Screen {
|
||||
paint: Color,
|
||||
@@ -399,6 +624,7 @@ pub fn halftone_art(d: &Document, n: &Node) -> Option<Node> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::Shape;
|
||||
|
||||
/// A black square's samples: `side` points of black from (10, 10), white around it.
|
||||
fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) {
|
||||
@@ -464,6 +690,73 @@ mod tests {
|
||||
assert_eq!(cmyk.layers(&one, Rect::new(2.0, 2.0, 18.0, 18.0), None).0.len(), 2);
|
||||
}
|
||||
|
||||
/// Is `p` (in cells of side 1) inside the dot `shape` draws for tone `t`?
|
||||
fn covers(shape: DotShape, t: f64, p: (f64, f64)) -> bool {
|
||||
fill_contains(&shape.path(t, 1.0).to_bezpath(), FillRule::NonZero, Point::new(p.0, p.1))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_dots_cover_the_tone() {
|
||||
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
|
||||
for k in 1..100 {
|
||||
let t = f64::from(k) / 100.0;
|
||||
let area = shape.path(t, 2.0).to_bezpath().area().abs() / 4.0;
|
||||
assert!((area - t).abs() < 2e-3, "{shape:?} at {t}: {area}");
|
||||
let b = shape.path(t, 2.0).control_bounds().unwrap();
|
||||
assert!(b.x0 >= -1.0 - 1e-9 && b.x1 <= 1.0 + 1e-9 && b.y0 >= -1.0 - 1e-9 && b.y1 <= 1.0 + 1e-9, "{shape:?} at {t}: {b:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!((DotShape::parse("Euclidean"), DotShape::parse("elliptical")), (Some(DotShape::Euclidean), Some(DotShape::Elliptical)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn euclidean_dots_meet_corner_to_corner_at_half() {
|
||||
let s = DotShape::Euclidean;
|
||||
// Round dots apart from their neighbors below half.
|
||||
assert!(!covers(s, 0.45, (0.49, 0.0)) && !covers(s, 0.45, (0.0, 0.49)) && covers(s, 0.45, (0.3, 0.0)));
|
||||
// At half the dot is the diamond reaching the middle of each side: a checkerboard.
|
||||
for p in [(0.49, 0.0), (-0.49, 0.0), (0.0, 0.49), (0.0, -0.49)] {
|
||||
assert!(covers(s, 0.5, p), "{p:?}");
|
||||
}
|
||||
assert!(!covers(s, 0.5, (0.26, 0.26)) && covers(s, 0.5, (0.24, 0.24)));
|
||||
// Past half the light becomes round holes at the corners.
|
||||
assert!(covers(s, 0.55, (0.0, 0.499)) && covers(s, 0.55, (0.499, 0.0)) && !covers(s, 0.55, (0.49, 0.49)));
|
||||
assert!(covers(s, 0.99, (0.3, 0.3)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elliptical_dots_join_along_their_length_then_their_width() {
|
||||
let s = DotShape::Elliptical;
|
||||
// Below 40% the dots stand apart.
|
||||
assert!(!covers(s, 0.38, (0.495, 0.0)) && !covers(s, 0.38, (0.0, 0.45)));
|
||||
// From 40% they reach their neighbors along x, making chains, but not along y.
|
||||
assert!(covers(s, 0.42, (0.495, 0.0)) && !covers(s, 0.42, (0.0, 0.45)));
|
||||
// The chains are bridges as tall as the tone allows across the shared side, not single
|
||||
// points: off the axis on the side x = 0.5, and on the cell's other side by symmetry.
|
||||
assert!(covers(s, 0.46, (0.499, 0.03)) && covers(s, 0.46, (-0.499, -0.03)) && !covers(s, 0.46, (0.499, 0.2)));
|
||||
assert!(covers(s, 0.5, (0.499, 0.12)) && !covers(s, 0.5, (0.499, 0.13)) && !covers(s, 0.5, (0.0, 0.49)));
|
||||
// Up to 60% the light still runs along the top edge between the corner holes.
|
||||
assert!(!covers(s, 0.55, (0.02, 0.499)) && covers(s, 0.55, (0.0, 0.3)));
|
||||
// Past 60% the dark joins across the top edge too, leaving elongated holes.
|
||||
assert!(covers(s, 0.65, (0.02, 0.499)) && covers(s, 0.65, (0.495, 0.0)) && !covers(s, 0.65, (0.49, 0.49)));
|
||||
// The holes are longer along x than along y.
|
||||
assert!(!covers(s, 0.8, (0.3, 0.49)) && covers(s, 0.8, (0.49, 0.3)), "ratio {ELLIPTICAL_RATIO}");
|
||||
// Today's Ellipse stays as it was: an ellipse 1.69 times as wide as tall.
|
||||
let b = DotShape::Ellipse.path(0.3, 1.0).control_bounds().unwrap();
|
||||
assert!((b.width() / b.height() - 1.69).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spot_shapes_make_dots_through_the_screen() {
|
||||
for shape in [DotShape::Euclidean, DotShape::Elliptical] {
|
||||
let h = Halftone::of(&effect(json!({"frequency": 18, "shape": format!("{shape:?}")}))).unwrap();
|
||||
assert_eq!(h.shape, shape);
|
||||
let (s, b) = black_square(60.0, &h);
|
||||
let (layers, dots) = h.layers(&s, b, None);
|
||||
assert!(layers.len() == 1 && (150..=320).contains(&dots), "{shape:?}: {dots}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_caps_refuse_too_many_cells() {
|
||||
let h = Halftone::of(&effect(json!({"frequency": 300}))).unwrap();
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Vector Halftone…",
|
||||
["Object"],
|
||||
None,
|
||||
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
"{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\"|\"euclidean\"|\"elliptical\" (circle; euclidean: round dots that meet corner to corner at 50%, then round holes; elliptical: long dots that join into chains at 40% and on all sides at 60%, then long holes), frequency?: lines per inch 1–300 (20), angle?: deg clockwise (45; 0: level rows of dots; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
|
||||
has_selection,
|
||||
halftone
|
||||
)]
|
||||
@@ -28,7 +28,9 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.vectorHalftone";
|
||||
let shape = match text_param(p, "shape", C)? {
|
||||
Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?,
|
||||
Some(v) => {
|
||||
DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line|euclidean|elliptical)")))?
|
||||
}
|
||||
None => DotShape::Circle,
|
||||
};
|
||||
let frequency = number_or(p, "frequency", 20.0, C)?;
|
||||
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New Document Profiles",
|
||||
[],
|
||||
None,
|
||||
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
|
||||
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), unusable?: why file.new does not read it (a link or a folder: new documents get the defaults, and file.newProfiles.edit refuses it), path?; customized, unusable and path left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
|
||||
always,
|
||||
list_profiles
|
||||
),
|
||||
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Profile",
|
||||
[],
|
||||
None,
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; an error when its file is a link or a folder, which file.new does not read either; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
|
||||
always,
|
||||
edit_profile
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset Profile",
|
||||
[],
|
||||
None,
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
|
||||
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again (a link is removed, not the file it leads to; a folder is not deleted, an error); an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
|
||||
always,
|
||||
reset_profile
|
||||
),
|
||||
@@ -996,6 +996,44 @@ pub fn profile_names() -> impl Iterator<Item = &'static str> {
|
||||
CATEGORIES.iter().map(|c| c.0)
|
||||
}
|
||||
|
||||
/// What is at a New Document profile's file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ProfileFile {
|
||||
/// Nothing: the shipped profile applies.
|
||||
None,
|
||||
/// A plain file, which `file.new` reads.
|
||||
Plain,
|
||||
/// A link or another entry that is not a plain file or a folder: `file.new` does not read it (the
|
||||
/// new document has the defaults), `file.newProfiles.edit` does not open it and
|
||||
/// `file.newProfiles.reset` removes it (a link, not what it leads to).
|
||||
NotPlain,
|
||||
/// A folder, which `file.new` does not read and `file.newProfiles.edit` does not open either.
|
||||
/// `file.newProfiles.reset` does not delete a folder.
|
||||
Folder,
|
||||
}
|
||||
|
||||
impl ProfileFile {
|
||||
/// Whether the category has a file in place of the shipped profile.
|
||||
pub fn customized(self) -> bool {
|
||||
self != Self::None
|
||||
}
|
||||
|
||||
/// Whether `file.newProfiles.reset` removes what is there.
|
||||
pub fn resettable(self) -> bool {
|
||||
matches!(self, Self::Plain | Self::NotPlain)
|
||||
}
|
||||
}
|
||||
|
||||
/// What is at `path`, looked at without following a link.
|
||||
fn profile_file(path: &std::path::Path) -> ProfileFile {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(m) if crate::store::is_plain(&m) => ProfileFile::Plain,
|
||||
Ok(m) if m.is_dir() && !crate::store::is_link_entry(&m) => ProfileFile::Folder,
|
||||
Ok(_) => ProfileFile::NotPlain,
|
||||
Err(_) => ProfileFile::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The profile `v` names (a built-in category, any case).
|
||||
fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> {
|
||||
let name = v.as_str().map(str::trim).unwrap_or_default();
|
||||
@@ -1022,9 +1060,9 @@ impl Session {
|
||||
Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION)))
|
||||
}
|
||||
|
||||
/// Whether profile `name` has a file, which `file.newProfiles.reset` deletes.
|
||||
pub fn new_doc_profile_customized(&self, name: &str) -> bool {
|
||||
self.profile_path(name).is_some_and(|p| p.is_file())
|
||||
/// What is at profile `name`'s file, looked at without following a link.
|
||||
pub fn new_doc_profile_file(&self, name: &str) -> ProfileFile {
|
||||
self.profile_path(name).map_or(ProfileFile::None, |p| profile_file(&p))
|
||||
}
|
||||
|
||||
/// Profile `name`'s document, its file's path and a warning for each color profile the file
|
||||
@@ -1045,7 +1083,7 @@ impl Session {
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
// A link is refused: the script's gate does not check where it leads.
|
||||
Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()),
|
||||
Ok(m) if !crate::store::is_plain(&m) => return Err(crate::store::NOT_PLAIN.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
@@ -1088,7 +1126,11 @@ fn list_profiles(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
// A request that may not read the folder learns nothing of its files.
|
||||
Some(path) => {
|
||||
if let Some(p) = shown(&path) {
|
||||
v["customized"] = json!(path.is_file());
|
||||
let file = profile_file(&path);
|
||||
v["customized"] = json!(file.customized());
|
||||
if matches!(file, ProfileFile::NotPlain | ProfileFile::Folder) {
|
||||
v["unusable"] = json!(crate::store::NOT_PLAIN);
|
||||
}
|
||||
v["path"] = json!(p);
|
||||
}
|
||||
}
|
||||
@@ -1121,12 +1163,19 @@ fn edit_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = file.to_string_lossy().to_string();
|
||||
// document.open reads it next: a profile it can't open is not written either.
|
||||
crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?;
|
||||
if !file.exists() {
|
||||
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
|
||||
file.parent()
|
||||
.map_or(Ok(()), std::fs::create_dir_all)
|
||||
.and_then(|()| std::fs::write(&file, bytes))
|
||||
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
|
||||
match profile_file(&file) {
|
||||
ProfileFile::Plain => {}
|
||||
// file.new does not read a link or a folder, so it is not opened as the profile either.
|
||||
ProfileFile::NotPlain | ProfileFile::Folder => return Err(profile_error(format!("{path}: {}", crate::store::NOT_PLAIN), &path)),
|
||||
// Made new, so a dangling link put there since is not written through.
|
||||
ProfileFile::None => {
|
||||
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
|
||||
file.parent()
|
||||
.map_or(Ok(()), std::fs::create_dir_all)
|
||||
.and_then(|()| std::fs::OpenOptions::new().write(true).create_new(true).open(&file))
|
||||
.and_then(|mut f| std::io::Write::write_all(&mut f, &bytes))
|
||||
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
|
||||
}
|
||||
}
|
||||
s.execute("document.open", &json!({ "path": path }))
|
||||
}
|
||||
@@ -1136,9 +1185,14 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?;
|
||||
let file = writable_profile(s, name, C)?;
|
||||
let path = file.to_string_lossy().to_string();
|
||||
if profile_file(&file) == ProfileFile::Folder {
|
||||
return Err(profile_error(format!("{path}: a folder, which Reset does not delete"), &path));
|
||||
}
|
||||
let reset = match std::fs::remove_file(&file) {
|
||||
Ok(()) => true,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
// On Windows a link to a folder, or a junction, is removed as a folder; what it leads to stays.
|
||||
Err(_) if std::fs::symlink_metadata(&file).is_ok_and(|m| crate::store::is_link_entry(&m)) && std::fs::remove_dir(&file).is_ok() => true,
|
||||
Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)),
|
||||
};
|
||||
Ok(json!({ "name": name, "reset": reset }))
|
||||
|
||||
@@ -646,10 +646,12 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
}
|
||||
|
||||
/// The ids of a document's page items, topmost first, each group or compound path before the
|
||||
/// objects in it ([`State`] keeps the lists of the last documents read).
|
||||
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// objects in it ([`State`] keeps the lists of the last documents read). Building the list again,
|
||||
/// after an edit or for another document, counts against the run's host-call allowance as a list
|
||||
/// of that many objects does ([`list_charge`]).
|
||||
fn page_items(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
|
||||
return ids;
|
||||
return Ok(ids);
|
||||
}
|
||||
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
|
||||
for n in nodes.iter().rev() {
|
||||
@@ -670,9 +672,16 @@ fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
}
|
||||
let mut ids = Vec::new();
|
||||
walk(&st.doc.layers, &mut ids);
|
||||
h.charge_call(list_charge(ids.len()))?;
|
||||
let ids = Rc::new(ids);
|
||||
keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone()));
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The bytes a list of `n` objects that a collection builds again counts against the run's
|
||||
/// host-call allowance, as the selection's list counts them ([`selection_of`]).
|
||||
pub(super) fn list_charge(n: usize) -> u64 {
|
||||
16u64.saturating_mul(n as u64)
|
||||
}
|
||||
|
||||
/// The objects directly in the layers and sublayers of a document: what deleting every page item
|
||||
@@ -932,8 +941,8 @@ fn on_doc_steps<T>(
|
||||
restored = restore_layer(h, uid, layer.0, &layer.1);
|
||||
}
|
||||
}
|
||||
// The document that was active is active again before any error is given: `f`'s error first,
|
||||
// then the selection's, then the switch back's.
|
||||
// The document that was active is active again before any error is given: an error that ends
|
||||
// the run first, then `f`'s error, then the selection's, then the switch back's.
|
||||
let back = match active {
|
||||
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
|
||||
_ => Ok(()),
|
||||
@@ -945,12 +954,35 @@ fn on_doc_steps<T>(
|
||||
{
|
||||
st.activated = activated;
|
||||
}
|
||||
first_error(r, restored, back)
|
||||
}
|
||||
|
||||
/// [`on_doc`]'s result from `f`'s result `r`, then putting back the selection and the layer
|
||||
/// (`restored`) and the active document (`back`): an error that ends the run first, since a
|
||||
/// script could catch `f`'s ordinary error, then the first error in that order.
|
||||
fn first_error<T>(
|
||||
r: std::result::Result<T, HostError>,
|
||||
restored: std::result::Result<(), HostError>,
|
||||
back: std::result::Result<(), HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
if !r.as_ref().is_err_and(ends_run) {
|
||||
restored.as_ref().err().into_iter().chain(back.as_ref().err()).find(|e| ends_run(e)).map_or(Ok(()), |e| Err(e.clone()))?;
|
||||
}
|
||||
let v = r?;
|
||||
restored?;
|
||||
back?;
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Whether `e` ends the run, so that a script cannot catch it.
|
||||
fn ends_run(e: &HostError) -> bool {
|
||||
match e {
|
||||
HostError::Abort(_) => true,
|
||||
HostError::Marked { error, .. } => ends_run(error),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
pub(super) fn after_kept_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
@@ -2112,7 +2144,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| page_items(h, st).len());
|
||||
let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
@@ -2153,7 +2185,7 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match position(*n) {
|
||||
Some(i) => Ok(item_at(h, doc, i)),
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
@@ -2164,8 +2196,8 @@ fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// The object at position `i` of `pageItems`, or `undefined` past the end.
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Data {
|
||||
with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(page_items(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2177,7 +2209,7 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
/// The first object of `pageItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
let ids = page_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -2189,7 +2221,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match position(*n).map(|i| item_at(h, doc, i)) {
|
||||
match position(*n).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
@@ -3269,6 +3301,24 @@ mod tests {
|
||||
assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into())));
|
||||
}
|
||||
|
||||
/// A stop from putting back the selection or the active document is not hidden by the edit's
|
||||
/// own error, which a script could catch; ordinary errors keep their order.
|
||||
#[test]
|
||||
fn an_edit_gives_a_stop_ahead_of_its_own_error() {
|
||||
let error = |m: &str| HostError::Error(m.into());
|
||||
let stop = || HostError::Abort("stop".into());
|
||||
let marked = || HostError::Marked { error: Box::new(stop()), mark: 0 };
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(stop()), Ok(())), Err(stop()));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Ok(()), Err(stop())), Err(stop()));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(marked())), Err(marked()));
|
||||
assert_eq!(first_error(Ok(1), Ok(()), Err(stop())), Err(stop()));
|
||||
// The edit's own stop comes first, and with no stop the edit's error does.
|
||||
assert_eq!(first_error::<()>(Err(HostError::Abort("edit".into())), Err(stop()), Ok(())), Err(HostError::Abort("edit".into())));
|
||||
assert_eq!(first_error::<()>(Err(error("edit")), Err(error("selection")), Err(error("back"))), Err(error("edit")));
|
||||
assert_eq!(first_error::<()>(Ok(()), Err(error("selection")), Err(error("back"))), Err(error("selection")));
|
||||
assert_eq!(first_error(Ok(1), Ok(()), Ok(())), Ok(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_item_lists_are_kept_for_several_documents() {
|
||||
let docs: Vec<Arc<Document>> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect();
|
||||
|
||||
@@ -367,16 +367,18 @@ fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
|
||||
|
||||
// ---- Document.pathItems ----
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// The ids of a document's paths, in the order of its page items. Building the list again counts
|
||||
/// the page items it looks through against the run's host-call allowance.
|
||||
fn path_items(h: &super::Host, st: &DocState) -> Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some(ids) = super::kept_list(&h.dom.paths, st) {
|
||||
return ids;
|
||||
return Ok(ids);
|
||||
}
|
||||
let all = super::page_items(h, st);
|
||||
let all = super::page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Rc<Vec<NodeId>> =
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect());
|
||||
super::keep_list(&h.dom.paths, st, &ids);
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -396,7 +398,7 @@ fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -408,14 +410,14 @@ fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st);
|
||||
let ids = path_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -438,10 +440,10 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st);
|
||||
let ids = path_items(h, st)?;
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused)
|
||||
});
|
||||
Ok::<_, HostError>((ids, refused))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
|
||||
|
||||
@@ -74,7 +74,7 @@ fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> Control
|
||||
Ok(())
|
||||
}),
|
||||
Owner::Doc(doc) => with_doc(h, doc, |_, st| {
|
||||
let ids = page_items(h, st);
|
||||
let ids = page_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
for id in ids.iter() {
|
||||
if let Some(n) = st.doc.node(*id) {
|
||||
|
||||
@@ -1233,18 +1233,21 @@ pub(super) fn doc_text_frames(link: &Link) -> HostMember {
|
||||
}
|
||||
|
||||
/// The ids of the document's type objects, topmost first as `pageItems` lists them, kept while the
|
||||
/// document is unchanged.
|
||||
fn frame_ids(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
|
||||
/// document is unchanged. Building the list again counts the page items it looks through against
|
||||
/// the run's host-call allowance.
|
||||
fn frame_ids(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow()
|
||||
&& *uid == st.uid
|
||||
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
{
|
||||
return ids.clone();
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids: Vec<NodeId> = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
|
||||
let all = page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let ids: Vec<NodeId> = all.iter().copied().filter(|i| text_of(st, *i).is_some()).collect();
|
||||
let ids = Rc::new(ids);
|
||||
*h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone()));
|
||||
ids
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
@@ -1253,7 +1256,7 @@ fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
|
||||
fn frames_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -1265,14 +1268,14 @@ fn frames_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn frames_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = frame_ids(h, st);
|
||||
let ids = frame_ids(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -1364,13 +1367,13 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
|
||||
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = frame_ids(h, st);
|
||||
let ids = frame_ids(h, st)?;
|
||||
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
|
||||
let locks = st.doc.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused, on_locked)
|
||||
});
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
|
||||
|
||||
@@ -633,7 +633,7 @@ fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostEr
|
||||
{
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids = frame_ids(h, st);
|
||||
let ids = frame_ids(h, st)?;
|
||||
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
|
||||
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
|
||||
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
|
||||
|
||||
@@ -222,6 +222,18 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
/// What [`read_capped_plain`] tells a path that is not a plain file.
|
||||
pub(crate) const NOT_PLAIN: &str = "not a plain file";
|
||||
|
||||
/// Whether `m`, read without following a link, is a plain file: not a link, a folder or (on Windows)
|
||||
/// a junction or other reparse point.
|
||||
pub(crate) fn is_plain(m: &std::fs::Metadata) -> bool {
|
||||
m.file_type().is_file() && !reparse_point(m)
|
||||
}
|
||||
|
||||
/// Whether `m`, read without following a link, is a link (on Windows also a junction or other
|
||||
/// reparse point).
|
||||
pub(crate) fn is_link_entry(m: &std::fs::Metadata) -> bool {
|
||||
m.file_type().is_symlink() || reparse_point(m)
|
||||
}
|
||||
|
||||
/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without
|
||||
/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and
|
||||
/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check
|
||||
|
||||
@@ -1168,6 +1168,70 @@ fn a_profile_that_is_a_link_is_not_followed() {
|
||||
assert!(r.get("profile").is_none(), "{r}");
|
||||
}
|
||||
|
||||
/// The listing entry of profile `name`.
|
||||
fn listed_profile(s: &mut Session, name: &str) -> Value {
|
||||
let listed = s.execute("file.newProfiles", &json!({})).unwrap();
|
||||
listed["profiles"].as_array().unwrap().iter().find(|p| p["name"] == name).cloned().unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_linked_profile_is_listed_as_unusable_and_reset_removes_the_link() {
|
||||
use crate::cmd::newdoc::ProfileFile;
|
||||
let (mut s, dir, root) = with_profiles("linked-listing");
|
||||
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
|
||||
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::Plain);
|
||||
assert!(listed_profile(&mut s, "Print").get("unusable").is_none());
|
||||
let outside = root.join("outside.vectorcraft");
|
||||
std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap();
|
||||
|
||||
// file.new does not read it, so the listing says so, and Edit does not open it.
|
||||
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::NotPlain);
|
||||
assert!(ProfileFile::NotPlain.resettable());
|
||||
let p = listed_profile(&mut s, "Print");
|
||||
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
|
||||
let e = s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap_err().to_string();
|
||||
assert!(e.contains("not a plain file"), "{e}");
|
||||
// Reset removes the link and leaves the file it led to.
|
||||
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap()["reset"], true);
|
||||
assert!(std::fs::symlink_metadata(dir.join("Print.vectorcraft")).is_err() && outside.is_file());
|
||||
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_profile_link_to_nothing_is_listed_and_edit_does_not_write_through_it() {
|
||||
let (mut s, dir, root) = with_profiles("dangling");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let outside = root.join("outside.vectorcraft");
|
||||
std::os::unix::fs::symlink(&outside, dir.join("Web.vectorcraft")).unwrap();
|
||||
let p = listed_profile(&mut s, "Web");
|
||||
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
|
||||
assert!(s.execute("file.newProfiles.edit", &json!({"name": "Web"})).is_err());
|
||||
assert!(!outside.exists(), "Edit wrote the shipped profile where the link leads");
|
||||
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Web"})).unwrap()["reset"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_in_a_profiles_place_is_listed_as_unusable() {
|
||||
let (mut s, dir, _root) = with_profiles("folder");
|
||||
std::fs::create_dir_all(dir.join("Mobile.vectorcraft")).unwrap();
|
||||
let p = listed_profile(&mut s, "Mobile");
|
||||
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
|
||||
let e = s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap_err().to_string();
|
||||
assert!(e.contains("not a plain file"), "{e}");
|
||||
let r = s.execute("file.new", &json!({"profile": "Mobile"})).unwrap();
|
||||
assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}");
|
||||
// Reset does not delete a folder, and Manage Profiles turns it off.
|
||||
let file = s.new_doc_profile_file("Mobile");
|
||||
assert_eq!(file, crate::cmd::newdoc::ProfileFile::Folder);
|
||||
assert!(file.customized() && !file.resettable());
|
||||
let e = s.execute("file.newProfiles.reset", &json!({"name": "Mobile"})).unwrap_err().to_string();
|
||||
assert!(e.contains("a folder"), "{e}");
|
||||
assert!(dir.join("Mobile.vectorcraft").is_dir());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_names_are_checked_and_editing_needs_the_folder() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -2468,8 +2468,17 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() {
|
||||
assert_eq!(out[0][0].as_array().map(Vec::len), Some(3));
|
||||
// Each pass edits the document, so nothing kept from the last read can be reused.
|
||||
let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;";
|
||||
// The script's fuel, and the host's calls and the bytes they count, which hold the work the
|
||||
// host does for them: 64 KiB is less than one list of the large document's objects.
|
||||
let cost = |s: &mut Session| {
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
|
||||
let r = run(s, edits);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let r = r.unwrap_or_else(|e| panic!("the reads went over: {e}"));
|
||||
(r["fuelUsed"].as_u64().unwrap(), r["hostCalls"].as_u64().unwrap())
|
||||
};
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap();
|
||||
let small = cost(&mut s);
|
||||
// 3 objects doubled 11 times: 6,144.
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
for _ in 0..11 {
|
||||
@@ -2477,11 +2486,39 @@ fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() {
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
|
||||
let large = run(&mut s, edits);
|
||||
assert_eq!(small, cost(&mut s));
|
||||
}
|
||||
|
||||
/// Building a collection's list again after an edit counts the objects it lists against the
|
||||
/// run's allowance, so a loop that edits and reads `pageItems`, `pathItems` or `textFrames` in a
|
||||
/// large document ends with the limit instead of walking the document each time for nothing.
|
||||
#[test]
|
||||
fn rebuilding_a_collection_after_an_edit_counts_against_the_run() {
|
||||
let (mut s, a, _) = doc();
|
||||
let source = |list: &str| {
|
||||
format!("var d = app.activeDocument, it = d.pageItems[0]; for (var i = 0; i < 40; i++) {{ it.opacity = 50 + i % 2; d.{list}.length; }}")
|
||||
};
|
||||
let lists = ["pageItems", "pathItems", "textFrames"];
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20)));
|
||||
let small: Vec<bool> = lists.iter().map(|l| run(&mut s, &source(l)).is_ok()).collect();
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap();
|
||||
assert_eq!(small, large);
|
||||
assert_eq!(small, vec![true; 3], "a small document stays under 1 MiB");
|
||||
// 2 objects doubled 11 times: 4,096, a list of 64 KiB each time it is built again.
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
for _ in 0..11 {
|
||||
s.execute("edit.duplicate", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
}
|
||||
// Nothing selected, so putting the selection back after each edit passes no list of ids.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
for list in lists {
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20)));
|
||||
let r = run(&mut s, &source(list));
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("{list}: 40 lists of 4,096 objects stayed under 1 MiB: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("passed more data to and from commands"), "{list}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A collection read with a name gives what `getByName` gives, and throws as it does for no match.
|
||||
|
||||
@@ -744,20 +744,41 @@ fn objects_beyond_the_document_range_are_left_out() {
|
||||
assert!(loaded.warnings.iter().any(|w| w.contains("beyond the document range")), "{:?}", loaded.warnings);
|
||||
}
|
||||
|
||||
/// A magenta rectangle with a Recolor adjustment (`RcRA`) attached, at `lightness`.
|
||||
fn recolored(visible: bool, lightness: f64) -> F {
|
||||
let mut node = rectangle(10, (0.0, 0.0), (50.0, 50.0));
|
||||
let recolor = F::Def(
|
||||
20,
|
||||
vec![tag(b"RcRA")],
|
||||
vec![
|
||||
(tag(b"Visi"), F::Bool(visible)),
|
||||
(tag(b"AdjP"), F::Obj(tag(b"RecP"), vec![(tag(b"RecH"), F::F64(0.0)), (tag(b"RecS"), F::F64(1.0)), (tag(b"RecL"), F::F64(lightness))])),
|
||||
],
|
||||
);
|
||||
if let F::Def(_, _, fields) = &mut node {
|
||||
fields.push((tag(b"AdCh"), F::Shared(vec![recolor])));
|
||||
}
|
||||
node
|
||||
}
|
||||
|
||||
fn first_fill(n: &Node) -> Paint {
|
||||
let Some(AppearanceItem::Fill(fill)) = n.appearance.items.first() else { panic!("no fill: {:?}", n.appearance) };
|
||||
fill.paint.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_af_g_symbol_fill_is_white() {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test.af");
|
||||
let Ok(bytes) = std::fs::read(&path) else {
|
||||
return;
|
||||
};
|
||||
let loaded = vectorcraft_engine::cmd::fileio::load("test.af", &bytes).unwrap();
|
||||
assert!(!loaded.preview_only, "{:?}", loaded.warnings);
|
||||
let d = &loaded.doc;
|
||||
// The visible "g41" group holds the "g" symbol (path43).
|
||||
let g41 = all(d).into_iter().find(|n| n.visible && n.name.as_deref() == Some("g41")).expect("visible g41 group must be present");
|
||||
let path43 = g41.children().and_then(|c| c.iter().find(|n| n.name.as_deref() == Some("path43"))).expect("path43 inside g41 must be present");
|
||||
let Some(AppearanceItem::Fill(fill)) = path43.appearance.items.first() else {
|
||||
panic!("path43 has no fill: {:?}", path43.appearance);
|
||||
};
|
||||
assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 1.0, 1.0)), "The 'g' symbol must have a white fill in test.af, got {:?}", fill.paint);
|
||||
fn attached_recolor_adjustments_recolor_the_shape() {
|
||||
// Lightness 1 recolors to white.
|
||||
let loaded = open("recolor.af", &canvas_with(vec![recolored(true, 1.0)], None));
|
||||
assert!(!loaded.warnings.iter().any(|w| w.contains("attached to other layers")), "{:?}", loaded.warnings);
|
||||
let rect = named(&loaded.doc, "Magenta box");
|
||||
assert!(rect.appearance.effects.is_empty());
|
||||
assert_eq!(first_fill(rect), Paint::solid(Color::rgb(1.0, 1.0, 1.0)));
|
||||
// Lightness 0.5 at hue 0 and full saturation is pure red.
|
||||
let d = open("red.af", &canvas_with(vec![recolored(true, 0.5)], None)).doc;
|
||||
let [r, g, b, a] = pixel(&d, 25, 25);
|
||||
assert!(r > 250 && g < 5 && b < 5 && a == 255, "{:?}", [r, g, b, a]);
|
||||
// A hidden adjustment leaves the shape as it is.
|
||||
let d = open("hidden.af", &canvas_with(vec![recolored(false, 1.0)], None)).doc;
|
||||
assert_eq!(first_fill(named(&d, "Magenta box")), Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)));
|
||||
}
|
||||
@@ -874,6 +874,29 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() {
|
||||
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into()));
|
||||
}
|
||||
|
||||
/// An answer that cannot be read as a value, for a global function or a member of a host class,
|
||||
/// is thrown at the call that waited, where the script catches it, and the run goes on.
|
||||
#[test]
|
||||
fn an_answer_that_cannot_be_read_is_thrown_at_the_waiting_call() {
|
||||
let mut nested = Data::Null;
|
||||
for _ in 0..20 {
|
||||
nested = Data::Array(vec![nested]);
|
||||
}
|
||||
for call in ["ask('x')", "thing.fetch()"] {
|
||||
let source = format!("var m = 'none'; try {{ {call}; }} catch (e) {{ m = e.name + '|' + e.message; }} m + '|after'");
|
||||
let mut r = realm(1_000_000);
|
||||
with_ask(&mut r);
|
||||
with_thing(&mut r, None);
|
||||
r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 });
|
||||
r.start(&source).unwrap();
|
||||
assert_eq!(r.advance(1_000).unwrap(), Progress::Paused);
|
||||
assert!(r.waits());
|
||||
r.answer(nested.clone()).unwrap();
|
||||
let JsValue::String(out) = finish(&mut r, 1_000).0.unwrap() else { panic!("{call}: not a string") };
|
||||
assert!(out.starts_with("RangeError|") && out.contains("nested too deep") && out.ends_with("|after"), "{call}: {out}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by
|
||||
/// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing`
|
||||
/// with the handle `[0]`.
|
||||
|
||||
+38
-4
@@ -254,8 +254,10 @@ pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult<Pause>
|
||||
/// resume function gives.
|
||||
pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult<Value>;
|
||||
|
||||
/// What a [`Pause`] does with its kept values when its host call fails.
|
||||
pub(crate) type FailFn = fn(&mut Interp, &[Value]);
|
||||
/// What a [`Pause`] does with its kept values when its host call fails. An error it gives that is
|
||||
/// not thrown (a stop, such as a host's Abort) ends the run in place of a thrown failure; a thrown
|
||||
/// one gives way to the failure.
|
||||
pub(crate) type FailFn = fn(&mut Interp, &[Value]) -> JsResult<()>;
|
||||
|
||||
/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to
|
||||
/// `resume` with `keep`, at once when the host answers at once. When the host waits
|
||||
@@ -274,6 +276,23 @@ pub(crate) struct Pause {
|
||||
pub(crate) struct Resumption {
|
||||
resume: ResumeFn,
|
||||
keep: Vec<Value>,
|
||||
/// Runs when the answer cannot be read, so the resume function never gets it.
|
||||
failed: Option<FailFn>,
|
||||
}
|
||||
|
||||
impl Resumption {
|
||||
/// The built-in does not get the host's answer: its failure function runs with its kept
|
||||
/// values, which `thrown` is kept from collection with. → the stop the failure function
|
||||
/// gave, which ends the run in place of `thrown`.
|
||||
pub(crate) fn fail(self, interp: &mut Interp, thrown: &Value) -> JsResult<()> {
|
||||
let Some(failed) = self.failed else { return Ok(()) };
|
||||
let mark = interp.temp_roots.len();
|
||||
interp.temp_roots.extend(self.keep.iter().cloned());
|
||||
interp.temp_roots.push(thrown.clone());
|
||||
let r = failed(interp, &self.keep);
|
||||
interp.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Interp {
|
||||
@@ -378,6 +397,10 @@ pub(crate) struct Interp {
|
||||
/// The call that waits is a member of a host class ([`crate::host::ArgRead::Hosted`]): its
|
||||
/// answer is read as such a member's result is ([`Interp::write_hosted`]).
|
||||
pub(crate) waiting_hosted: bool,
|
||||
/// The answer to the call that waited could not be read as a value
|
||||
/// ([`crate::Realm::answer`]): the value on top of the stack is the exception, which the next
|
||||
/// step throws at that call.
|
||||
pub(crate) answer_throws: bool,
|
||||
/// A host class's constructor runs with `new`: it may not wait for its result.
|
||||
pub(crate) constructing: bool,
|
||||
/// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before
|
||||
@@ -690,6 +713,7 @@ impl Interp {
|
||||
can_wait: Rc::default(),
|
||||
waiting: false,
|
||||
waiting_hosted: false,
|
||||
answer_throws: false,
|
||||
constructing: false,
|
||||
resuming: None,
|
||||
again: None,
|
||||
@@ -1031,6 +1055,11 @@ impl Interp {
|
||||
|
||||
fn step(&mut self) -> JsResult<Option<Value>> {
|
||||
self.tick()?;
|
||||
// An answer that could not be read is thrown at the call that waited for it.
|
||||
if std::mem::take(&mut self.answer_throws) {
|
||||
let thrown = self.pop()?;
|
||||
return Err(Abrupt::Throw(thrown));
|
||||
}
|
||||
// A built-in that waited for the host takes the answer on top of the stack before the
|
||||
// instruction after its call runs; what it throws is thrown at that call.
|
||||
if let Some(r) = self.resuming.take() {
|
||||
@@ -3560,6 +3589,7 @@ impl Interp {
|
||||
Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read),
|
||||
_ => self.call(&host, &Value::Undefined, &args),
|
||||
};
|
||||
let mut stop = Ok(());
|
||||
if let Err(e) = &answer
|
||||
&& let Some(failed) = failed
|
||||
{
|
||||
@@ -3567,11 +3597,15 @@ impl Interp {
|
||||
if let Abrupt::Throw(v) = e {
|
||||
self.temp_roots.push(v.clone());
|
||||
}
|
||||
failed(self, &keep);
|
||||
stop = failed(self, &keep);
|
||||
}
|
||||
self.temp_roots.truncate(mark);
|
||||
// A stop from `failed` is not masked by a thrown error the script could catch.
|
||||
if matches!(answer, Err(Abrupt::Throw(_))) {
|
||||
stop?;
|
||||
}
|
||||
let answer = answer?;
|
||||
let r = Resumption { resume, keep };
|
||||
let r = Resumption { resume, keep, failed };
|
||||
if self.waiting && !was_waiting {
|
||||
self.resuming = Some(r);
|
||||
return Ok(answer);
|
||||
|
||||
+28
-6
@@ -380,6 +380,7 @@ impl Realm {
|
||||
interp.host_abort = None;
|
||||
interp.waiting = false;
|
||||
interp.waiting_hosted = false;
|
||||
interp.answer_throws = false;
|
||||
interp.constructing = false;
|
||||
interp.resuming = None;
|
||||
interp.again = None;
|
||||
@@ -426,6 +427,7 @@ impl Realm {
|
||||
interp.join_stack.clear();
|
||||
interp.waiting = false;
|
||||
interp.waiting_hosted = false;
|
||||
interp.answer_throws = false;
|
||||
interp.constructing = false;
|
||||
interp.resuming = None;
|
||||
interp.again = None;
|
||||
@@ -566,8 +568,10 @@ impl Realm {
|
||||
/// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next
|
||||
/// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the
|
||||
/// call, the built-in takes `d` first and gives its own result, and what it throws is thrown
|
||||
/// at its call. A result past the heap limit ends the run with that
|
||||
/// limit, and with no call waiting this gives an internal error.
|
||||
/// at its call. A result that cannot be read as a value, such as one nested too deep, is
|
||||
/// thrown at the call as an immediate result would be, and the built-in does not get it. A
|
||||
/// result past the heap limit ends the run with that limit, and with no call waiting this gives
|
||||
/// an internal error.
|
||||
pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> {
|
||||
let interp = &mut self.interp;
|
||||
if !interp.waiting {
|
||||
@@ -584,10 +588,28 @@ impl Realm {
|
||||
let hosted = std::mem::take(&mut interp.waiting_hosted);
|
||||
// The value on top of the stack stood in for the result.
|
||||
let written = if hosted { interp.write_hosted(d) } else { interp.write_data(d, 0, false) };
|
||||
let r = written.and_then(|v| {
|
||||
interp.stack.pop();
|
||||
interp.push(v)
|
||||
});
|
||||
let r = match written {
|
||||
// An answer that cannot be read as a value (too deep, too many entries, a stale host
|
||||
// reference) is thrown at the call, where the script can catch it, and a built-in
|
||||
// that waited with the call does not get it: it fails as when its host call throws. A
|
||||
// stop its failure gives (an Abort from the host) ends the run before the error is
|
||||
// thrown.
|
||||
Err(Abrupt::Throw(thrown)) => {
|
||||
interp.stack.pop();
|
||||
let stop = match interp.resuming.take() {
|
||||
Some(r) => r.fail(interp, &thrown),
|
||||
None => Ok(()),
|
||||
};
|
||||
stop.and_then(|()| {
|
||||
interp.answer_throws = true;
|
||||
interp.push(thrown)
|
||||
})
|
||||
}
|
||||
written => written.and_then(|v| {
|
||||
interp.stack.pop();
|
||||
interp.push(v)
|
||||
}),
|
||||
};
|
||||
match r {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => self.outcome(Err(e)).map(drop),
|
||||
|
||||
@@ -1543,16 +1543,21 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult<Pause> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing.
|
||||
fn failed(i: &mut Interp, keep: &[Value]) {
|
||||
let Some(win) = arg(keep, 0).as_object() else { return };
|
||||
/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. → a stop
|
||||
/// (an Abort) the host's `end` gave; an error `end` throws gives way to the failure.
|
||||
fn failed(i: &mut Interp, keep: &[Value]) -> JsResult<()> {
|
||||
let Some(win) = arg(keep, 0).as_object() else { return Ok(()) };
|
||||
if classes(i).ok().and_then(|c| c.showing) != Some(win) {
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
set_showing(i, None);
|
||||
if let Ok(end) = host_fn(i, "end") {
|
||||
let _ = i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]);
|
||||
match i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]) {
|
||||
Ok(_) | Err(Abrupt::Throw(_)) => {}
|
||||
Err(stop) => return Err(stop),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `show()` ends with `result`.
|
||||
@@ -1611,10 +1616,15 @@ fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResu
|
||||
Abrupt::Throw(t) => vec![t.clone()],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let thrown_error = !thrown.is_empty();
|
||||
let mark = i.temp_roots.len();
|
||||
i.temp_roots.extend(thrown);
|
||||
failed(i, keep);
|
||||
let stop = failed(i, keep);
|
||||
i.temp_roots.truncate(mark);
|
||||
// A stop from `end` is not masked by a thrown error the script could catch.
|
||||
if thrown_error {
|
||||
stop?;
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
@@ -229,6 +229,82 @@ fn a_dialog_can_be_shown_again_after_it_closed() {
|
||||
assert_eq!(r.run(&format!("{FORM} [w.show(), w.show()].join()")).unwrap(), JsValue::String("1,2".into()));
|
||||
}
|
||||
|
||||
/// An event the host gives a waiting `show()` that cannot be read is thrown at `show()`, and the
|
||||
/// dialog is no longer showing, so it can be shown again.
|
||||
#[test]
|
||||
fn an_event_that_cannot_be_read_ends_show_and_the_dialog_can_show_again() {
|
||||
let (mut r, seen, _) = realm(Vec::new());
|
||||
r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 });
|
||||
let mut nested = Data::Null;
|
||||
for _ in 0..20 {
|
||||
nested = Data::Array(vec![nested]);
|
||||
}
|
||||
r.start("var w = new Window('dialog'), m = 'none'; try { w.show(); } catch (e) { m = e.name; } m + '|' + w.show()").unwrap();
|
||||
assert_eq!(r.advance(100_000).unwrap(), Progress::Paused);
|
||||
assert!(r.waits());
|
||||
r.answer(nested).unwrap();
|
||||
assert_eq!(seen.borrow().ends, vec![(0.0, false)], "show ended without its result");
|
||||
assert_eq!(r.advance(100_000).unwrap(), Progress::Paused);
|
||||
assert!(r.waits(), "the second show waits for its event");
|
||||
r.answer(close()).unwrap();
|
||||
let mut out = r.advance(100_000).unwrap();
|
||||
while out == Progress::Paused {
|
||||
out = r.advance(100_000).unwrap();
|
||||
}
|
||||
assert_eq!(out, Progress::Done(JsValue::String("RangeError|0".into())));
|
||||
assert_eq!(seen.borrow().ends, vec![(0.0, false), (0.0, true)]);
|
||||
}
|
||||
|
||||
/// A realm whose `end` stops the run (an Abort) when `show()` ends without its result, whose
|
||||
/// `open` throws when `open_fails`, and whose `wait` gives `events` in order, then waits.
|
||||
fn stopping_realm(open_fails: bool, events: Vec<Data>) -> Realm {
|
||||
let mut r = Realm::new();
|
||||
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
let queue = RefCell::new(VecDeque::from(events));
|
||||
let open: HostFunction = Rc::new(move |_| if open_fails { Err(HostError::Error("no window".into())) } else { Ok(Data::Undefined) });
|
||||
let wait: HostFunction = Rc::new(move |_| queue.borrow_mut().pop_front().ok_or(HostError::Wait));
|
||||
let end: HostFunction = Rc::new(|args| match args.get(1) {
|
||||
Some(Data::Bool(true)) => Ok(Data::Undefined),
|
||||
_ => Err(HostError::Abort("stopped by the host".into())),
|
||||
});
|
||||
let items = vec![("open".into(), HostItem::Function(open)), ("wait".into(), HostItem::Function(wait)), ("end".into(), HostItem::Function(end))];
|
||||
r.define_script_ui(items).unwrap();
|
||||
r
|
||||
}
|
||||
|
||||
fn is_host_stop(e: &RunError) -> bool {
|
||||
e.kind == RunErrorKind::Limit(LimitKind::Host) && e.message == "stopped by the host"
|
||||
}
|
||||
|
||||
/// A stop the host's `end` gives when `show()` fails ends the run: the script cannot catch the
|
||||
/// failure and go on, whether the event could not be read, the host call threw or a handler threw.
|
||||
#[test]
|
||||
fn a_stop_from_end_when_show_fails_ends_the_run() {
|
||||
let caught = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { throw new Error('handler'); }; \
|
||||
try { w.show(); } catch (e) {} 'went on'";
|
||||
|
||||
let mut r = stopping_realm(false, Vec::new());
|
||||
r.set_data_limits(DataLimits { depth: 8, bytes: 16 << 20, entries: 1_000 });
|
||||
let mut nested = Data::Null;
|
||||
for _ in 0..20 {
|
||||
nested = Data::Array(vec![nested]);
|
||||
}
|
||||
r.start(caught).unwrap();
|
||||
assert_eq!(r.advance(100_000).unwrap(), Progress::Paused);
|
||||
assert!(r.waits());
|
||||
let answered = r.answer(nested);
|
||||
assert!(answered.as_ref().is_err_and(is_host_stop), "unreadable event: {answered:?}");
|
||||
|
||||
let mut r = stopping_realm(true, Vec::new());
|
||||
let ran = r.run(caught);
|
||||
assert!(ran.as_ref().is_err_and(is_host_stop), "open threw: {ran:?}");
|
||||
|
||||
let mut r = stopping_realm(false, vec![click(1)]);
|
||||
let ran = r.run(caught);
|
||||
assert!(ran.as_ref().is_err_and(is_host_stop), "handler threw: {ran:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn types_that_are_not_available_yet_throw_errors_that_say_so() {
|
||||
for (source, want) in [
|
||||
|
||||
@@ -1192,7 +1192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"tool.options",
|
||||
"Tool Options…",
|
||||
"",
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options,
Line truncated
|
||||
"{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyl
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
@@ -1531,7 +1531,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
@@ -1549,19 +1549,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.simplifyAuto",
|
||||
"Auto-Simplify",
|
||||
"",
|
||||
"{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open",
|
||||
"{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `simplifySlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open",
|
||||
),
|
||||
(
|
||||
"ui.smoothAuto",
|
||||
"Auto-Smooth",
|
||||
"",
|
||||
"{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open",
|
||||
"{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `smoothSlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open",
|
||||
),
|
||||
(
|
||||
"ui.simplifyMoreOptions",
|
||||
"More Options",
|
||||
"",
|
||||
"{} the Simplify dialog (dialog `simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open",
|
||||
"{} the Simplify dialog (dialog `object.path.simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open",
|
||||
),
|
||||
(
|
||||
"ui.dialogReset",
|
||||
|
||||
@@ -59,7 +59,7 @@ pub fn interior_point(path: &PathData) -> Option<Point>;
|
||||
|
||||
Unlike `regions`, which splits the filled areas of closed shapes, `live_paint` treats every path as an edge, open paths included. Three crossing lines enclose a triangle, a line across a rectangle splits it in two, and an area enclosed by paths becomes a face even when nothing fills it. Each face lists the inputs whose fill covers it; the list is empty for an area that is only enclosed by paths. Each edge is a piece of a path, split wherever another path meets it, and keeps the key of the front-most input it lies on.
|
||||
|
||||
`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas.
|
||||
`shape_builder` gives the Shape Builder's regions. With closed paths only, they are the `regions`. Once an open path is among them, they are the `live_paint` faces, so a stroke-only line across a shape splits it and lines can enclose a region of their own. The second list holds the pieces of each path that has no closed subpath, keyed by its index, so the Shape Builder can delete them one by one. The caller closes any open path whose fill should count. Inputs with more than `SHAPE_BUILDER_MAX_SEGMENTS` segments fall back to the filled areas. When the paths cross each other so often that the sweep cuts them into more than `SHAPE_BUILDER_MAX_MAP_EDGES` pieces, it skips the full map and returns only the regions of the filled areas, which are capped on their own: a filled shape apart from open paths that cross too often still has its region.
|
||||
|
||||
```rust
|
||||
pub struct Adjacency { pub faces: Vec<MapFace>, pub edges: Vec<MapEdge>, pub slivers: Vec<PathData>, pub outlines: Vec<MapOutline> }
|
||||
|
||||
@@ -33,8 +33,9 @@ pub use pathfinder::{
|
||||
FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within,
|
||||
};
|
||||
pub use planar::{
|
||||
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out,
|
||||
encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
|
||||
Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS,
|
||||
adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder,
|
||||
shape_builder_with_gap,
|
||||
};
|
||||
pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within};
|
||||
pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band};
|
||||
|
||||
@@ -561,6 +561,16 @@ pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec<Region> {
|
||||
arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`regions_with`], or `None` when the sweep cuts the shapes into more than `max_edges` pieces
|
||||
/// (the faces are then not built).
|
||||
pub(crate) fn regions_capped(shapes: &[Shape], precision: f64, max_edges: usize) -> Option<Vec<Region>> {
|
||||
let Some(a) = arrangement(shapes, precision) else { return Some(Vec::new()) };
|
||||
if a.top.segment_indices().nth(max_edges).is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(regions_of(&a))
|
||||
}
|
||||
|
||||
/// [`regions`] when there are at most `limit` of them; `None` when there are more, found as soon
|
||||
/// as the face past `limit` is built (the faces after it are not built).
|
||||
pub fn regions_within(shapes: &[Shape], limit: usize) -> Option<Vec<Region>> {
|
||||
|
||||
@@ -41,8 +41,8 @@ pub use live_paint::{find_gaps, live_paint, live_paint_with_gaps};
|
||||
pub use map::interior_point;
|
||||
pub(crate) use map::{Map, Rest, map};
|
||||
pub use shape_builder::{
|
||||
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path, run_around, shape_builder,
|
||||
shape_builder_with_gap,
|
||||
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_MAP_EDGES, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, has_open_path,
|
||||
run_around, shape_builder, shape_builder_with_gap,
|
||||
};
|
||||
pub(crate) use shape_builder::{builder, gap_inputs};
|
||||
|
||||
|
||||
@@ -42,6 +42,11 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> {
|
||||
|
||||
/// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped.
|
||||
pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {
|
||||
map_within(shapes, cover, precision, usize::MAX)
|
||||
}
|
||||
|
||||
/// [`map_with`], or `None` when the sweep cuts the paths into more than `max_edges` pieces.
|
||||
pub(super) fn map_within(shapes: &[Shape], cover: bool, precision: f64, max_edges: usize) -> Option<Map> {
|
||||
let mut inputs: Vec<(BezPath, usize)> = Vec::new();
|
||||
for (i, s) in shapes.iter().enumerate() {
|
||||
let mut bp = BezPath::new();
|
||||
@@ -69,7 +74,7 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<
|
||||
return None;
|
||||
}
|
||||
let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0));
|
||||
let (points, edges) = sweep_graph(&inputs, eps, precision)?;
|
||||
let (points, edges) = sweep_graph(&inputs, eps, precision, max_edges)?;
|
||||
let nv = points.len();
|
||||
|
||||
// Half-edges leaving each vertex, sorted by direction; walking a face, the next half-edge is
|
||||
@@ -188,11 +193,17 @@ pub(super) fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<
|
||||
Some(Map { edges, around, slot_of, faces, face_index, slivers, holes, face_holes, tidy, anchors, snap })
|
||||
}
|
||||
|
||||
fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64) -> Option<(Vec<Point>, Vec<Edge>)> {
|
||||
fn sweep_graph(inputs: &[(BezPath, usize)], eps: f64, precision: f64, max_edges: usize) -> Option<(Vec<Point>, Vec<Edge>)> {
|
||||
// The sweep can panic on rare near-degenerate input; that must never take the app down.
|
||||
let sweep =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::<Crossings>::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps)));
|
||||
let top = sweep.ok()?.ok()?;
|
||||
// What is built from here on takes time and memory in proportion to the pieces the sweep cut
|
||||
// the paths into, and paths that cross many times are cut into far more pieces than they have
|
||||
// segments.
|
||||
if top.segment_indices().nth(max_edges).is_some() {
|
||||
return None;
|
||||
}
|
||||
// The planar graph: vertices are the sweep's points, edges its segments. Points closer than
|
||||
// the sweep's tolerance are one vertex (it can put a corner that lies on another path's edge
|
||||
// a rounding error away from where it cuts that edge).
|
||||
@@ -426,8 +437,9 @@ impl Map {
|
||||
/// Faces and edges of `shapes`, and the pieces of the open paths (those with no closed subpath)
|
||||
/// that lie under another path in front of them, whose edges are that path's: under a closed
|
||||
/// path's outline, or along an open path in front.
|
||||
/// `None` when the sweep cuts the paths into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces.
|
||||
pub(super) fn build(shapes: &[Shape], precision: f64) -> Option<(Vec<Region>, Vec<Shape>, Vec<Shape>)> {
|
||||
let m = map_with(shapes, false, precision)?;
|
||||
let m = map_within(shapes, false, precision, SHAPE_BUILDER_MAX_MAP_EDGES)?;
|
||||
let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m;
|
||||
let snap = *snap;
|
||||
let fills: Vec<Fill> = shapes.iter().map(Fill::new).collect();
|
||||
|
||||
@@ -9,6 +9,16 @@ use super::*;
|
||||
/// can take on art far past what a drawing holds.
|
||||
pub const SHAPE_BUILDER_MAX_SEGMENTS: usize = 65_536;
|
||||
|
||||
/// Most pieces the sweep may cut the Shape Builder's paths into, where they cross each other and
|
||||
/// where an open path is traced there and back: twice [`SHAPE_BUILDER_MAX_SEGMENTS`], what open
|
||||
/// paths that cross nothing make at that cap. Paths that cross many times make far more pieces
|
||||
/// than they have segments (400 circles stacked nearly on top of each other, 1,600 segments, make
|
||||
/// about 320,000), and the regions and edges built from them took minutes and gigabytes of memory.
|
||||
/// Past this the Shape Builder skips the full map and keeps only the regions of the filled areas,
|
||||
/// which are capped on their own: when the open paths alone cross too often, a filled shape apart
|
||||
/// from them still has its region.
|
||||
pub const SHAPE_BUILDER_MAX_MAP_EDGES: usize = 2 * SHAPE_BUILDER_MAX_SEGMENTS;
|
||||
|
||||
/// The Shape Builder's arrangement: see [`shape_builder`].
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct BuilderArrangement {
|
||||
@@ -40,7 +50,10 @@ pub fn has_open_path(shapes: &[Shape]) -> bool {
|
||||
/// nothing fills, and each path with no closed subpath comes back cut wherever another path meets
|
||||
/// it, as pieces keyed by its index in `shapes`. Outlines are cut the same way. With more than
|
||||
/// [`SHAPE_BUILDER_MAX_SEGMENTS`] segments or a map that can't be built, only the filled areas
|
||||
/// count and there are no pieces.
|
||||
/// count and there are no pieces. The same happens when the sweep cuts the paths into more than
|
||||
/// [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces; the filled areas are then capped on their own. They
|
||||
/// then have no regions when they alone are cut into more pieces than that, and a filled area
|
||||
/// thinner than the precision is dropped as a sliver, as in [`regions`](crate::regions).
|
||||
pub fn shape_builder(shapes: &[Shape], edges: bool) -> BuilderArrangement {
|
||||
shape_builder_with_gap(shapes, edges, 0.0)
|
||||
}
|
||||
@@ -97,7 +110,7 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) -
|
||||
faces
|
||||
} else {
|
||||
// The filled areas from their arrangement, whose faces merge exactly, then the gaps.
|
||||
let mut regions = crate::pathfinder::regions_with(shapes, precision);
|
||||
let mut regions = crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default();
|
||||
regions.extend(faces.into_iter().filter(|f| f.sources.is_empty()));
|
||||
regions
|
||||
};
|
||||
@@ -112,14 +125,16 @@ pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) -
|
||||
/// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no
|
||||
/// area, such as cutting lines) is left out, so a flood of them cannot push the arrangement past its
|
||||
/// size budget and take the filled shapes down with it; the regions keep the original indices.
|
||||
/// There are none when the sweep cuts the filled shapes into more than [`SHAPE_BUILDER_MAX_MAP_EDGES`] pieces.
|
||||
fn filled_regions(shapes: &[Shape], precision: f64) -> Vec<crate::Region> {
|
||||
let fills = |s: &Shape| s.path.subpaths.iter().any(|sp| sp.closed || encloses_area(sp));
|
||||
let keep: Vec<usize> = (0..shapes.len()).filter(|&i| shapes.get(i).is_some_and(fills)).collect();
|
||||
if keep.len() == shapes.len() {
|
||||
return crate::pathfinder::regions_with(shapes, precision);
|
||||
return crate::pathfinder::regions_capped(shapes, precision, SHAPE_BUILDER_MAX_MAP_EDGES).unwrap_or_default();
|
||||
}
|
||||
let kept: Vec<Shape> = keep.iter().filter_map(|&i| shapes.get(i).cloned()).collect();
|
||||
crate::pathfinder::regions_with(&kept, precision)
|
||||
crate::pathfinder::regions_capped(&kept, precision, SHAPE_BUILDER_MAX_MAP_EDGES)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|mut r| {
|
||||
r.sources = r.sources.iter().filter_map(|&s| keep.get(s).copied()).collect();
|
||||
|
||||
@@ -603,6 +603,49 @@ fn shape_builder_offers_the_gaps_closed_shapes_enclose() {
|
||||
assert!(shape_builder(&s, false).regions.iter().all(|r| !r.sources.is_empty()));
|
||||
}
|
||||
|
||||
/// `n` horizontal and `n` vertical lines across one square, every one crossing every other.
|
||||
fn line_grid(n: usize) -> Vec<Shape> {
|
||||
let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64;
|
||||
let across = (0..n).map(|k| line((0.0, at(k)), (1000.0, at(k)), k as u64));
|
||||
let down = (0..n).map(|k| line((at(k), 0.0), (at(k), 1000.0), (n + k) as u64));
|
||||
across.chain(down).collect()
|
||||
}
|
||||
|
||||
/// `n` horizontal and `n` vertical bars across one square, every one crossing every other.
|
||||
fn bar_grid(n: usize) -> Vec<Shape> {
|
||||
let at = |k: usize| 10.0 + k as f64 * 980.0 / n as f64;
|
||||
let across = (0..n).map(|k| rect(0.0, at(k), 1000.0, at(k) + 1.0, k as u64));
|
||||
let down = (0..n).map(|k| rect(at(k), 0.0, at(k) + 1.0, 1000.0, (n + k) as u64));
|
||||
across.chain(down).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_past_its_edge_cap_is_not_built() {
|
||||
// 20 lines each way: each line is cut into 21 pieces, 840 in all.
|
||||
let s = line_grid(20);
|
||||
assert!(map::map_within(&s, false, DEFAULT_PRECISION, 1000).is_some());
|
||||
assert!(map::map_within(&s, false, DEFAULT_PRECISION, 500).is_none());
|
||||
let bars = bar_grid(20);
|
||||
assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 100_000).is_some_and(|r| r.len() > 400));
|
||||
assert!(crate::pathfinder::regions_capped(&bars, DEFAULT_PRECISION, 1000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_builds_no_regions_past_its_edge_cap() {
|
||||
// 300 lines each way cross 90,000 times with 600 segments: the sweep cuts them into about
|
||||
// 180,000 pieces, past the cap, and nothing is built from them.
|
||||
let s = line_grid(300);
|
||||
let started = work_done();
|
||||
let BuilderArrangement { regions, lines, edges, lines_under } = shape_builder(&s, true);
|
||||
assert!(regions.is_empty() && lines.is_empty() && edges.is_empty() && lines_under.is_empty(), "{} regions", regions.len());
|
||||
assert_eq!(work_done() - started, 0, "no face or edge was looked up");
|
||||
// Bars, closed paths only, each edge crossing 300 others: their filled areas are not built
|
||||
// either.
|
||||
assert!(shape_builder(&bar_grid(150), true).regions.is_empty());
|
||||
// Under the cap, the same grid is built.
|
||||
assert_eq!(shape_builder(&line_grid(20), false).regions.len(), 19 * 19);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_builder_stays_quick_up_to_its_cap() {
|
||||
// A wavy ring of nearly the most segments the map takes, crossed by a few lines.
|
||||
|
||||
@@ -1034,6 +1034,19 @@ mod tests {
|
||||
assert!(unread.is_empty(), "{unread:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hex_string_broken_by_a_non_hex_byte_hides_no_stream_after_it() {
|
||||
// A `<` followed by hex digits and then a byte that is neither a hex digit nor white space
|
||||
// is no hex string: the scan goes on from the next byte instead of skipping to a `>`.
|
||||
let bad = b"<< /Type /XRef /DecodeParms 9 0 R >> stream\nx\nendstream";
|
||||
for lead in [&b"<4G "[..], b"<41 4z ", b"<\x00 "] {
|
||||
let pdf = [lead, &bad[..]].concat();
|
||||
assert!(unsafe_file_streams(&pdf), "{}", String::from_utf8_lossy(&pdf));
|
||||
}
|
||||
// A hex string that ends is skipped, and the stream after it is still read.
|
||||
assert!(unsafe_file_streams(&[&b"<41 42> "[..], &bad[..]].concat()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_of_lt_in_an_image_a_string_or_a_comment_opens() {
|
||||
// #3924 review: every `<<` in a run of `<` (an image's flat area of grey 60) was read as a
|
||||
|
||||
@@ -10,7 +10,7 @@ use kurbo::{Point, Rect, Shape};
|
||||
use vectorcraft_doc::{Document, FILE_FONT_MIME, TextObject};
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
use crate::tests::live_text::{SOURCE_SERIF, outlines, texts, uninstalled_serif};
|
||||
use crate::tests::live_text::{SOURCE_SERIF, outlines, renamed, texts, uninstalled_serif};
|
||||
use crate::*;
|
||||
|
||||
/// Lines of (x, y from the top, size, text): kerned pairs, a long line, two sizes.
|
||||
@@ -274,3 +274,29 @@ fn two_glyphs_for_one_character_both_survive_import() {
|
||||
};
|
||||
close(&glyph_ink(db, &imported), "imported");
|
||||
}
|
||||
|
||||
/// The license flags (OS/2 `fsType`) of the font a PDF carries go with the font the document keeps:
|
||||
/// a restricted font (0x0002) still draws its type, and a PDF saved from the document draws that
|
||||
/// type as outlines with the license warning instead of embedding the font again.
|
||||
#[test]
|
||||
fn a_restricted_font_the_file_carries_is_not_embedded_again() {
|
||||
let mut font = renamed(SOURCE_SERIF, &[("SourceSerif4", "SourceSerif7"), ("Source Serif 4", "Source Serif 7")]);
|
||||
let tables = usize::from(u16::from_be_bytes([font[4], font[5]]));
|
||||
let os2 = (0..tables).map(|i| 12 + 16 * i).find(|r| &font[*r..*r + 4] == b"OS/2").unwrap();
|
||||
let at = u32::from_be_bytes(font[os2 + 8..os2 + 12].try_into().unwrap()) as usize;
|
||||
font[at + 8..at + 10].copy_from_slice(&0x0002u16.to_be_bytes());
|
||||
|
||||
let carried = import(&page_pdf(font));
|
||||
let t = texts(&carried.document);
|
||||
assert!(t.iter().any(|t| t.file_fonts.is_some()), "the file's font draws its type");
|
||||
|
||||
let saved = export_with_report(&carried.document, &PdfOptions::default()).unwrap();
|
||||
assert!(saved.warnings.iter().any(|w| w.contains("Source Serif 7") && w.contains("doesn't allow embedding")), "{:?}", saved.warnings);
|
||||
let back = import(&saved.bytes);
|
||||
assert!(
|
||||
texts(&back.document).is_empty(),
|
||||
"no type in the saved file: {:?}",
|
||||
texts(&back.document).iter().map(TextObject::plain_text).collect::<Vec<_>>()
|
||||
);
|
||||
assert!(!back.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "no font in the saved file");
|
||||
}
|
||||
@@ -271,7 +271,7 @@ fn invisible_text_is_type_whatever_its_glyphs_look_like() {
|
||||
}
|
||||
|
||||
/// `font` with each of `names` (`from`, `to`, the same length) replaced, in ASCII and UTF-16.
|
||||
fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec<u8> {
|
||||
pub(crate) fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec<u8> {
|
||||
let mut bytes = font.to_vec();
|
||||
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
for &(from, to) in names {
|
||||
|
||||
+60
-11
@@ -19,7 +19,7 @@ pub(crate) fn outline(line: &BezPath, st: &StrokeLayer, width: f64, tol: f64) ->
|
||||
}
|
||||
// Closed endpoint rounding must not consume a substantial part of a subpixel band.
|
||||
let fine = (tol / 8.0).min(width / 32.0).max(1e-4);
|
||||
if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, st, width, fine)) {
|
||||
if let Some(band) = thin_line(line, st, width).and_then(|lines| thin_band(&lines, &corners(line), st, width, fine)) {
|
||||
return band;
|
||||
}
|
||||
let outline = effects::stroke::line_outline(line, st, width, fine);
|
||||
@@ -49,21 +49,65 @@ fn thin_line(line: &BezPath, st: &StrokeLayer, width: f64) -> Option<BezPath> {
|
||||
lines.elements().iter().all(|el| !matches!(el, PathEl::QuadTo(..) | PathEl::CurveTo(..))).then_some(lines)
|
||||
}
|
||||
|
||||
/// The points where `line` has a corner: where two of its segments meet with tangents that are not
|
||||
/// in line ([`SMOOTH`]), or where a segment has no direction there. One list for each subpath, in
|
||||
/// order, each sorted by [`point_order`]. [`draw_sub`] leaves these points where they are, so the
|
||||
/// lines a curve is drawn with have each corner at the same point, and draws one subpath for each.
|
||||
fn corners(line: &BezPath) -> Vec<Vec<Point>> {
|
||||
let tangents = |seg: PathSeg| {
|
||||
let c = match seg {
|
||||
PathSeg::Line(l) => CubicBez::new(l.p0, l.p0, l.p1, l.p1),
|
||||
other => cubic(other)?,
|
||||
};
|
||||
Some((start_tangent(&c)?, end_tangent(&c)?))
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
// A span of `f64::INFINITY` gives every segment no steps: only the segments are wanted.
|
||||
for sub in subpaths(line.elements(), f64::INFINITY, 1.0).unwrap_or_default() {
|
||||
let mut here = Vec::new();
|
||||
let n = sub.segs.len();
|
||||
let first = if sub.closed { 0 } else { 1 };
|
||||
for i in first..n {
|
||||
let before = if i == 0 { n - 1 } else { i - 1 };
|
||||
let (Some((a, _)), Some((b, _))) = (sub.segs.get(before), sub.segs.get(i)) else { continue };
|
||||
let smooth = match (tangents(*a).map(|t| t.1), tangents(*b).map(|t| t.0)) {
|
||||
(Some(u), Some(v)) => u.dot(v) > 0.0 && u.cross(v).abs() <= SMOOTH * u.hypot() * v.hypot(),
|
||||
_ => false,
|
||||
};
|
||||
if !smooth {
|
||||
here.push(b.start());
|
||||
}
|
||||
}
|
||||
here.sort_by(point_order);
|
||||
out.push(here);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Points in order of `x`, then `y` ([`corners`]).
|
||||
fn point_order(a: &Point, b: &Point) -> std::cmp::Ordering {
|
||||
a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))
|
||||
}
|
||||
|
||||
/// The outline of stroke `st` at `width` along `lines`, a path of lines only ([`thin_line`]), to fill
|
||||
/// with the non-zero rule. Each side of each line is offset by half the width. Where two lines meet
|
||||
/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross; elsewhere the
|
||||
/// stroke's join is drawn, and an open subpath ends in the stroke's caps, with round parts drawn as
|
||||
/// at a small angle ([`THIN_SMOOTH`]) both sides go to where the offsets cross. Elsewhere the
|
||||
/// stroke's join is drawn at the corners of the same subpath of the path (`corners`, one list for
|
||||
/// each subpath of `lines`, [`corners`]) and a round join where the lines a
|
||||
/// curve is drawn with meet. An open subpath ends in the stroke's caps, with round parts drawn as
|
||||
/// lines within `fine` of their arcs. `None` when a subpath has fewer than two distinct points or a
|
||||
/// point that isn't finite, or is closed and no wider or taller than the stroke: those take
|
||||
/// [`effects::stroke::line_outline`].
|
||||
fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option<BezPath> {
|
||||
fn thin_band(lines: &BezPath, corners: &[Vec<Point>], st: &StrokeLayer, width: f64, fine: f64) -> Option<BezPath> {
|
||||
let h = width / 2.0;
|
||||
// The angle between two points of an arc of radius `h` drawn as lines within `fine` of it.
|
||||
let step = 2.0 * (1.0 - (fine / h).min(1.0)).acos().max(1e-3);
|
||||
let mut out = BezPath::new();
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
let mut closed = false;
|
||||
let flush = |pts: &mut Vec<Point>, closed: bool, out: &mut BezPath| -> Option<()> {
|
||||
// The subpath being read; `None` before the first move.
|
||||
let mut sub: Option<usize> = None;
|
||||
let flush = |pts: &mut Vec<Point>, closed: bool, sub: Option<usize>, out: &mut BezPath| -> Option<()> {
|
||||
if pts.is_empty() {
|
||||
return Some(());
|
||||
}
|
||||
@@ -80,14 +124,15 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
return None;
|
||||
}
|
||||
}
|
||||
band_sub(out, pts, closed, st, h, step);
|
||||
band_sub(out, pts, corners.get(sub?)?, closed, st, h, step);
|
||||
pts.clear();
|
||||
Some(())
|
||||
};
|
||||
for el in lines.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut pts, closed, &mut out)?;
|
||||
flush(&mut pts, closed, sub, &mut out)?;
|
||||
sub = Some(sub.map_or(0, |s| s + 1));
|
||||
closed = false;
|
||||
pts.push(p);
|
||||
}
|
||||
@@ -100,7 +145,7 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
PathEl::QuadTo(..) | PathEl::CurveTo(..) => return None,
|
||||
}
|
||||
}
|
||||
flush(&mut pts, closed, &mut out)?;
|
||||
flush(&mut pts, closed, sub, &mut out)?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -108,8 +153,9 @@ fn thin_band(lines: &BezPath, st: &StrokeLayer, width: f64, fine: f64) -> Option
|
||||
/// repeating the first when `closed`) to `out`: for an open subpath one contour, its left side,
|
||||
/// the end cap, its right side backward and the start cap; for a closed one its left side and its
|
||||
/// right side backward, as two contours. `h` is half the width and `step` the angle between the
|
||||
/// points of a round join or cap.
|
||||
fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) {
|
||||
/// points of a round join or cap. A sharp turn takes the stroke's join at one of this subpath's
|
||||
/// `corners` (sorted by [`point_order`]) and a round join elsewhere.
|
||||
fn band_sub(out: &mut BezPath, pts: &[Point], corners: &[Point], closed: bool, st: &StrokeLayer, h: f64, step: f64) {
|
||||
use vectorcraft_doc::{LineCap, LineJoin};
|
||||
let n = pts.len();
|
||||
let chords = if closed { n } else { n - 1 };
|
||||
@@ -143,7 +189,10 @@ fn band_sub(out: &mut BezPath, pts: &[Point], closed: bool, st: &StrokeLayer, h:
|
||||
inner.push(p);
|
||||
inner.push(p - nb * sign);
|
||||
outer.push(p + na * sign);
|
||||
match st.join {
|
||||
// Only the path's corners take the stroke's join; where the lines of a curve turn sharply
|
||||
// the stroke along the curve is round.
|
||||
let kind = if corners.binary_search_by(|c| point_order(c, &p)).is_ok() { st.join } else { LineJoin::Round };
|
||||
match kind {
|
||||
LineJoin::Miter if 2.0 < (1.0 + dot) * st.miter_limit.powi(2) => outer.push(p + miter * sign),
|
||||
LineJoin::Round => arc(outer, p, na * sign, cross.atan2(dot)),
|
||||
LineJoin::Miter | LineJoin::Bevel => {}
|
||||
|
||||
@@ -133,6 +133,148 @@ fn thin_strokes_drawn_as_lines_keep_both_turns_of_a_curve() {
|
||||
assert!(bounds.x1 <= turn + past && bounds.x0 >= -turn - past, "the outline spans {bounds:?}");
|
||||
}
|
||||
|
||||
/// A path with a bend at (10, 0) and then six smooth anchors `gap` apart, each with handles
|
||||
/// `handle` and 1.7 times `handle` long, scaled by `zoom`, and its points flattened within 0.001.
|
||||
fn close_smooth_anchors(gap: f64, handle: f64, zoom: f64) -> (BezPath, Vec<kurbo::Point>) {
|
||||
let path = close_smooth_path(gap, handle, zoom);
|
||||
let mut line = Vec::new();
|
||||
vectorcraft_geom::flatten(path.iter(), 1e-3, |el| {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = el {
|
||||
line.push(p);
|
||||
}
|
||||
});
|
||||
(path, line)
|
||||
}
|
||||
|
||||
/// How far `q` is from the nearest point of `path`.
|
||||
fn from_curve(path: &BezPath, q: kurbo::Point) -> f64 {
|
||||
use kurbo::ParamCurveNearest;
|
||||
path.segments().map(|s| s.nearest(q, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// The path of [`close_smooth_anchors`].
|
||||
fn close_smooth_path(gap: f64, handle: f64, zoom: f64) -> BezPath {
|
||||
use vectorcraft_geom::path::{Anchor, AnchorKind, PathData, SubPath};
|
||||
let dir = kurbo::Vec2::new(0.8, 0.6);
|
||||
let mut anchors = vec![
|
||||
Anchor::corner(kurbo::Point::new(0.0, 0.0)),
|
||||
Anchor::with_handles(kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 0.0), kurbo::Point::new(10.0, 5.0)),
|
||||
];
|
||||
let mut x = 10.0;
|
||||
for i in 0..6 {
|
||||
x += gap;
|
||||
let p = kurbo::Point::new(x, 1.0 + if i % 2 == 0 { 0.3 } else { -0.2 } * gap);
|
||||
anchors.push(Anchor { p, h_in: p - dir * handle, h_out: p + dir * handle * 1.7, kind: AnchorKind::Smooth });
|
||||
}
|
||||
anchors.push(Anchor::smooth(kurbo::Point::new(x + 20.0, 0.0), kurbo::Point::new(x + 25.0, -4.0)));
|
||||
kurbo::Affine::scale(zoom) * PathData::single(SubPath::new(anchors, false)).to_bezpath()
|
||||
}
|
||||
|
||||
/// A thin stroke along smooth anchors that sit close together after a bend follows the curve: its
|
||||
/// outline has no point farther than a stroke's width from the curve, and covers the curve. The
|
||||
/// lines such a curve is drawn with are short beside the stroke and turn sharply, so offsetting
|
||||
/// them drew the stroke's miter joins as spikes.
|
||||
#[test]
|
||||
fn thin_strokes_follow_smooth_anchors_close_together() {
|
||||
for gap in [0.1, 1.0] {
|
||||
let (path, line) = close_smooth_anchors(gap, 1.0, 1.0);
|
||||
for w in [0.6, 0.9] {
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&path, &st, w, 0.25);
|
||||
for el in o.elements() {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el {
|
||||
let d = from_curve(&path, p);
|
||||
assert!(d <= w, "gap {gap}, width {w}: outline point {p:?} is {d} from the curve");
|
||||
}
|
||||
}
|
||||
for p in line.iter().step_by(7) {
|
||||
assert!(o.winding(*p) != 0, "gap {gap}, width {w}: the curve at {p:?} is not covered");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin stroke's outline stays within the stroke's width of its curve where the lines the curve is
|
||||
/// drawn with turn sharply, as near a cusp: they meet with a round join, not the stroke's miter.
|
||||
/// 200 cubic curves, each about 100 device pixels across.
|
||||
#[test]
|
||||
fn thin_strokes_meet_round_where_a_curves_lines_turn_sharply() {
|
||||
let mut seed: u64 = 7;
|
||||
let mut r = |lo: f64, hi: f64| {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64)
|
||||
};
|
||||
let w = 0.5;
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
st.join = LineJoin::Miter;
|
||||
st.miter_limit = 10.0;
|
||||
for _ in 0..200 {
|
||||
let (x, y) = (r(20.0, 980.0), r(20.0, 980.0));
|
||||
let mut q = [kurbo::Point::ZERO; 3];
|
||||
for p in &mut q {
|
||||
*p = kurbo::Point::new((x + r(-30.0, 30.0)) * 1.71, (y + r(-30.0, 30.0)) * 1.71);
|
||||
}
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((x * 1.71, y * 1.71));
|
||||
path.curve_to(q[0], q[1], q[2]);
|
||||
let o = raster_stroke_outline(&path, &st, w, 0.25);
|
||||
for el in o.elements() {
|
||||
if let kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) = *el {
|
||||
let d = from_curve(&path, p);
|
||||
assert!(d <= w, "outline point {p:?} is {d} from the curve {path:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A thin stroke along smooth anchors close together, with handles long beside the gaps between
|
||||
/// them, covers what the curve's own outline covers: at every point of a grid more than 0.25 pixels
|
||||
/// nearer or farther than half the stroke's width from the curve, both outlines agree. The miter
|
||||
/// joins drawn where the curve's lines turned sharply covered points well outside the stroke.
|
||||
#[test]
|
||||
fn thin_strokes_along_long_handles_cover_the_curve_outline() {
|
||||
let tol = 0.25;
|
||||
for (gap, w) in [(1.0, 0.6), (1.0, 0.9), (0.1, 0.6)] {
|
||||
let path = close_smooth_path(gap, 10.0, 4.0);
|
||||
let st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
let o = raster_stroke_outline(&path, &st, w, tol);
|
||||
let fine = (tol / 8.0).min(w / 32.0);
|
||||
let mut want = BezPath::new();
|
||||
vectorcraft_geom::flatten(crate::effects::stroke::line_outline(&path, &st, w, fine).iter(), fine, |el| want.push(el));
|
||||
let bb = want.bounding_box().inflate(w, w);
|
||||
for i in 0..90 {
|
||||
for j in 0..90 {
|
||||
let q = kurbo::Point::new(bb.x0 + bb.width() * f64::from(i) / 90.0, bb.y0 + bb.height() * f64::from(j) / 90.0);
|
||||
let d = from_curve(&path, q);
|
||||
if (d - w / 2.0).abs() > 0.25 {
|
||||
assert_eq!(o.winding(q) != 0, want.winding(q) != 0, "gap {gap}, width {w}: at {q:?}, {d} from the curve");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A corner of one subpath does not change the join where the lines of another subpath's curve
|
||||
/// meet at the same point: the first subpath's outline is the same with or without the second.
|
||||
#[test]
|
||||
fn thin_strokes_take_corners_from_their_own_subpath() {
|
||||
let w = 0.5;
|
||||
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), w);
|
||||
st.join = LineJoin::Miter;
|
||||
st.miter_limit = 10.0;
|
||||
let mut alone = BezPath::new();
|
||||
alone.move_to((-1.0, 0.0));
|
||||
alone.line_to((0.0, 0.0));
|
||||
alone.curve_to((0.000001, 0.0), (-1.0, 0.5), (-2.0, 1.0));
|
||||
let mut both = alone.clone();
|
||||
both.move_to((-10.0, -10.0));
|
||||
both.line_to((0.0, 0.0));
|
||||
both.line_to((-10.0, 10.0));
|
||||
let one = raster_stroke_outline(&alone, &st, w, 0.25);
|
||||
let two = raster_stroke_outline(&both, &st, w, 0.25);
|
||||
assert_eq!(two.elements().get(..one.elements().len()), Some(one.elements()), "the second subpath changed the first one's outline");
|
||||
}
|
||||
|
||||
/// Independently integrate coverage in radial/angle bins of an original notched ring. Checking
|
||||
/// only the outline geometry misses raster flattening that cancels its two nearby contours.
|
||||
#[test]
|
||||
|
||||
@@ -709,7 +709,7 @@ mod cancel_tests {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::behavior::IconId;
|
||||
use craft::ui::primitives::{has_icon, register_app_icons};
|
||||
use craft::ui::primitives::has_icon;
|
||||
|
||||
use super::icon_for_shape;
|
||||
|
||||
@@ -717,7 +717,7 @@ mod tests {
|
||||
/// would show the placeholder instead of the toolbar's icon.
|
||||
#[test]
|
||||
fn every_shape_button_shows_its_tools_icon() {
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
crate::icons::register();
|
||||
for id in ["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"] {
|
||||
let tool = vectorcraft_tools::tool_info(id).unwrap_or_else(|| panic!("{id} is a tool"));
|
||||
assert_eq!(icon_for_shape(id), crate::icons::tool_icon(tool.icon), "{id}");
|
||||
|
||||
@@ -9,7 +9,7 @@ use craft::ui::choice::ChoiceLook;
|
||||
use craft::ui::contract::{Bind, CaptionInk, GlyphColon, LinkLabelInk, LinkLabelUnderline, MoveBandCursor, QuietHeader, SectionRhythm};
|
||||
use craft::ui::docking::IconGroupSeparator;
|
||||
use craft::ui::list::{CommandHighlight, ThumbRows};
|
||||
use craft::ui::menu::MenuTitleLook;
|
||||
use craft::ui::menu::{MenuTitleLook, MenuTitlePad};
|
||||
use craft::ui::patterns::form_dialogs::PresetCardLook;
|
||||
use craft::ui::runtime::env::{RootEnv, Scale, ScrubDrags, WindowKey};
|
||||
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
|
||||
@@ -67,7 +67,7 @@ impl VectorcraftApp {
|
||||
/// once, gives Data Recovery the host's store and makes a view for each open document.
|
||||
pub fn new(mut session: Session, mut services: Services) -> Self {
|
||||
// Every entry point (desktop, web, tests) makes the app before its first pass.
|
||||
craft::ui::primitives::register_app_icons(&super::icons::APP_ICONS);
|
||||
super::icons::register();
|
||||
craft::ui::primitives::register_app_icons(&super::cursors::CURSOR_ICONS);
|
||||
// The font menus and the first file opened need the installed fonts: catalog them now.
|
||||
vectorcraft_text::FontDb::global().scan_in_background();
|
||||
@@ -818,8 +818,9 @@ pub(crate) fn root_env(prefs: &vectorcraft_engine::Prefs, native_ppp: f32, print
|
||||
root.values.set(ThumbRows::Tight);
|
||||
// The Layers Objects search field fills the filter bar up to its Filter button, as production's did.
|
||||
root.values.set(ObjectsSearch::Fill);
|
||||
// The menu bar's titles are production's egui buttons: a push button high, 2 points beside the text, rounded.
|
||||
root.values.set(MenuTitleLook::Button);
|
||||
// The menu bar's titles are menu rows with the control padding (`space.pad.control`) on each side of the text.
|
||||
root.values.set(MenuTitleLook::Row);
|
||||
root.values.set(MenuTitlePad::Control);
|
||||
// The title bar and the panel headers keep the arrow, over the menu titles too, as production's did.
|
||||
root.values.set(MoveBandCursor::Arrow);
|
||||
// Document tabs show their title and its `*` in the label's semibold face, as production drew them.
|
||||
|
||||
@@ -29,7 +29,6 @@ use super::outline::{ViewHides, c32, linked_crosses, node_outline, selection_hit
|
||||
// PLAN: `BodyKind`, `Win` and `ViewKey::from(CanvasView)` are canvas-w10's (cv.S1, S2, S5); their paths here follow the contract.
|
||||
use super::{BodyKind, VectorcraftApp, Win};
|
||||
// PLAN: `anchors` takes `tool_points` because the Curvature tool's own points come from `session.overlays`, which only `show` may call (`&mut app`).
|
||||
// PLAN: BezierOverlay selects anchors of every path under `HandlesShown`, so a whole-selected container draws handles that the old marks hid outside Direct Selection.
|
||||
|
||||
/// The anchor square's side at Selection & Anchor Display › Size 3, the default, in points.
|
||||
const ANCHOR_AT_DEFAULT_SIZE: f32 = 5.0;
|
||||
@@ -60,6 +59,12 @@ pub(super) struct Anchors {
|
||||
pub paths: Vec<EditPath>,
|
||||
/// The selected anchors and the selected segment.
|
||||
pub selection: PathSelection,
|
||||
/// The paths whose anchors show selected without direction handles: paths selected whole, or inside a container
|
||||
/// selected whole, under a tool that does not drag handles, and the paths inside a container selected whole under
|
||||
/// one that does ([`vectorcraft_tools::catalog::edits_anchors`]).
|
||||
pub plain: Vec<EditPath>,
|
||||
/// Every anchor of `plain`, selected.
|
||||
pub plain_selection: PathSelection,
|
||||
/// Anchors as squares, or as circles under the Curvature tool.
|
||||
pub shown: AnchorsShown,
|
||||
/// Whose direction handles show.
|
||||
@@ -259,15 +264,21 @@ fn grid_path(key: u64, points: impl Iterator<Item = Point>, color: Color32) -> E
|
||||
|
||||
/// The anchors and handles of the selection. An object selected whole has every anchor selected, and so do the
|
||||
/// paths inside a group, compound path or clip group selected whole; with Direct Selection's partial selection only
|
||||
/// the chosen anchors are, and a selected segment hollows the others. `tool_points` is whether the tool draws its own
|
||||
/// points (the Curvature tool while it draws), which leaves nothing here. `tool` is the tool whose marks show
|
||||
/// ([`super::shown_tool`]). Nothing too big to outline, and nothing during Halftone Preview.
|
||||
/// the chosen anchors are, and a selected segment hollows the others. Direction handles show for a partial selection's
|
||||
/// anchors, for a selected segment, and for a path selected whole when `tool` drags handles
|
||||
/// ([`vectorcraft_tools::catalog::edits_anchors`]); every other path goes to [`Anchors::plain`], whose anchors show
|
||||
/// without handles. `tool_points` is whether the tool draws its own points (the Curvature tool while it draws), which
|
||||
/// leaves nothing here. `tool` is the tool whose marks show ([`super::shown_tool`]). Nothing too big to outline, and
|
||||
/// nothing during Halftone Preview.
|
||||
pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool) -> Anchors {
|
||||
let curvature = tool == "curvature";
|
||||
let drags_handles = vectorcraft_tools::catalog::edits_anchors(tool);
|
||||
let prefs = &app.session.prefs;
|
||||
let mut out = Anchors {
|
||||
paths: vec![],
|
||||
selection: PathSelection::default(),
|
||||
plain: vec![],
|
||||
plain_selection: PathSelection::default(),
|
||||
shown: if curvature { AnchorsShown::Curvature } else { AnchorsShown::All },
|
||||
handles: if prefs.show_handles_multiple_anchors { HandlesShown::Selected } else { HandlesShown::OneAnchor },
|
||||
segment_mark: SegmentMark::Line,
|
||||
@@ -279,6 +290,7 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin
|
||||
let (sel, hides) = (&st.selection, ViewHides::of(app));
|
||||
// The selected anchors by path, and the selected segment with its path.
|
||||
let mut chosen: Vec<(u64, Vec<KnotRef>)> = vec![];
|
||||
let mut plain: Vec<(u64, Vec<KnotRef>)> = vec![];
|
||||
let mut segment: Option<(u64, KnotRef)> = None;
|
||||
for id in &sel.objects {
|
||||
let Some(node) = st.doc.node(*id) else { continue };
|
||||
@@ -295,8 +307,15 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin
|
||||
return;
|
||||
}
|
||||
let NodeKind::Path { path, .. } = &c.kind else { return };
|
||||
out.paths.push(edit_path(c.id.0, path, color));
|
||||
let segments = sel.segments.get(&c.id);
|
||||
// The handles the tools drag ([`vectorcraft_tools::direct`]'s `handle_anchors`): a partial selection's, a
|
||||
// selected segment's, and those of a path selected itself under a tool that edits anchors.
|
||||
if partial.is_none() && segments.is_none() && !(drags_handles && c.id == *id) {
|
||||
out.plain.push(edit_path(c.id.0, path, color));
|
||||
plain.push((c.id.0, path.anchors().map(|(si, ai, _)| KnotRef::new(si, ai)).collect()));
|
||||
return;
|
||||
}
|
||||
out.paths.push(edit_path(c.id.0, path, color));
|
||||
if let Some(&(si, seg)) = segments.and_then(|s| s.iter().next()) {
|
||||
segment.get_or_insert((c.id.0, KnotRef::new(si, seg)));
|
||||
}
|
||||
@@ -326,6 +345,14 @@ pub(super) fn anchors(app: &VectorcraftApp, st: &DocState, tool: &str, tool_poin
|
||||
);
|
||||
selection.others = by_key(chosen.into_iter().filter(|(key, _)| Some(*key) != primary));
|
||||
out.selection = selection;
|
||||
// `show` draws `plain` with `HandlesShown::OneAnchor`, which shows handles only while one anchor is selected. A
|
||||
// lone anchor is drawn with its handles retracted instead; the selection's outline still draws its path.
|
||||
if plain.iter().map(|(_, knots)| knots.len()).sum::<usize>() == 1 {
|
||||
for knot in out.plain.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) {
|
||||
(knot.in_ctrl, knot.out_ctrl) = (knot.anchor, knot.anchor);
|
||||
}
|
||||
}
|
||||
out.plain_selection.others = by_key(plain);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -660,6 +687,15 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
|
||||
.path_options(&anchors.options)
|
||||
.show_at(ui, rect);
|
||||
}
|
||||
if !anchors.plain.is_empty() {
|
||||
let mut paths = anchors.plain.clone();
|
||||
let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection)
|
||||
.tool(BezierTool::Anchors)
|
||||
.handles(HandlesShown::OneAnchor)
|
||||
.anchors(anchors.shown)
|
||||
.path_options(&anchors.options)
|
||||
.show_at(ui, rect);
|
||||
}
|
||||
let dots = &marks.dots;
|
||||
if !(dots.centers.is_empty() && dots.origins.is_empty() && dots.key_anchor.is_none()) {
|
||||
SelectionDots { common: Common::new(), dots }.label("Selection dots").show_at(ui, rect);
|
||||
@@ -734,7 +770,7 @@ impl SelectionMarks {
|
||||
o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift));
|
||||
o.revision = outline_revision(&o.paths, o.key.as_ref(), o.color.to_array());
|
||||
}
|
||||
for knot in self.anchors.paths.iter_mut().flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) {
|
||||
for knot in self.anchors.paths.iter_mut().chain(&mut self.anchors.plain).flat_map(|p| &mut p.subpaths).flat_map(|sp| &mut sp.knots) {
|
||||
knot.anchor += by;
|
||||
knot.in_ctrl += by;
|
||||
knot.out_ctrl += by;
|
||||
|
||||
@@ -50,6 +50,11 @@ fn marks(app: &VectorcraftApp) -> Anchors {
|
||||
anchors(app, app.session.active().unwrap(), app.session.tool_id(), false)
|
||||
}
|
||||
|
||||
/// Every path whose anchors show, with handles or without.
|
||||
fn shown_paths(anchors: &Anchors) -> Vec<&EditPath> {
|
||||
anchors.paths.iter().chain(&anchors.plain).collect()
|
||||
}
|
||||
|
||||
fn all_selected(selection: &PathSelection) -> usize {
|
||||
selection.anchors.len() + selection.others.iter().map(|(_, knots)| knots.len()).sum::<usize>()
|
||||
}
|
||||
@@ -215,7 +220,7 @@ fn a_clip_group_over_a_huge_path_shows_its_clipping_path() {
|
||||
vec![vectorcraft_geom::Rect::new(100.0, 100.0, 200.0, 200.0)],
|
||||
"the square's outline, not the bounds of the huge art"
|
||||
);
|
||||
assert_eq!(marks(&app).paths.iter().map(|p| p.anchor_count()).sum::<usize>(), 4, "and its four anchors");
|
||||
assert_eq!(shown_paths(&marks(&app)).iter().map(|p| p.anchor_count()).sum::<usize>(), 4, "and its four anchors");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -228,13 +233,13 @@ fn a_huge_selection_shows_its_bounds_instead_of_every_outline() {
|
||||
assert_eq!((huge.len(), huge[0].0, huge[0].1.len()), (1, color, 1), "one bounds path in the layer colour");
|
||||
let st = app.session.active().unwrap();
|
||||
assert!(outlines(&app, st)[0].paths[0].elements().len() < 10, "a rectangle, not the outline");
|
||||
assert!(marks(&app).paths.is_empty(), "no anchors either");
|
||||
assert!(shown_paths(&marks(&app)).is_empty(), "no anchors either");
|
||||
assert!(dots(&app, st).origins.is_empty());
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
app.run("path.create", json!({"d": format!("M20 20 {} Z", points(200))})).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
assert!(outlines(&app, st)[0].paths[0].elements().len() > 200, "a path of few points is outlined whole");
|
||||
assert_eq!(marks(&app).paths.len(), 1);
|
||||
assert_eq!(shown_paths(&marks(&app)).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -389,7 +394,7 @@ fn a_selected_group_leaves_its_hidden_members_unmarked() {
|
||||
app.run("select.set", json!({"ids": [group.0]})).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
let outlined: Vec<Vec<PathEl>> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.elements().to_vec()).collect();
|
||||
let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::<Vec<_>>();
|
||||
let anchored = shown_paths(&marks(app)).iter().map(|p| p.anchor_count()).collect::<Vec<_>>();
|
||||
let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.elements().to_vec());
|
||||
(outlined, anchored, hovered)
|
||||
};
|
||||
@@ -422,7 +427,7 @@ fn a_selected_group_leaves_out_its_guides_while_guides_are_hidden() {
|
||||
app.run("select.set", json!({"ids": [group.0]})).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
let outlined: Vec<vectorcraft_geom::Rect> = outlines(app, st).into_iter().flat_map(|o| o.paths).map(|p| p.bounding_box()).collect();
|
||||
let anchored = marks(app).paths.iter().map(|p| p.anchor_count()).collect::<Vec<_>>();
|
||||
let anchored = shown_paths(&marks(app)).iter().map(|p| p.anchor_count()).collect::<Vec<_>>();
|
||||
let hovered = outline_of(st, group, ViewHides::of(app)).map(|h| h.path.bounding_box());
|
||||
(outlined, anchored, hovered)
|
||||
};
|
||||
@@ -554,9 +559,64 @@ fn the_anchors_of_a_container_selected_whole_draw_selected() {
|
||||
app.select_tool("directSelection");
|
||||
app.run("select.set", json!({"ids": [group.0]})).unwrap();
|
||||
let shown = marks(&app);
|
||||
// The ellipse's four anchors and the square's four.
|
||||
assert_eq!(all_selected(&shown.selection), 8);
|
||||
assert_eq!(shown.paths.len(), 2);
|
||||
// The ellipse's four anchors and the square's four, drawn without handles: the tools drag only the handles of a
|
||||
// path selected itself.
|
||||
assert_eq!(all_selected(&shown.plain_selection), 8);
|
||||
assert_eq!(shown.plain.len(), 2);
|
||||
assert!(shown.paths.is_empty() && all_selected(&shown.selection) == 0, "no member's handles show");
|
||||
}
|
||||
|
||||
/// The Selection tool shows a path selected whole with every anchor selected and no direction handles; Direct
|
||||
/// Selection shows the same path's handles, and a partial selection's anchors keep theirs under either tool.
|
||||
#[test]
|
||||
fn the_selection_tool_shows_a_whole_paths_anchors_without_handles() {
|
||||
let (mut app, curve) = scene();
|
||||
let count = {
|
||||
let NodeKind::Path { path, .. } = &app.session.active().unwrap().doc.node(curve).unwrap().kind else { panic!("a path") };
|
||||
path.anchor_count()
|
||||
};
|
||||
app.select_tool("selection");
|
||||
app.run("select.set", json!({"ids": [curve.0]})).unwrap();
|
||||
let shown = marks(&app);
|
||||
assert!(shown.paths.is_empty(), "no path of the Selection tool's marks shows handles");
|
||||
assert_eq!(shown.plain.iter().map(|p| p.key).collect::<Vec<_>>(), vec![curve.0]);
|
||||
assert_eq!(all_selected(&shown.plain_selection), count, "every anchor draws selected");
|
||||
|
||||
app.select_tool("directSelection");
|
||||
let direct = marks(&app);
|
||||
assert!(direct.plain.is_empty(), "Direct Selection draws the path with its handles");
|
||||
assert_eq!((direct.selection.path, direct.selection.anchors.len()), (Some(curve.0), count));
|
||||
|
||||
app.select_tool("selection");
|
||||
app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 2]], "mode": "set"})).unwrap();
|
||||
let partial = marks(&app);
|
||||
assert!(partial.plain.is_empty(), "a partial selection keeps its anchor's handles");
|
||||
assert_eq!(partial.selection.anchors, vec![KnotRef::new(0, 2)]);
|
||||
}
|
||||
|
||||
/// A lone anchor selected whole under the Selection tool is drawn with its handles retracted, since the overlay shows
|
||||
/// handles while one anchor is selected.
|
||||
#[test]
|
||||
fn a_lone_anchor_selected_whole_shows_no_handles() {
|
||||
let mut app = blank();
|
||||
let point = id_of(&app.run("path.create", json!({"d": "M40 40"})).unwrap());
|
||||
app.run("path.setHandle", json!({"id": point.0, "anchor": 0, "which": "out", "x": 60, "y": 10, "independent": true})).unwrap();
|
||||
let NodeKind::Path { path, .. } = &app.session.active().unwrap().doc.node(point).unwrap().kind else { panic!("a path") };
|
||||
assert_eq!((path.anchor_count(), path.subpaths[0].anchors[0].h_out), (1, Point::new(60.0, 10.0)), "one anchor with a handle");
|
||||
app.select_tool("selection");
|
||||
app.run("select.set", json!({"ids": [point.0]})).unwrap();
|
||||
let shown = marks(&app);
|
||||
assert_eq!(all_selected(&shown.plain_selection), 1);
|
||||
let knots: Vec<_> = shown.plain.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots).collect();
|
||||
assert_eq!(knots.len(), 1);
|
||||
assert!(knots.iter().all(|k| k.in_ctrl == k.anchor && k.out_ctrl == k.anchor), "the lone anchor's handles are retracted");
|
||||
|
||||
// Two anchors keep their handles in the marks: the overlay shows none while more than one is selected.
|
||||
let curve = id_of(&app.run("path.create", json!({"d": "M40 140 C60 110 90 110 110 140"})).unwrap());
|
||||
app.run("select.set", json!({"ids": [curve.0]})).unwrap();
|
||||
let two = marks(&app);
|
||||
assert_eq!(all_selected(&two.plain_selection), 2);
|
||||
assert!(two.plain.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots).any(|k| k.out_ctrl != k.anchor), "the curve keeps its shape");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -844,9 +904,9 @@ fn the_outline_revision_follows_what_is_drawn() {
|
||||
#[test]
|
||||
fn an_empty_selection_has_no_marks() {
|
||||
let (mut app, _) = scene();
|
||||
assert!(!seen(&app).is_empty() && !marks(&app).paths.is_empty());
|
||||
assert!(!seen(&app).is_empty() && !shown_paths(&marks(&app)).is_empty());
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
assert!(seen(&app).is_empty() && marks(&app).paths.is_empty());
|
||||
assert!(seen(&app).is_empty() && shown_paths(&marks(&app)).is_empty());
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(dots(&app, st).centers.len() + dots(&app, st).origins.len(), 0);
|
||||
}
|
||||
@@ -891,7 +951,7 @@ thread_local! {
|
||||
fn kept(app: &VectorcraftApp) -> (Vec<Vec<vectorcraft_geom::Rect>>, usize) {
|
||||
let marks = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks");
|
||||
let boxes = marks.outlines.iter().map(|o| o.paths.iter().map(|p| p.bounding_box()).collect()).collect();
|
||||
(boxes, all_selected(&marks.anchors.selection))
|
||||
(boxes, all_selected(&marks.anchors.selection) + all_selected(&marks.anchors.plain_selection))
|
||||
}
|
||||
|
||||
// Whole-app frames build the selection's marks once for each change: none in frames that change nothing, one after
|
||||
@@ -914,7 +974,8 @@ fn the_canvas_builds_the_selection_marks_once_per_change() {
|
||||
assert_eq!(frames(&mut app, 5), 1, "a new selection builds its marks once");
|
||||
let st = app.session.active().unwrap();
|
||||
let boxes = outlines(&app, st).iter().map(|o| o.paths.iter().map(|p| p.bounding_box()).collect()).collect::<Vec<_>>();
|
||||
assert_eq!(kept(&app), (boxes, all_selected(&marks(&app).selection)));
|
||||
let shown = marks(&app);
|
||||
assert_eq!(kept(&app), (boxes, all_selected(&shown.selection) + all_selected(&shown.plain_selection)));
|
||||
app.select_tool("directSelection");
|
||||
assert_eq!(frames(&mut app, 5), 1, "another tool builds the marks once");
|
||||
}
|
||||
@@ -932,7 +993,7 @@ fn points_of(outlines: &[Outlined], anchors: &Anchors, dots: &Dots) -> Vec<Point
|
||||
}
|
||||
}
|
||||
}
|
||||
for knot in anchors.paths.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots) {
|
||||
for knot in anchors.paths.iter().chain(&anchors.plain).flat_map(|p| &p.subpaths).flat_map(|sp| &sp.knots) {
|
||||
out.extend([knot.anchor, knot.in_ctrl, knot.out_ctrl]);
|
||||
}
|
||||
out.extend(dots.origins.iter().chain(&dots.centers).chain(&dots.key_anchor).map(|(at, _)| *at));
|
||||
|
||||
@@ -463,7 +463,14 @@ impl CanvasTool for SessionTool<'_> {
|
||||
if claim(&mut app, EngineKey::Left) {
|
||||
claims = claims.nudges();
|
||||
}
|
||||
if claim(&mut app, EngineKey::AltTap) {
|
||||
// A lone Alt while the canvas has the keys is the tools' modifier let go without a click: the canvas takes it,
|
||||
// so it does not give the menu bar the keys and the next tool letter still chooses its tool. F10 and Alt with
|
||||
// a letter still reach the bar, and a lone Alt in a field or the bar keeps the framework's rule.
|
||||
let canvas_has_keys = app
|
||||
.ui_ctx
|
||||
.as_ref()
|
||||
.is_some_and(|ctx| !ctx.egui_wants_keyboard_input() && !craft::ui::menu::bar::is_focused(ctx) && !craft::ui::menu::bar::is_open(ctx));
|
||||
if canvas_has_keys || claim(&mut app, EngineKey::AltTap) {
|
||||
claims = claims.alt_tap();
|
||||
}
|
||||
claims
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::cell::RefCell;
|
||||
|
||||
use craft::behavior::IconId;
|
||||
use craft::menu::MenuBarUi;
|
||||
use craft::theme::ControlSize;
|
||||
use craft::ui::buttons::{Button, IconButton, ToggleButton};
|
||||
use craft::ui::contract::{Bind, BodyCx, Gap, Props, Show, ShowContainer};
|
||||
use craft::ui::display::Picture;
|
||||
@@ -101,8 +102,9 @@ fn leading(ui: &mut Ui, app: &mut VectorcraftApp) {
|
||||
}
|
||||
let mut home = menus::home_showing(app);
|
||||
let before = home;
|
||||
// The title bar's Home has no rule after it, as an options bar's `BarHome` does.
|
||||
ToggleButton::new(tl!("Home"), Bind::bound(&mut home)).icon(IconSpec::svg(IconId::new("home"))).icon_only().show(ui);
|
||||
// The title bar's Home has no rule after it, as an options bar's `BarHome` does. It is a small control: its square
|
||||
// and glyph take the small sizes (`size.control.sm`, `size.icon.glyph_sm`).
|
||||
ToggleButton::new(tl!("Home"), Bind::bound(&mut home)).icon(IconSpec::svg(IconId::new("home"))).icon_only().size(ControlSize::Sm).show(ui);
|
||||
if home != before {
|
||||
app.run("app.home", json!({})).ok();
|
||||
}
|
||||
|
||||
@@ -548,6 +548,34 @@ fn the_app_bar_keeps_its_right_hand_controls_an_item_gap_apart() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The app bar's Home is a small control (`size.control.sm` high), and each menu title keeps `space.pad.control`
|
||||
/// between its text and the edges of its highlight.
|
||||
#[test]
|
||||
fn the_app_bar_home_is_small_and_menu_titles_pad_their_text() {
|
||||
crate::i18n::set_current(crate::i18n::Lang::EN);
|
||||
let app = crate::VectorcraftApp::new(Session::new(), Default::default());
|
||||
let read = Rc::new(std::cell::Cell::new((0.0_f32, 0.0_f32)));
|
||||
let set = Rc::clone(&read);
|
||||
let mut bar = Shown::new(app, egui::vec2(1600.0, 600.0), move |app, ui| {
|
||||
let tokens = &craft::ui::runtime::env::Env::of(ui).tokens;
|
||||
set.set((tokens.size.control.sm, tokens.space.pad.control));
|
||||
app.ui(ui);
|
||||
});
|
||||
bar.frame(Vec::new()).frame(Vec::new());
|
||||
let (small, pad) = read.get();
|
||||
assert!(small > 0.0 && pad > 0.0, "the sizes are read from the theme");
|
||||
let home = bar.starting("Home").unwrap_or_else(|| panic!("Home shows in {:?}", bar.names())).rect;
|
||||
assert!(home.height() <= small + 0.5, "Home is {} high, over the small control height {small}", home.height());
|
||||
let texts = bar.texts();
|
||||
for title in ["File", "Edit", "Object"] {
|
||||
let rect = bar.find(title).unwrap_or_else(|| panic!("{title} shows in {:?}", bar.names())).rect;
|
||||
let text =
|
||||
texts.iter().find(|t| t.text == title && rect.contains(t.bounds.center())).unwrap_or_else(|| panic!("{title}'s text in {texts:?}"));
|
||||
let (left, right) = (text.bounds.left() - rect.left(), rect.right() - text.bounds.right());
|
||||
assert!(left >= pad - 0.5 && right >= pad - 0.5, "{title}'s text is {left} and {right} from its edges, under {pad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A text the status bar painted, with where it lies.
|
||||
#[derive(Debug)]
|
||||
struct StatusText {
|
||||
|
||||
@@ -17,7 +17,7 @@ fn every_tool_cursors_hotspot_is_on_its_glyph() {
|
||||
use craft::ui::primitives::{painted_image, register_app_icons};
|
||||
use craft::ui::runtime::env::Env;
|
||||
use craft::ui::style::rgba_color;
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
crate::icons::register();
|
||||
register_app_icons(&CURSOR_ICONS);
|
||||
let mut missed = Vec::new();
|
||||
crate::testing::ui_context()
|
||||
|
||||
@@ -47,7 +47,15 @@ pub(super) fn options<I: AsRef<str>>(list: &[(I, &str)]) -> Vec<(String, Label)>
|
||||
/// Vector Halftone adds Keep Original. The Color row depends on two values, so the rows are built
|
||||
/// from `fields`.
|
||||
pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec<Param> {
|
||||
let shapes = [("circle", "Circle"), ("ellipse", "Ellipse"), ("square", "Square"), ("diamond", "Diamond"), ("line", "Line")];
|
||||
let shapes = [
|
||||
("circle", "Circle"),
|
||||
("ellipse", "Ellipse"),
|
||||
("square", "Square"),
|
||||
("diamond", "Diamond"),
|
||||
("line", "Line"),
|
||||
("euclidean", "Euclidean"),
|
||||
("elliptical", "Elliptical"),
|
||||
];
|
||||
let mut rows = vec![
|
||||
Param::new("shape", tl!("Shape"), ParamKind::choice(options(&shapes), Some("circle".into()))),
|
||||
Param::new("frequency", tl!("Frequency"), ParamKind::range(1.0, 150.0, 20.0, SliderScale::Linear)).unit(UnitKind::LinesPerInch),
|
||||
|
||||
@@ -18,7 +18,7 @@ use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Background, ColorMode, Unit};
|
||||
use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI};
|
||||
use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, ProfileFile, RASTER_PPI};
|
||||
|
||||
use craft::behavior::{ColumnWidth, IconId};
|
||||
use craft::ui::buttons::Button;
|
||||
@@ -155,8 +155,8 @@ impl<'de> Deserialize<'de> for VcNewDocument {
|
||||
pub(crate) struct Setup {
|
||||
/// The name of the next untitled document.
|
||||
untitled: String,
|
||||
/// The New Document profiles, each with whether it was edited.
|
||||
profiles: Vec<(&'static str, bool)>,
|
||||
/// The New Document profiles, each with what is at its file.
|
||||
profiles: Vec<(&'static str, ProfileFile)>,
|
||||
/// Whether profiles can be edited (the web build and runs without preferences have no folder).
|
||||
has_profile_folder: bool,
|
||||
/// Numbers Without Units Are Points.
|
||||
@@ -168,7 +168,7 @@ impl Setup {
|
||||
fn of(app: &VectorcraftApp) -> Self {
|
||||
Self {
|
||||
untitled: app.session.peek_untitled().to_string(),
|
||||
profiles: newdoc::profile_names().map(|name| (name, app.session.new_doc_profile_customized(name))).collect(),
|
||||
profiles: newdoc::profile_names().map(|name| (name, app.session.new_doc_profile_file(name))).collect(),
|
||||
has_profile_folder: app.session.new_doc_profile_dir().is_some(),
|
||||
bare_points: app.session.prefs.numbers_without_units_are_points,
|
||||
}
|
||||
@@ -618,12 +618,22 @@ fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option<String>
|
||||
Text::new(text(tl!("NEW DOCUMENT PROFILES"))).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui);
|
||||
// The names in one column and the Edit and Reset buttons in columns of their own, so the buttons line up.
|
||||
Grid::new(&PROFILE_COLUMNS).gap(Gap::Item).show(ui, |ui, _| {
|
||||
for (name, customized) in &setup.profiles {
|
||||
Text::new(text(tl!(name))).id_salt(("profile", name)).show(ui);
|
||||
if clicked(&Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder).show(ui)) {
|
||||
for (name, file) in &setup.profiles {
|
||||
// A link or a folder in the profile's place is not read: its name is dimmed and says why, Edit
|
||||
// is off, and Reset removes a link but not a folder.
|
||||
let unusable = matches!(file, ProfileFile::NotPlain | ProfileFile::Folder);
|
||||
let mut shown = Text::new(text(tl!(name))).id_salt(("profile", name));
|
||||
if unusable {
|
||||
let why = tl!("The profile's file is a link or a folder, so new documents get the default settings");
|
||||
shown = shown.shade(Shade::Muted).tooltip(text(why));
|
||||
}
|
||||
shown.show(ui);
|
||||
let edit = Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder && !unusable);
|
||||
if clicked(&edit.show(ui)) {
|
||||
*action = Some(format!("{EDIT_PROFILE}:{name}"));
|
||||
}
|
||||
if clicked(&Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(*customized).show(ui)) {
|
||||
let reset = Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(file.resettable());
|
||||
if clicked(&reset.show(ui)) {
|
||||
*action = Some(format!("{RESET_PROFILE}:{name}"));
|
||||
}
|
||||
}
|
||||
@@ -1427,11 +1437,11 @@ mod tests {
|
||||
let setup = Setup::of(&app);
|
||||
assert!(setup.has_profile_folder);
|
||||
assert_eq!(setup.profiles.len(), newdoc::profile_names().count());
|
||||
assert!(setup.profiles.iter().all(|(_, customized)| !customized));
|
||||
assert!(setup.profiles.iter().all(|(_, file)| *file == ProfileFile::None));
|
||||
assert!(profile_action(&mut app, "profile.edit:Print"), "Edit closes the dialog");
|
||||
assert_eq!(app.session.active().unwrap().doc.title, "Print");
|
||||
assert!(dir.join("Print.vectorcraft").is_file());
|
||||
assert!(Setup::of(&app).profiles.iter().any(|(name, customized)| *name == "Print" && *customized));
|
||||
assert!(Setup::of(&app).profiles.iter().any(|(name, file)| *name == "Print" && *file == ProfileFile::Plain));
|
||||
assert!(!profile_action(&mut app, "profile.reset:Print"), "Reset leaves the dialog open");
|
||||
assert!(!dir.join("Print.vectorcraft").exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
@@ -1003,3 +1003,231 @@ fn a_failed_tool_choice_restores_the_brush_key_color_initiator() {
|
||||
assert_eq!(app.session.tool_id(), "rectangle", "Cancel must preserve the successful replacement");
|
||||
assert_eq!(unchanged(&app), before);
|
||||
}
|
||||
|
||||
/// The `key` of each dialog `ui.inspect` lists, bottom first.
|
||||
fn dialog_keys(app: &VectorcraftApp) -> Vec<String> {
|
||||
let ctx = app.ui_ctx.clone().expect("a window app");
|
||||
let ui = crate::control::inspect(app, &ctx);
|
||||
ui["dialogs"].as_array().into_iter().flatten().filter_map(|d| d["key"].as_str().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
/// The `key` of each dialog `ui.inspect` lists, bottom first, `None` for a dialog without one.
|
||||
fn dialog_entries(app: &VectorcraftApp) -> Vec<Option<String>> {
|
||||
let ctx = app.ui_ctx.clone().expect("a window app");
|
||||
let ui = crate::control::inspect(app, &ctx);
|
||||
ui["dialogs"].as_array().into_iter().flatten().map(|d| d["key"].as_str().map(str::to_string)).collect()
|
||||
}
|
||||
|
||||
/// A drawing every dialog `ui.menuDialog` lists can open on: two artboards and two selected rectangles, the first a
|
||||
/// crease, and for `command` a selected envelope when Reset or Envelope Options needs one.
|
||||
fn menu_dialog_app(command: &str) -> VectorcraftApp {
|
||||
let mut app = window(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 200, "height": 200, "artboards": 2})).unwrap();
|
||||
let crease = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 60, "height": 20})).unwrap();
|
||||
app.run(crate::addons::packaging::SET_ROLE, json!({"role": "crease", "ids": [crease]})).unwrap();
|
||||
// A variable and a data set, for the dialogs that edit one.
|
||||
app.session.execute("variable.define", &json!({"name": "Name", "kind": "text"})).unwrap();
|
||||
app.session.execute("dataset.new", &json!({"name": "Row"})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
if let Some(make) = envelope_for(command) {
|
||||
app.session.execute(make, &json!({})).unwrap();
|
||||
}
|
||||
app
|
||||
}
|
||||
|
||||
/// The command that makes the envelope `command`'s dialog needs selected, if it needs one.
|
||||
fn envelope_for(command: &str) -> Option<&'static str> {
|
||||
match command {
|
||||
"object.envelope.resetWithWarp" | "object.envelope.options" => Some("object.envelope.makeWithWarp"),
|
||||
"object.envelope.resetWithMesh" => Some("object.envelope.makeWithMesh"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of `doc` after `start`, up to the first of `ends`; empty when `doc` does not have `start`.
|
||||
fn clause<'a>(doc: &'a str, start: &str, ends: &[char]) -> &'a str {
|
||||
let Some(at) = doc.find(start) else { return "" };
|
||||
let rest = &doc[at + start.len()..];
|
||||
&rest[..rest.find(ends).unwrap_or(rest.len())]
|
||||
}
|
||||
|
||||
/// Whether `clause` names command `id` as a word of its own.
|
||||
fn names(clause: &str, id: &str) -> bool {
|
||||
clause.split([' ', ',']).any(|word| word == id)
|
||||
}
|
||||
|
||||
/// Each command `ui.menuDialog`'s params text lists opens the dialog that text names, by the `key` `ui.inspect`
|
||||
/// reports: the command id unless the text names another key for that command, none for the commands the text says
|
||||
/// have no key, and the slider's key for Smooth and Simplify, whose sliders show over the canvas. Every key the text
|
||||
/// names is one a listed command opens.
|
||||
#[test]
|
||||
fn menu_dialog_opens_the_dialog_keys_its_params_text_names() {
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.menuDialog").expect("registered").3;
|
||||
let list = doc.strip_prefix("{command: ").and_then(|rest| rest.split_once('}')).expect("a command list").0;
|
||||
let keyless = clause(doc, "the dialogs of ", &[';']);
|
||||
let except = clause(doc, "is the command id, except ", &[';']);
|
||||
let mut opened = Vec::new();
|
||||
for id in list.split('|') {
|
||||
let expected = except
|
||||
.split(',')
|
||||
.filter_map(|entry| entry.split_once('`')?.1.split_once("` for "))
|
||||
.find_map(|(key, commands)| names(commands, id).then_some(key))
|
||||
.unwrap_or(id);
|
||||
let mut app = menu_dialog_app(id);
|
||||
app.run("ui.menuDialog", json!({"command": id})).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
settle(&mut app);
|
||||
let entries = dialog_entries(&app);
|
||||
assert_eq!(
|
||||
entries.last().is_some_and(Option::is_none),
|
||||
names(keyless, id),
|
||||
"{id}: whether its dialog has a `key` differs from the params text"
|
||||
);
|
||||
let keys: Vec<String> = entries.into_iter().flatten().collect();
|
||||
match keys.last() {
|
||||
None => assert!(names(keyless, id), "{id} opens no dialog"),
|
||||
Some(key) => assert_eq!(key, expected, "{id}: its dialog key differs from the params text"),
|
||||
}
|
||||
// Smooth and Simplify open the slider over the canvas, which ui.inspect lists under its own key.
|
||||
let showing = match id {
|
||||
"object.path.simplify" => crate::dialogs::simplify_slider::showing(&app),
|
||||
"object.path.smooth" => crate::dialogs::smooth_slider::showing(&app),
|
||||
_ => true,
|
||||
};
|
||||
assert!(showing, "{id}: its slider is not showing");
|
||||
opened.extend(keys);
|
||||
}
|
||||
for named in except.split('`').skip(1).step_by(2) {
|
||||
assert!(opened.iter().any(|key| key == named), "the params text names `{named}`, which no listed command opens");
|
||||
}
|
||||
// Simplify opens its dialog, under its command id, with the kept tolerance once OK in that dialog has kept the
|
||||
// settings.
|
||||
let mut app = menu_dialog_app("object.path.simplify");
|
||||
app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap();
|
||||
settle(&mut app);
|
||||
app.run("ui.simplifyMoreOptions", json!({})).unwrap();
|
||||
settle(&mut app);
|
||||
set_all(&mut app, [("tolerance", json!(7.5)), ("retain", json!(true))]);
|
||||
assert!(confirm(&mut app), "OK in the Simplify dialog is taken");
|
||||
settle(&mut app);
|
||||
app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap();
|
||||
settle(&mut app);
|
||||
assert_eq!(dialog_keys(&app), ["object.path.simplify"]);
|
||||
assert_eq!(field(&app, "tolerance"), Some(7.5), "the reopened dialog shows the kept tolerance");
|
||||
assert!(flag(&app, "retain"), "the reopened dialog keeps Retain on");
|
||||
}
|
||||
|
||||
/// Every command whose dialog `ui.menuDialog` opens and `ui.inspect` lists, with a `key` or without one, is one its
|
||||
/// params text lists. Open Simplify and Smooth sliders count as dialogs too.
|
||||
#[test]
|
||||
fn menu_dialog_params_text_lists_every_command_whose_dialog_it_opens() {
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.menuDialog").expect("registered").3;
|
||||
let list: Vec<&str> = doc.strip_prefix("{command: ").and_then(|rest| rest.split_once('}')).expect("a command list").0.split('|').collect();
|
||||
let mut app = menu_dialog_app("");
|
||||
let ids: Vec<String> =
|
||||
app.session.commands().into_iter().map(|c| c.id.to_string()).chain(crate::menus::UI_COMMANDS.iter().map(|c| c.0.to_string())).collect();
|
||||
let mut missing = Vec::new();
|
||||
for id in ids {
|
||||
// The Reset and Envelope Options dialogs open only with an envelope selected.
|
||||
if envelope_for(&id).is_some() {
|
||||
app = menu_dialog_app(&id);
|
||||
}
|
||||
if app.run("ui.menuDialog", json!({"command": id})).is_err() {
|
||||
if envelope_for(&id).is_some() {
|
||||
app = menu_dialog_app("");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
settle(&mut app);
|
||||
let opened =
|
||||
!dialog_entries(&app).is_empty() || crate::dialogs::simplify_slider::showing(&app) || crate::dialogs::smooth_slider::showing(&app);
|
||||
if opened && !list.contains(&id.as_str()) {
|
||||
missing.push(id.clone());
|
||||
}
|
||||
app = menu_dialog_app("");
|
||||
}
|
||||
assert!(missing.is_empty(), "ui.menuDialog opens a dialog for {missing:?}, which its params text does not list");
|
||||
}
|
||||
|
||||
/// The transform, selection and Type on a Path tools' `tool.options` open dialogs whose `key` its params text names.
|
||||
#[test]
|
||||
fn tool_options_opens_the_dialog_keys_its_params_text_names() {
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "tool.options").expect("registered").3;
|
||||
let plain = doc.replace('`', "");
|
||||
assert!(plain.contains("key in ui.inspect"), "the params text must say the dialog names are the `key` in ui.inspect");
|
||||
let field = clause(&plain, "returned dialog field holds ", &['.']);
|
||||
// The `dialog` value the params text gives for `tool`: "<values> for <tools>" pairs, where <values> names the tool
|
||||
// itself (with <tools> a phrase rather than a `|` list of tool ids, and every value in the transform group) or one
|
||||
// value for every tool in <tools>.
|
||||
let documented_dialog = |tool: &str| -> Option<String> {
|
||||
let mut mappings = field.split(", ").map(|part| part.trim_start_matches("and ")).filter_map(|part| {
|
||||
let (values, tools) = part.split_once(" for ")?;
|
||||
if tools.contains(' ') && values.split('|').any(|v| v == tool) {
|
||||
Some(tool.to_string())
|
||||
} else if tools.split('|').any(|t| t == tool) {
|
||||
Some(values.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
let mapping = mappings.next();
|
||||
assert!(mappings.next().is_none(), "{tool}: the params text gives more than one `dialog` mapping");
|
||||
mapping
|
||||
};
|
||||
let groups = ["rotate|scale|reflect|shear", "selection|directSelection|groupSelection", "typeOnPath|verticalTypeOnPath"];
|
||||
let checked: Vec<&str> = groups.iter().flat_map(|g| g.split('|')).collect();
|
||||
let mut named_tools = Vec::new();
|
||||
for part in field.split(", ").map(|part| part.trim_start_matches("and ")) {
|
||||
let (values, tools) = part.split_once(" for ").unwrap_or_else(|| panic!("`{part}` pairs no dialog value with tools"));
|
||||
let named = if tools.contains(' ') {
|
||||
assert!(values.split('|').all(|value| groups[0].split('|').any(|tool| tool == value)), "`{part}` names a non-transform tool");
|
||||
values
|
||||
} else {
|
||||
tools
|
||||
};
|
||||
for tool in named.split('|') {
|
||||
assert!(checked.contains(&tool), "the params text gives a `dialog` value for {tool}, which this test does not check");
|
||||
assert!(!named_tools.contains(&tool), "{tool}: the params text gives more than one `dialog` mapping");
|
||||
named_tools.push(tool);
|
||||
}
|
||||
}
|
||||
for group in groups {
|
||||
let documented = clause(doc, &format!("{group} → "), &[';']);
|
||||
let keys: Vec<&str> = documented.split('`').skip(1).step_by(2).collect();
|
||||
let tools: Vec<&str> = group.split('|').collect();
|
||||
assert!(keys.len() == 1 || keys.len() == tools.len(), "{group}: the params text must pair tools with dialog keys");
|
||||
for (index, tool) in tools.into_iter().enumerate() {
|
||||
let expected = keys[if keys.len() == 1 { 0 } else { index }];
|
||||
let mut app = window(VectorcraftApp::new(Session::new(), Default::default()));
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
if tool.ends_with("OnPath") {
|
||||
let text = app.session.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap();
|
||||
app.session.execute("select.set", &json!({"ids": [text["id"]]})).unwrap();
|
||||
}
|
||||
let response = app.run("tool.options", json!({"tool": tool})).unwrap_or_else(|e| panic!("{tool}: {e}"));
|
||||
let expected_dialog =
|
||||
documented_dialog(tool).unwrap_or_else(|| panic!("{tool}: the params text does not say which `dialog` its response holds"));
|
||||
assert_eq!(response["dialog"], expected_dialog.as_str(), "{tool}: its response names a `dialog` other than the params text's");
|
||||
settle(&mut app);
|
||||
let keys = dialog_keys(&app);
|
||||
let key = keys.last().unwrap_or_else(|| panic!("{tool} opens no dialog"));
|
||||
assert_eq!(key, expected, "{tool}: its dialog key differs from the params text");
|
||||
assert!(doc.contains(&format!("`{key}`")), "{tool} opens `{key}`, which the tool.options params text does not name");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// More Options on the Simplify slider opens the dialog whose `key` the ui.simplifyMoreOptions params text names.
|
||||
#[test]
|
||||
fn simplify_more_options_opens_the_dialog_key_its_params_text_names() {
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.simplifyMoreOptions").expect("registered").3;
|
||||
let mut app = menu_dialog_app("object.path.simplify");
|
||||
app.run("ui.menuDialog", json!({"command": "object.path.simplify"})).unwrap();
|
||||
settle(&mut app);
|
||||
app.run("ui.simplifyMoreOptions", json!({})).unwrap();
|
||||
settle(&mut app);
|
||||
let keys = dialog_keys(&app);
|
||||
let key = keys.last().expect("More Options opens a dialog");
|
||||
assert!(doc.contains(&format!("(dialog `{key}`")), "More Options opens `{key}`, which its params text does not name");
|
||||
}
|
||||
@@ -67,7 +67,8 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
|
||||
ui.ctx().request_repaint_after(Duration::from_secs_f64(DELAY - age));
|
||||
return;
|
||||
}
|
||||
if app.any_dialog_open() {
|
||||
// Progress is modal for input, but the window must not block itself on its next pass.
|
||||
if app.asking_dialog_open() {
|
||||
return;
|
||||
}
|
||||
let Shown { title, step, fraction, counts, queued, cancel, hide, .. } = shown;
|
||||
@@ -208,17 +209,21 @@ mod tests {
|
||||
assert_eq!(r["background"], true, "{r}");
|
||||
}
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
assert!(!frame(&mut app, &ctx).contains("Saving a.vectorcraft"), "not before the delay");
|
||||
age(&mut app);
|
||||
frame(&mut app, &ctx);
|
||||
let shown = frame(&mut app, &ctx);
|
||||
assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("waiting"), "{shown}");
|
||||
assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}");
|
||||
let visible: Vec<_> = (0..6).map(|_| (frame(&mut app, &ctx), app.any_dialog_open())).collect();
|
||||
assert_eq!(app.run("file.saveInBackground", json!({})).unwrap()["hidden"], 2);
|
||||
assert!(!frame(&mut app, &ctx).contains("Saving"), "hidden saves aren't shown");
|
||||
assert!(crate::menus::enabled(&app, "file.cancelSave"), "they can still be canceled");
|
||||
go.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
background::wait_all(&mut app);
|
||||
for (shown, modal) in visible {
|
||||
assert!(shown.contains("Saving a.vectorcraft…") && shown.contains("waiting"), "{shown}");
|
||||
assert!(shown.contains("Cancel") && shown.contains("Continue in Background") && !shown.contains("export"), "{shown}");
|
||||
assert!(modal, "progress remains modal for input");
|
||||
}
|
||||
assert!(app.background.jobs.is_empty());
|
||||
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/docs/b.vectorcraft"));
|
||||
app.session.execute("prefs.set", &json!({"values": {"backgroundSave": false}})).unwrap();
|
||||
|
||||
@@ -4,31 +4,8 @@
|
||||
/// The Selection and Direct Selection arrows' fill, painted black or white under their outline.
|
||||
pub const DC_ARROW_FILL: &[u8] = include_bytes!("../../../assets/icons/dc-arrow-fill.svg");
|
||||
|
||||
/// VectorCraft's own `dc-*` icons, drawn with 1.5-unit strokes in a 24-unit view box.
|
||||
pub static ICONS: &[(&str, &[u8])] = &[
|
||||
("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")),
|
||||
("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")),
|
||||
("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")),
|
||||
("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")),
|
||||
("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")),
|
||||
("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")),
|
||||
("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")),
|
||||
("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")),
|
||||
("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")),
|
||||
("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")),
|
||||
("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")),
|
||||
("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")),
|
||||
("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")),
|
||||
("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")),
|
||||
("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")),
|
||||
("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")),
|
||||
("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")),
|
||||
("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")),
|
||||
("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")),
|
||||
("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")),
|
||||
// PLAN: circle-off.svg is plugins-w11's file; the row waits for it.
|
||||
("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")),
|
||||
("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")),
|
||||
("combine", include_bytes!("../../../assets/icons/combine.svg")),
|
||||
("dc-actions", include_bytes!("../../../assets/icons/dc-actions.svg")),
|
||||
("dc-al-bottom", include_bytes!("../../../assets/icons/dc-al-bottom.svg")),
|
||||
("dc-al-center", include_bytes!("../../../assets/icons/dc-al-center.svg")),
|
||||
@@ -244,6 +221,34 @@ pub static ICONS: &[(&str, &[u8])] = &[
|
||||
("dc-wrinkle", include_bytes!("../../../assets/icons/dc-wrinkle.svg")),
|
||||
("dc-zoom-large", include_bytes!("../../../assets/icons/dc-zoom-large.svg")),
|
||||
("dc-zoom-small", include_bytes!("../../../assets/icons/dc-zoom-small.svg")),
|
||||
];
|
||||
|
||||
/// Lucide icons the built-in catalog lacks, drawn with Lucide's 2-unit strokes in a 24-unit view box.
|
||||
pub static LUCIDE_ICONS: &[(&str, &[u8])] = &[
|
||||
("align-center-horizontal", include_bytes!("../../../assets/icons/align-center-horizontal.svg")),
|
||||
("align-center-vertical", include_bytes!("../../../assets/icons/align-center-vertical.svg")),
|
||||
("align-end-horizontal", include_bytes!("../../../assets/icons/align-end-horizontal.svg")),
|
||||
("align-end-vertical", include_bytes!("../../../assets/icons/align-end-vertical.svg")),
|
||||
("align-horizontal-justify-center", include_bytes!("../../../assets/icons/align-horizontal-justify-center.svg")),
|
||||
("align-horizontal-justify-end", include_bytes!("../../../assets/icons/align-horizontal-justify-end.svg")),
|
||||
("align-horizontal-justify-start", include_bytes!("../../../assets/icons/align-horizontal-justify-start.svg")),
|
||||
("align-start-horizontal", include_bytes!("../../../assets/icons/align-start-horizontal.svg")),
|
||||
("align-start-vertical", include_bytes!("../../../assets/icons/align-start-vertical.svg")),
|
||||
("align-vertical-justify-center", include_bytes!("../../../assets/icons/align-vertical-justify-center.svg")),
|
||||
("align-vertical-justify-end", include_bytes!("../../../assets/icons/align-vertical-justify-end.svg")),
|
||||
("align-vertical-justify-start", include_bytes!("../../../assets/icons/align-vertical-justify-start.svg")),
|
||||
("arrow-left-right", include_bytes!("../../../assets/icons/arrow-left-right.svg")),
|
||||
("arrow-up-down", include_bytes!("../../../assets/icons/arrow-up-down.svg")),
|
||||
("chart-column", include_bytes!("../../../assets/icons/chart-column.svg")),
|
||||
("chevron-down", include_bytes!("../../../assets/icons/chevron-down.svg")),
|
||||
("chevron-left", include_bytes!("../../../assets/icons/chevron-left.svg")),
|
||||
("chevron-right", include_bytes!("../../../assets/icons/chevron-right.svg")),
|
||||
("chevrons-left", include_bytes!("../../../assets/icons/chevrons-left.svg")),
|
||||
("chevrons-right", include_bytes!("../../../assets/icons/chevrons-right.svg")),
|
||||
// PLAN: circle-off.svg is plugins-w11's file; the row waits for it.
|
||||
("circle-off", include_bytes!("../../../assets/icons/circle-off.svg")),
|
||||
("clipboard-paste", include_bytes!("../../../assets/icons/clipboard-paste.svg")),
|
||||
("combine", include_bytes!("../../../assets/icons/combine.svg")),
|
||||
("ellipsis", include_bytes!("../../../assets/icons/ellipsis.svg")),
|
||||
("eye-off", include_bytes!("../../../assets/icons/eye-off.svg")),
|
||||
("file-plus", include_bytes!("../../../assets/icons/file-plus.svg")),
|
||||
|
||||
+60
-18
@@ -2,14 +2,24 @@
|
||||
|
||||
use craft::ui::primitives::{AppIcons, icon_names};
|
||||
|
||||
use crate::icon_data::{DC_ARROW_FILL, ICONS};
|
||||
use crate::icon_data::{DC_ARROW_FILL, ICONS, LUCIDE_ICONS};
|
||||
|
||||
/// The fills of the Selection and Direct Selection arrows: black and white whatever the theme, as users
|
||||
/// know them, under an outline in the theme's colour.
|
||||
const FILLS: &[(&str, &[u8], [u8; 4])] = &[("dc-selection", DC_ARROW_FILL, [0, 0, 0, 255]), ("dc-direct", DC_ARROW_FILL, [255, 255, 255, 255])];
|
||||
|
||||
/// The app's icons, for `register_app_icons`.
|
||||
pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.6), ICONS).with_fills(FILLS);
|
||||
/// The app's own icons, for `register_app_icons`. The stroke width is the documents' own, so the framework redraws
|
||||
/// their strokes at the width it draws the catalog's.
|
||||
pub static APP_ICONS: AppIcons = AppIcons::new("vectorcraft", Some(1.5), ICONS).with_fills(FILLS);
|
||||
|
||||
/// The Lucide icons the catalog lacks, with Lucide's own stroke width.
|
||||
pub static LUCIDE_APP_ICONS: AppIcons = AppIcons::new("vectorcraft-lucide", Some(2.0), LUCIDE_ICONS);
|
||||
|
||||
/// Registers both of the app's icon sets beside the framework's catalog.
|
||||
pub fn register() {
|
||||
craft::ui::primitives::register_app_icons(&APP_ICONS);
|
||||
craft::ui::primitives::register_app_icons(&LUCIDE_APP_ICONS);
|
||||
}
|
||||
|
||||
/// Map tool-catalogue icon names to the names of icons that resolve.
|
||||
pub fn tool_icon(name: &str) -> &'static str {
|
||||
@@ -114,23 +124,63 @@ pub fn tool_icon(name: &str) -> &'static str {
|
||||
"tool-print-tiling" => "dc-print-tiling",
|
||||
"tool-zoom" => "zoom_in",
|
||||
// A name that is already an icon maps to itself, as the `'static` name of the set that has it.
|
||||
other => icon_names().iter().copied().chain(APP_ICONS.icons.iter().map(|(n, _)| *n)).find(|n| *n == other).unwrap_or("rect_dashed"),
|
||||
other => icon_names()
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons).map(|(n, _)| *n))
|
||||
.find(|n| *n == other)
|
||||
.unwrap_or("rect_dashed"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::ui::primitives::{has_icon, register_app_icons};
|
||||
use craft::ui::primitives::has_icon;
|
||||
// PLAN: assumed the `craft` facade is a dependency of vectorcraft-ui-egui (Cargo.toml is not in this set's files; craft-ui does not re-export IconId)
|
||||
use craft::behavior::IconId;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn resolves(name: &'static str) -> bool {
|
||||
register_app_icons(&APP_ICONS);
|
||||
register();
|
||||
has_icon(&IconId::new(name))
|
||||
}
|
||||
|
||||
/// The SVG document of the app icon `name`, from either set.
|
||||
fn app_svg(name: &str) -> String {
|
||||
let (_, bytes) = ICONS.iter().chain(LUCIDE_ICONS).find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an app icon"));
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
|
||||
/// The `stroke-width` the document's root `<svg>` element sets, the width of every stroke that sets none of its
|
||||
/// own; `None` for a document drawn with fills.
|
||||
fn root_stroke_width(svg: &str) -> Option<f32> {
|
||||
let root = svg.split("<svg").nth(1)?.split('>').next()?;
|
||||
Some(root.split("stroke-width=\"").nth(1)?.split('"').next()?.parse().unwrap_or(f32::NAN))
|
||||
}
|
||||
|
||||
// Regression test: the tool rail's icons drew uneven outlines. The app set declared a 1.6-unit stroke while its own icons drew 1.5 and
|
||||
// its Lucide copies drew 2, so the framework drew them 6% thinner and 25% heavier than the catalog's icons.
|
||||
/// The framework scales every stroke in a set by the drawn width over the set's declared width, so an icon's
|
||||
/// outline matches the catalog's only when its root stroke width equals its set's declared width. Details with
|
||||
/// a width of their own keep their ratio to the outline.
|
||||
#[test]
|
||||
fn every_app_icon_draws_its_outline_at_the_catalog_width() {
|
||||
let mut off = Vec::new();
|
||||
for set in [&APP_ICONS, &LUCIDE_APP_ICONS] {
|
||||
let declared = set.stroke_width.unwrap_or_else(|| panic!("{} declares its stroke width", set.name));
|
||||
for (name, bytes) in set.icons {
|
||||
let Some(width) = root_stroke_width(&String::from_utf8_lossy(bytes)) else { continue };
|
||||
// The outline's drawn width relative to the catalog's.
|
||||
let relative = width / declared;
|
||||
if !(0.99..=1.01).contains(&relative) {
|
||||
off.push(format!("{name} in {}: {width} draws at {relative:.3} of the catalog width", set.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(off.is_empty(), "app icons whose outlines do not draw at the catalog width: {off:#?}");
|
||||
}
|
||||
|
||||
/// The ways a source line writes an icon id as a literal; a `const` that holds one is read by `const_icon`.
|
||||
const FORMS: [&str; 3] = ["IconId::new(\"", "icon(\"", "icon = \""];
|
||||
|
||||
@@ -153,7 +203,7 @@ mod tests {
|
||||
/// app's set. Other ids built in match arms and tuple tables are not scanned.
|
||||
#[test]
|
||||
fn every_icon_id_literal_and_panel_icon_resolves() {
|
||||
register_app_icons(&APP_ICONS);
|
||||
register();
|
||||
let resolves = |id: &str| has_icon(&IconId::from(std::borrow::Cow::Owned(id.to_owned())));
|
||||
let (mut seen, mut unknown) = (0, Vec::new());
|
||||
let mut stack = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
|
||||
@@ -212,10 +262,7 @@ mod tests {
|
||||
// as opaque as the line, so the line vanished where it crossed the bar.
|
||||
#[test]
|
||||
fn the_cap_icons_mark_the_path_end_in_one_place_over_a_lighter_stroke() {
|
||||
let svg = |name: &str| {
|
||||
let (_, bytes) = crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{name} isn't an icon"));
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
};
|
||||
let svg = app_svg;
|
||||
// The end-of-path line is the icon's last shape, a vertical line `M{x} …V…`.
|
||||
let end_line = |icon: &str| -> String {
|
||||
let last = icon.rsplit("<path").next().unwrap_or_default();
|
||||
@@ -274,12 +321,7 @@ mod tests {
|
||||
// plus or a minus beside it.
|
||||
#[test]
|
||||
fn the_add_and_delete_anchor_tool_icons_are_the_pen_icon_with_a_badge() {
|
||||
let svg = |tool: &str| {
|
||||
let name = tool_icon(tool);
|
||||
let (_, bytes) =
|
||||
crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).unwrap_or_else(|| panic!("{tool} maps to {name}, which isn't an icon"));
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
};
|
||||
let svg = |tool: &str| app_svg(tool_icon(tool));
|
||||
let shapes =
|
||||
|svg: &str| svg.lines().map(|l| l.trim().to_string()).filter(|l| l.starts_with("<path") || l.starts_with("<circle")).collect::<Vec<_>>();
|
||||
let pen = shapes(&svg("tool-pen"));
|
||||
@@ -331,7 +373,7 @@ mod tests {
|
||||
assert!(resolves(name), "{} maps to {name}, which no icon set has", tool.icon);
|
||||
}
|
||||
let catalog = icon_names();
|
||||
for (name, _) in APP_ICONS.icons {
|
||||
for (name, _) in APP_ICONS.icons.iter().chain(LUCIDE_APP_ICONS.icons) {
|
||||
assert!(!catalog.contains(name), "{name} is in the catalog: the app's copy is refused");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,13 +372,22 @@ pub struct VectorcraftApp {
|
||||
|
||||
impl VectorcraftApp {
|
||||
/// Whether a layer that takes the keys (a modal dialog, a popup) showed in the last pass, or a
|
||||
/// modal dialog opened since: a command or a canvas gesture waits while one does. A modeless
|
||||
/// dialog blocks nothing, and the job progress window does not count (its layer has the
|
||||
/// progress role). False before the app has a context.
|
||||
/// modal dialog opened since: a command or a canvas gesture waits while one does. This includes
|
||||
/// job progress, which is a modal layer.
|
||||
pub(crate) fn any_dialog_open(&self) -> bool {
|
||||
self.dialog_open(OpenFilter::Modal)
|
||||
}
|
||||
|
||||
/// Whether a question or popup is open. Applying a job's result can close its progress window.
|
||||
pub(crate) fn asking_dialog_open(&self) -> bool {
|
||||
self.dialog_open(OpenFilter::Asks)
|
||||
}
|
||||
|
||||
/// Whether a layer matching the filter, a popup or a pending app modal is open.
|
||||
fn dialog_open(&self, filter: OpenFilter) -> bool {
|
||||
// A modeless layer with a focus scope (the canvas's task bar) takes keys too, and blocks nothing.
|
||||
let popup = |ctx: &egui::Context| overlay::top(ctx).and_then(|id| overlay::entry(ctx, id)).is_some_and(|e| e.rank == overlay::Rank::Popup);
|
||||
self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, OpenFilter::Modal) || popup(ctx))
|
||||
self.ui_ctx.as_ref().is_some_and(|ctx| overlay::any_open(ctx, filter) || popup(ctx))
|
||||
|| self.dialogs().is_some_and(|d| d.with(|h| h.shows_modal()))
|
||||
}
|
||||
|
||||
|
||||
@@ -1193,7 +1193,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"tool.options",
|
||||
"Tool Options…",
|
||||
"",
|
||||
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options,
Line truncated
|
||||
"{tool: id} what double-clicking a tool button opens. For transform, selection and Type on a Path tools, the dialog names below are their `key` in `ui.inspect`. The returned `dialog` field holds rotate|scale|reflect|shear for the corresponding transform tool, move for selection|directSelection|groupSelection, and command for typeOnPath|verticalTypeOnPath. Tool behavior: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `object.rotate`, `object.scale`, `object.reflect` or `object.shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `object.move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), curvatureCircle → Curvature Circle Tool Options (dialog `curvatureCircleOptions`, fields snapTolerance (screen points, 1–40; 5), snapWithoutGuides, annotateRadius, standardAnchors and constantRadius (all on); OK runs tool.setOption {tool: \"curvatureCircle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `type.pathOptions`, which runs that command; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyl
Line truncated
|
||||
),
|
||||
(
|
||||
"ui.colorGuideOptions",
|
||||
@@ -1532,7 +1532,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.menuDialog",
|
||||
"Menu Dialog",
|
||||
"",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
|
||||
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|object.stepAndRepeat|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.offset|addon.arrange.replace|addon.arrange.size|addon.arrange.match|addon.packaging.setFoldAngle|addon.pathtools.cornerSet|addon.pathtools.divideDashes|addon.pathtools.bridge|addon.pathtools.tangentCircle|addon.type.textTweaker|addon.color.swatchLegend|addon.arrange.randomizeOpacity|addon.arrange.sort|addon.color.applyNearestSwatch|addon.select.byArtboards|addon.select.editPointsOnly|type.smartPunctuation|variable.define|variable.rename|variable.bind|dataset.new|dataset.set|dataset.rename|dataset.select} open the dialog that command's menu item opens (its `key` in ui.inspect is the command id, except `transformEach` for object.transformEach, `envelopeWarp` for object.envelope.makeWithWarp and object.envelope.resetWithWarp, `envelopeMesh` for object.envelope.makeWithMesh and object.envelope.resetWithMesh, `variables` for variable.define and variable.rename and variable.bind and dataset.new and dataset.set and dataset.rename and dataset.select, `envelopeOptions` for object.envelope.options, `smoothSlider` for object.path.smooth, and `simplifySlider` for object.path.simplify; the dialogs of addon.color.applyNearestSwatch and addon.select.byArtboards have no `key`; smoothSlider and simplifySlider are the sliders over the canvas, with field `level`, and object.path.simplify opens its dialog `object.path.simplify` instead once OK in that dialog keeps the settings (`retain`); Set Fold Angle's `angle` is the selected fold lines' angle, and it is refused while the selection has no fold line it can change; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected; variable.rename opens only while the document has a variable, and dataset.set and dataset.rename only while it has a data set, and otherwise the status bar says why; ui.dialog.set, ui.dialog.confirm and ui.dialog.cancel take the dialog's `id` from ui.inspect, or `top`, not its `key`)",
|
||||
),
|
||||
(
|
||||
"ui.widthPointEdit",
|
||||
@@ -1550,19 +1550,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.simplifyAuto",
|
||||
"Auto-Simplify",
|
||||
"",
|
||||
"{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open",
|
||||
"{} the open Simplify slider (Object › Path › Simplify opens it: a canvas popover with slider `level` 0..100, object.path.simplify's level, opening at the level object.path.simplify {auto: true} picks for the selection, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `simplifySlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `object.path.simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open",
|
||||
),
|
||||
(
|
||||
"ui.smoothAuto",
|
||||
"Auto-Smooth",
|
||||
"",
|
||||
"{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: dialog `smoothSlider` with field `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until ui.dialog.confirm keeps it as one undo step) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open",
|
||||
"{} the open Smooth slider (Object › Path › Smooth, the canvas context menu's Smooth… and the Contextual Task Bar's Smooth open it: a canvas popover with slider `level` 0..100, object.path.smooth's level, opening at the level object.path.smooth {auto: true} picks, previewed on the canvas until Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths; ui.inspect lists the popover as dialog `smoothSlider` with field `level`, ui.dialog.set moves the slider (refusing a level outside 0..100), ui.dialog.confirm keeps the result as Enter does, and ui.dialog.cancel restores the paths as Escape does) moves to the level object.path.smooth {auto: true} picks and previews it → {level}; an error when the slider isn't open",
|
||||
),
|
||||
(
|
||||
"ui.simplifyMoreOptions",
|
||||
"More Options",
|
||||
"",
|
||||
"{} the Simplify dialog (dialog `simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open",
|
||||
"{} the Simplify dialog (dialog `object.path.simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open",
|
||||
),
|
||||
(
|
||||
"ui.dialogReset",
|
||||
|
||||
@@ -148,7 +148,7 @@ fn track(app: &mut VectorcraftApp, path: &str, done: Receiver<Result<ReadFile, S
|
||||
|
||||
/// May the active document change now ([`poll`])?
|
||||
pub(crate) fn may_switch(app: &mut VectorcraftApp) -> bool {
|
||||
if app.any_dialog_open() || crate::dialogs::missing_fonts::waiting(app) {
|
||||
if app.asking_dialog_open() || crate::dialogs::missing_fonts::waiting(app) {
|
||||
return false;
|
||||
}
|
||||
let s = &app.session;
|
||||
|
||||
@@ -545,16 +545,20 @@ fn a_file_that_takes_a_while_to_open_shows_a_progress_window() {
|
||||
// The app's clock stands still: a read is only old enough for its window after `age`.
|
||||
app.now_override = Some(0.0);
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
assert_eq!(progress(&mut app, &ctx), "", "nothing opening");
|
||||
start(&mut app, "/art/Big.vectorcraft", bytes("Big"));
|
||||
assert_eq!(progress(&mut app, &ctx), "", "not at once");
|
||||
age(&mut app);
|
||||
progress(&mut app, &ctx); // a new window measures itself unseen first
|
||||
let texts = progress(&mut app, &ctx);
|
||||
for want in ["Opening Big.vectorcraft…", "Reading the file…", "Cancel", "Continue in Background"] {
|
||||
assert!(texts.contains(want), "{want} in {texts}");
|
||||
for _ in 0..6 {
|
||||
let texts = progress(&mut app, &ctx);
|
||||
for want in ["Opening Big.vectorcraft…", "Reading the file…", "Cancel", "Continue in Background"] {
|
||||
assert!(texts.contains(want), "{want} in {texts}");
|
||||
}
|
||||
assert!(!texts.contains("waiting"), "{texts}");
|
||||
assert!(app.any_dialog_open(), "progress remains modal for input");
|
||||
}
|
||||
assert!(!texts.contains("waiting"), "{texts}");
|
||||
start(&mut app, "/art/Next.vectorcraft", bytes("Next"));
|
||||
let texts = progress(&mut app, &ctx);
|
||||
assert!(texts.contains("Opening Big.vectorcraft…") && texts.contains("waiting"), "{texts}");
|
||||
@@ -569,6 +573,24 @@ fn a_file_that_takes_a_while_to_open_shows_a_progress_window() {
|
||||
assert_eq!(app.session.documents().len(), before + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_ready_while_progress_is_visible_opens_without_hiding_progress() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Services::default());
|
||||
app.now_override = Some(0.0);
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
start(&mut app, "/art/Big.vectorcraft", bytes("Big"));
|
||||
age(&mut app);
|
||||
progress(&mut app, &ctx);
|
||||
assert!(progress(&mut app, &ctx).contains("Opening Big.vectorcraft"));
|
||||
assert!(app.any_dialog_open());
|
||||
|
||||
open_ready(&mut app);
|
||||
assert!(app.opening.pending.is_empty());
|
||||
assert_eq!(app.session.doc().unwrap().path.as_deref(), Some("/art/Big.vectorcraft"));
|
||||
assert_eq!(progress(&mut app, &ctx), "", "completion closes progress");
|
||||
}
|
||||
|
||||
/// #5930: the progress window's Cancel (`file.cancelOpen`): the file doesn't open, even once it
|
||||
/// has been read, and the status bar no longer says it is opening.
|
||||
#[test]
|
||||
|
||||
@@ -341,7 +341,7 @@ fn rows_list_by_depth_and_ruler_guide_nodes_get_no_object_row() {
|
||||
/// guide kind's ruler, and both glyphs are in the app's icon set.
|
||||
#[test]
|
||||
fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() {
|
||||
use craft::ui::primitives::{has_icon, register_app_icons};
|
||||
use craft::ui::primitives::has_icon;
|
||||
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
@@ -355,7 +355,7 @@ fn horizontal_and_vertical_guide_rows_show_their_own_drawn_glyphs() {
|
||||
};
|
||||
let (across, down) = (icon_of(false), icon_of(true));
|
||||
assert_ne!(across, down, "the two kinds of guide rows look alike");
|
||||
register_app_icons(&crate::icons::APP_ICONS);
|
||||
crate::icons::register();
|
||||
for icon in [&across, &down] {
|
||||
assert!(has_icon(icon), "{icon:?} is in no icon set, so the row draws nothing");
|
||||
}
|
||||
|
||||
@@ -445,7 +445,7 @@ fn spawn_labeled(
|
||||
/// the file is placed unless the tool has a preview open (the Flare tool after its center drag).
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
settle_swatch_paste(app);
|
||||
while !app.any_dialog_open()
|
||||
while !app.asking_dialog_open()
|
||||
&& !app.session.in_interaction()
|
||||
&& !(app.session.tool_busy() && app.session.pointer_held())
|
||||
&& let Some(p) = app.placing.pending.first()
|
||||
|
||||
@@ -1980,6 +1980,7 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() {
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
|
||||
let ctx = crate::testing::ui_context();
|
||||
app.adopt_context(&ctx);
|
||||
assert_eq!(progress(&mut app, &ctx), "", "nothing placing");
|
||||
|
||||
let slow_path = saved("progress", "slow.png", &picture(Png, 100, 100));
|
||||
@@ -2002,10 +2003,12 @@ fn a_file_that_takes_a_while_to_place_shows_a_progress_window() {
|
||||
start(&mut app, &json!({"path": next_path, "at": [200, 150]}), false).unwrap();
|
||||
let texts = progress(&mut app, &ctx);
|
||||
assert!(texts.contains("Placing slow.png…") && texts.contains("waiting"), "{texts}");
|
||||
assert!(app.any_dialog_open());
|
||||
|
||||
// Release and finish
|
||||
// Releasing the read applies both files without dismissing the progress window first.
|
||||
drop(go);
|
||||
placed(&mut app);
|
||||
assert_eq!(progress(&mut app, &ctx), "", "completion closes progress");
|
||||
}
|
||||
|
||||
/// #5930: cancelling a place aborts the operation, drops the parsed asset, leaves the document
|
||||
|
||||
@@ -458,7 +458,7 @@ pub fn poll(app: &mut VectorcraftApp) {
|
||||
poll_checks(app);
|
||||
let mut i = 0;
|
||||
while let Some(r) = app.plugin_runs.running.get(i) {
|
||||
let dialog = app.any_dialog_open() || app.session.script_running();
|
||||
let dialog = app.asking_dialog_open() || app.session.script_running();
|
||||
let ended = match &r.backend {
|
||||
Backend::Thread(_) if dialog => None,
|
||||
Backend::Worker(..) if dialog => watch_worker(app, i),
|
||||
|
||||
@@ -130,7 +130,7 @@ fn stop(app: &mut VectorcraftApp) {
|
||||
/// Runs the command of the search that is done (each frame). Not while a dialog is open, nor while
|
||||
/// an interaction is open or a tool drags with the pointer button held, as [`crate::trace_runs::poll`].
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) {
|
||||
if app.asking_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) {
|
||||
return;
|
||||
}
|
||||
let Some(r) = &app.retype_runs.running else { return };
|
||||
|
||||
@@ -11,7 +11,7 @@ fn the_cut_tools_have_their_own_icons_and_toolbar_slot() {
|
||||
let info = vectorcraft_tools::tool_info(tool).unwrap();
|
||||
assert_eq!(icons::tool_icon(info.icon), icon);
|
||||
// The app registers its icons at start; a test run alone in its process must too.
|
||||
craft::ui::primitives::register_app_icons(&icons::APP_ICONS);
|
||||
icons::register();
|
||||
assert!(craft::ui::primitives::has_icon(&IconId::new(icon)), "{icon}");
|
||||
assert!(crate::toolbar::BASIC.iter().flat_map(|(_, slots)| slots.iter()).any(|s| s.contains(&tool) && s.contains(&"knife")));
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ pub fn start(app: &mut VectorcraftApp, command: &str, p: Value, from_panel: bool
|
||||
/// dialog is open (its OK acts on the active document, which a trace's result changes), nor while
|
||||
/// an interaction is open or a tool drags with the pointer button held, as [`crate::placing::poll`].
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
if app.any_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) {
|
||||
if app.asking_dialog_open() || app.session.in_interaction() || (app.session.tool_busy() && app.session.pointer_held()) {
|
||||
return;
|
||||
}
|
||||
let mut i = 0;
|
||||
|
||||
@@ -164,10 +164,22 @@ fn menu_access_custom_shortcut_typing_tool_altgr_and_cancel_ownership() {
|
||||
assert_eq!(s.app.session.tool_id(), "pen", "after the dismissal the letter selects its tool");
|
||||
s.app.select_tool("selection");
|
||||
|
||||
// While the bar holds the keys after a lone Alt, the letter does not reach the tool either.
|
||||
// A lone Alt over the canvas is a tool modifier let go: the bar does not take the keys, and the next tool
|
||||
// letters choose their tools instead of opening View or Window.
|
||||
s.bare_alt();
|
||||
s.settle();
|
||||
assert!(is_focused(&s.ctx), "a lone Alt gives the bar the keys");
|
||||
assert!(!is_focused(&s.ctx) && !is_open(&s.ctx), "a lone Alt over the canvas leaves the bar alone");
|
||||
s.letter(Key::V, "v", Modifiers::NONE);
|
||||
assert!(!is_open(&s.ctx), "V after a lone Alt opens no menu");
|
||||
s.letter(Key::P, "p", Modifiers::NONE);
|
||||
assert_eq!(s.app.session.tool_id(), "pen", "P after a lone Alt chooses the Pen");
|
||||
s.app.select_tool("selection");
|
||||
|
||||
// While the bar holds the keys after F10, the letter does not reach the tool.
|
||||
s.frame(vec![key(Key::F10, true, Modifiers::NONE)]);
|
||||
s.frame(vec![key(Key::F10, false, Modifiers::NONE)]);
|
||||
s.settle();
|
||||
assert!(is_focused(&s.ctx), "F10 gives the bar the keys");
|
||||
s.letter(Key::P, "p", Modifiers::NONE);
|
||||
assert_eq!(s.app.session.tool_id(), "selection", "a focused bar takes the letter");
|
||||
s.click(outside);
|
||||
|
||||
@@ -194,8 +194,10 @@ for `eyedropper` it opens Eyedropper Options, an `eyedropperOptions` dialog (fie
|
||||
`apply`, the attribute trees of `eyedropper.setOptions`) whose `ui.dialog.confirm` runs `eyedropper.setOptions` (what
|
||||
`appearance.copyFrom` copies). For `hand` it fits the artboard in the window (`view.fitArtboard`) and for `zoom` it
|
||||
shows 100% (`view.actualSize`). For `rotate`, `scale`, `reflect` and `shear` it opens the same dialog as Object ›
|
||||
Transform (dialog kind = the tool id), or fails with `nothing selected`. For `selection`, `directSelection` and
|
||||
`groupSelection` it opens the Move dialog (kind `move`), with the same failure; Move opens on the offset of the last
|
||||
Transform (`key` in `ui.inspect`: `object.<tool>`, such as `object.rotate`), or fails with `nothing selected`.
|
||||
The returned `dialog` field holds `rotate`, `scale`, `reflect` or `shear`, respectively. For `selection`, `directSelection` and
|
||||
`groupSelection` it opens the Move dialog (`key` in `ui.inspect`: `object.move`), with the same failure, and returns
|
||||
`dialog: "move"`. Move opens on the offset of the last
|
||||
drag or Move (`dx`, `dy`) and with the `copy`, `objects` and `preview` it was last confirmed with (its `patterns` is
|
||||
the `transformPatternTiles` preference, which its OK sets). `ui.key` Enter with one of those seven
|
||||
tools opens its dialog too (nothing happens without a selection), with the transform tools' `origin` at their reference
|
||||
@@ -203,8 +205,9 @@ point. For `lineSegment`, `arc`, `rectangularGrid` and `polarGrid` it opens the
|
||||
click opens (kind = the tool id), without `x` and `y` and with `__toolOptions: true`, whose `ui.dialog.confirm` runs
|
||||
`tool.setOption {tool, values}` and draws nothing; the next drag with the tool and its click dialog use the values
|
||||
(the line's `fillLine`, the grids' Default Size `width`, `height` and `reference` too). For `typeOnPath` and
|
||||
`verticalTypeOnPath` it opens Type on a Path Options for the selected type on a path (a `command` dialog running
|
||||
`type.pathOptions`), or fails when no type on a path is selected. Gradient tool handles snap to
|
||||
`verticalTypeOnPath` it opens Type on a Path Options for the selected type on a path (`key` in `ui.inspect`:
|
||||
`type.pathOptions`, which runs that command), or fails when no type on a path is selected. The returned `dialog` field
|
||||
holds `command`. Gradient tool handles snap to
|
||||
anchors, edges and smart guides; Shift constrains them to 45° steps from the `constrainAngle` preference.
|
||||
|
||||
Effect dialogs: `engine.execute {command: "effect.dialog", params: {effect, index?, item?}}` opens the `effect` dialog
|
||||
@@ -637,9 +640,9 @@ Spot Colors: the Swatches panel menu's Spot Colors… (`ui.spotColors`) opens th
|
||||
true shows and separates spot colours defined in Lab from their Lab values, false from their working-CMYK
|
||||
equivalents); `ui.dialog.confirm` runs `swatch.spotOptions {useLab}` as one undo step.
|
||||
|
||||
Scale options: `ui.menuDialog {command}` opens the dialog a command's menu item opens (`object.scale` → `scale`,
|
||||
Scale options: `ui.menuDialog {command}` opens the dialog a command's menu item opens (`object.scale` → `object.scale`,
|
||||
`object.transformEach` → `transformEach`, also Move, Rotate, Reflect, Shear and the Path dialogs). The Scale dialog
|
||||
(`scale`) and Object → Transform → Transform Each… (dialog `transformEach`: `scaleH`,
|
||||
(`object.scale`) and Object → Transform → Transform Each… (dialog `transformEach`: `scaleH`,
|
||||
`scaleV` %, and `absH`, `absV` pt, the width and height each object becomes with `relative` false, absent while they
|
||||
read "Mixed"; `moveH`, `moveV` pt, `rotate` °, `reflectX`, `reflectY`, `random`, `reference` 0–8, `copy`, `preview`)
|
||||
have the fields `corners` (Scale Corners) and `strokes` (Scale Strokes & Effects). They start from the preferences
|
||||
@@ -768,8 +771,8 @@ stays open.
|
||||
Document Raster Effects Settings: Effect → Document Raster Effects Settings… (`ui.rasterEffectsSettingsDialog` for
|
||||
agents) opens the `rasterEffectsSettings` dialog. Its fields are what `document.rasterEffectsSettings` reports
|
||||
(`resolution`, `colorModel`, `background`, `antiAlias`, `clippingMask`, `addAround` in pt, `preserveSpotColors`);
|
||||
`ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens a
|
||||
`command` dialog for `object.rasterize` whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`,
|
||||
`ui.dialog.confirm` runs it with them as one undo step; a bad value keeps the dialog open. Object → Rasterize… opens the
|
||||
`object.rasterize` dialog, whose fields (`ppi`, `colorModel`, `background`, `antiAlias`, `clippingMask`,
|
||||
`addAround`) start from these settings. `colorModel`, `antiAlias` (`none`, `art`, `type`) and `background` (`white`,
|
||||
`transparent`) are dropdowns; `ui.dialog.set` also takes any other value the command takes, and the dialog sends it
|
||||
unchanged.
|
||||
@@ -1074,7 +1077,7 @@ Colour adjustment effects (Effect → Color Adjustments) open the `effect` dialo
|
||||
`channel` for Curves and Levels, `points` for Curves, `color` for Shift to Color) and they preview live; set them with
|
||||
`ui.dialog.set` and `ui.dialog.confirm` to apply (Curves also has a graph: drag its points). Object → Vector
|
||||
Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "object.vectorHalftone"}}`) opens the
|
||||
`vectorHalftone` dialog (fields `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal`,
|
||||
`object.vectorHalftone` dialog (fields `shape`, `frequency`, `angle`, `mode`, `color`, `invert`, `clip`, `keepOriginal`,
|
||||
`preview`): it previews live and `ui.dialog.confirm` keeps the halftone as one undo step.
|
||||
|
||||
Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and
|
||||
|
||||
+32
-23
@@ -8745,9 +8745,12 @@ A path with only lone anchors selected, and every path with `wholePaths: true`,
|
||||
{"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}}
|
||||
```
|
||||
|
||||
In the desktop app, Object › Path › Simplify opens the slider (`ui.menuDialog {command: "object.path.simplify"}`,
|
||||
dialog `simplifySlider` with field `level`) at the Auto-Simplify level for the selection and previews the result until
|
||||
`ui.dialog.confirm`. `ui.simplifyAuto` moves the open slider back to the Auto-Simplify level, and `ui.simplifyMoreOptions`
|
||||
In the desktop app, unless retained settings select the Simplify dialog (see below), Object › Path › Simplify opens a
|
||||
canvas popover (`ui.menuDialog {command: "object.path.simplify"}`) with a slider for `level` (0..100) at the Auto-Simplify level for the selection. The canvas previews the result.
|
||||
Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise; Escape restores the paths. `ui.inspect` lists
|
||||
the popover as dialog `simplifySlider` with field `level`. `ui.dialog.set` moves the slider and refuses a level outside
|
||||
0..100, `ui.dialog.confirm` keeps the result as Enter does, and `ui.dialog.cancel` restores the paths as Escape does.
|
||||
`ui.simplifyAuto` moves the open slider back to the Auto-Simplify level, and `ui.simplifyMoreOptions`
|
||||
opens the Simplify dialog at the slider's tolerance. When OK confirms the dialog with `retain` ticked, the menu item opens
|
||||
the dialog on those settings next time.
|
||||
|
||||
@@ -8833,9 +8836,11 @@ are VectorCraft's own.
|
||||
|
||||
In the desktop app, Object › Path › Smooth, the canvas context menu's Smooth… (listed while the selection holds a
|
||||
path) and the Contextual Task Bar's Smooth (with a path selected whole with the Direct Selection tool) open the
|
||||
slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` with field `level`) at the
|
||||
Auto-Smooth level, and the slider previews the result until `ui.dialog.confirm`; `ui.smoothAuto` moves the open
|
||||
slider back to the Auto-Smooth level.
|
||||
canvas popover (`ui.menuDialog {command: "object.path.smooth"}`) with a slider for `level` (0..100) at the
|
||||
Auto-Smooth level. The canvas previews the result. Enter or a click outside the popover keeps the result, recording one undo step if the paths changed and none otherwise;
|
||||
Escape restores the paths. `ui.inspect` lists the popover as dialog `smoothSlider` with field `level`. `ui.dialog.set`
|
||||
moves the slider and refuses a level outside 0..100, `ui.dialog.confirm` keeps the result as Enter does, and
|
||||
`ui.dialog.cancel` restores the paths as Escape does. `ui.smoothAuto` moves the open slider back to the Auto-Smooth level.
|
||||
|
||||
## Circle through two or three points
|
||||
|
||||
@@ -10859,13 +10864,17 @@ preferences (VectorCraft's own place and form). A category without a file has th
|
||||
defaults. Runs without preferences (`VECTORCRAFT_NO_PREFS`) and the web build have no folder, so every document starts
|
||||
with the defaults.
|
||||
|
||||
- `file.newProfiles` lists `{profiles: [{name, customized?, path?}], folder?}`. `customized` is true when the category
|
||||
has a file. A request whose read roots leave out the folder gets neither `customized` nor `path`.
|
||||
- `file.newProfiles` lists `{profiles: [{name, customized?, unusable?, path?}], folder?}`. `customized` is true when the
|
||||
category has a file. `unusable` is `"not a plain file"` when that file is a link or a folder: `file.new` does not
|
||||
read it, so new documents of the category get the defaults. Manage Profiles dims its name and turns Edit off; Reset
|
||||
stays on for a link and is off for a folder. A request whose read roots leave out the folder gets none of
|
||||
`customized`, `unusable` and `path`.
|
||||
- `file.newProfiles.edit {name}` opens the profile as a document and returns `document.open`'s result. A category
|
||||
without a file gets the shipped profile written first. File › Save keeps the changes, and the next `file.new` reads
|
||||
them.
|
||||
them. A profile whose file is a link or a folder gives an error instead.
|
||||
- `file.newProfiles.reset {name}` deletes the category's file, so the shipped profile applies again, and returns
|
||||
`{name, reset}`. `reset` is false when there was no file. A copy of the profile that is open stays open.
|
||||
`{name, reset}`. `reset` is false when there was no file. A link is removed and the file it leads to is kept; a
|
||||
folder is not deleted, and the command gives an error. A copy of the profile that is open stays open.
|
||||
- `file.newProfiles.applyDefaults {name}` (Use Profile Defaults, VectorCraft's own command) gives the active document
|
||||
the default fill and stroke and the default font of another profile. The document's Default Graphic Style takes the
|
||||
fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] takes the profile's
|
||||
@@ -11173,7 +11182,7 @@ Artboard tool has selected, else its active one. One artboard takes `name`, trim
|
||||
order, `name-1`, `name-2` and so on. A locked artboard is renamed too. An empty name fails with
|
||||
`` `name` must not be empty ``, a name that is not a string fails with `` `name` must be a string ``, and an artboard
|
||||
that is not in the document fails with `no such artboard`. When every artboard already has its new name, the command
|
||||
records no undo step → `{renamed: [index…]}`. With no params, a menu click opens the `renameArtboards` dialog (fields
|
||||
records no undo step → `{renamed: [index…]}`. With no params, a menu click opens the `artboard.rename` dialog (fields
|
||||
`name` and `indices`), and OK with an empty name changes nothing. The Artboards panel's name field runs this command too.
|
||||
|
||||
Switch Orientation: `artboard.switchOrientation {index? | indices?, scaleArt?, patterns?, lockedAndHidden?}` swaps the width and height of each
|
||||
@@ -11278,7 +11287,7 @@ The reply adds `indices` and `moved`, the number of artboards that moved; with n
|
||||
locked, or already in place) no undo step is recorded. Without `indices` the command lays out every artboard, and its
|
||||
reply is `{artboards, rows, columns}`; `at` there puts the grid's top-left at `at` too. In the desktop app, the
|
||||
Artboard tool's canvas menu and Contextual Task Bar (Rearrange), and while the Artboard tool is in use the Artboards
|
||||
panel's menu (Rearrange…), open the Rearrange dialog (kind `rearrangeArtboards` with field `indices`) for the
|
||||
panel's menu (Rearrange…), open the Rearrange dialog (key `artboard.rearrange` with field `indices`) for the
|
||||
artboards the tool has selected, showing their count. With another tool Rearrange… is off. The panel's Rearrange
|
||||
button stays Rearrange All Artboards. Its OK changes nothing yet: the grid's outline follows the pointer, and the
|
||||
next press on the canvas runs `artboard.rearrange` with `indices` and `at` at the press, as one undo step. Enter, when
|
||||
@@ -15652,7 +15661,7 @@ effects keep their colours.
|
||||
## Vector halftone
|
||||
|
||||
`object.vectorHalftone` turns the selection into vector dots, lines or shapes sized by its
|
||||
tone (mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the
|
||||
tone (the `shape` values are those of the live effect below, Euclidean and Elliptical dots included; mono, or CMYK screens multiplied over each other), clipped to the art's outline by default. An image in the
|
||||
art that can't be decoded is sampled as blank (no dots, or full dots with `invert`), and the result carries the
|
||||
`warning` that Flatten Transparency gives:
|
||||
|
||||
@@ -17013,7 +17022,7 @@ Commands:
|
||||
With `fit`, every run between corners and ends holds a whole number of dashes, all stretched or squeezed alike so it
|
||||
starts and ends on a dash (a closed path with no corner holds whole periods); otherwise the lengths are exact and the
|
||||
last piece of each run is what is left. The pieces are selected; more than 100,000 is refused. → `{ids, dashes}`.
|
||||
Divide into Dashes… opens a dialog (`ui.menuDialog {command}`, kind `divideDashes`) whose fields are these
|
||||
Divide into Dashes… opens a dialog (`ui.menuDialog {command}`, key `addon.pathtools.divideDashes`) whose fields are these
|
||||
parameters, with Preview.
|
||||
- `addon.pathtools.expandDashes {ids?}` turns the dashed stroke of each path and compound path under `ids` (default:
|
||||
the selection) into separate open paths, one per dash, as one undo step (Object › Plug-ins › Path Precision Tools ›
|
||||
@@ -17060,7 +17069,7 @@ Commands:
|
||||
reach has one circle inside the other, when no pair within reach can be bridged (suggesting a larger radius or gap
|
||||
only when the largest would bridge a pair of them under these rules), when no two circles are within reach, and above 2,000 circles or 8,000 bridges. → `{ids, alone}`:
|
||||
the shapes and the circles left as they are, with `id` as well for two circles. Smooth Bridge… opens a dialog
|
||||
(`ui.menuDialog {command}`, kind `smoothBridge`) with Constant Gap (a Gap field in place of the Radius field in
|
||||
(`ui.menuDialog {command}`, key `addon.pathtools.bridge`) with Constant Gap (a Gap field in place of the Radius field in
|
||||
percent), Reach (unavailable when the selection, a selected group's objects counted, holds two objects), Keep Originals
|
||||
and Preview.
|
||||
- `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths
|
||||
@@ -17081,7 +17090,7 @@ Commands:
|
||||
circles), when `circle` is past the last one, when `ids` names an object twice, when the shapes lie at one point or
|
||||
are too small for the radius, above 2,000 segments in all, and when the search for other shapes goes past its
|
||||
limits. → `{ids, found}` (`found`: how many circles touch the shapes). Tangent Circle… opens a dialog
|
||||
(`ui.menuDialog {command}`, kind `tangentCircle`) with the radius (used with two shapes selected; 36 pt to start), a
|
||||
(`ui.menuDialog {command}`, key `addon.pathtools.tangentCircle`) with the radius (used with two shapes selected; 36 pt to start), a
|
||||
Circle menu (All, or one circle by number, as many as the last preview found) and Preview, which starts on.
|
||||
- `addon.pathtools.cornerSet {ids?, anchors?, items?, radius, kind?, every?, minAngle?, maxAngle?}` cuts live corners, the ones Direct Selection's
|
||||
corner widgets and the Corners dialog edit, as one undo step. `ids` (default: the selection) are the paths and
|
||||
@@ -17668,8 +17677,8 @@ anchor points selected on them. Nothing selected, no anchor point left to keep (
|
||||
{"name":"run_command","arguments":{"command":"addon.select.editPointsOnly","params":{"segmentEnds":false}}}
|
||||
```
|
||||
|
||||
In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog with Keep Ends of Selected
|
||||
Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection
|
||||
In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog (`ui.menuDialog {command}`, key
|
||||
`addon.select.editPointsOnly`) with Keep Ends of Selected Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection
|
||||
back.
|
||||
After a failed preview, a successful preview or OK clears the dialog's error only if that error is still the current
|
||||
status message. Messages from other commands stay displayed.
|
||||
@@ -17683,7 +17692,7 @@ Object › Vector Halftone without Keep Original, and the Appearance panel reope
|
||||
|
||||
| Parameter | Values (default) | Does |
|
||||
|---|---|---|
|
||||
| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line` (`circle`) | The dot shape; lines join along a row |
|
||||
| `shape` | `circle`, `ellipse`, `square`, `diamond`, `line`, `euclidean`, `elliptical` (`circle`) | The dot shape; lines join along a row; `euclidean` dots are round, meet corner to corner at 50% and turn into round holes past it; `elliptical` dots are long, join into chains along their length at 40% and on every side at 60%, then turn into long holes |
|
||||
| `frequency` | lines per inch 1…300 (20) | Cells per inch of the screen |
|
||||
| `angle` | degrees (45) | The screen angle; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it |
|
||||
| `mode` | `mono`, `cmyk` (`mono`) | One screen following lightness, or four ink screens following the art's ink amounts, multiplied over each other |
|
||||
@@ -17808,7 +17817,7 @@ as `object.setBounds` measures them (Use Preview Bounds), except Arrange in Grid
|
||||
Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the
|
||||
active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard,
|
||||
and fails with nothing selected. Arrange in Grid…, Replace with Top Object…, Set Size of Each…, Randomize Opacity… and Sort Objects… open dialogs
|
||||
(`ui.menuDialog {command}`, dialog kinds `arrangeGrid`, `arrangeReplace`, `arrangeSize`, `arrangeOpacity` and `arrangeSort`) whose
|
||||
(`ui.menuDialog {command}`; each dialog's `key` is its command id, such as `addon.arrange.grid`) whose
|
||||
fields are the command's parameters, with Preview (Randomize Opacity's seed, and Sort Objects' `seed`, which is not shown, start new whenever the document has changed); Set Size of Each's `__width` and `__height` say which sizes OK applies.
|
||||
Match Objects… opens a dialog of its own in the same way, keyed by its command, whose fields are the command's
|
||||
parameters, with Preview; it opens on the key object when the selection has one, else on the top object, and OK is
|
||||
@@ -18011,7 +18020,7 @@ are skipped as `addon.packaging.setRole` skips them; cut lines and objects witho
|
||||
command fails when the objects hold no Crease, Partial Cut or Perforation line it can change, and with an angle outside
|
||||
the range or one that is not a number. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`.
|
||||
|
||||
Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, kind `command`) on the
|
||||
Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, key `addon.packaging.setFoldAngle`) on the
|
||||
angle that the selected lines it can change fold at (90° when they differ), shown with every decimal place it has.
|
||||
While the selection holds no such line, `ui.menuDialog` fails with the reason the command gives. While the selection
|
||||
holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it as it is typed, as one undo step; canceling the edit restores the lines' angles and leaves no undo step. The Reset button beside it takes their own angles away.
|
||||
@@ -18200,8 +18209,8 @@ A `start` or `end` byte inside a character rounds down to that character's start
|
||||
| `seed` | whole number (0): `random` with the same seed and text gives the same values |
|
||||
| `skipSpaces` | true: spaces and line breaks keep their values and don't count |
|
||||
|
||||
→ `{count (characters changed), ids}`. Text Tweaker… opens a dialog (`ui.menuDialog {command}`, dialog kind
|
||||
`textTweaker`) whose fields are the command's parameters, with Preview; another attribute starts from its own
|
||||
→ `{count (characters changed), ids}`. Text Tweaker… opens a dialog (`ui.menuDialog {command}`, dialog key
|
||||
`addon.type.textTweaker`) whose fields are the command's parameters, with Preview; another attribute starts from its own
|
||||
default values, and the seed starts new whenever the document has changed.
|
||||
|
||||
```json
|
||||
|
||||
@@ -1462,6 +1462,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`).
|
||||
- Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`).
|
||||
- Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369).
|
||||
- Vector Halftone (Object › Vector Halftone and the live effect) has Euclidean and Elliptical dot shapes: Euclidean dots meet corner to corner at 50% and become round holes past it; Elliptical dots join into chains at 40% and on every side at 60%, then become long holes. Each dot covers its cell's tone.
|
||||
- Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`).
|
||||
- Shift+Tab (`window.panels`) shows and hides the dock and the floating panels and leaves the toolbar and the Control bar as they are; hiding the panels with Tab or Shift+Tab also closes a panel popped out of the icon column.
|
||||
- The second Tab (`window.dock`) shows again only the bars the first Tab hid, after a restart too: a Control bar that was off stays off, a toolbar hidden with Window › Tools stays hidden, and panels shown with Shift+Tab in between stay shown.
|
||||
|
||||
@@ -36,6 +36,11 @@ def earlier(conclusion):
|
||||
return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}]
|
||||
|
||||
|
||||
def split_job(shard, status, completed_at=None):
|
||||
return {"name": f"gate / cache warm {shard}/5 (ubuntu-24.04)", "status": status,
|
||||
"conclusion": "success" if status == "completed" else None, "completed_at": completed_at}
|
||||
|
||||
|
||||
class SaveStep(unittest.TestCase):
|
||||
def test_the_leg_is_saving_once_its_save_step_starts(self):
|
||||
self.assertFalse(clear.saving(warm_job("in_progress", steps=[("Setup", "completed", "success"), ("Gate", "in_progress", None)])))
|
||||
@@ -99,6 +104,34 @@ class Deadline(unittest.TestCase):
|
||||
self.assertFalse(clear.started_late(warm_job("queued"), self.began))
|
||||
self.assertFalse(clear.started_late(None, self.began))
|
||||
|
||||
def test_split_progress_suspends_the_start_deadline(self):
|
||||
for status in ("queued", "in_progress"):
|
||||
with self.subTest(status=status):
|
||||
jobs = [split_job(1, "completed", "2026-11-28T06:00:00Z"), split_job(2, status)]
|
||||
ready = clear.start_wait_began(jobs, self.began)
|
||||
self.assertIsNone(ready)
|
||||
now = self.began + timedelta(seconds=clear.START_SECONDS + 60)
|
||||
self.assertFalse(clear.start_overdue(None, now, ready))
|
||||
self.assertFalse(clear.started_late(warm_job("in_progress", started_at=now.isoformat()), ready))
|
||||
|
||||
def test_the_last_split_completion_starts_the_wait(self):
|
||||
jobs = [split_job(1, "completed", "2026-11-28T08:00:00Z"),
|
||||
split_job(2, "completed", "2026-11-28T07:00:00Z")]
|
||||
ready = clear.start_wait_began(jobs, self.began)
|
||||
self.assertEqual(ready, clear.parse_time("2026-11-28T08:00:00Z"))
|
||||
self.assertFalse(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS), ready))
|
||||
self.assertTrue(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS + 1), ready))
|
||||
self.assertFalse(clear.started_late(warm_job("in_progress", started_at="2026-11-28T08:01:00Z"), ready))
|
||||
late = warm_job("in_progress", started_at=(ready + timedelta(seconds=clear.START_SECONDS + 1)).isoformat())
|
||||
self.assertTrue(clear.started_late(late, ready))
|
||||
|
||||
def test_without_split_legs_the_script_start_starts_the_wait(self):
|
||||
self.assertEqual(clear.start_wait_began([], self.began), self.began)
|
||||
self.assertEqual(clear.start_wait_began(ME + [warm_job("queued")], self.began), self.began)
|
||||
|
||||
def test_a_split_completion_without_a_timestamp_does_not_start_the_wait(self):
|
||||
self.assertIsNone(clear.start_wait_began([split_job(1, "completed")], self.began))
|
||||
|
||||
|
||||
class Workflow(unittest.TestCase):
|
||||
ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text()
|
||||
@@ -116,10 +149,17 @@ class Workflow(unittest.TestCase):
|
||||
self.fail(f"no timeout-minutes under {job}")
|
||||
|
||||
def test_the_job_outlasts_the_start_wait_and_the_save_wait(self):
|
||||
# Five minutes are left for the steps before the script and for the deletion.
|
||||
# Without split legs, five minutes remain for setup and deletion.
|
||||
spare = self.timeout_minutes("cold-cache-clear") * 60 - clear.START_SECONDS - clear.GIVE_UP_SECONDS
|
||||
self.assertGreaterEqual(spare, 5 * 60)
|
||||
|
||||
def test_the_job_allows_both_warm_builds_within_the_hosted_job_limit(self):
|
||||
# Runner waits and the full start allowance may exceed the 360-minute job limit.
|
||||
timeout = self.timeout_minutes("cold-cache-clear")
|
||||
spare = timeout * 60 - self.timeout_minutes("gate") * 60 - clear.GIVE_UP_SECONDS
|
||||
self.assertGreaterEqual(spare, 5 * 60)
|
||||
self.assertEqual(timeout, 360)
|
||||
|
||||
def test_the_save_wait_outlasts_the_gate(self):
|
||||
self.assertGreater(clear.GIVE_UP_SECONDS, self.timeout_minutes("gate") * 60)
|
||||
|
||||
@@ -156,6 +196,9 @@ class Jobs(unittest.TestCase):
|
||||
self.assertTrue(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (ubuntu-24.04)", "cancelled")]))
|
||||
self.assertFalse(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (${{ matrix.os }})", "skipped")]))
|
||||
self.assertFalse(clear.legs_stopped([done("gate / test 1/5 (ubuntu-24.04)", "failure")]))
|
||||
# With warm-split, the saving `cache warm (<os>)` leg also needs every `cache warm <k>/<N>` leg.
|
||||
self.assertTrue(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "failure")]))
|
||||
self.assertFalse(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "success")]))
|
||||
|
||||
|
||||
class Caches(unittest.TestCase):
|
||||
@@ -192,6 +235,60 @@ class Clock(datetime):
|
||||
return datetime(2026, 11, 28, 4, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
class BeforeSaving(unittest.TestCase):
|
||||
def run_main(self, polls):
|
||||
began = Clock.now()
|
||||
current = began
|
||||
remaining = iter(polls)
|
||||
|
||||
class PollClock(datetime):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return current
|
||||
|
||||
def gh(url):
|
||||
nonlocal current
|
||||
if "/jobs?" in url:
|
||||
minutes, jobs = next(remaining)
|
||||
current = began + timedelta(minutes=minutes)
|
||||
return {"jobs": ME + jobs}
|
||||
if "/caches?" in url:
|
||||
return {"actions_caches": []}
|
||||
return {"run_started_at": began.isoformat()}
|
||||
|
||||
env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"}
|
||||
with mock.patch.object(clear, "gh", gh), mock.patch.object(clear.time, "sleep"), \
|
||||
mock.patch.object(clear, "datetime", PollClock), mock.patch.dict(os.environ, env), \
|
||||
mock.patch.object(clear.subprocess, "run") as delete, contextlib.redirect_stdout(io.StringIO()):
|
||||
status = clear.main()
|
||||
delete.assert_not_called()
|
||||
return status
|
||||
|
||||
def test_queued_and_running_split_legs_can_outlast_the_original_start_deadline(self):
|
||||
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
|
||||
saved = warm_job("completed", "success", [("Post Setup", "completed", "success")],
|
||||
started_at="2026-11-28T07:50:00Z")
|
||||
self.assertFalse(self.run_main([
|
||||
(181, [split_job(1, "queued")]),
|
||||
(201, [split_job(1, "in_progress"), warm_job("queued")]),
|
||||
(220, [done, warm_job("queued")]),
|
||||
(230, [done, saved]),
|
||||
]))
|
||||
|
||||
def test_a_saving_leg_that_never_starts_expires_after_the_last_split_completion(self):
|
||||
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
|
||||
self.assertEqual(self.run_main([
|
||||
(220, [done, warm_job("queued")]),
|
||||
(401, [done, warm_job("queued")]),
|
||||
]), 1)
|
||||
|
||||
def test_a_late_start_after_split_completion_is_rejected_even_if_already_saving(self):
|
||||
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
|
||||
late = warm_job("in_progress", steps=[("Post Setup", "in_progress", None)],
|
||||
started_at="2026-11-28T10:40:01Z")
|
||||
self.assertEqual(self.run_main([(401, [done, late])]), 1)
|
||||
|
||||
|
||||
class AfterDeletion(unittest.TestCase):
|
||||
SAVING = [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]
|
||||
|
||||
@@ -230,9 +327,17 @@ class AfterDeletion(unittest.TestCase):
|
||||
canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")])
|
||||
self.assertEqual(self.run_main(canceled), 1)
|
||||
|
||||
def test_a_saving_leg_skipped_after_a_failed_split_warm_leg_fails_this_job(self):
|
||||
skipped = warm_job("completed", conclusion="skipped")
|
||||
failed = {"name": "gate / cache warm 2/5 (ubuntu-24.04)", "status": "completed", "conclusion": "failure"}
|
||||
env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"}
|
||||
with mock.patch.object(clear, "gh", lambda url: {"jobs": ME + [failed, skipped]}), mock.patch.object(clear.time, "sleep"), \
|
||||
mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(clear.main(), 1)
|
||||
|
||||
def test_a_leg_that_starts_late_and_saves_deletes_nothing(self):
|
||||
# Clock.now() is 04:00, so the leg starts 120 minutes 5 seconds after the script.
|
||||
late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T06:00:05Z")
|
||||
# Clock.now() is 04:00, so the leg starts 180 minutes 5 seconds after the script.
|
||||
late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T07:00:05Z")
|
||||
deleted = []
|
||||
|
||||
def run(args, **kwargs):
|
||||
|
||||
@@ -16,8 +16,10 @@ save step started saves nothing: its old entries stay, and this exits 1, so "Re-
|
||||
runs it again beside the re-run leg. A save step that is canceled or fails after the old entries
|
||||
were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure
|
||||
in a later post step does not count once the save step has succeeded. This also exits 1 when the
|
||||
leg has not started START_SECONDS after this script started, and when the leg has not reached its
|
||||
save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only
|
||||
leg has not started START_SECONDS after the last split warm leg completed (or after this script
|
||||
started when there are no split legs). The start deadline does not expire while a split leg is
|
||||
queued or running. This exits 1 when the leg has not reached its save, or its save has not finished,
|
||||
GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only
|
||||
when the most recent earlier attempt that lists it reports success and the current attempt still
|
||||
lists no `gate / select legs` job RERUN_GRACE_SECONDS after this script started: "Re-run all
|
||||
jobs" lists that job from its start, and "Re-run failed jobs" after a successful leg does not.
|
||||
@@ -34,9 +36,11 @@ import time
|
||||
|
||||
REF = 'refs/heads/main'
|
||||
WARM_JOB = re.compile(r'^gate / cache warm \(')
|
||||
SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(')
|
||||
# The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of
|
||||
# them fails or is canceled, the legs are skipped and no warm leg is listed.
|
||||
NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()')
|
||||
# them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the
|
||||
# saving leg also needs every `cache warm <k>/<N>` leg.
|
||||
NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \(|cache warm \d+/\d+ \()')
|
||||
# The gate's first job. "Re-run all jobs" lists it; "Re-run failed jobs" lists it only when it
|
||||
# failed, and then no warm leg succeeded before.
|
||||
SELECT_JOB = 'gate / select legs'
|
||||
@@ -52,12 +56,11 @@ PAGE_SIZE = 100
|
||||
# Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold
|
||||
# leg that starts late and runs to its limit still reaches its save before this gives up.
|
||||
GIVE_UP_SECONDS = 160 * 60
|
||||
# How long the leg may take to start, timed from this script's start: the leg waits for
|
||||
# `gate / select legs` and then for a runner, which took 44 minutes on a push to main on
|
||||
# 2026-11-28. The `cold-cache-clear` job's `timeout-minutes` in ci.yml is longer than
|
||||
# START_SECONDS and GIVE_UP_SECONDS together, so this exits with its own error before the job
|
||||
# times out.
|
||||
START_SECONDS = 120 * 60
|
||||
# How long the saving leg may take to start after the last split warm leg completed, or after
|
||||
# this script started when there are no split legs. Queued or running split legs suspend this
|
||||
# deadline. The `cold-cache-clear` job's 360-minute timeout in ci.yml can end the wait before
|
||||
# this deadline or GIVE_UP_SECONDS expires when split builds or runner waits take too long.
|
||||
START_SECONDS = 180 * 60
|
||||
STOPPED = ('failure', 'cancelled', 'timed_out')
|
||||
# Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml.
|
||||
TOLERATED_FAILURES = ('Trim the cache entry to this build',)
|
||||
@@ -103,16 +106,25 @@ def started_at(job):
|
||||
return parse_time(started) if started else None
|
||||
|
||||
|
||||
def start_wait_began(jobs, began):
|
||||
"""The last split warm completion, the script's start without splits, or None while waiting."""
|
||||
splits = [j for j in jobs if SPLIT_WARM_JOB.match(j['name'])]
|
||||
if not splits:
|
||||
return began
|
||||
if any(j['status'] != 'completed' or not j.get('completed_at') for j in splits):
|
||||
return None
|
||||
return max(parse_time(j['completed_at']) for j in splits)
|
||||
|
||||
|
||||
def start_overdue(job, now, began):
|
||||
"""True once START_SECONDS have passed since `began` (this script's start) and the warm leg
|
||||
has not started."""
|
||||
return started_at(job) is None and (now - began).total_seconds() > START_SECONDS
|
||||
"""True once START_SECONDS have passed since the start wait began and the leg has not started."""
|
||||
return began is not None and started_at(job) is None and (now - began).total_seconds() > START_SECONDS
|
||||
|
||||
|
||||
def started_late(job, began):
|
||||
"""True when the warm leg started more than START_SECONDS after `began` (this script's start)."""
|
||||
"""True when the warm leg started more than START_SECONDS after the start wait began."""
|
||||
started = started_at(job)
|
||||
return started is not None and (started - began).total_seconds() > START_SECONDS
|
||||
return began is not None and started is not None and (started - began).total_seconds() > START_SECONDS
|
||||
|
||||
|
||||
def gave_up(job, now):
|
||||
@@ -180,7 +192,8 @@ def main():
|
||||
while True:
|
||||
jobs = gh(jobs_url) or {}
|
||||
job = warm_job(jobs.get('jobs', []))
|
||||
if started_late(job, began):
|
||||
ready = start_wait_began(jobs.get('jobs', []), began)
|
||||
if started_late(job, ready):
|
||||
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
return 1
|
||||
if job and saving(job):
|
||||
@@ -199,13 +212,14 @@ def main():
|
||||
print('::error::the gate stopped before its cache warm leg started; nothing deleted')
|
||||
return 1
|
||||
if job and job['status'] == 'completed':
|
||||
if job.get('conclusion') in STOPPED:
|
||||
# A saving leg skipped because a leg it needs failed (a `cache warm <k>/<N>` leg).
|
||||
if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])):
|
||||
print(f'::error::{NO_SAVE}')
|
||||
return 1
|
||||
print('the cache warm leg finished without a save step; nothing deleted')
|
||||
return
|
||||
now = datetime.now(timezone.utc)
|
||||
if start_overdue(job, now, began):
|
||||
if start_overdue(job, now, ready):
|
||||
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
|
||||
return 1
|
||||
if gave_up(job, now):
|
||||
|
||||
+23
-7
@@ -49,6 +49,7 @@ commands:
|
||||
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs
|
||||
the tests and doctests of its crates, the last shard the other steps
|
||||
ci warm build what every shard builds, without running it (fills the gate's cache); with
|
||||
GATE_SHARD of GATE_SHARDS set, only what that shard builds; with
|
||||
CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file
|
||||
shards list the crates each shard tests; fails when a member is in no shard or in two,
|
||||
or builds with other features in its shard than in the whole workspace
|
||||
@@ -410,18 +411,26 @@ fn cmd_ci_shard() -> Result<(), String> {
|
||||
/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that
|
||||
/// only an integration test uses.
|
||||
///
|
||||
/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that
|
||||
/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build
|
||||
/// nothing in either case, since part 1 builds the same tests.
|
||||
///
|
||||
/// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS`
|
||||
/// (xtask/src/cache_units.rs), xtask's own build included.
|
||||
fn cmd_ci_warm() -> Result<(), String> {
|
||||
let var = |key: &str| match std::env::var(key) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(std::env::VarError::NotPresent) => Ok(None),
|
||||
Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")),
|
||||
};
|
||||
let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?);
|
||||
let only = shards::warm_only(shard.as_deref(), count.as_deref())?;
|
||||
cache_units::record_xtask()?;
|
||||
let checked = shards::run()?;
|
||||
let (tests, checks) = shards::warm_plan(&checked, only);
|
||||
let mut steps: Vec<Step> = Vec::new();
|
||||
for shard in checked {
|
||||
// A split's later parts build the same tests as its first.
|
||||
if let shards::Shard::Tests(crates, part) = shard {
|
||||
if part.is_some_and(|p| !p.is_first()) {
|
||||
continue;
|
||||
}
|
||||
for i in tests {
|
||||
if let shards::Shard::Tests(crates, _) = checked[i].clone() {
|
||||
steps.push((
|
||||
"build tests",
|
||||
Box::new(move || {
|
||||
@@ -431,6 +440,14 @@ fn cmd_ci_warm() -> Result<(), String> {
|
||||
));
|
||||
}
|
||||
}
|
||||
if checks {
|
||||
push_warm_checks(&mut steps);
|
||||
}
|
||||
run_steps(&steps)
|
||||
}
|
||||
|
||||
/// The builds of the checks shard that [`cmd_ci_warm`] runs.
|
||||
fn push_warm_checks(steps: &mut Vec<Step>) {
|
||||
steps.push((
|
||||
"clippy",
|
||||
Box::new(|| {
|
||||
@@ -454,7 +471,6 @@ fn cmd_ci_warm() -> Result<(), String> {
|
||||
}),
|
||||
));
|
||||
steps.push(("wasm", Box::new(cmd_wasm)));
|
||||
run_steps(&steps)
|
||||
}
|
||||
|
||||
/// The command `ci warm` builds one test shard's tests with, and its description.
|
||||
|
||||
@@ -364,10 +364,107 @@ pub fn run() -> Result<Vec<Shard>, String> {
|
||||
Ok(shards)
|
||||
}
|
||||
|
||||
/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's
|
||||
/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one,
|
||||
/// a value that is not a number, a count other than the number of shards, or a shard out of range
|
||||
/// is an error.
|
||||
pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result<Option<usize>, String> {
|
||||
let (shard, count) = match (shard, count) {
|
||||
(None, None) => return Ok(None),
|
||||
(Some(shard), Some(count)) => (shard, count),
|
||||
_ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()),
|
||||
};
|
||||
let number =
|
||||
|key: &str, value: &str| -> Result<usize, String> { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) };
|
||||
let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?);
|
||||
if count != GROUPS.len() {
|
||||
return Err(format!(
|
||||
"ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
|
||||
GROUPS.len()
|
||||
));
|
||||
}
|
||||
if !(1..=count).contains(&shard) {
|
||||
return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}"));
|
||||
}
|
||||
Ok(Some(shard - 1))
|
||||
}
|
||||
|
||||
/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it
|
||||
/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it
|
||||
/// builds that shard alone, and without it every shard. A split's later parts build nothing: they
|
||||
/// build the same tests as part 1, whose leg puts them in the cache.
|
||||
pub fn warm_plan(shards: &[Shard], only: Option<usize>) -> (Vec<usize>, bool) {
|
||||
let mut tests = Vec::new();
|
||||
let mut checks = false;
|
||||
for (i, shard) in shards.iter().enumerate() {
|
||||
if only.is_some_and(|k| k != i) {
|
||||
continue;
|
||||
}
|
||||
match shard {
|
||||
Shard::Checks => checks = true,
|
||||
Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {}
|
||||
Shard::Tests(..) => tests.push(i),
|
||||
}
|
||||
}
|
||||
(tests, checks)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warm_builds_every_shard_unless_the_gate_names_one() {
|
||||
let n = GROUPS.len().to_string();
|
||||
assert_eq!(warm_only(None, None), Ok(None));
|
||||
assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0)));
|
||||
assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1)));
|
||||
for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] {
|
||||
assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}");
|
||||
}
|
||||
let past = (GROUPS.len() + 1).to_string();
|
||||
assert!(warm_only(Some(&past), Some(&n)).is_err());
|
||||
assert!(warm_only(Some("1"), Some(&past)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_builds_each_shard_of_the_plan() {
|
||||
let ws = [m("a"), m("b")];
|
||||
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
|
||||
assert_eq!(warm_plan(&shards, None), (vec![0, 2], true));
|
||||
assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false));
|
||||
assert_eq!(warm_plan(&shards, Some(1)), (vec![], false));
|
||||
assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false));
|
||||
assert_eq!(warm_plan(&shards, Some(3)), (vec![], true));
|
||||
// The real plan: every leg the gate names builds its own shard (a split's later part
|
||||
// builds nothing), and the legs together, like a full warm, build every crate's tests
|
||||
// once and the checks.
|
||||
let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap();
|
||||
let mut owned: Vec<&str> = real.iter().flat_map(owners).collect();
|
||||
owned.sort_unstable();
|
||||
let (mut legs, mut leg_checks) = (Vec::new(), 0);
|
||||
for i in 0..GROUPS.len() {
|
||||
let n = GROUPS.len().to_string();
|
||||
let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap();
|
||||
let (tests, checks) = warm_plan(&real, only);
|
||||
let want = match &real[i] {
|
||||
Shard::Checks => (vec![], true),
|
||||
Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false),
|
||||
Shard::Tests(..) => (vec![i], false),
|
||||
};
|
||||
assert_eq!((tests.clone(), checks), want, "shard {}", i + 1);
|
||||
legs.extend(tests);
|
||||
leg_checks += usize::from(checks);
|
||||
}
|
||||
let (tests, checks) = warm_plan(&real, None);
|
||||
assert!(checks);
|
||||
assert_eq!(leg_checks, 1);
|
||||
assert_eq!(tests, legs);
|
||||
let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect();
|
||||
built.sort_unstable();
|
||||
assert_eq!(built, owned);
|
||||
}
|
||||
|
||||
fn m(name: &str) -> Member {
|
||||
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user