Merge main into fix/area-type-band-coverage

This commit is contained in:
dotCooCoo committed 2026-11-13 10:04:24 -08:00
commit 1f13d1f8b7
155 files changed
+8441 -815

No files matched your search

Generated
+1
View File
@@ -6477,6 +6477,7 @@ dependencies = [
"vectorcraft-text",
"vectorcraft-three-d",
"vectorcraft-trace",
"wat",
]
[[package]]
+27
View File
@@ -108,10 +108,37 @@ impl eframe::App for App {
self.app.start_pending_update();
#[cfg(target_os = "macos")]
super::mac_cursor::release();
#[cfg(not(any(target_os = "macos", windows)))]
hide_before_teardown(self.winit_window.as_deref());
end_before_teardown(self.frames);
}
}
/// The main window as [`hide_before_teardown`] sees it.
#[cfg(not(any(target_os = "macos", windows)))]
pub(crate) trait QuittingWindow {
fn hide(&self);
}
#[cfg(not(any(target_os = "macos", windows)))]
impl QuittingWindow for winit::window::Window {
fn hide(&self) {
self.set_visible(false);
}
}
/// On Linux and the BSDs, hide the main window before eframe drops the app. Dropping the app waits
/// up to [`vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT`] for the clipboard handles to let go, and
/// the window would stay on screen for that time. The window is hidden, not closed: the Wayland
/// clipboard reads text on the window's connection. winit hides X11 windows (XWayland included) and
/// cannot hide a Wayland window.
#[cfg(not(any(target_os = "macos", windows)))]
pub(crate) fn hide_before_teardown<W: QuittingWindow + ?Sized>(window: Option<&W>) {
if let Some(window) = window {
window.hide();
}
}
impl App {
/// The frame's times for the hang report, and its last stage ([`hang_beacon::after_frame`]): a
/// focused, shown window whose windows had input waits for the renderer and the next frame,
+10
View File
@@ -1504,6 +1504,16 @@ mod portable {
assert_eq!(finish(true), Duration::ZERO);
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn quitting_waits_for_the_paste_checks_handle_as_long_as_its_reads_last() {
// The Paste check's handle is one of these: when the app quits, its unanswered X11 read
// ends `X11_READ_LIMIT` after it was sent, and an idle worker stops within `LOAD_WAIT`.
// Quitting waits for that handle until both are over.
assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(false) + super::super::loads::LOAD_WAIT);
assert!(vectorcraft_ui_egui::CLIPBOARD_PROBE_STOP_WAIT >= finish(true) + super::super::loads::LOAD_WAIT);
}
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
#[test]
fn a_bitmap_paste_waits_for_the_owner_off_the_ui_thread() {
+3 -2
View File
@@ -393,8 +393,9 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
// Its calls are marked for the hang report (`hang_watch`).
system_clipboard: Some(Box::new(vectorcraft_ui_egui::hang_beacon::Marked(clipboard::system_clipboard(clip)))),
// Linux checks whether Paste has something to take on a background thread: an X11 clipboard
// owner that never answers holds a read for up to 4 s. Windows only asks which formats the
// clipboard holds and macOS asks the pasteboard server, so they check in line.
// owner that never answers holds a text read for up to 4 s for each format it tries, and
// quitting waits up to `CLIPBOARD_PROBE_STOP_WAIT` for that thread. Windows only asks which
// formats the clipboard holds and macOS asks the pasteboard server, so they check in line.
// The probe's handle is made on its own thread, from the window (`Send`), not its raw display.
clipboard_probe: cfg!(target_os = "linux").then(|| Box::new(move || clipboard::system_clipboard(clip_probe)) as ClipboardProbeFactory),
// Help → Discord / website / GitHub, the Discord button, About and Home links.
+4 -1
View File
@@ -87,6 +87,8 @@ mod titlebar;
use app::bring_window_forward;
use app::native_input_hook;
use app::open_or_hold;
#[cfg(all(test, not(any(target_os = "macos", windows))))]
use app::{QuittingWindow, hide_before_teardown};
use host_services::services;
#[cfg(all(test, feature = "wgpu"))]
use prefs::{KEEP_UI_PREFS, decode_saved_prefs, keep_prefs_copy, prefs_bytes};
@@ -116,7 +118,8 @@ struct App {
frames: u64,
/// Keeps the custom title bar's window borderless (Windows, #1758).
window_frame: Option<window_frame::WindowFrameFn>,
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635).
/// The main window; used to read and set maximized state the UI layer does not see on Linux (#3635),
/// and to hide the window on quit before the clipboard handles let go (`app::hide_before_teardown`).
winit_window: Option<std::sync::Arc<winit::window::Window>>,
/// A saved or fitted geometry asked for maximize once the window is mapped (Linux).
pending_maximize: bool,
+18
View File
@@ -460,3 +460,21 @@ fn the_linux_desktop_entry_opens_every_readable_format() {
}
}
}
/// On Linux and the BSDs, quitting hides the main window before eframe drops the app, whose
/// clipboard handles may take up to `CLIPBOARD_PROBE_STOP_WAIT` to let go.
#[cfg(not(any(target_os = "macos", windows)))]
#[test]
fn quitting_hides_the_window_before_the_clipboards_let_go() {
struct Window(std::cell::Cell<u32>);
impl QuittingWindow for Window {
fn hide(&self) {
self.0.set(self.0.get() + 1);
}
}
let window = Window(std::cell::Cell::new(0));
hide_before_teardown(Some(&window));
assert_eq!(window.0.get(), 1, "the window was not hidden");
// Without a window (none was made), there is nothing to hide.
hide_before_teardown::<Window>(None);
}
+30
View File
@@ -1381,6 +1381,14 @@ pub fn blend_spine(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<(PathData, Op
layout_spine(keys, spec)
}
/// The line the steps of a blend of `keys` are placed along: [`blend_spine`]'s path for a blend
/// with a spine, and the straight lines between the key centers, in key order, for a blend made
/// without one ([`BlendSpec::no_spine`]). For a blend without a spine the line places the steps
/// only; it is not a spine and is not drawn as one. `None` with fewer than two keys.
pub fn blend_layout_line(keys: &[Arc<Node>], spec: &BlendSpec) -> Option<PathData> {
layout_spine(keys, spec).map(|(path, _)| path)
}
/// The spine `spec` stores, unless the blend was made without one.
fn stored_spine(spec: &BlendSpec) -> Option<&PathData> {
spec.spine.as_ref().filter(|_| !spec.no_spine)
@@ -1852,6 +1860,28 @@ mod tests {
assert_eq!(moved.subpaths[0].anchors[2].p, Point::new(305.0, 5.0));
}
#[test]
fn a_blend_without_a_spine_has_a_layout_line_through_its_key_centers() {
let at =
|x: f64, y: f64| Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(x - 5.0, y - 5.0, x + 5.0, y + 5.0)), Appearance::default()));
let line_of = |path: &PathData| path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect::<Vec<_>>();
// A stored spine is ignored once the blend is made without one.
let stored = PathData::single(SubPath::polyline(&[Point::new(0.0, 50.0), Point::new(300.0, 50.0)], false));
let spec = BlendSpec { no_spine: true, spine: Some(stored), ..Default::default() };
for keys in [vec![at(10.0, 20.0), at(110.0, 20.0)], vec![at(10.0, 20.0), at(110.0, 20.0), at(110.0, 220.0), at(-40.0, 0.0)]] {
assert!(blend_spine(&keys, &spec).is_none(), "still no spine");
let line = blend_layout_line(&keys, &spec).unwrap();
assert_eq!(line.subpaths.len(), 1);
assert!(!line.subpaths[0].closed);
let centers: Vec<Point> = keys.iter().map(|k| center_of(k)).collect();
assert_eq!(line_of(&line), centers, "in key order");
}
// With a spine, the layout line is the spine.
let keys = vec![key(0.0), key(100.0), key(300.0)];
assert_eq!(blend_layout_line(&keys, &BlendSpec::default()), blend_spine(&keys, &BlendSpec::default()).map(|(p, _)| p));
assert!(blend_layout_line(&keys[..1], &spec).is_none(), "one key");
}
#[test]
fn steps_follow_a_bent_spine() {
let keys = vec![key(0.0), key(100.0)];
+189 -37
View File
@@ -166,24 +166,180 @@ fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
/// that many samples, which includes images whose planes together need more than the decoder's
/// limit (256 MB of samples).
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
Some(match read_samples_at_depth(d, n, per)? {
Samples::Eight(v) => v,
Samples::Sixteen(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
})
}
/// Samples of an image, pixel by pixel, at the depth its file stores them.
#[derive(Clone, Debug, PartialEq)]
enum Samples {
Eight(Vec<u8>),
Sixteen(Vec<u16>),
}
impl Samples {
fn as_slice(&self) -> SampleSlice<'_> {
match self {
Self::Eight(v) => SampleSlice::Eight(v),
Self::Sixteen(v) => SampleSlice::Sixteen(v),
}
}
}
/// [`Samples`], borrowed.
#[derive(Clone, Copy, Debug)]
enum SampleSlice<'a> {
Eight(&'a [u8]),
Sixteen(&'a [u16]),
}
/// [`read_samples`], keeping 16-bit samples at 16 bits.
fn read_samples_at_depth(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Samples> {
let mut buf = tiff::decoder::DecodingResult::U8(Vec::new());
let layout = d.read_image_to_buffer(&mut buf).ok()?;
let data = match buf {
tiff::decoder::DecodingResult::U8(v) => v,
tiff::decoder::DecodingResult::U16(v) => v.iter().map(|s| (s >> 8) as u8).collect(),
_ => return None,
};
match buf {
tiff::decoder::DecodingResult::U8(v) => chunky(v, layout.planes, n, per).map(Samples::Eight),
tiff::decoder::DecodingResult::U16(v) => chunky(v, layout.planes, n, per).map(Samples::Sixteen),
_ => None,
}
}
/// `data`, the samples of `n` pixels, `per` to a pixel, stored in `planes` planes, as the samples
/// pixel by pixel; `None` when it doesn't hold that many samples or a plane per sample.
fn chunky<T: Copy>(data: Vec<T>, planes: usize, n: usize, per: usize) -> Option<Vec<T>> {
if Some(data.len()) != n.checked_mul(per) {
return None;
}
if layout.planes <= 1 {
if planes <= 1 {
return Some(data);
}
if layout.planes != per {
if planes != per {
return None;
}
let planes: Vec<&[u8]> = data.chunks_exact(n).collect();
Some((0..n).flat_map(|i| planes.iter().map(move |p| p.get(i).copied().unwrap_or(0))).collect())
let planes: Vec<&[T]> = data.chunks_exact(n).collect();
Some((0..n).flat_map(|i| planes.iter().filter_map(move |p| p.get(i).copied())).collect())
}
/// The color space an ICC profile's header names (bytes 16 to 19, such as `RGB `, `GRAY` or
/// `CMYK`); `None` when `icc` is shorter than a header.
pub fn icc_color_space(icc: &[u8]) -> Option<[u8; 4]> {
if icc.len() < 128 {
return None;
}
icc.get(16..20)?.try_into().ok()
}
/// The ICC profile of TIFF tag 34675 (ICCProfile) of the image `d` reads; `None` without one.
fn tiff_icc(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> Option<Vec<u8>> {
d.get_tag_u8_vec(tiff::tags::Tag::IccProfile).ok().filter(|icc| !icc.is_empty())
}
/// The ICC profile of TIFF `bytes`' first image (tag 34675), read with the `tiff` decoder's own
/// limits, whatever the size of the image; `None` for other images and TIFFs without one.
pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
let (_, mut d) = tiff(bytes)?;
tiff_icc(&mut d)
}
/// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments;
/// `None` without one.
fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
d.icc_profile().filter(|icc| !icc.is_empty())
}
/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in.
fn cmyk_icc(icc: Option<Vec<u8>>) -> Option<Vec<u8>> {
icc.filter(|icc| icc_color_space(icc) == Some(*b"CMYK"))
}
/// The CMYK samples of a CMYK image at the depth its file stores them, and its ICC profile.
struct CmykSource {
width: u32,
height: u32,
samples: Samples,
icc: Option<Vec<u8>>,
}
/// The samples of CMYK TIFF `bytes` (8 or 16 bits), their inks together or one plane per ink, with
/// the TIFF's CMYK ICC profile; `None` for other images and ones larger than [`MAX_CMYK_PIXELS`].
fn tiff_source(bytes: &[u8]) -> Option<CmykSource> {
let (kind, mut d) = tiff(bytes)?;
if !matches!(kind, tiff::ColorType::CMYK(8 | 16)) {
return None;
}
let (width, height) = d.dimensions().ok()?;
let n = usize::try_from(pixels(width, height)?).ok()?;
let icc = cmyk_icc(tiff_icc(&mut d));
let samples = read_samples_at_depth(&mut d, n, 4)?;
Some(CmykSource { width, height, samples, icc })
}
/// The ink amounts of a four-component JPEG, 8 bits each, with its CMYK ICC profile.
fn jpeg_source(bytes: &[u8]) -> Option<CmykSource> {
let Inks { width, height, data } = jpeg_inks(bytes)?;
Some(CmykSource { width, height, samples: Samples::Eight(data), icc: cmyk_icc(jpeg_icc(bytes)) })
}
/// A Deflate-compressed CMYK TIFF of `width` × `height` pixels of `samples` (inks together, 8 or 16
/// bits as they are given), declaring the resolution `ppi` when both of its values are finite and
/// above 0, and carrying `icc` as tag 34675 (ICCProfile, of type UNDEFINED); `None` when it can't be
/// written.
fn write_cmyk_tiff(width: u32, height: u32, samples: SampleSlice<'_>, ppi: Option<(f64, f64)>, icc: Option<&[u8]>) -> Option<Vec<u8>> {
use tiff::encoder::colortype::{CMYK8, CMYK16, ColorType};
use tiff::encoder::{Compression, ImageEncoder, Rational, TiffEncoder, TiffKind, compression::DeflateLevel};
use tiff::tags::{ResolutionUnit, Tag};
fn tags<W: std::io::Write + std::io::Seek, C: ColorType, K: TiffKind>(
img: &mut ImageEncoder<'_, W, C, K>,
ppi: Option<(f64, f64)>,
icc: Option<&[u8]>,
) -> Option<()> {
if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) {
// Ten-thousandths of a pixel per inch.
let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 };
img.encoder().write_tag(Tag::XResolution, r(x)).ok()?;
img.encoder().write_tag(Tag::YResolution, r(y)).ok()?;
img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?;
}
if let Some(icc) = icc {
img.encoder().write_tag(Tag::IccProfile, Undefined(icc)).ok()?;
}
Some(())
}
let mut out = Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced));
match samples {
SampleSlice::Eight(data) => {
let mut img = enc.new_image::<CMYK8>(width, height).ok()?;
tags(&mut img, ppi, icc)?;
img.write_data(data).ok()?;
}
SampleSlice::Sixteen(data) => {
let mut img = enc.new_image::<CMYK16>(width, height).ok()?;
tags(&mut img, ppi, icc)?;
img.write_data(data).ok()?;
}
}
Some(out.into_inner())
}
/// Bytes written as a TIFF field of type UNDEFINED, the type of an embedded ICC profile.
struct Undefined<'a>(&'a [u8]);
impl tiff::encoder::TiffValue for Undefined<'_> {
const BYTE_LEN: u8 = 1;
const FIELD_TYPE: tiff::tags::Type = tiff::tags::Type::UNDEFINED;
fn count(&self) -> usize {
self.0.len()
}
fn data(&self) -> std::borrow::Cow<'_, [u8]> {
std::borrow::Cow::Borrowed(self.0)
}
}
impl ImageBlob {
@@ -195,20 +351,8 @@ impl ImageBlob {
/// [`ImageBlob::cmyk_tiff`], declaring the resolution `ppi` (horizontal, vertical pixels per
/// inch) when it is given and both are finite and above 0.
pub fn cmyk_tiff_at(inks: &Inks, ppi: Option<(f64, f64)>) -> Option<Self> {
use tiff::encoder::{Compression, Rational, TiffEncoder, colortype::CMYK8, compression::DeflateLevel};
use tiff::tags::{ResolutionUnit, Tag};
let mut out = Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced));
let mut img = enc.new_image::<CMYK8>(inks.width, inks.height).ok()?;
if let Some((x, y)) = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0)) {
// Ten-thousandths of a pixel per inch.
let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 };
img.encoder().write_tag(Tag::XResolution, r(x)).ok()?;
img.encoder().write_tag(Tag::YResolution, r(y)).ok()?;
img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?;
}
img.write_data(&inks.data).ok()?;
Some(Self::new("image/tiff", out.into_inner()))
let tiff = write_cmyk_tiff(inks.width, inks.height, SampleSlice::Eight(&inks.data), ppi, None)?;
Some(Self::new("image/tiff", tiff))
}
/// Does the image hold CMYK samples (a four-component JPEG or a CMYK TIFF)? Reads only its
@@ -333,30 +477,38 @@ fn tiff_inks(bytes: &[u8]) -> Option<Inks> {
/// CMYK TIFF `bytes` that no orientation turns ([`turned_cmyk`] stores the others) as Open and
/// Place store them: as they are, or, when they store one plane per ink, which the image decoder
/// doesn't read, their ink amounts written again by [`ImageBlob::cmyk_tiff_at`] with the resolution
/// `ppi`. `None` for other images and for CMYK TIFFs whose inks [`ImageBlob::cmyk`] doesn't read.
/// doesn't read, their inks together in a CMYK TIFF with the resolution `ppi`, at the 8 or 16 bits
/// the file has, carrying the file's CMYK ICC profile. `None` for other images and for CMYK TIFFs
/// whose inks [`ImageBlob::cmyk`] doesn't read.
pub fn stored_cmyk_tiff(bytes: &[u8], ppi: Option<(f64, f64)>) -> Option<Vec<u8>> {
let inks = tiff_inks(bytes)?;
let source = tiff_source(bytes)?;
let (_, mut d) = tiff(bytes)?;
if !planar(&mut d) {
return Some(bytes.to_vec());
}
ImageBlob::cmyk_tiff_at(&inks, ppi).map(|b| Arc::unwrap_or_clone(b.bytes))
write_cmyk_tiff(source.width, source.height, source.samples.as_slice(), ppi, source.icc.as_deref())
}
/// CMYK JPEG or TIFF `bytes` that `orientation` turns or flips, as Open and Place store them: their
/// ink amounts ([`ImageBlob::cmyk`], 8 bits each) turned and written again by
/// [`ImageBlob::cmyk_tiff_at`] with the resolution `ppi` of the turned pixels, with the turned
/// width and height. `None` for other images and for CMYK images whose inks [`ImageBlob::cmyk`]
/// doesn't read.
/// inks turned and written again as a CMYK TIFF with the resolution `ppi` of the turned pixels,
/// with the turned width and height. A TIFF keeps its 8 or 16 bits, a JPEG has 8, and both keep
/// their CMYK ICC profile (a JPEG's put together from all its APP2 segments). `None` for other
/// images and for CMYK images whose inks [`ImageBlob::cmyk`] doesn't read.
pub fn turned_cmyk(bytes: &[u8], orientation: image::metadata::Orientation, ppi: Option<(f64, f64)>) -> Option<(Vec<u8>, (u32, u32))> {
let inks = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_inks(bytes) } else { tiff_inks(bytes) }?;
// Four 8-bit inks to a pixel, turned as four 8-bit channels are.
let mut px = image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(inks.width, inks.height, inks.data)?);
let CmykSource { width, height, samples, icc } = if bytes.starts_with(&[0xFF, 0xD8]) { jpeg_source(bytes) } else { tiff_source(bytes) }?;
// Four inks to a pixel, turned as four channels of the same depth are.
let mut px = match samples {
Samples::Eight(v) => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(width, height, v)?),
Samples::Sixteen(v) => image::DynamicImage::ImageRgba16(image::ImageBuffer::from_raw(width, height, v)?),
};
px.apply_orientation(orientation);
let inks = Inks::new(px.width(), px.height(), px.into_bytes())?;
let tiff = ImageBlob::cmyk_tiff_at(&inks, ppi)?;
Some((Arc::unwrap_or_clone(tiff.bytes), (inks.width, inks.height)))
let size = (px.width(), px.height());
let samples = match px {
image::DynamicImage::ImageRgba16(v) => Samples::Sixteen(v.into_raw()),
other => Samples::Eight(other.into_rgba8().into_raw()),
};
let tiff = write_cmyk_tiff(size.0, size.1, samples.as_slice(), ppi, icc.as_deref())?;
Some((tiff, size))
}
/// A TIFF whose pixels have samples after their colour, which the image decoder doesn't read at
+1 -1
View File
@@ -39,7 +39,7 @@ fn fifty() -> f64 {
// =====================================================================================
pub use crate::blend::{
Spine, blend_expand, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine,
Spine, blend_expand, blend_layout_line, blend_spine, blend_step_count, lerp_appearance, lerp_color, lerp_node, lerp_paint, lerp_path, pin_spine,
steps_knockout_shows,
};
+2
View File
@@ -29,3 +29,5 @@ serde_json = { workspace = true }
vectorcraft-color = { workspace = true }
# A face built in code from the bundled Source Sans 3 (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
# Test live-effect plug-ins written in WebAssembly text.
wat = { workspace = true }
+2 -2
View File
@@ -182,8 +182,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
REVOLVE,
"Revolve…",
&["Effect", "3D and Materials"],
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true}),
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[]}),
),
g(
EXTRUDE,
+2 -1
View File
@@ -95,7 +95,8 @@ pub use solids::{
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, rename_appearance_graphic_symbol,
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after,
rename_appearance_graphic_symbol,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
+356 -60
View File
@@ -1901,22 +1901,30 @@ fn paint_leaf(
/// effects' budget for the object it becomes, so that a budget of [`Budget::EFFECTS`] holds at most
/// [`MAX_OBJECTS`](vectorcraft_plugins::objects::MAX_OBJECTS) pieces however small their paths.
fn piece_cost(path: &PathData) -> Budget {
Budget::of(path).plus(piece_share())
}
/// The share of the effects' budget each painted piece costs besides its path ([`piece_cost`]).
fn piece_share() -> Budget {
let max = vectorcraft_plugins::objects::MAX_OBJECTS;
Budget::of(path).plus(Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max })
Budget { anchors: Budget::EFFECTS.anchors / max, lines: Budget::EFFECTS.lines / max }
}
/// Live-effect plug-in `plugin` (one that paints what it returns) with `params`, a later effect of
/// `item`, run on `leaf`, a path of [`transform_piece`] painted by copies of `item`, with reference
/// box `bounds`: `leaf` becomes a group of one path for each piece returned, in order. A piece that
/// gives fills (on a fill) or strokes (on a stroke) is painted by copies of `item`, the leaf's first
/// fill or stroke, with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's
/// other fills and strokes; one that gives none keeps the leaf's. Returns
/// `item`, run on `leaf`, a path of [`transform_piece`] painted by `item` (its first fill or stroke),
/// with reference box `bounds`: `leaf` becomes a group of one path for each piece returned, in
/// order. The plug-in is given `appearance`'s fills and strokes and told that it is on item `index`
/// of them. A piece that gives fills (on a fill) or strokes (on a stroke) is painted by copies of
/// `item` with those paints ([`vectorcraft_plugins::painted::items`]), under the leaf's other fills
/// and strokes; one that gives none keeps the leaf's. Returns
/// what the paths cost ([`piece_cost`]); `None` (the leaf stays as it is) when the plug-in fails,
/// the pieces are refused (a swatch or pattern not in `doc`, or any without one), or they would pass
/// `budget`. A deferred run is listed by `at`.
#[allow(clippy::too_many_arguments)]
fn paint_piece(
leaf: &mut Node,
item: &AppearanceItem,
(appearance, index): (&Appearance, usize),
(plugin, params): (&str, &serde_json::Value),
bounds: Rect,
budget: Budget,
@@ -1924,7 +1932,7 @@ fn paint_piece(
at: Option<vectorcraft_plugins::deferred::Stage>,
) -> Option<Budget> {
let (path, rule) = leaf_geometry(leaf)?;
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(&leaf.appearance), item: Some(0), at };
let paints = vectorcraft_plugins::effect::Paints { appearance: Some(appearance), item: Some(index), at };
let pieces = vectorcraft_plugins::effect::apply_painted(plugin, params, &path, bounds, rule, paints, doc)?;
let made = pieces.iter().map(|p| piece_cost(&p.path)).fold(Budget { anchors: 0, lines: 0 }, Budget::plus);
if !budget.fits(made) {
@@ -2093,7 +2101,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
group.push(Arc::new(p));
}
let mut p = Node::group(leaf.id, group);
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), limit, used, doc);
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), true, limit, used, doc);
pieces.push(Arc::new(p));
continue;
}
@@ -2116,7 +2124,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
if moved && !held_later {
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
}
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), limit, used, doc);
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc);
pieces.push(Arc::new(p));
}
if !plain.is_empty() {
@@ -2129,7 +2137,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
leaf.kind = NodeKind::Group { children: pieces, clip: false };
}
/// Apply the visible geometry effects left on the one fill or stroke of each path under `p` (a
/// Apply the visible geometry effects left on the fills or strokes of each path under `p` (a
/// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece:
/// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's
/// own effects reshape all its paths ([`reshape_leaves_carrying`]). Each path applies its own copy of
@@ -2138,19 +2146,32 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
/// the effects after it, and with Transform Objects off those before it, as they are
/// ([`keep_listed`]).
/// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path
/// for each piece it returns ([`paint_piece`]). The raster effects before a Transform effect
/// follow it ([`follow_piece`]), except the first `held` effects, which a Transform effect before
/// the piece's effects that makes copies or moves at random holds back, and the effects before
/// such a Transform effect among the piece's effects. The geometry effects then
/// for each piece it returns ([`paint_piece`]). A path with several fills or strokes (those a
/// painted plug-in returned) takes such an effect, a live-effect plug-in or a geometry effect on
/// strokes once for each of them, in paint order, given its own place among them
/// ([`shares_stage`]): each run's pieces replace only that fill or stroke, and a run that fails or
/// would pass the budget leaves that fill or stroke on the path as it was. The raster effects
/// before a Transform effect follow it ([`follow_piece`]), except the first `held` effects, which
/// a Transform effect before the piece's effects that makes copies or moves at random holds back,
/// and the effects before such a Transform effect among the piece's effects. The geometry effects then
/// leave the fills and strokes; their other effects stay. The paths keep to `max` together with
/// the rest of the art (`used`), and the swatches and patterns painted pieces name must be in
/// `doc`. `(seed, source, kept)`: the object's seed, the index in the object's appearance of the
/// fill or stroke the piece was made from, and the index among that item's effects of each effect
/// the piece kept, which a deferred live-effect plug-in is listed by.
fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), held: usize, max: Budget, used: &mut Budget, doc: Option<&Document>) {
/// the piece kept, which a deferred live-effect plug-in is listed by. `painted`: `p`'s paths are
/// the pieces of a painted run, each of which `used` counts at [`piece_cost`].
fn transform_piece(
p: &mut Node,
(seed, source, kept): (u64, usize, &[usize]),
held: usize,
painted: bool,
max: Budget,
used: &mut Budget,
doc: Option<&Document>,
) {
let mut count = 0;
for_each_leaf(p, &mut |l| {
if let Some(item) = l.appearance.items.first() {
for item in &l.appearance.items {
count = count.max(item.effects().len());
}
});
@@ -2158,60 +2179,207 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), h
// random are held back from the Transform effects before it too.
let mut held = held;
for_each_leaf(p, &mut |l| {
if let Some(last) = l.appearance.items.first().and_then(|item| item.effects().iter().rposition(crate::raster::holds_back)) {
held = held.max(last);
for item in &l.appearance.items {
if let Some(last) = item.effects().iter().rposition(crate::raster::holds_back) {
held = held.max(last);
}
}
});
// Whether `used` counts each path under `p`, in the order `for_each_leaf` visits them, at
// [`piece_cost`] (its geometry and a painted piece's share) rather than at its geometry alone.
// The pieces of a painted run are counted so, and so is the first path an effect makes of one
// that was: the paths of a Transform effect's copies share their original's share.
let mut shares = vec![painted; leaf_count(p)];
for j in 0..count {
let Some(bounds) = p.geometric_bounds() else { break };
let from = held.min(j);
let mut holds = false;
for_each_leaf(p, &mut |leaf| {
let Some(item) = leaf.appearance.items.first().cloned() else { return };
let Some(e) = item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned() else { return };
holds |= crate::raster::holds_back(&e);
// The effects before this one as they were before it moved the path.
let was = item.effects().get(from..j).unwrap_or_default();
let Some((path, rule)) = leaf_geometry(leaf) else { return };
// What the other paths leave of the budget.
let before = Budget::of(&path);
let room = max.minus(used.minus(before));
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
if let Some(plugin) = painted_plugin(&e) {
if let Some(made) = paint_piece(leaf, &item, (plugin, &merged_params(&e.id, &e.params)), bounds, room, doc, Some(stage)) {
*used = used.minus(before).plus(made);
}
return;
}
if reaches_appearance(&e) {
let params = merged_params(&e.id, &e.params);
let (_, copies) = crate::distort::transform_map(bounds, &params, seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(bounds, &params, seed);
let keep = |k: usize| k > j || (k < j && !options.objects);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
let at = PieceStage { j, from, seed, bounds, doc, stage };
// Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used`
// counts each path it became so, or `None` when it stays as it was.
let mut on_leaf = |leaf: &mut Node, share: bool| -> Option<Vec<bool>> {
let effect = |item: &AppearanceItem| item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned();
let items = &leaf.appearance.items;
let first = items.first()?;
let (path, _) = leaf_geometry(leaf)?;
// What `used` counts the path at; what the other paths leave of the budget is the rest.
let geometry = Budget::of(&path);
let counted = if share { piece_cost(&path) } else { geometry };
if shares_stage(items, j) {
let e = effect(first)?;
holds |= crate::raster::holds_back(&e);
let appearance = leaf.appearance.clone();
// A painted run's pieces each cost a share of their own ([`paint_piece`]); the
// paths of any other effect keep the leaf's.
let painted = painted_plugin(&e).is_some();
let before = if painted { counted } else { geometry };
let room = max.minus(used.minus(before));
let made = piece_stage(leaf, &e, &at, (&appearance, 0), room)?;
*used = used.minus(before).plus(made);
if moved {
follow_piece(leaf, was, from, &e);
}
return;
return Some((0..leaf_count(leaf)).map(|k| painted || (share && k == 0)).collect());
}
// Each fill or stroke takes the effect on its own path, given the leaf's fills and
// strokes and its own place among them; those left with the same path as the one
// before them stay on it. Each path costs its geometry and a painted piece's share.
// Each run is first given all the room the art leaves. When a fill or stroke that keeps
// the leaf's path then finds no room for its copy of it, the results are placed again,
// each but the last leaving room for one more copy of the leaf's own path; a result
// that does not fit that room is left out. Only a fill or stroke that keeps the leaf's
// path right after one that changed costs such a copy (the ones after it stay on that
// copy), so every copy fits but the first fill's or stroke's, when the art leaves no
// room for it: the leaf then stays as it was. A live-effect plug-in is given all the
// room the art leaves, and each placing checks that its result fits; a built-in effect
// builds within the room of each placing.
let appearance = leaf.appearance.clone();
let stroke = match &item {
AppearanceItem::Stroke(s) => Some(s),
AppearanceItem::Fill(_) => None,
let one = piece_cost(&path);
let n = appearance.items.len();
let base = used.minus(counted);
let alone = |item: &AppearanceItem| {
let mut sub = leaf.clone();
sub.appearance.items = vec![item.clone()];
sub
};
let ctx = GeomContext { stroke, rule, seed, appearance: Some(&appearance), item: Some(0), doc, stage: Some(stage) };
let mut carry = crate::Carry::default();
let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(&e), &path, bounds, &ctx, room, Some(&mut carry));
*used = used.minus(before).plus(Budget::of(&out));
// The fill's or stroke's gradient follows the effect as the object's does.
if carry.moves(&leaf.appearance) {
carry.apply(&mut leaf.appearance);
}
set_geometry(leaf, out, rule);
follow_piece(leaf, was, from, &e);
// `item`, the `k`th fill or stroke, alone on the leaf's path with effect `e` applied
// within `room`, and what its paths cost; `None` when it failed or found no room.
let apply = |item: &AppearanceItem, k: usize, e: &Effect, room: Budget| {
let painted = painted_plugin(e).is_some();
let room = if painted { room } else { room.minus(piece_share()) };
let mut sub = alone(item);
let made = piece_stage(&mut sub, e, &at, (&appearance, k), room)?;
Some((sub, if painted { made } else { made.plus(piece_share()) }))
};
// Each fill's or stroke's live-effect plug-in run. A result is kept only while a
// placing places it on a path of its own; one that does not fit is dropped, with what
// it cost, and the plug-in runs again in the second placing only when that much room
// is left there (a result small enough to cache comes back from the cache). A result
// with the same path as the one before it costs nothing: it is placed on that path
// whatever room is left, and dropped once its fill or stroke is moved there. The
// results kept at once cost at most what the two placings place.
let mut runs: Vec<PluginRun> = vec![PluginRun::Not; n];
let mut kept_cost = Budget { anchors: 0, lines: 0 };
// Each placing gives the paths, whether `used` counts each of the paths they hold at
// `piece_cost` (all of a painted run's, and the first of any other result's), and what
// the art then spends.
let mut split = |reserve: bool| -> Option<(Vec<Node>, Vec<bool>, Budget)> {
let mut spent = base;
let mut out: Vec<Node> = vec![];
let mut counts: Vec<bool> = vec![];
for (k, (item, ran)) in appearance.items.iter().zip(runs.iter_mut()).enumerate() {
let room = if reserve && k + 1 < n { max.minus(spent).minus(one) } else { max.minus(spent) };
let e = effect(item);
let paints = e.as_ref().is_some_and(|e| painted_plugin(e).is_some());
// Does `sub` stay on the path of the result before it, at no cost?
let merges = |sub: &Node| out.last().is_some_and(|last| same_path(last, sub));
// What the kept plug-in result this fill or stroke takes cost.
let mut taken = None;
let result = match e {
None => None,
Some(e) => {
holds |= crate::raster::holds_back(&e);
if vectorcraft_plugins::effect::plugin_id(&e.id).is_some() {
let again = match ran {
PluginRun::Not | PluginRun::Merged => true,
PluginRun::Left(cost) => room.fits(*cost),
PluginRun::Kept(..) | PluginRun::Failed => false,
};
if again {
#[cfg(test)]
PLUGIN_RUNS.with(|n| n.set(n.get() + 1));
*ran = match apply(item, k, &e, max.minus(base)) {
None => PluginRun::Failed,
Some((sub, cost)) if !room.fits(cost) && !merges(&sub) => PluginRun::Left(cost),
Some((sub, cost)) => {
kept_cost = kept_cost.plus(cost);
PluginRun::Kept(sub, cost)
}
};
}
match ran {
PluginRun::Kept(sub, cost) if room.fits(*cost) || merges(sub) => {
taken = Some(*cost);
Some((sub.clone(), *cost))
}
PluginRun::Kept(_, cost) => {
let cost = *cost;
kept_cost = kept_cost.minus(cost);
*ran = PluginRun::Left(cost);
None
}
PluginRun::Not | PluginRun::Merged | PluginRun::Left(_) | PluginRun::Failed => None,
}
} else {
// A built-in effect that finds no room within `room` leaves the
// leaf's path. When its result is not on the path before it, it
// is built again with all the room the art leaves and taken only
// when that result is on the path before it, which costs nothing.
let made = apply(item, k, &e, room);
let short = match &made {
None => true,
Some((sub, cost)) => !merges(sub) && (!room.fits(*cost) || same_path(sub, leaf)),
};
match out.last() {
Some(_) if short => match apply(item, k, &e, max.minus(base)) {
Some((sub, cost)) if merges(&sub) => Some((sub, cost)),
_ => made,
},
_ => made,
}
}
}
};
let placed = match result {
Some((sub, cost)) if room.fits(cost) || merges(&sub) => Some((sub, cost, paints)),
_ => None,
};
// A fill or stroke whose result is not placed stays on the leaf's path, which
// is copied only when the path before it is another.
let (mut sub, cost, all) = match placed {
Some(placed) => placed,
None => match out.last_mut() {
Some(last) if same_path(last, leaf) => {
last.appearance.items.push(item.clone());
continue;
}
_ => (alone(item), one, true),
},
};
match out.last_mut() {
Some(last) if same_path(last, &sub) => {
last.appearance.items.append(&mut sub.appearance.items);
if let Some(cost) = taken {
kept_cost = kept_cost.minus(cost);
*ran = PluginRun::Merged;
}
}
_ if !max.minus(spent).fits(cost) => return None,
_ => {
spent = spent.plus(cost);
counts.extend((0..leaf_count(&sub)).map(|k| all || k == 0));
out.push(sub);
}
}
#[cfg(test)]
HELD_PEAK.with(|p| p.set(p.get().at_least(kept_cost)));
}
Some((out, counts, spent))
};
let (mut out, counts, spent) = split(false).or_else(|| split(true))?;
*used = spent;
*leaf = match out.len() {
1 => out.pop().unwrap_or_else(|| leaf.clone()),
_ => Node::group(leaf.id, out.into_iter().map(Arc::new).collect()),
};
Some(counts)
};
let mut next: Vec<bool> = vec![];
let mut visited = 0;
for_each_leaf(p, &mut |leaf| {
let share = shares.get(visited).copied().unwrap_or(false);
visited += 1;
next.extend(on_leaf(leaf, share).unwrap_or_else(|| vec![share]));
});
shares = next;
if holds {
held = held.max(j);
}
@@ -2223,6 +2391,134 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), h
});
}
/// A fill's or stroke's live-effect plug-in run in a placing of [`transform_piece`]: not run yet,
/// its result and what that costs while a placing places it on a path of its own, what a result
/// that did not fit cost (the result itself is dropped), a result dropped once its fill or stroke
/// was placed on the path before it, or failed.
#[derive(Clone)]
enum PluginRun {
Not,
Kept(Node, Budget),
Left(Budget),
Merged,
Failed,
}
#[cfg(test)]
thread_local! {
/// The most the live-effect plug-in results [`transform_piece`] keeps from one fill or stroke
/// to the next have cost at once on this thread.
pub(crate) static HELD_PEAK: std::cell::Cell<Budget> = const { std::cell::Cell::new(Budget { anchors: 0, lines: 0 }) };
/// How many times [`transform_piece`] has run a fill's or stroke's live-effect plug-in on this
/// thread when they did not share the stage.
pub(crate) static PLUGIN_RUNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's
/// effects; `from`, the first of the effects before it whose raster effects follow a Transform
/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document
/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect
/// plug-in is listed by.
struct PieceStage<'a> {
j: usize,
from: usize,
seed: u64,
bounds: Rect,
doc: Option<&'a Document>,
stage: vectorcraft_plugins::deferred::Stage,
}
/// Can stage `j` of [`transform_piece`] run once for all of a path's `items`: there is at most one,
/// or they hold the same effects and the effect at `j` is not a visible geometry effect, is a
/// Transform effect, or is a built-in geometry effect and they are all fills (an effect that
/// changes a fill's path does not depend on which fill it is on)?
fn shares_stage(items: &[AppearanceItem], j: usize) -> bool {
let Some(first) = items.first() else { return true };
if items.len() == 1 {
return true;
}
if !items.iter().all(|i| i.effects() == first.effects()) {
return false;
}
match first.effects().get(j) {
Some(e) if e.visible && is_geometry(&e.id) => {
vectorcraft_plugins::effect::plugin_id(&e.id).is_none() && (reaches_appearance(e) || items.iter().all(AppearanceItem::is_fill))
}
_ => true,
}
}
/// Effect `e`, a visible geometry effect at stage `at` of [`transform_piece`], applied to `leaf`, a
/// path painted by its first fill or stroke (and, when they share the stage, [`shares_stage`], the
/// others): `appearance` is what the effect is given of the path's fills and strokes and `index`
/// which of them it is on. A live-effect plug-in that paints what it returns makes `leaf` a group
/// of its pieces ([`paint_piece`]), and a Transform effect that reaches its appearance transforms
/// it ([`transform_leaf`]). Returns what the new paths cost, within `room`; `None` when `leaf`
/// stays as it is.
fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index): (&Appearance, usize), room: Budget) -> Option<Budget> {
let item = leaf.appearance.items.first()?.clone();
// The effects before this one as they were before it moved the path.
let was = item.effects().get(at.from..at.j).unwrap_or_default();
let (path, rule) = leaf_geometry(leaf)?;
if let Some(plugin) = painted_plugin(e) {
let params = merged_params(&e.id, &e.params);
return paint_piece(leaf, &item, (appearance, index), (plugin, &params), at.bounds, room, at.doc, Some(at.stage));
}
if reaches_appearance(e) {
let params = merged_params(&e.id, &e.params);
let (_, copies) = crate::distort::transform_map(at.bounds, &params, at.seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(at.bounds, &params, at.seed);
let j = at.j;
let keep = |k: usize| k > j || (k < j && !options.objects);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
if moved {
follow_piece(leaf, was, at.from, e);
}
return Some(made);
}
let stroke = match &item {
AppearanceItem::Stroke(s) => Some(s),
AppearanceItem::Fill(_) => None,
};
let ctx = GeomContext { stroke, rule, seed: at.seed, appearance: Some(appearance), item: Some(index), doc: at.doc, stage: Some(at.stage) };
let mut carry = crate::Carry::default();
let out = crate::geometry::apply_geometry_carrying_within(std::slice::from_ref(e), &path, at.bounds, &ctx, room, Some(&mut carry));
let made = Budget::of(&out);
// The fill's or stroke's gradient follows the effect as the object's does.
if carry.moves(&leaf.appearance) {
carry.apply(&mut leaf.appearance);
}
set_geometry(leaf, out, rule);
follow_piece(leaf, was, at.from, e);
Some(made)
}
/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes?
fn same_path(a: &Node, b: &Node) -> bool {
let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
if !leaf(a) || !leaf(b) {
return false;
}
// Every field but the fills and strokes, compared in place; the geometry last.
let Node { id, name, visible, locked, opacity, blend, isolate, knockout, knockout_shape, appearance, kind, bbox_angle, extras } = a;
let Appearance { items: _, effects, contents_index } = &**appearance;
*id == b.id
&& *name == b.name
&& *visible == b.visible
&& *locked == b.locked
&& *opacity == b.opacity
&& *blend == b.blend
&& *isolate == b.isolate
&& *knockout == b.knockout
&& *knockout_shape == b.knockout_shape
&& *bbox_angle == b.bbox_angle
&& *extras == b.extras
&& *effects == b.appearance.effects
&& *contents_index == b.appearance.contents_index
&& *kind == b.kind
}
/// The effects a Transform effect in a fill's or stroke's own list leaves as they were
/// ([`keep_listed`]): the list as it was before the Transform effect was applied, and which of its
/// indices keep their values. `None` for an object's own Transform effect.
+158 -28
View File
@@ -29,6 +29,15 @@ pub fn is_revolve(id: &str) -> bool {
/// thousands of faces took gigabytes; past this the source path is drawn.
pub(crate) const MAX_PAINT_COPIES: usize = 256 << 20;
/// The bytes of an object's paint copies so far: those of its surfaces' faces, and those of the parts
/// of its graphics, each within [`MAX_PAINT_COPIES`] of its own. Graphics past their budget are left
/// out without taking room the surfaces need.
#[derive(Default)]
struct Copies {
surfaces: usize,
graphics: usize,
}
/// The most face and box tests a group's transparent members' faces take together to rejoin their
/// members' last runs; past them each starts a run of its own.
pub(crate) const MAX_OVERLAP_TESTS: usize = 1 << 22;
@@ -96,13 +105,18 @@ pub fn revolve_options(p: &Value) -> Revolve {
smooth_shading: true,
cap_ends: flag(p, "cap", true),
curve_samples: None,
map_surface: false,
}
}
/// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with
/// parameters `p` sweeps its surface with.
/// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them.
fn options_of(id: &str, p: &Value) -> Revolve {
if id == CLASSIC_REVOLVE { classic::options(p) } else { revolve_options(p) }
if id == CLASSIC_REVOLVE {
classic::options(p)
} else {
Revolve { map_surface: id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty(), ..revolve_options(p) }
}
}
/// The options effect `fx`, a Revolve or a Revolve (Classic), sweeps its surface with.
@@ -140,6 +154,17 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
let options = shared_options(&shapes, options_of(id, p))?;
let mut copies = 0;
shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?;
// Without graphics, or without the document they draw from, no member is measured for them.
if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) {
match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) {
Some(s) => check_graphics(Some(doc), id, &s.path, b, options, p, &mut 0)?,
// With no member to carry them, the graphics' art must still fit its limits.
None => {
crate::solids::graphics::validate_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p)?;
}
}
}
let casting = shapes.iter().filter(|s| surface_item(&s.items).is_some_and(|i| paint_of(i).1 * s.opacity > 0.0));
return check_shadow(p, casting.map(|s| &s.path), b, options);
}
@@ -151,9 +176,44 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let paints = solid_paints(n);
check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?;
check_graphics(doc, id, &path, b, options_of(id, p), p, &mut 0)?;
check_shadow(p, [&path], b, options_of(id, p))
}
/// An error when the graphics in Revolve (`id`) parameters `p`, with the symbols of `doc`, are past
/// their limits on the surface of `path` about the axis of `b`: their art, or the parts they draw
/// on its faces ([`crate::solids::graphics::surface_parts`]), whose paint copies count after
/// `copies`, the bytes of the copies of the object's graphics so far ([`Copies`]). The parts'
/// copies are added to `copies` when they fit, as drawing adds them. Without `doc` nothing is
/// drawn, and nothing is checked.
fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, options: Revolve, p: &Value, copies: &mut usize) -> Result<(), String> {
let graphics = crate::solids::mapped_graphics(p);
let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) };
crate::solids::graphics::validate_symbols(doc, p)?;
crate::solids::graphics::validate_surface_symbols(doc, p)?;
let faces = vectorcraft_three_d::revolve(path, b, options)?;
let mut used = *copies;
match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) {
Some(_) => {
*copies = used;
Ok(())
}
None => Err("The graphics are too complex for this surface: simplify the symbols' art or reduce Segments".into()),
}
}
/// The member of a group whose side takes the group's graphics: the first with the longest
/// profile among those with a fill or stroke.
fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option<usize> {
shapes
.iter()
.enumerate()
.filter(|(_, s)| surface_item(&s.items).is_some())
.filter_map(|(k, s)| vectorcraft_three_d::revolve_surface_size(&s.path, b, options).map(|(_, h)| (k, h)))
.fold(None, |best: Option<(usize, f64)>, (k, h)| if best.is_some_and(|(_, top)| top >= h) { best } else { Some((k, h)) })
.map(|(k, _)| k)
}
/// With the shadow of Revolve parameters `p` on, an error when the surfaces of `paths` it is cast
/// from, about the axis of `b`, are past the limits together.
fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, options: Revolve) -> Result<(), String> {
@@ -168,16 +228,17 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator<Item = &'a PathData>, b:
/// appearance item `target` of `n` ([`validate_item_of`]).
#[cfg(test)]
pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> {
validate_item_of(n, REVOLVE, p, target, index)
validate_item_of(None, n, REVOLVE, p, target, index)
}
/// [`validate_revolve`] for a Revolve or Revolve (Classic), `id`, with parameters `p` at index
/// `index` of the effects of appearance item `target` of `n`. The surfaces of every fill and stroke
/// that carries one, `target`'s included, share one budget of paint copies, as in [`art`]. A visible
/// object-level Revolve draws in place of those surfaces.
pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> {
/// object-level Revolve draws in place of those surfaces. With `doc`, `target`'s graphics must fit
/// its surface ([`check_graphics`]).
pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &Value, target: usize, index: usize) -> Result<(), String> {
if is_container(n) || visible(&n.appearance.effects) || target >= n.appearance.items.len() {
return validate_in(None, n, id, p);
return validate_in(doc, n, id, p);
}
validate_params_of(id, p)?;
const EMPTY: &str = "Revolve requires a shape with at least two anchors";
@@ -187,7 +248,7 @@ pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, ind
}
let ctx = GeomContext::of(n);
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut copies = 0;
let (mut copies, mut graphic_copies) = (0, 0);
for (i, item) in n.appearance.items.iter().enumerate() {
let effects = item.effects();
let at = if i == target { Some(index) } else { effects.iter().position(|e| e.visible && is_revolve(&e.id)) };
@@ -200,6 +261,12 @@ pub(crate) fn validate_item_of(n: &Node, id: &str, p: &Value, target: usize, ind
let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item));
let b = path.bounds().ok_or(EMPTY)?;
check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?;
// The graphics of every item add their paints' copies to the graphics' budget, as they
// are drawn; only the edited item's graphics are refused here.
let graphics = check_graphics(doc, kind, &path, b, options, &params, &mut graphic_copies);
if i == target {
graphics?;
}
check_shadow(&params, [&path], b, options)?;
}
Ok(())
@@ -234,7 +301,7 @@ fn shared_options(shapes: &[Profile], options: Revolve) -> Result<Revolve, Strin
}
/// The item whose paint an object's surface takes: its top fill, else its top stroke.
fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> {
pub(crate) fn surface_item(items: &[AppearanceItem]) -> Option<&AppearanceItem> {
items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last())
}
@@ -255,6 +322,7 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
/// only its own parameters, each in its range.
pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> {
validate_revolve_params(p)?;
crate::solids::graphics::validate(id, p)?;
if id == CLASSIC_REVOLVE {
classic::validate(p)?;
}
@@ -303,10 +371,13 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R
}
/// One object's surface of revolution about the axis of `b`, and each face's depth. `copies` counts
/// the bytes of the paint copies of every surface of the object. Revolve (Classic) draws every face
/// with its classic surface, as Extrude & Bevel (Classic) does.
/// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
/// a face with a part of a graphic is a group of the face and that part.
#[allow(clippy::too_many_arguments)]
fn surface(
doc: Option<&Document>,
n: &Node,
path: &PathData,
b: Rect,
@@ -316,14 +387,14 @@ fn surface(
opacity: f32,
blend: vectorcraft_doc::color::BlendMode,
expand: bool,
copies: &mut usize,
copies: &mut Copies,
) -> Option<(Vec<f64>, Node)> {
// A loaded file or a profile edited past the limits keeps drawing its source path instead
// of crashing the frame. Commands validate the same evaluator and report its errors.
if fx.id == CLASSIC_REVOLVE {
let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?;
*copies = copies.saturating_add(paint_copies(facets.len(), &paint));
if *copies > MAX_PAINT_COPIES {
copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint));
if copies.surfaces > MAX_PAINT_COPIES {
return None;
}
let depths = facets.iter().map(|f| f.depth).collect();
@@ -332,14 +403,33 @@ fn surface(
}
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
*copies = copies.saturating_add(paint_copies(faces.len(), &paint));
if *copies > MAX_PAINT_COPIES {
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
if copies.surfaces > MAX_PAINT_COPIES {
return None;
}
let graphics = crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params));
let shade = |face: &vectorcraft_three_d::Face, c: Color| graphic_paint(face, c, colored);
// Graphics past the limits are left out, and the surface draws without them and their paints'
// copies.
let mut used = copies.graphics;
let mut parts = if graphics.is_empty() {
vec![]
} else {
match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) {
Some(parts) => {
copies.graphics = used;
parts
}
None => vec![],
}
};
let drawn = parts.iter().any(|p| !p.is_empty());
// Visibility is an expansion option, never a change to live geometry or export baking.
// Keep all faces for paints whose coverage we cannot prove opaque. A bounded visibility
// failure also retains the complete surface rather than losing any of the user's art.
// failure also retains the complete surface rather than losing any of the user's art. With
// graphics drawn, every face stays, each with its part of the graphics.
let visible = (expand
&& !drawn
&& flag(&fx.params, "expandVisibleOnly", true)
&& paint.color().is_some()
&& opacity == 1.0
@@ -414,7 +504,16 @@ fn surface(
.collect();
Arc::new(Node::path(n.id, face.path, Appearance { items, ..Default::default() }))
})
.collect();
.collect::<Vec<_>>();
let children = if drawn {
children
.into_iter()
.zip(parts.iter_mut().map(std::mem::take).chain(std::iter::repeat_with(Vec::new)))
.map(|(face, part)| if part.is_empty() { face } else { Arc::new(Node::group(n.id, std::iter::once(face).chain(part).collect())) })
.collect()
} else {
children
};
let mut group = Node::group(n.id, children);
group.opacity = opacity;
group.blend = blend;
@@ -422,11 +521,33 @@ fn surface(
}
/// A surface of one object about the bounds of `path`, built with options derived from `fx`.
/// `copies` is the count [`surface`] adds to.
fn object_surface(n: &Node, path: &PathData, fx: &Effect, item: &AppearanceItem, expand: bool, copies: &mut usize) -> Option<Node> {
/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`.
fn object_surface(
doc: Option<&Document>,
n: &Node,
path: &PathData,
fx: &Effect,
item: &AppearanceItem,
expand: bool,
copies: &mut Copies,
) -> Option<Node> {
let b = path.bounds()?;
let (paint, opacity, blend) = paint_of(item);
surface(n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
}
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
/// that color: across the face with its smooth shading, under colored lights (`colored`) with
/// their color.
fn graphic_paint(face: &vectorcraft_three_d::Face, c: Color, colored: bool) -> Paint {
if colored {
return face
.light_gradient
.map_or_else(|| Paint::solid(crate::lighting::shade(c, face.illumination)), |g| crate::lighting::smooth_paint(g, c));
}
let [r, g, b] = c.to_rgb();
let color = |s: f64| Color::rgb(r * s as f32, g * s as f32, b * s as f32);
face.gradient.map_or_else(|| Paint::solid(color(face.brightness)), |g| shading_paint(g, color, |_| 1.0))
}
fn shading_paint(g: vectorcraft_three_d::ShadeGradient, color: impl Fn(f64) -> Color, opacity: impl Fn(f64) -> f32) -> Paint {
@@ -592,12 +713,12 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
}
let n = &*resolve_for(doc, n, "Revolve", false).ok()?;
if is_container(n) {
return group_art(n, expand);
return group_art(doc, n, expand);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
let mut children = vec![];
let mut copies = 0;
let mut copies = Copies::default();
let mut remaining = n.appearance.effects.clone();
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let fx = n.appearance.effects.get(index)?;
@@ -606,7 +727,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let paints = solid_paints(n);
let item = surface_item(&paints)?;
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let surface = object_surface(n, &path, fx, item, expand, &mut copies)?;
let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
if let Some(b) = path.bounds()
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()?
{
@@ -632,7 +753,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let fx = item.effects().get(index)?;
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
if let Some(b) = p.bounds()
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()?
@@ -774,7 +895,7 @@ pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
/// [`art`] of group or layer `n`: every member swept about one axis on the bounds of all of them,
/// each in its own paint. Every member's faces are drawn in one back-to-front order. `None` when
/// the effect is only on the group's own fills or strokes or when its members can't be revolved.
fn group_art(n: &Node, expand: bool) -> Option<Node> {
fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
let index = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id))?;
let fx = n.appearance.effects.get(index)?;
let mut shapes = members(n, "").ok()?;
@@ -782,17 +903,22 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> {
let b = union_bounds(&shapes)?;
let options = shared_options(&shapes, fx_options(fx)).ok()?;
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut copies = 0;
let mut copies = Copies::default();
let mut surfaces = vec![];
let mut opaque = true;
for s in &shapes {
// The graphics go once, on the side of the member with the longest profile. Without graphics
// no member is measured for them.
let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty();
let longest = if mapped { graphics_member(&shapes, b, options) } else { None };
for (k, s) in shapes.iter().enumerate() {
let Some(item) = surface_item(&s.items) else { continue };
// The opacity and blending of the member and the groups it is in apply through its scopes.
let (paint, opacity, blend) = paint_of(item);
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
// A member with transparency of its own keeps every face, as a transparent object does.
let expand = expand && s.scopes.is_empty();
let (depths, art) = surface(n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
let doc = doc.filter(|_| longest == Some(k));
let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
surfaces.push((depths, art, s.scopes.as_slice()));
}
if surfaces.is_empty() {
@@ -1517,3 +1643,7 @@ mod tests {
assert_eq!(expand_revolve_art(&sample), revolve_art(&sample));
}
}
#[cfg(test)]
#[path = "revolve/tests_graphics.rs"]
mod tests_graphics;
@@ -0,0 +1,576 @@
use serde_json::json;
use vectorcraft_doc::Symbol;
use vectorcraft_doc::color::Color;
use vectorcraft_geom::{BezPath, shapes};
use super::*;
use crate::solids::three_d_params_as;
fn bar(r: Rect, color: Color) -> Node {
Node::path(NodeId(0), shapes::rectangle(r), Appearance::basic(Paint::solid(color), Paint::None, 0.0))
}
/// A document with symbols "Red" and "Blue" (10 × 20 bars) and "Wide" (a red 300 × 10 bar).
fn document() -> Document {
let mut d = Document::new(1000.0, 1000.0);
for (name, r, color) in [
("Red", Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(1.0, 0.0, 0.0)),
("Blue", Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(0.0, 0.0, 1.0)),
("Wide", Rect::new(0.0, 0.0, 300.0, 10.0), Color::rgb(1.0, 0.0, 0.0)),
("Flat", Rect::new(0.0, 0.0, 10.0, 2.0), Color::rgb(1.0, 0.0, 0.0)),
] {
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(bar(r, color)) });
}
d
}
/// A gray open profile through `points` (its first and last on the axis at x 0), revolved with
/// `params` over a view straight on without shading.
fn revolved(points: &[(f64, f64)], params: Value) -> Node {
let mut b = BezPath::new();
b.move_to(points[0]);
points[1..].iter().for_each(|p| b.line_to(*p));
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone());
let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0));
n.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap());
n
}
/// A cylinder of radius 50 about x 0, from y 0 to 200.
const CYLINDER: [(f64, f64); 4] = [(0.0, 0.0), (50.0, 0.0), (50.0, 200.0), (0.0, 200.0)];
/// A profile that narrows from 50 to 20 from the axis at y 100 and widens again.
const NECK: [(f64, f64); 5] = [(0.0, 0.0), (50.0, 0.0), (20.0, 100.0), (50.0, 200.0), (0.0, 200.0)];
/// The red channel of each color `paint` draws when it is a shade of pure red or pure blue (`blue`):
/// a solid color or the stops of a gradient. `None` for any other paint.
fn shade_of(paint: &Paint, blue: bool) -> Option<Vec<f32>> {
let hue = |c: &Color| {
let [r, g, b] = c.to_rgb();
let (on, off) = if blue { (b, r) } else { (r, b) };
(on > 0.02 && off < 0.01 && g < 0.01).then_some(on)
};
match paint {
Paint::Solid { .. } => Some(vec![hue(&paint.color()?)?]),
Paint::Gradient(g) => g.gradient.stops.iter().map(|s| hue(&s.color)).collect(),
_ => None,
}
}
/// The paths in `art` filled in a shade of red (or blue), with their shades.
fn parts(art: &Node, blue: bool) -> Vec<(PathData, Vec<f32>)> {
let mut out = vec![];
art.walk(&mut |n| {
let Some(path) = n.path_data() else { return };
let fill = n.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) => shade_of(&f.paint, blue),
AppearanceItem::Stroke(_) => None,
});
if let Some(shades) = fill {
out.push((path.clone(), shades));
}
});
out
}
fn reach(parts: &[(PathData, Vec<f32>)]) -> Rect {
parts.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap()
}
fn near(a: f64, b: f64, tolerance: f64) -> bool {
(a - b).abs() <= tolerance
}
#[test]
fn a_graphic_wraps_around_the_side_and_narrows_toward_the_silhouette() {
let d = document();
let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}, {"symbol": "Blue", "x": 60.0}]}));
let art = revolve_art_in(Some(&d), &n).unwrap();
// At the middle of the side, facing the viewer, the bar keeps its size: 10 wide at the axis's
// line, from 10 above the middle of the profile to 10 below.
let front = reach(&parts(&art, false));
let half = 50.0 * (5.0f64 / 50.0).sin();
assert!(near(front.x0, -half, 0.05) && near(front.x1, half, 0.05), "{front:?}");
assert!(near(front.y0, 90.0, 1e-6) && near(front.y1, 110.0, 1e-6), "{front:?}");
// 60 to its right the side has turned 1.1 to 1.3 radians away: the same bar draws less than
// half as wide, at the sine of those angles.
let turned = reach(&parts(&art, true));
assert!(near(turned.x0, 50.0 * 1.1f64.sin(), 0.15) && near(turned.x1, 50.0 * 1.3f64.sin(), 0.15), "{turned:?}");
assert!(turned.width() < front.width() / 2.0);
}
#[test]
fn the_part_past_the_silhouette_and_on_the_back_is_not_drawn() {
let d = document();
// A bar wider than the half of the side seen from the front reaches the silhouette and no
// further.
let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Wide"}]}));
let wide = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false));
assert!(wide.x0 > -50.0 - 1e-6 && wide.x1 < 50.0 + 1e-6, "{wide:?}");
assert!(wide.x0 < -49.5 && wide.x1 > 49.5, "{wide:?}");
// On the back, half a turn around the axis, nothing is drawn.
let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red", "x": 150.0}]}));
assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
// Turned half a turn, the back faces the viewer.
let n = revolved(&CYLINDER, json!({"rotationY": 180.0, "graphics": [{"symbol": "Red", "x": 150.0}]}));
assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
}
#[test]
fn a_graphic_follows_the_profile_and_keeps_its_size_where_it_comes_nearer_the_axis() {
let d = document();
// A 10 wide bar keeps its length around the axis at every distance from it: at the neck, 20
// from the axis, it spans 0.5 radians; half way up the slanted side (52.2 along it, 35 from
// the axis, at y 50), 2/7 of a radian. Straight on, both draw nearly 10 wide.
let slant = (30.0f64 * 30.0 + 100.0 * 100.0).sqrt();
let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat"}, {"symbol": "Flat", "y": -slant / 2.0}]}));
let art = revolve_art_in(Some(&d), &n).unwrap();
let all = parts(&art, false);
let neck: Vec<_> = all.iter().filter(|(p, _)| p.bounds().unwrap().center().y > 75.0).cloned().collect();
let up: Vec<_> = all.iter().filter(|(p, _)| p.bounds().unwrap().center().y <= 75.0).cloned().collect();
let (neck, up) = (reach(&neck), reach(&up));
// Each bar is 2 tall, so its ends are up to 0.3 farther from the axis than its middle.
assert!(near(neck.width(), 2.0 * 20.0 * 0.25f64.sin(), 0.15), "{neck:?}");
assert!(near(neck.center().y, 100.0, 0.05), "{neck:?}");
assert!(near(up.width(), 2.0 * 35.0 * (5.0f64 / 35.0).sin(), 0.15), "{up:?}");
assert!(near(up.center().y, 50.0, 0.05), "{up:?}");
// At the neck a bar 25 to the right lies 1 to 1.5 radians around, near the silhouette; one 40
// to the right lies 1.75 to 2.25 radians around, past the silhouette, and is not drawn.
let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat", "x": 25.0}]}));
let side = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false));
assert!(near(side.x0, 20.0 * 1.0f64.sin(), 0.3) && near(side.x1, 20.0 * 1.5f64.sin(), 0.3), "{side:?}");
let n = revolved(&NECK, json!({"graphics": [{"symbol": "Flat", "x": 40.0}]}));
assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
}
#[test]
fn with_the_axis_on_the_right_a_graphic_starts_on_the_front() {
let d = document();
// The cylinder of radius 50 about x 0, swept from its right edge.
let profile = [(0.0, 0.0), (-50.0, 0.0), (-50.0, 200.0), (0.0, 200.0)];
let n = revolved(&profile, json!({"edge": "right", "graphics": [{"symbol": "Red"}]}));
let front = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false));
let half = 50.0 * (5.0f64 / 50.0).sin();
assert!(near(front.x0, -half, 0.05) && near(front.x1, half, 0.05), "{front:?}");
assert!(near(front.y0, 90.0, 1e-6) && near(front.y1, 110.0, 1e-6), "{front:?}");
// x increases to the viewer's right here too.
let n = revolved(&profile, json!({"edge": "right", "graphics": [{"symbol": "Red", "x": 25.0}]}));
let right = reach(&parts(&revolve_art_in(Some(&d), &n).unwrap(), false));
assert!(near(right.center().x, 50.0 * 0.5f64.sin(), 0.3), "{right:?}");
}
#[test]
fn a_graphic_is_shaded_with_the_surface() {
let d = document();
// The light is on the left: the bar left of the middle is lighter than the one on its right,
// and neither keeps its unlit red.
let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Red", "x": -30.0}, {"symbol": "Red", "x": 30.0}]}));
let all = parts(&revolve_art_in(Some(&d), &n).unwrap(), false);
let mean = |left: bool| {
let shades: Vec<f32> =
all.iter().filter(|(p, _)| (p.bounds().unwrap().center().x < 0.0) == left).flat_map(|(_, s)| s.iter().copied()).collect();
shades.iter().sum::<f32>() / shades.len() as f32
};
assert!(mean(true) > mean(false) + 0.05, "{} {}", mean(true), mean(false));
assert!(all.iter().all(|(_, s)| s.iter().all(|r| *r < 0.999)));
}
#[test]
fn overlapping_graphics_keep_their_order_on_every_face() {
let d = document();
// The wide red bar, listed second, reaches across the narrow blue one, listed first. Shaded,
// each face is one triangle.
let n = revolved(&CYLINDER, json!({"shade": true, "graphics": [{"symbol": "Blue", "x": 30.0}, {"symbol": "Wide"}]}));
let art = revolve_art_in(Some(&d), &n).unwrap();
let mut both = 0;
art.walk(&mut |g| {
// A face with parts of graphics: the face's path, then the parts' paths.
let NodeKind::Group { children, clip: false } = &g.kind else { return };
if !children.iter().all(|c| matches!(c.kind, NodeKind::Path { .. })) {
return;
}
let colors: Vec<bool> = children
.iter()
.filter_map(|c| {
let blue = !parts(c, true).is_empty();
(blue || !parts(c, false).is_empty()).then_some(blue)
})
.collect();
if colors.contains(&true) && colors.contains(&false) {
both += 1;
assert!(colors.iter().position(|b| !b) > colors.iter().position(|b| *b), "{colors:?}");
}
});
assert!(both > 0);
}
#[test]
fn a_graphic_past_the_end_reaches_the_curved_rim_and_no_further() {
let d = document();
// A tube 50 from the axis with a cap at each end, in 10 segments, tilted to show its top: the
// bottom rim is an arc on the page whose lowest point, in front, lies between two corners of
// the faces. The wide bar runs 5 past the bottom of the profile.
for shade in [true, false] {
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.line_to((0.0, 200.0));
let p = json!({"offset": 50.0, "segments": 10, "rotationX": -30.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": shade, "graphics": [{"symbol": "Wide", "y": 100.0}]});
let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0));
n.appearance.effects.push(crate::new_effect(REVOLVE, &p).unwrap());
let art = revolve_art_in(Some(&d), &n).unwrap();
let mut lowest = f64::NEG_INFINITY;
art.walk(&mut |c| {
if let Some(b) = c.path_data().and_then(PathData::bounds) {
lowest = lowest.max(b.y1);
}
});
let bar = reach(&parts(&art, false));
assert!(near(bar.y1, lowest, 0.05), "shade {shade}: {bar:?} {lowest}");
// A thin bar wholly past the end, 0.35 to 0.85 below it in front, lies between the faces'
// straight lower edge and the rim's arc there: it is drawn, inside the rim.
let mut thin = n.clone();
let p = json!({"offset": 50.0, "segments": 10, "rotationX": -30.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": shade, "graphics": [{"symbol": "Flat", "y": 100.6, "scale": 25.0}]});
thin.appearance.effects = vec![crate::new_effect(REVOLVE, &p).unwrap()];
let past = parts(&revolve_art_in(Some(&d), &thin).unwrap(), false);
assert!(!past.is_empty(), "shade {shade}");
assert!(reach(&past).y1 <= lowest + 1e-6, "shade {shade}: {:?} {lowest}", reach(&past));
}
}
#[test]
fn under_several_lights_a_graphic_takes_each_faces_own_lit_art() {
let d = document();
let lights = json!([{"color": "#ff8080", "rotation": 120.0}, {"color": "#8080ff", "rotation": -30.0}]);
let clips = |n: &Node| {
let mut count = 0;
revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(matches!(c.kind, NodeKind::Group { clip: true, .. })));
count
};
let plain = revolved(&CYLINDER, json!({"shade": true, "lights": lights}));
let mapped = revolved(&CYLINDER, json!({"shade": true, "lights": lights, "graphics": [{"symbol": "Red"}]}));
// Each part of the bar is the face's lit art clipped to the part: one clip more for the
// part, one for the face's own art inside it.
assert!(clips(&mapped) > clips(&plain), "{} {}", clips(&mapped), clips(&plain));
// A lit face draws its paint under the face's light: a layer of the light's three channels,
// multiplied over the paint. Every part of the bar takes such a layer of its own, so the bar
// is shaded with each face's colored light; a bar drawn in flat red would add none.
let lit = |n: &Node| {
let mut count = 0;
revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(c.blend == vectorcraft_doc::color::BlendMode::Multiply));
count
};
assert!(lit(&mapped) > lit(&plain), "{} {}", lit(&mapped), lit(&plain));
// An opaque part also draws its lit art clipped to the band of its seam stroke; a translucent
// part, whose overlap would show, does not.
let mut d = d.clone();
let mut clear = bar(Rect::new(0.0, 0.0, 10.0, 20.0), Color::rgb(1.0, 0.0, 0.0));
if let Some(AppearanceItem::Fill(f)) = clear.appearance.items.first_mut() {
f.opacity = 0.5;
}
d.symbols.push(Symbol { dynamic: false, name: "Clear".into(), art: Arc::new(clear) });
let clips = |n: &Node| {
let mut count = 0;
revolve_art_in(Some(&d), n).unwrap().walk(&mut |c| count += usize::from(matches!(c.kind, NodeKind::Group { clip: true, .. })));
count
};
let translucent = revolved(&CYLINDER, json!({"shade": true, "lights": lights, "graphics": [{"symbol": "Clear"}]}));
let (base, opaque, translucent) = (clips(&plain), clips(&mapped), clips(&translucent));
assert!(translucent > base && opaque - base == 2 * (translucent - base), "{base} {opaque} {translucent}");
}
#[test]
fn graphics_past_the_point_limit_are_refused() {
let mut d = document();
let dots: Vec<Arc<Node>> = (0..2000)
.map(|i| {
let c = Point::new(f64::from(i % 50) * 12.0, f64::from(i / 50) * 12.0);
Arc::new(Node::path(
NodeId(0),
shapes::ellipse(Rect::new(c.x, c.y, c.x + 10.0, c.y + 10.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
))
})
.collect();
d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) });
let n = revolved(&CYLINDER, json!({}));
let p = |scale: f64| json!({"graphics": [{"symbol": "Dots", "scale": scale}]});
assert!(validate_revolve_in(Some(&d), &n, &p(100.0)).is_ok());
// At 100 times the size each dot is cut into hundreds of straight pieces.
let e = validate_revolve_in(Some(&d), &n, &p(10_000.0)).unwrap_err();
assert!(e.contains("too complex"), "{e}");
}
#[test]
fn graphics_cut_into_too_many_parts_are_refused_on_the_object_and_on_a_fill() {
let mut d = document();
// 4,000 thin bars across the side: few points each, but each is cut at every face it crosses.
let bars: Vec<Arc<Node>> =
(0..4000).map(|i| Arc::new(bar(Rect::new(0.0, f64::from(i) * 0.05, 300.0, f64::from(i) * 0.05 + 0.02), Color::BLACK))).collect();
d.symbols.push(Symbol { dynamic: false, name: "Bars".into(), art: Arc::new(Node::group(NodeId(0), bars)) });
let p = json!({"segments": 128, "graphics": [{"symbol": "Bars"}]});
let n = revolved(&CYLINDER, json!({}));
let e = validate_revolve_in(Some(&d), &n, &p).unwrap_err();
assert!(e.contains("too complex for this surface"), "{e}");
assert!(validate_revolve_in(Some(&d), &n, &json!({"graphics": [{"symbol": "Red"}]})).is_ok());
// The same on a Revolve on the object's fill.
let mut filled = n.clone();
let fx = filled.appearance.effects.remove(0);
if let Some(AppearanceItem::Fill(f)) = filled.appearance.items.first_mut() {
f.effects.push(fx);
}
let e = crate::solids::validate_three_d_at_in(Some(&d), &filled, REVOLVE, &p, (Some(0), 0)).unwrap_err();
assert!(e.contains("too complex for this surface"), "{e}");
}
#[test]
fn without_the_document_nothing_is_drawn_and_expand_keeps_the_graphics() {
let d = document();
let n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}]}));
assert!(parts(&revolve_art(&n).unwrap(), false).is_empty());
let shown = parts(&revolve_art_in(Some(&d), &n).unwrap(), false);
let expanded = parts(&expand_revolve_art_in(Some(&d), &n).unwrap(), false);
assert!(!shown.is_empty());
assert_eq!(shown, expanded);
// In a group the graphics go once, on the side of the member with the longest profile.
let mut member = n.clone();
member.appearance.effects.clear();
let mut short = member.clone();
if let NodeKind::Path { path, .. } = &mut short.kind {
*path = PathData::from_bezpath(&{
let mut b = BezPath::new();
b.move_to((0.0, 80.0));
b.line_to((30.0, 80.0));
b.line_to((30.0, 120.0));
b.line_to((0.0, 120.0));
b
});
}
let mut group = Node::group(NodeId(9), vec![Arc::new(short), Arc::new(member)]);
group.appearance.effects = n.appearance.effects.clone();
assert_eq!(parts(&revolve_art_in(Some(&d), &group).unwrap(), false).len(), shown.len());
}
#[test]
fn revolve_takes_graphics_on_its_side_only() {
let front = json!({"graphics": [{"symbol": "Red"}]});
let back = json!({"graphics": [{"symbol": "Red", "face": "back"}]});
assert!(crate::solids::graphics::validate(REVOLVE, &front).is_ok());
assert!(crate::solids::graphics::validate(REVOLVE, &back).unwrap_err().contains("side"));
assert!(crate::solids::graphics::validate(CLASSIC_REVOLVE, &front).is_err());
let n = revolved(&CYLINDER, json!({}));
assert!(validate_revolve(&n, &back).is_err());
// Changing the type keeps the front's graphics on Revolve's side and drops the back's.
let both = json!({"graphics": [{"symbol": "Red"}, {"symbol": "Blue", "face": "back"}]});
let kept = three_d_params_as(crate::EXTRUDE, &both, REVOLVE);
assert_eq!(kept["graphics"].as_array().map(Vec::len), Some(1));
assert_eq!(kept["graphics"][0]["symbol"], "Red");
assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE).get("graphics"), None);
}
#[test]
fn revolve_classic_draws_no_graphics_its_parameters_carry() {
let d = document();
let mut n = revolved(&CYLINDER, json!({"graphics": [{"symbol": "Red"}]}));
assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
// A file can hold graphics on Revolve (Classic), which commands refuse: Revolve (Classic)
// draws its classic surface, without them.
if let Some(fx) = n.appearance.effects.first_mut() {
fx.id = CLASSIC_REVOLVE.into();
}
assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
}
#[test]
fn a_group_with_no_member_to_carry_graphics_still_checks_their_art() {
let mut d = document();
let dots: Vec<Arc<Node>> = (0..2000)
.map(|i| {
let c = Point::new(f64::from(i % 50) * 12.0, f64::from(i / 50) * 12.0);
Arc::new(Node::path(
NodeId(0),
shapes::ellipse(Rect::new(c.x, c.y, c.x + 10.0, c.y + 10.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
))
})
.collect();
d.symbols.push(Symbol { dynamic: false, name: "Dots".into(), art: Arc::new(Node::group(NodeId(0), dots)) });
let n = revolved(&CYLINDER, json!({}));
let mut member = n.clone();
member.appearance.effects.clear();
member.appearance.items.clear();
let mut group = Node::group(NodeId(9), vec![Arc::new(member)]);
group.appearance.effects = n.appearance.effects.clone();
// No member has a fill or stroke, so none carries the graphics, but art past the limits is
// refused as it is on a group whose member carries them.
let e = validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Dots", "scale": 10_000.0}]})).unwrap_err();
assert!(e.contains("too complex"), "{e}");
assert!(validate_in(Some(&d), &group, REVOLVE, &json!({"graphics": [{"symbol": "Red"}]})).is_ok());
}
#[test]
fn a_full_turn_draws_a_graphic_on_either_side_of_the_cut_at_the_back() {
let mut d = document();
d.symbols.push(Symbol { dynamic: false, name: "Thin".into(), art: Arc::new(bar(Rect::new(0.0, 0.0, 2.0, 20.0), Color::rgb(1.0, 0.0, 0.0))) });
// Half a turn around a radius of 50 is about 157 to each side of the middle: turned to face
// the viewer, a graphic just inside either end is drawn.
for x in [155.0, -155.0] {
let n = revolved(&CYLINDER, json!({"rotationY": 180.0, "graphics": [{"symbol": "Thin", "x": x}]}));
assert!(!parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty(), "x {x}");
}
}
/// A gray cylinder of radius 50 whose side is 200 edges along the profile, from y 0 to 200.
fn ribbed() -> Vec<(f64, f64)> {
let mut points = vec![(0.0, 0.0)];
points.extend((0..=200).map(|k| (50.0, f64::from(k))));
points.push((0.0, 200.0));
points
}
/// A symbol `name` of one red path whose contours are `contours`, each a polygon through its
/// points.
fn contours_symbol(name: &str, contours: &[Vec<Point>]) -> Symbol {
let mut b = BezPath::new();
for contour in contours {
b.move_to(contour[0]);
contour[1..].iter().for_each(|p| b.line_to(*p));
b.close_path();
}
let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0));
Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }
}
#[test]
fn contours_away_from_a_face_are_not_cut_at_it() {
// 2,000 small squares in two clusters on the back, at opposite corners of the side: the path's
// bounds reach across every face, but no square reaches a face that is drawn.
let squares: Vec<Vec<Point>> = (0..2000)
.map(|i| {
let (x, y) = if i < 1000 { (0.0, 0.0) } else { (290.0, 190.0) };
let (x, y) = (x + f64::from(i % 10) * 0.1, y + f64::from(i % 1000 / 10) * 0.1);
vec![Point::new(x, y), Point::new(x + 0.05, y), Point::new(x + 0.05, y + 0.05), Point::new(x, y + 0.05)]
})
.collect();
let mut d = document();
d.symbols.push(contours_symbol("Clusters", &squares));
let n = revolved(&ribbed(), json!({}));
let p = json!({"graphics": [{"symbol": "Clusters"}]});
assert_eq!(validate_revolve_in(Some(&d), &n, &p), Ok(()));
}
#[test]
fn a_contour_that_reaches_every_face_and_draws_on_none_is_refused() {
// One contour of 10,000 points: a thin frame around the whole side, past its ends and on the
// back, so it is cut at every face and keeps nothing.
let edge = |from: Point, to: Point| (0..2500).map(move |k| from.lerp(to, f64::from(k) / 2500.0));
let (outer, inner) = ([(0.0, 0.0), (400.0, 0.0), (400.0, 400.0), (0.0, 400.0)], [(1.0, 1.0), (1.0, 399.0), (399.0, 399.0), (399.0, 1.0)]);
let ring = |corners: [(f64, f64); 4]| (0..4).flat_map(move |k| edge(corners[k].into(), corners[(k + 1) % 4].into())).collect::<Vec<Point>>();
let mut frame = ring(outer);
frame.extend(ring(inner));
let mut d = document();
d.symbols.push(contours_symbol("Frame", &[frame]));
let n = revolved(&ribbed(), json!({}));
let e = validate_revolve_in(Some(&d), &n, &json!({"graphics": [{"symbol": "Frame"}]})).unwrap_err();
assert!(e.contains("too complex for this surface"), "{e}");
assert!(parts(&revolve_art_in(Some(&d), &n).unwrap(), false).is_empty());
}
/// A red linear gradient of `stops` stops, each with `opacity`.
fn ramp(stops: usize, opacity: f32) -> Paint {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let stops = (0..stops)
.map(|i| {
let mut stop = GradientStop::new(i as f32 / stops as f32, Color::rgb(1.0, 0.0, 0.0));
stop.opacity = opacity;
stop
})
.collect();
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))))
}
#[test]
fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() {
let mut d = document();
for (name, opacity) in [("Ramp", 1.0), ("Clear ramp", 0.5)] {
let art =
Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 10.0)), Appearance::basic(ramp(4096, opacity), Paint::None, 0.0));
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
let p = json!({"graphics": [{"symbol": "Ramp"}]});
let n = revolved(&CYLINDER, json!({}));
let NodeKind::Path { path, .. } = &n.kind else { panic!("a path") };
let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap();
let parts_of = |symbol: &str, copies: &mut usize| {
let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]}));
crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len())
};
// Each opaque part copies the paint into its fill and its seam stroke; a part with
// transparent stops takes no seam stroke and copies it once.
let (opaque, clear) = (paint_bytes(&ramp(4096, 1.0)), paint_bytes(&ramp(4096, 0.5)));
let mut used = 0;
let count = parts_of("Ramp", &mut used).unwrap();
assert!(count >= 2, "the graphic draws on several faces");
assert_eq!(used, 2 * count * opaque);
let mut used = 0;
assert_eq!(parts_of("Clear ramp", &mut used), Some(count));
assert_eq!(used, count * clear);
// Past the budget the graphic is refused.
assert_eq!(parts_of("Ramp", &mut (MAX_PAINT_COPIES - opaque)), None);
// A surface whose own gradient takes nearly the whole budget for surfaces still takes the
// graphic, on the object, on one fill of two and on a member of a group.
let stop = paint_bytes(&ramp(2, 1.0)) - paint_bytes(&ramp(1, 1.0));
let base = paint_bytes(&ramp(1, 1.0)) - stop;
let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5));
let full = ramp(((MAX_PAINT_COPIES - paint_copies(faces.len(), &gray)) / (faces.len() * 4) - base) / stop, 1.0);
assert!(MAX_PAINT_COPIES - paint_copies(faces.len(), &gray) - paint_copies(faces.len(), &full) < opaque);
let mut object = n.clone();
if let Some(AppearanceItem::Fill(f)) = object.appearance.items.first_mut() {
f.paint = ramp(((MAX_PAINT_COPIES - opaque) / (faces.len() * 4) - base) / stop, 1.0);
}
assert_eq!(validate_revolve_in(Some(&d), &object, &p), Ok(()));
let fill = |paint: Paint, params: Value| {
let mut fill = FillLayer::new(paint);
fill.effects.push(crate::new_effect(REVOLVE, &params).unwrap());
AppearanceItem::Fill(fill)
};
let mut two = n.clone();
two.appearance = Appearance { items: vec![fill(gray.clone(), p.clone()), fill(full.clone(), json!({}))], ..Default::default() }.into();
assert_eq!(crate::solids::validate_three_d_at_in(Some(&d), &two, REVOLVE, &json!({}), (Some(1), 0)), Ok(()));
let mut member = n.clone();
member.appearance.effects.clear();
let mut second = member.clone();
if let Some(AppearanceItem::Fill(f)) = second.appearance.items.first_mut() {
f.paint = full;
}
let mut group = Node::group(NodeId(9), vec![Arc::new(member), Arc::new(second)]);
group.appearance.effects = n.appearance.effects.clone();
assert_eq!(validate_in(Some(&d), &group, REVOLVE, &p), Ok(()));
}
/// Whether each part of `art` filled with a gradient has a stroke over its seams.
fn gradient_seams(art: &Node) -> Vec<bool> {
let mut out = vec![];
art.walk(&mut |n| {
let items = &n.appearance.items;
let red = |p: &Paint| matches!(p, Paint::Gradient(_)) && shade_of(p, false).is_some();
if n.path_data().is_some() && matches!(items.first(), Some(AppearanceItem::Fill(f)) if red(&f.paint)) {
out.push(items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))));
}
});
out
}
#[test]
fn a_gradient_with_transparent_stops_takes_no_stroke_over_its_seams() {
let mut d = document();
for (name, opacity) in [("Opaque", 1.0), ("Clear", 0.5)] {
let art = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 10.0)), Appearance::basic(ramp(2, opacity), Paint::None, 0.0));
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
let seams = |symbol: &str| gradient_seams(&revolve_art_in(Some(&d), &revolved(&CYLINDER, json!({"graphics": [{"symbol": symbol}]}))).unwrap());
let opaque = seams("Opaque");
assert!(!opaque.is_empty() && opaque.iter().all(|s| *s), "{opaque:?}");
let clear = seams("Clear");
assert!(!clear.is_empty() && clear.iter().all(|s| !*s), "{clear:?}");
}
+25 -7
View File
@@ -21,13 +21,14 @@ pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLO
mod source;
pub(crate) use source::{resolve, resolve_for};
mod graphics;
pub(crate) mod graphics;
pub use graphics::{
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, rename_appearance_graphic_symbol,
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
rename_appearance_graphic_symbol,
};
pub(crate) mod shadow;
@@ -80,8 +81,9 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
}
}
}
// A plane has only a front, so graphics on the back cap are dropped.
if to == ROTATE
// A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics
// on the back cap are dropped.
if (to == ROTATE || to == crate::REVOLVE)
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
{
list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id()));
@@ -505,7 +507,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va
(Some(_), _) if is_container(n) || source::resolves(n) => {
Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into())
}
(Some(item), index) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(n, id, p, item, index),
(Some(item), index) if crate::revolve::is_revolve(id) => crate::revolve::validate_item_of(doc, n, id, p, item, index),
(None, _) if crate::revolve::is_revolve(id) => crate::revolve::validate_in(doc, n, id, p),
(item, index) => validate_solid_for(doc, n, id, p, (item, Some(index))),
}
@@ -1840,9 +1842,10 @@ pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option<usize>) -> O
}
/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude &
/// Bevel or Rotate.
/// Bevel, Rotate or Revolve. Revolve's frame is its unrolled side seen from the front, centered on
/// the origin, with no face maps: it sizes a new graphic and places no handles.
pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && SOLIDS.contains(&e.id.as_str())).map(|e| (index, e)))
frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && is_three_d(&e.id)).map(|e| (index, e)))
}
/// Does a visible geometry effect come after the 3D effect at `index` in the effects of `n` (on the
@@ -1886,6 +1889,21 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
}
let p = crate::merged_params(&fx.id, &fx.params);
let b = union_bounds(&shapes)?;
if fx.id == crate::REVOLVE {
// Revolve's graphics lie on its unrolled side (in a group, the side of the member with the
// longest profile): the frame is the part of it seen from the front, with no planar face
// to place a handle on.
let options = crate::revolve::revolve_options(&p);
let (w, h) = shapes
.iter()
.filter(|s| crate::revolve::surface_item(&s.items).is_some())
.filter_map(|s| vectorcraft_three_d::revolve_surface_size(&s.path, b, options))
.fold((0.0f64, 0.0f64), |best, size| if size.1 > best.1 { size } else { best });
if w <= 0.0 || h <= 0.0 {
return None;
}
return Some(graphics::GraphicFrame::new(Rect::new(-w / 2.0, -h / 2.0, w / 2.0, h / 2.0), None, None));
}
let view = view_options(&p);
if fx.id == ROTATE {
let plane = vectorcraft_three_d::plane_face_map(b, view);
+448 -7
View File
@@ -8,6 +8,11 @@
//! seen from the front of that face), its size as a share of the symbol's own, and its turn
//! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from
//! behind, so the graphic reads the right way round there.
//!
//! On Revolve the graphics lie on the swept side surface, unrolled flat
//! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the
//! middle of that surface, x around the axis and y along the profile, and each face of the side
//! draws the part of the graphics that falls on it ([`surface_parts`]).
use std::sync::Arc;
@@ -15,7 +20,7 @@ use serde_json::{Map, Value, json};
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol};
use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use vectorcraft_three_d::{FaceMap, Facet, PlanarFace};
/// The effect parameter that holds the graphics.
@@ -41,6 +46,33 @@ const MAX_NESTING: usize = 8;
/// places: as deep as an object may be drawn.
const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH;
/// The error for graphics on a 3D effect that takes none.
pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude and Revolve object types";
/// The buckets around the unrolled side surface that the pieces of Revolve's graphics are sorted
/// into, so each face looks only at the pieces near it.
const SURFACE_BUCKETS: usize = 256;
/// How closely the curves of a graphic on Revolve's side follow their shape when they are cut into
/// straight pieces, in points of the unrolled surface.
const SURFACE_TOLERANCE: f64 = 0.05;
/// How far from the middle of Revolve's unrolled side a curve of a graphic may reach, in points:
/// as far as a Revolve profile's coordinates may.
const SURFACE_REACH: f64 = 1e8;
/// The most points the parts of Revolve's graphics draw on its faces together, a graphic's area cut
/// at every face it crosses. Past it no graphic is drawn on that surface.
const MAX_SURFACE_POINTS: usize = 2_000_000;
/// The most points of Revolve's graphics cut at its faces together, counted before each cut whether
/// or not it keeps any of them. Past it no graphic is drawn on that surface.
const MAX_SURFACE_CUTS: usize = 32 * MAX_SURFACE_POINTS;
/// The width of the stroke of the same paint around each opaque part of a graphic on Revolve's
/// side, which covers the seams between the parts on neighboring faces.
const SURFACE_SEAM: f64 = 0.3;
/// The size range of a graphic, as a percentage of its symbol's own size.
pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0);
@@ -116,10 +148,10 @@ impl MappedGraphic {
}
}
/// The 3D effects that take graphics: Extrude & Bevel (its caps) and Rotate (the plane), the two
/// object types of the 3D and Materials panel with planar faces.
/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve
/// (its swept side).
pub fn takes_graphics(id: &str) -> bool {
id == super::EXTRUDE || id == super::ROTATE
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE
}
/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold
@@ -131,8 +163,9 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
}
}
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel and Rotate take
/// graphics, and a plane has only a front.
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and
/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named
/// the front.
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
let list = match p.get(GRAPHICS) {
None => return Ok(()),
@@ -143,7 +176,7 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
return Ok(());
}
if !takes_graphics(id) {
return Err("Graphics map onto planar faces: use the Extrude or Plane object type".into());
return Err(NOT_TAKEN.into());
}
if list.len() > MAX_GRAPHICS {
return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics"));
@@ -153,6 +186,9 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
if id == super::ROTATE && g.face == PlanarFace::Back {
return Err("A plane has one face: map its graphics onto the front".into());
}
if id == crate::REVOLVE && g.face == PlanarFace::Back {
return Err("Revolve maps graphics onto its side: map them onto the front".into());
}
}
Ok(())
}
@@ -483,6 +519,411 @@ pub(super) fn face_art(
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
}
/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces.
struct Unrolled {
polygons: Vec<Vec<Point>>,
/// The bounds of each of `polygons`.
boxes: Vec<Rect>,
bounds: Rect,
rule: FillRule,
paint: Paint,
opacity: f32,
blend: BlendMode,
/// Where the graphic's art goes on the surface: its gradients and patterns are placed with it.
place: Affine,
}
/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side
/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is
/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than
/// [`MAX_ELEMENTS`] points together.
fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option<Vec<Unrolled>> {
let mut pieces = vec![];
let mut points = 0usize;
for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let Ok(art) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
let place = g.placement(bounds, Point::ZERO);
for piece in art {
let placed = place * piece.path.to_bezpath();
let mut polygons = straight_pieces(&placed, &mut points)?;
polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite()));
let boxes: Vec<Rect> =
polygons.iter().filter_map(|polygon| polygon.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b))).collect();
let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue };
pieces.push(Unrolled {
polygons,
boxes,
bounds,
rule: piece.rule,
paint: piece.paint,
opacity: piece.opacity,
blend: piece.blend,
place,
});
}
}
Some(pieces)
}
/// The contours of `path` cut into straight pieces within [`SURFACE_TOLERANCE`], adding the points
/// made to `points`. Each curve is cut on its own and the count is checked before the next one, so
/// the work stops at the first curve past [`MAX_ELEMENTS`] points: `None` then, and for a path with
/// a coordinate of a line or a curve farther than [`SURFACE_REACH`] from the origin, which bounds
/// the pieces of one curve and the arithmetic of the cuts at the faces.
fn straight_pieces(path: &BezPath, points: &mut usize) -> Option<Vec<Vec<Point>>> {
let near = |p: &Point| p.x.abs() <= SURFACE_REACH && p.y.abs() <= SURFACE_REACH;
let mut polygons: Vec<Vec<Point>> = vec![];
let mut current: Vec<Point> = vec![];
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
for el in path.elements() {
if *points > MAX_ELEMENTS {
return None;
}
match *el {
PathEl::MoveTo(p) | PathEl::LineTo(p) if !near(&p) => return None,
PathEl::MoveTo(p) => {
polygons.push(std::mem::take(&mut current));
current.push(p);
*points += 1;
(start, last) = (p, p);
}
PathEl::LineTo(p) => {
current.push(p);
*points += 1;
last = p;
}
PathEl::ClosePath => {
polygons.push(std::mem::take(&mut current));
last = start;
}
PathEl::QuadTo(a, p) | PathEl::CurveTo(_, a, p) => {
let first = if let PathEl::CurveTo(b, ..) = *el { b } else { a };
if ![last, first, a, p].iter().all(near) {
return None;
}
vectorcraft_geom::kurbo::flatten([PathEl::MoveTo(last), *el], SURFACE_TOLERANCE, |cut| {
if let PathEl::LineTo(q) = cut {
current.push(q);
*points += 1;
}
});
last = p;
}
}
}
polygons.push(current);
(*points <= MAX_ELEMENTS).then_some(polygons)
}
/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art,
/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together.
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> {
let list = mapped_graphics(p);
if list.is_empty() || unrolled(doc, &list).is_some() {
return Ok(());
}
Err("The graphics are too complex: simplify the symbols' art".into())
}
/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing
/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces
/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows
/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it.
/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the
/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol
/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past
/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`]
/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take
/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for
/// them: commands refuse such graphics, and a loaded file draws the surface without them.
pub(crate) fn surface_parts(
doc: Option<&Document>,
id: NodeId,
graphics: &[MappedGraphic],
faces: &[vectorcraft_three_d::Face],
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
copies: &mut usize,
) -> Option<Vec<Vec<Arc<Node>>>> {
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; faces.len()];
let Some(doc) = doc else { return Some(out) };
let pieces = unrolled(doc, graphics)?;
let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) };
// Each piece listed in the buckets of the surface's x its bounds reach across.
let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9);
let bucket = |x: f64| (((x - all.x0) / width).floor().max(0.0) as usize).min(SURFACE_BUCKETS - 1);
let mut buckets: Vec<Vec<usize>> = vec![vec![]; SURFACE_BUCKETS];
for (k, p) in pieces.iter().enumerate() {
for b in buckets.get_mut(bucket(p.bounds.x0)..=bucket(p.bounds.x1)).into_iter().flatten() {
b.push(k);
}
}
let mut seen = vec![usize::MAX; pieces.len()];
let mut drawn = 0usize;
let mut cut_points = 0usize;
let mut triangle_id = 0usize;
for (face, parts) in faces.iter().zip(out.iter_mut()) {
let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue };
if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) {
continue;
}
let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] };
for corners in triangles {
triangle_id += 1;
let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::<Option<Vec<Point>>>();
let (Some(uv), Some(page)) = (pick(&cell.uv), pick(&cell.page)) else { continue };
let (Some(map), Some(window)) = (triangle_map(&uv, &page), counterclockwise(&uv)) else { continue };
// A face along an end cap's ring has that edge curved on the page: its parts are cut
// from a larger triangle and then to the face's own outline, so they reach the curve
// where the graphic runs past the end of the profile. A four-cornered face is cut into
// two triangles along its diagonal from corner 0 to corner 2: each takes the part of
// the outline on its own side of it.
let window = if face.outline.is_some() { grown(window, 3.0) } else { window };
// The pieces are looked up over the whole of the window they are cut to.
let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue };
if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 {
continue;
}
// The pieces near the triangle, each once, in the graphics' drawing order.
let mut near = vec![];
for b in buckets.get(bucket(reach.x0)..=bucket(reach.x1)).into_iter().flatten() {
for &k in b {
let Some(slot) = seen.get_mut(k) else { continue };
if *slot != triangle_id {
*slot = triangle_id;
near.push(k);
}
}
}
near.retain(|k| {
pieces
.get(*k)
.is_some_and(|p| p.bounds.x1 >= reach.x0 && p.bounds.x0 <= reach.x1 && p.bounds.y1 >= reach.y0 && p.bounds.y0 <= reach.y1)
});
if near.is_empty() {
continue;
}
near.sort_unstable();
let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2);
let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) {
(Some(&toward), Some(&a), Some(&b)) => {
let side = side_of(a, b, toward);
vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect)
}
_ => outline.clone(),
});
let rim = rim.as_ref();
for k in near {
let Some(piece) = pieces.get(k) else { continue };
let mut path = BezPath::new();
// Each contour is cut only where its own bounds reach the triangle.
for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) {
if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 {
continue;
}
cut_points = cut_points.saturating_add(polygon.len());
if cut_points > MAX_SURFACE_CUTS {
return None;
}
let cut = clip_to(polygon, &window);
let Some((first, rest)) = cut.split_first() else { continue };
path.move_to(map * *first);
rest.iter().for_each(|q| path.line_to(map * *q));
path.close_path();
drawn = drawn.saturating_add(cut.len());
}
if drawn > MAX_SURFACE_POINTS {
return None;
}
if path.elements().is_empty() {
continue;
}
let (path, rule) = match rim {
Some(outline) => {
let cut = vectorcraft_pathops::boolean(
&PathData::from_bezpath(&path),
piece.rule,
outline,
FillRule::NonZero,
vectorcraft_pathops::BoolOp::Intersect,
);
(cut.to_bezpath(), FillRule::NonZero)
}
None => (path, piece.rule),
};
if path.elements().is_empty() {
continue;
}
// Each part copies its paint into its fill, and into the stroke over its seams when
// it takes one.
if !crate::revolve::paint_copies_add(copies, 1 + usize::from(takes_seam(piece)), &piece.paint) {
return None;
}
parts.push(Arc::new(surface_piece(id, piece, (path, rule), map, face, shade)));
}
}
}
Some(out)
}
/// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes
/// from the unrolled surface onto `face`.
fn surface_piece(
id: NodeId,
piece: &Unrolled,
(path, rule): (BezPath, FillRule),
map: Affine,
face: &vectorcraft_three_d::Face,
shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint,
) -> Node {
let gradient_map = map * piece.place;
// Under several lights a face's light varies across it in each channel: a solid color draws
// as the face's own lit art in that color, clipped to the part. An opaque part also draws that
// art clipped to a band of the seam stroke's width around its edges, as the other parts take
// a stroke over their seams.
if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) {
let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light));
let clipped = |area: &BezPath, rule: FillRule| {
let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default());
if let NodeKind::Path { rule: r, .. } = &mut clip.kind {
*r = rule;
}
Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), lit.clone()], clip: true })
};
let mut group = clipped(&path, rule);
if takes_seam(piece) {
let style = vectorcraft_geom::kurbo::Stroke::new(SURFACE_SEAM).with_join(vectorcraft_geom::kurbo::Join::Round);
let band = vectorcraft_geom::kurbo::stroke(path.iter(), &style, &vectorcraft_geom::kurbo::StrokeOpts::default(), SURFACE_TOLERANCE);
group = Node::group(id, vec![Arc::new(group), Arc::new(clipped(&band, FillRule::NonZero))]);
}
group.opacity = piece.opacity;
group.blend = piece.blend;
return group;
}
let mut paint = piece.paint.clone();
if let Paint::Pattern { xf, .. } = &mut paint {
*xf = gradient_map * *xf;
}
let solid = paint.color().filter(|_| matches!(paint, Paint::Solid { .. }));
let mut fill = FillLayer::new(paint);
fill.opacity = piece.opacity;
fill.blend = piece.blend;
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
appearance.transform_gradients(gradient_map);
for item in appearance.items.iter_mut() {
if let AppearanceItem::Fill(f) = item {
match solid {
Some(c) => f.paint = shade(face, c),
None => {
vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination));
}
}
}
}
// Parts on neighboring faces meet edge to edge: an opaque part takes a narrow stroke of its
// paint over the seam, as the faces do.
if takes_seam(piece)
&& let Some(AppearanceItem::Fill(f)) = appearance.items.first()
{
let mut seam = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), SURFACE_SEAM);
seam.join = vectorcraft_doc::LineJoin::Round;
appearance.items.push(AppearanceItem::Stroke(seam));
}
let mut node = Node::path(id, PathData::from_bezpath(&path), appearance);
if let NodeKind::Path { rule: r, .. } = &mut node.kind {
*r = rule;
}
node
}
/// Does each part of `piece` take a stroke of its paint over its seams? Only an opaque part does:
/// the overlap of a transparent one, of one whose gradient has a stop or a freeform point that is
/// not fully opaque, or of a pattern, whose tile may hold transparent art, would show.
fn takes_seam(piece: &Unrolled) -> bool {
let clear = match &piece.paint {
Paint::Gradient(g) => {
g.gradient.stops.iter().any(|s| s.opacity < 1.0) || g.freeform.as_ref().is_some_and(|f| f.points.iter().any(|p| p.opacity < 1.0))
}
Paint::Pattern { .. } => true,
_ => false,
};
piece.opacity >= 1.0 && piece.blend == BlendMode::Normal && !clear
}
/// A region far larger than the face on the side of the line through `a` and `b` that `toward` is
/// on: a rectangle with one edge along the line, reaching a thousand times the line's length past
/// its ends and away from it.
fn side_of(a: Point, b: Point, toward: Point) -> PathData {
let along = b - a;
let mut across = Vec2::new(-along.y, along.x);
if across.dot(toward - a) < 0.0 {
across = -across;
}
let (far, wide) = (across * 1000.0, along * 1000.0);
let mut out = BezPath::new();
out.move_to(a - wide);
out.line_to(b + wide);
out.line_to(b + wide + far);
out.line_to(a - wide + far);
out.close_path();
PathData::from_bezpath(&out)
}
/// Triangle `t` scaled by `factor` about its centroid, wound as it was.
fn grown(t: [Point; 3], factor: f64) -> [Point; 3] {
let c = Point::new((t[0].x + t[1].x + t[2].x) / 3.0, (t[0].y + t[1].y + t[2].y) / 3.0);
t.map(|p| c + (p - c) * factor)
}
/// The affine map that takes the corners `from` of a triangle onto `to`. `None` for a triangle
/// with no area or a map that is not finite.
fn triangle_map(from: &[Point], to: &[Point]) -> Option<Affine> {
let ([u0, u1, u2], [p0, p1, p2]) = (<[Point; 3]>::try_from(from).ok()?, <[Point; 3]>::try_from(to).ok()?);
let (a, b) = (u1 - u0, u2 - u0);
let det = a.x * b.y - b.x * a.y;
if det.abs() <= 1e-12 * (a.hypot2() + b.hypot2()).max(1e-300) {
return None;
}
let (c, d) = (p1 - p0, p2 - p0);
let m = [(c.x * b.y - d.x * a.y) / det, (c.y * b.y - d.y * a.y) / det, (d.x * a.x - c.x * b.x) / det, (d.y * a.x - c.y * b.x) / det];
let xf = Affine::new([m[0], m[1], m[2], m[3], p0.x - m[0] * u0.x - m[2] * u0.y, p0.y - m[1] * u0.x - m[3] * u0.y]);
xf.as_coeffs().iter().all(|v| v.is_finite()).then_some(xf)
}
/// Triangle `t` wound counterclockwise (y up), as [`clip_to`] reads its window. `None` without
/// three corners.
fn counterclockwise(t: &[Point]) -> Option<[Point; 3]> {
let [a, b, c] = <[Point; 3]>::try_from(t).ok()?;
Some(if (b - a).cross(c - a) < 0.0 { [a, c, b] } else { [a, b, c] })
}
/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for
/// each of its edges). A polygon that is not convex keeps its area, with edges along the window's
/// sides where it leaves and comes back.
fn clip_to(polygon: &[Point], window: &[Point; 3]) -> Vec<Point> {
let mut out = polygon.to_vec();
for k in 0..3 {
let (a, b) = (window[k], window[(k + 1) % 3]);
let side = |p: Point| (b - a).cross(p - a);
let input = std::mem::take(&mut out);
for (i, &p) in input.iter().enumerate() {
let q = input[(i + 1) % input.len()];
let (sp, sq) = (side(p), side(q));
if sp >= 0.0 {
out.push(p);
}
if (sp >= 0.0) != (sq >= 0.0) {
out.push(p.lerp(q, sp / (sp - sq)));
}
}
if out.len() < 3 {
return vec![];
}
}
out
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
let symbol = doc.symbols.iter().find(|s| s.name == name)?;
+73 -1
View File
@@ -505,7 +505,10 @@ fn graphics_are_checked() {
}
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
// Revolve takes graphics on its side, named the front; Revolve (Classic) takes none.
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err());
assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
// A loaded file's invalid entries are left out when drawn.
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
}
@@ -796,3 +799,72 @@ fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() {
let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum();
assert!((area - 30_000.0).abs() < 1e-3, "{area}");
}
#[test]
fn curves_are_cut_one_at_a_time_and_the_work_stops_at_the_limit() {
let ellipse = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 6.0)).to_bezpath();
// Cut curve by curve, a path gives the points it gives cut whole.
for scale in [1.0, 100.0, 10_000.0] {
let placed = Affine::scale(scale) * ellipse.clone();
let mut whole = vec![];
vectorcraft_geom::kurbo::flatten(placed.iter(), SURFACE_TOLERANCE, |el| {
if let PathEl::MoveTo(p) | PathEl::LineTo(p) = el {
whole.push(p);
}
});
let mut points = 0;
let cut: Vec<Point> = straight_pieces(&placed, &mut points).unwrap().into_iter().flatten().collect();
assert_eq!(points, cut.len());
assert_eq!(cut.len(), whole.len(), "{scale}");
assert!(cut.iter().zip(&whole).all(|(a, b)| a.distance(*b) < 1e-9), "{scale}");
}
// Past the limit no further curve is cut: of 1,000 ellipses that each take more than 3,000
// points, the count stops within one curve of the limit.
let mut many = BezPath::new();
(0..1000).for_each(|_| many.extend(Affine::scale(10_000.0) * ellipse.clone()));
let mut points = 0;
assert!(straight_pieces(&many, &mut points).is_none());
assert!(points > MAX_ELEMENTS && points < MAX_ELEMENTS + 2000, "{points}");
// A curve that reaches farther than any surface, or to no finite point, is not cut at all.
for scale in [1e12, f64::INFINITY] {
let mut points = 0;
assert!(straight_pieces(&(Affine::scale(scale) * ellipse.clone()), &mut points).is_none());
assert!(points <= 1, "{scale}: {points}");
}
}
#[test]
fn a_line_that_reaches_farther_than_any_surface_is_not_cut() {
let triangle = |far: f64| {
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.line_to((far, 0.0));
b.line_to((0.0, 1.0));
b.close_path();
b
};
assert!(straight_pieces(&triangle(1e7), &mut 0).is_some());
for far in [1e12, 1e300] {
assert!(straight_pieces(&triangle(far), &mut 0).is_none(), "{far}");
assert!(straight_pieces(&(Affine::translate((far, 0.0)) * triangle(1.0)), &mut 0).is_none(), "{far}");
}
}
#[test]
fn only_an_opaque_part_on_revolve_takes_a_seam_stroke() {
let piece = |paint: Paint, opacity: f32, blend: BlendMode| Unrolled {
polygons: vec![],
boxes: vec![],
bounds: Rect::ZERO,
rule: FillRule::NonZero,
paint,
opacity,
blend,
place: Affine::IDENTITY,
};
assert!(takes_seam(&piece(Paint::solid(red()), 1.0, BlendMode::Normal)));
assert!(!takes_seam(&piece(Paint::solid(red()), 0.5, BlendMode::Normal)));
assert!(!takes_seam(&piece(Paint::solid(red()), 1.0, BlendMode::Multiply)));
// A pattern's tile may hold transparent art, which the overlap would show.
assert!(!takes_seam(&piece(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 1.0, BlendMode::Normal)));
}
+1
View File
@@ -5,6 +5,7 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes};
use super::*;
mod imageoutline;
mod painted;
mod rasterfollow;
mod scale;
mod transformfx;
+270
View File
@@ -0,0 +1,270 @@
//! Live-effect plug-ins that paint what they return, run on each fill a painted effect returned.
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Effect, Node, NodeId, NodeKind};
use vectorcraft_geom::{Anchor, PathData, Point, Rect, SubPath, shapes};
use vectorcraft_plugins::wat as tpl;
use crate::geometry::Budget;
use crate::reshape;
use crate::reshape::{HELD_PEAK, PLUGIN_RUNS};
/// Installs live-effect plug-in `id`, which paints what it returns, replacing one with the same id:
/// its effect returns `output` whatever it is given.
fn install_painting(id: &str, output: &serde_json::Value) {
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","api":2,"paintOutput":true,"params":{{}}}}"#);
let module = wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap();
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
}
/// An open path of `curves` tall curves, each drawn with about 5,200 lines.
fn tall_curves(curves: u32) -> PathData {
let h = 3_000_000.0;
let anchors = (0..=curves)
.map(|i| {
let x = 40.0 + f64::from(i);
Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h))
})
.collect();
PathData::single(SubPath::new(anchors, false))
}
/// Installs live-effect plug-in `id`, which reshapes the path it is given: its effect returns
/// `output` whatever it is given.
fn install_reshaping(id: &str, output: &serde_json::Value) {
let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"effect","params":{{}}}}"#);
let module = wat::parse_str(tpl::returning(&manifest, &output.to_string())).unwrap();
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
}
/// `curves` curves from `x`, each `h` tall at its handles.
fn curves_at(x: f64, curves: u32, h: f64) -> SubPath {
let anchors = (0..=curves)
.map(|i| {
let x = x + f64::from(i);
Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h))
})
.collect();
SubPath::new(anchors, false)
}
/// An open path, `dx` to the right of 40, drawn with about `lines` lines: tall curves and one
/// curve that makes up the rest.
fn drawn_with(lines: usize, dx: f64) -> PathData {
let h = 3_000_000.0;
let per = Budget::of(&PathData::single(curves_at(0.0, 1, h))).lines;
let tall = u32::try_from(lines / per).unwrap();
let rest = lines % per;
let mut subpaths = vec![curves_at(40.0 + dx, tall, h)];
if rest > 0 {
// A curve `h` tall at its handles is drawn with about √(9h) lines.
let rest = rest as f64;
subpaths.push(curves_at(40.0 + dx + f64::from(tall) + 2.0, 1, rest * rest / 9.0));
}
PathData::new(subpaths)
}
/// Stacks a painted effect that returns `first` on a path drawn with about `lines` lines with five
/// later effects on a square's fill, the `k`th returning that path `k` to the right (`later`
/// installs each). Each piece's share of the budget is counted once, so every effect fits, and the
/// art ends on the last effect's path, painted by `paints`.
fn later_effects_count_each_piece_once(name: &str, lines: usize, first: &serde_json::Value, later: fn(&str, &serde_json::Value), paints: &[Paint]) {
let near = drawn_with(lines, 0.0);
let drawn = Budget::of(&near).lines;
assert!(drawn.abs_diff(lines) <= 2, "the path is drawn with {drawn} lines");
let first_id = format!("test.effects.{name}.first");
let mut first = first.clone();
first["objects"][0]["path"] = serde_json::to_value(&near).unwrap();
install_painting(&first_id, &first);
let mut ids = vec![format!("plugin.{first_id}")];
for k in 1..=5u8 {
let id = format!("test.effects.{name}.later{k}");
later(&id, &json!({"objects": [{"path": drawn_with(lines, f64::from(k))}]}));
ids.push(format!("plugin.{id}"));
}
let mut n =
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
for id in ids {
n.appearance.items[fill].effects_mut().push(Effect { id, params: json!({}), visible: true });
}
let art = reshape(None, &n, None).unwrap();
let mut paths = vec![];
// The path is a compound path of two (the tall curves and the one that makes up the rest).
art.walk(&mut |c| {
let bounds = match &c.kind {
NodeKind::Compound { children, .. } => children.iter().filter_map(|k| k.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)),
_ => c.path_data().and_then(PathData::bounds),
};
let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect();
if bounds.is_some() && !paints.is_empty() {
paths.push((bounds, paints));
}
});
assert_eq!(paths, [(drawn_with(lines, 5.0).bounds(), paints.to_vec())]);
}
/// Later geometry effects on the two fills a painted effect returned run on each fill, and the
/// path they both stay on counts its piece's share of the budget once: each fill's result, drawn
/// with about 200 lines fewer than half the budget allows, fits at every stage.
#[test]
fn later_geometry_effects_on_two_fills_count_the_piece_once() {
let colors = [Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 1.0, 0.0))];
let fills: Vec<_> = colors.iter().map(|p| serde_json::to_value(p).unwrap()).collect();
let lines = Budget::EFFECTS.lines / 2 - 200;
later_effects_count_each_piece_once("twofills", lines, &json!({"objects": [{"fills": fills}]}), install_reshaping, &colors);
}
/// Later painted effects on a painted effect's piece count the piece's share of the budget once:
/// each run's pieces take the place of the piece they were made of, so a result drawn with about
/// 300 lines fewer than the budget allows fits at every stage.
#[test]
fn later_painted_effects_on_a_painted_piece_count_it_once() {
let lines = Budget::EFFECTS.lines - 300;
later_effects_count_each_piece_once("painted", lines, &json!({"objects": [{}]}), install_painting, &[Paint::solid(Color::BLACK)]);
}
/// A path's bounds and the paints of its fills and strokes.
type PaintedPath = (Option<Rect>, Vec<Paint>);
/// The paths of the art a painted effect `name` that returns `square` with eight fills makes, each
/// path with its paints, when a later effect returns `first` on the first fill and `rest` on the
/// others, painting what it returns when `paints`; and the eight paints. Checks that the plug-in
/// results kept from one fill to the next never cost more than the effects' budget together.
fn eight_fills_then(name: &str, square: &PathData, paints: bool, results: (&PathData, &PathData)) -> (Vec<PaintedPath>, Vec<Paint>) {
let (paths, colors, _) = fills_then(name, 8, square, paints, results);
(paths, colors)
}
/// [`eight_fills_then`] with `n` fills, and how many times the later effect ran on a fill.
fn fills_then(name: &str, n: u8, square: &PathData, paints: bool, (first, rest): (&PathData, &PathData)) -> (Vec<PaintedPath>, Vec<Paint>, usize) {
let colors: Vec<Paint> = (0..n).map(|i| Paint::solid(Color::rgb(f32::from(i) / f32::from(n), 0.0, 0.0))).collect();
let fills: Vec<_> = colors.iter().map(|p| serde_json::to_value(p).unwrap()).collect();
let fills_id = format!("test.effects.{name}.fills");
install_painting(&fills_id, &json!({"objects": [{"path": square, "fills": fills}]}));
let each_id = format!("test.effects.{name}.each");
let declared = if paints { r#","api":2,"paintOutput":true"# } else { "" };
let manifest = format!(r#"{{"id":"{each_id}","name":"Test {each_id}","version":"1","kind":"effect"{declared},"params":{{}}}}"#);
let (on_first, on_rest) = (json!({"objects": [{"path": first}]}).to_string(), json!({"objects": [{"path": rest}]}).to_string());
let module = wat::parse_str(tpl::when_given_else(&manifest, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_rest)).unwrap();
vectorcraft_plugins::registry::install_bytes(&module).unwrap();
let mut n =
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let fill = n.appearance.items.iter().position(|i| i.is_fill()).unwrap();
for id in [fills_id, each_id] {
n.appearance.items[fill].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
}
HELD_PEAK.with(|p| p.set(Budget { anchors: 0, lines: 0 }));
PLUGIN_RUNS.with(|r| r.set(0));
let art = reshape(None, &n, None).unwrap();
let runs = PLUGIN_RUNS.with(std::cell::Cell::get);
let mut paths = vec![];
art.walk(&mut |c| {
if let Some(p) = c.path_data() {
let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect();
if !paints.is_empty() {
paths.push((p.bounds(), paints));
}
}
});
let peak = HELD_PEAK.with(std::cell::Cell::get);
assert!(Budget::EFFECTS.fits(peak), "the results kept cost {peak:?}");
(paths, colors, runs)
}
/// A later painted effect's results on eight fills, each costing more than half the effects'
/// budget and the first fill's on another path than the rest: only the first fill's result fits,
/// the other fills stay together on the square, and the results kept never cost more than the
/// budget together.
#[test]
fn painted_results_that_do_not_fit_are_not_kept() {
let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0));
let (large, other) = (tall_curves(900), PathData::single(curves_at(3_000.0, 900, 3_000_000.0)));
let (paths, colors) = eight_fills_then("held", &square, true, (&large, &other));
assert_eq!(paths, [(large.bounds(), colors[..1].to_vec()), (square.bounds(), colors[1..].to_vec())]);
}
/// A later effect that reshapes each of eight painted fills to the same path, drawn with about a
/// fifth of the effects' budget: the fills share that one path, and the results that move onto it
/// are not kept as well, so what is kept never costs more than the budget.
#[test]
fn results_on_one_path_are_not_kept_for_each_fill() {
let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0));
let same = tall_curves(300);
let (paths, colors) = eight_fills_then("merged", &square, false, (&same, &same));
assert_eq!(paths, [(same.bounds(), colors)]);
}
/// A later effect that reshapes each of eight painted fills to the same path, drawn with more than
/// half the effects' budget: the path costs the art once, so every fill moves onto it, although a
/// second copy of it would not fit.
#[test]
fn results_on_one_path_share_it_near_the_budget() {
let square = shapes::rectangle(Rect::new(40.0, 40.0, 60.0, 60.0));
let large = tall_curves(900);
let (paths, colors) = eight_fills_then("shared", &square, false, (&large, &large));
assert_eq!(paths, [(large.bounds(), colors)]);
}
/// An open path of tall curves `dx` to the right of 40, drawn with about `share` of the effects'
/// budget's lines.
fn drawn_share(share: f64, dx: f64) -> PathData {
let h = 3_000_000.0;
let per = Budget::of(&PathData::single(curves_at(0.0, 1, h))).lines as f64;
let curves = (Budget::EFFECTS.lines as f64 * share / per) as u32;
PathData::single(curves_at(40.0 + dx, curves, h))
}
/// A later painted effect runs once on each of three fills although the results are placed twice:
/// a result that fits both placings is kept between them, and one that did not fit in the first is
/// not run again when it does not fit the second either. The first fill's result (a tenth of the
/// budget) and the second's (half of it) fit, the third's (half of it) does not, and the square
/// (45%) left for the third fill then has no room; in the second placing the second fill's result
/// does not fit beside the square kept for the fills after it.
#[test]
fn a_later_plug_in_runs_once_on_each_fill_across_both_placings() {
let (square, first, rest) = (drawn_share(0.45, 0.0), drawn_share(0.1, 2_000.0), drawn_share(0.5, 4_000.0));
let (paths, colors, runs) = fills_then("once", 3, &square, true, (&first, &rest));
assert_eq!(paths, [(first.bounds(), colors[..1].to_vec()), (square.bounds(), colors[1..].to_vec())]);
assert_eq!(runs, 3, "the later effect ran {runs} times on three fills");
}
/// A built-in geometry effect on two strokes that a painted effect returned, which doubles the lines
/// of a path drawn with 30% of the budget: the second stroke's result does not fit beside the
/// first's, but it is the same path, so it is built again with all the room the art leaves and
/// both strokes are drawn on that one path.
#[test]
fn a_built_in_result_on_the_path_before_it_is_taken_near_the_budget() {
let square = drawn_share(0.3, 0.0);
let transform = json!({"scaleV": 400});
let tall = crate::distort::transform_within(&square, square.bounds().unwrap(), &transform, 0, usize::MAX);
let (s, t) = (Budget::of(&square).lines, Budget::of(&tall).lines);
let lines = Budget::EFFECTS.lines;
assert!(t > lines / 2 + lines / 20 && t < lines - lines / 20 && s + t < lines, "the paths are drawn with {s} and {t} lines");
let colors = [Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::rgb(0.0, 1.0, 0.0))];
let strokes: Vec<_> = colors.iter().map(|p| json!({"paint": p, "width": 1})).collect();
let id = "test.effects.builtin.strokes";
install_painting(id, &json!({"objects": [{"path": square, "strokes": strokes}]}));
let mut n =
Node::path(NodeId(9), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0));
let stroke = n.appearance.items.iter().position(|i| !i.is_fill()).unwrap();
n.appearance.items[stroke].effects_mut().push(Effect { id: format!("plugin.{id}"), params: json!({}), visible: true });
n.appearance.items[stroke].effects_mut().push(Effect { id: "distort.transform".into(), params: transform, visible: true });
let art = reshape(None, &n, None).unwrap();
let mut paths = vec![];
art.walk(&mut |c| {
if let Some(p) = c.path_data() {
let paints: Vec<Paint> = c.appearance.items.iter().map(|i| i.paint().clone()).filter(|p| !p.is_none()).collect();
if !paints.is_empty() {
paths.push((p.bounds(), paints));
}
}
});
// One path, scaled about a reference point of the piece's own, painted by both strokes.
assert_eq!(paths.len(), 1, "{paths:?}");
let (bounds, paints) = &paths[0];
assert_eq!(paints, &colors.to_vec());
let height = |b: Option<Rect>| b.map_or(0.0, |b| b.height());
assert!((height(*bounds) - height(tall.bounds())).abs() < 1.0, "{bounds:?} is not {:?} tall", tall.bounds());
}
+29 -4
View File
@@ -245,6 +245,12 @@ pub fn has_selected_member(s: &Session) -> std::result::Result<(), String> {
let Some(root) = ordinary_isolation(st) else { return has_selection(s) };
if st.selection.objects.iter().any(|id| inside_isolation(&st.doc, root, *id)) { Ok(()) } else { Err("nothing selected".into()) }
}
/// [`has_selected_member`], or a ruler guide is selected outside isolation mode: Object › Lock ›
/// Selection and Object › Hide › Selection.
pub fn has_selected_member_or_guide(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if ordinary_isolation(st).is_none() && !st.selection.guides.is_empty() { Ok(()) } else { has_selected_member(s) }
}
/// Whether `id` lies inside the isolated object `root` (the root itself does not).
pub(crate) fn inside_isolation(d: &vectorcraft_doc::Document, root: vectorcraft_doc::NodeId, id: vectorcraft_doc::NodeId) -> bool {
id != root && d.ancestry(id).is_some_and(|a| a.contains(&root))
@@ -506,8 +512,13 @@ fn id_entry(value: &Value, key: &str, index: usize, cmd: &str) -> Result<NodeId>
/// them), each checked ([`checked_id`]): a malformed one, or one naming no object, is an error,
/// never the selection. `None` when it gives neither (or gives them as `null`).
pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Option<Vec<NodeId>>> {
given_nodes(s, p, command, false)
}
/// The nodes `p` gives `command`, as [`given_objects`] reads them; ruler guide nodes are taken
/// too when `guides`, else refused.
pub(crate) fn given_nodes(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Option<Vec<NodeId>>> {
if p.get("ids").is_some_and(|v| !v.is_null()) {
return checked_ids_param(s, p, "ids", command).map(Some);
return checked_nodes_param(s, p, "ids", command, guides).map(Some);
}
match p.get("id").filter(|v| !v.is_null()) {
None => Ok(None),
@@ -515,7 +526,7 @@ pub(crate) fn given_objects(s: &Session, p: &Value, command: &str) -> Result<Opt
Some(Value::String(r)) if r.starts_with('$') => {
Err(bad(command, format!("`id` is the step reference {r:?}, which only `run` and `command_batch` resolve")))
}
Some(v) => Ok(Some(vec![checked_id(s, v, command)?])),
Some(v) => Ok(Some(vec![checked_node(s, v, command, guides)?])),
}
}
/// The objects `p` gives `command`, as [`given_objects`] reads them, checked only for their form:
@@ -541,9 +552,18 @@ pub(crate) fn index(v: u64) -> usize {
}
/// Validate all explicit targets before a command changes the document or selection.
pub(crate) fn checked_ids_param(s: &Session, p: &Value, key: &str, command: &str) -> Result<Vec<NodeId>> {
checked_nodes_param(s, p, key, command, false)
}
/// The `key` list as [`checked_ids_param`] checks it; ruler guide nodes are taken too when
/// `guides`, else refused.
pub(crate) fn checked_nodes_param(s: &Session, p: &Value, key: &str, command: &str, guides: bool) -> Result<Vec<NodeId>> {
let values =
p.get(key).and_then(Value::as_array).ok_or_else(|| bad(command, format!("{key} must be an array of non-negative integer object ids")))?;
values.iter().enumerate().map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_id(s, value, command))).collect()
values
.iter()
.enumerate()
.map(|(index, value)| id_entry(value, key, index, command).and_then(|_| checked_node(s, value, command, guides)))
.collect()
}
/// The objects a command acts on: `ids` when given (every one checked, and those inside another
@@ -557,11 +577,16 @@ pub(crate) fn checked_ids_or_selection(s: &Session, p: &Value, command: &str) ->
}
pub(crate) fn checked_id(s: &Session, value: &Value, command: &str) -> Result<NodeId> {
checked_node(s, value, command, false)
}
/// `value` as the id of a node of the active document; a ruler guide's is taken only when
/// `guides`.
pub(crate) fn checked_node(s: &Session, value: &Value, command: &str, guides: bool) -> Result<NodeId> {
let id = value.as_u64().map(NodeId).ok_or_else(|| bad(command, format!("invalid object id {value}: expected a non-negative integer")))?;
match s.doc()?.doc.node(id) {
None => Err(bad(command, format!("no such object id {value}"))),
// The guide commands take ruler guides by index.
Some(n) if n.is_ruler_guide() => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
Some(n) if n.is_ruler_guide() && !guides => Err(bad(command, format!("id {value} is a ruler guide, not an object"))),
Some(_) => Ok(id),
}
}
@@ -341,6 +341,33 @@ fn fix_all_is_one_undo_step() {
assert_eq!(s.doc().unwrap().doc.artboards.len(), doc.artboards.len());
}
#[test]
fn a_long_straight_run_loses_its_inner_anchors_in_one_step() {
let mut s = session();
let n: u32 = 5_000;
let mut pts: Vec<(f64, f64)> = (0..n).map(|i| (10.0 + f64::from(i) * 0.05, 150.0)).collect();
pts.push((260.0, 190.0));
let id = line(&mut s, &pts);
let other = rect(&mut s, 300.0, 20.0, 40.0, 40.0);
select(&mut s, &[other]);
let check = s.execute("addon.cleanup.check", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap();
assert_eq!(check["total"], n - 2, "{check}");
assert_eq!(check["findings"][0]["ids"], json!([id.0]));
let shown = s.execute("addon.cleanup.show", &json!({"kind": "collinearAnchors", "scope": "document"})).unwrap();
assert_eq!(shown["count"], n - 2);
assert_eq!(s.doc().unwrap().selection.objects, [id], "Show selects the path");
select(&mut s, &[other]);
let (steps, before) = (undo_steps(&s), node(&s, id).unwrap());
let r = s.execute("addon.cleanup.fix", &json!({"kinds": ["collinearAnchors"], "scope": "document"})).unwrap();
assert_eq!((r["total"].as_u64(), r["fixed"]["collinearAnchors"].as_u64()), (Some(u64::from(n) - 2), Some(u64::from(n) - 2)));
assert_eq!(undo_steps(&s), steps + 1);
assert_eq!(s.doc().unwrap().selection.objects, [other], "Fix keeps the selection");
let ends: Vec<(f64, f64)> = node(&s, id).unwrap().path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect();
assert_eq!(ends, [(10.0, 150.0), (10.0 + f64::from(n - 1) * 0.05, 150.0), (260.0, 190.0)]);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(node(&s, id).unwrap(), before);
}
#[test]
fn the_scope_is_the_selection_or_the_document() {
let mut s = session();
+153 -38
View File
@@ -19,7 +19,10 @@
//! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the
//! image as its Contents row says; new ones go right below that row.
use std::{collections::HashMap, sync::Arc};
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
@@ -45,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Fill",
["Window", "Appearance"],
Some("Cmd+/"),
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
|s, p| add_item(s, p, true)
),
@@ -54,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Stroke",
["Window", "Appearance"],
Some("Cmd+Alt+/"),
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
|s, p| add_item(s, p, false)
),
@@ -63,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)",
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md)",
has_doc,
clear_appearance
),
@@ -72,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reduce to Basic Appearance",
["Window", "Appearance"],
None,
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
reduce_basic
),
@@ -81,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Appearance Item",
[],
None,
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
set_item
),
@@ -90,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Item",
[],
None,
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
remove_item
),
@@ -108,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Duplicate Item",
["Window", "Appearance"],
None,
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
duplicate_item
),
@@ -117,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder Appearance Item",
[],
None,
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {index: where the item landed | contents: the row's slot}",
has_doc,
move_item
),
@@ -144,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show All Hidden Attributes",
["Window", "Appearance"],
None,
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md) → {ids}",
has_doc,
show_all_hidden
),
@@ -162,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Appearance",
[],
None,
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}",
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {source, target}",
has_doc,
transfer
),
@@ -416,9 +419,87 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>>
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
}
/// [`appearance_targets`] of `cmd`, which needs at least one.
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
/// the Appearance panel lists those rows and edits them by index.
pub(crate) fn rowless_series_marks(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
super::graph::series_group_marks_where(d, ids, |group| group.appearance.items.is_empty())
}
/// Whether series group `group` holds nothing of its own, as the graph draws it: no fill or stroke row, no effect, the
/// default opacity, blend mode, isolation and knockout, and no graphic style link.
fn holds_no_look(group: &Node) -> bool {
let ap = &group.appearance;
ap.items.is_empty()
&& ap.effects.is_empty()
&& group.opacity == 1.0
&& group.blend == BlendMode::Normal
&& !group.isolate
&& group.knockout == Default::default()
&& !group.knockout_shape
&& group.extras().graphic_style.is_none()
}
/// The objects whose appearance a command reads for `id`: a graph series group that holds nothing of its own
/// ([`holds_no_look`]) gives the paths directly inside it, backmost first. A series group with an effect, an opacity or
/// another attribute of its own is read itself, with that attribute.
fn look_holders(d: &Document, id: NodeId) -> Vec<NodeId> {
super::graph::series_group_marks_where(d, &[id], holds_no_look)
}
/// The object whose appearance a command reads for `n`: a graph series group that holds nothing of its own stands for
/// the topmost path directly inside it ([`look_holders`]).
pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n)
}
/// Objects whose fill and stroke rows a command edits: the [`appearance_targets`], with a graph series group standing
/// for the paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let ids = appearance_targets(s, p)?;
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
}
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
/// which can hold effects and a graphic style link of its own.
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let own = appearance_targets(s, p)?;
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
let groups = stood_for(&own, &ids);
ids.extend(groups);
Ok(ids)
}
/// The series groups among `own` that `ids` ([`rowless_series_marks`] of `own`) replaced with their paths.
pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec<NodeId> {
let kept: HashSet<NodeId> = ids.iter().copied().collect();
own.iter().copied().filter(|id| !kept.contains(id)).collect()
}
/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it.
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
for id in groups {
if let Some(n) = d.node_mut(*id) {
clear(n);
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
n.extras_mut().graphic_style = None;
}
}
}
/// [`whole_targets`] of `cmd`, which needs at least one.
fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let ids = whole_targets(s, p)?;
if ids.is_empty() {
return Err(bad(cmd, "select objects or give ids"));
}
Ok(ids)
}
/// [`row_targets`] of `cmd`, which needs at least one.
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let ids = row_targets(s, p)?;
if ids.is_empty() {
return Err(bad(cmd, "select objects or give ids"));
}
@@ -616,7 +697,7 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
}
fn clear_appearance(s: &mut Session, p: &Value) -> Result<Value> {
let ids = require_targets(s, p, "appearance.clear")?;
let ids = require_whole_targets(s, p, "appearance.clear")?;
// When every object is cleared already, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, "Clear Appearance", |d| {
@@ -732,35 +813,64 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, "`source` and `target` are the same object"));
}
let copy = switch_or(p, "copy", false, C)?;
// A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a
// move clears them all; as the target, each of them other than a source takes the appearance.
let sources = look_holders(&s.doc()?.doc, source);
let read = sources.last().copied().unwrap_or(source);
let from: Vec<NodeId> = sources.iter().copied().chain(stood_for(&[source], &sources)).collect();
let marks = rowless_series_marks(&s.doc()?.doc, &[target]);
let stands = !marks.contains(&target);
let within: HashSet<NodeId> = from.iter().copied().collect();
let mut targets: Vec<NodeId> = marks.iter().copied().filter(|id| !within.contains(id)).collect();
if targets.is_empty() {
if stands {
return Err(bad(C, "`source` is the only path in series group `target`"));
}
targets.push(target);
}
// A source that is one of the target group's paths keeps its look: the group stands for it too.
let part: HashSet<NodeId> = if stands { marks.into_iter().collect() } else { HashSet::new() };
let from: Vec<NodeId> = stood_for(&from, &targets);
let cleared: Vec<NodeId> = if copy { vec![] } else { from.iter().copied().filter(|id| !part.contains(id)).collect() };
// The group its paths stand for loses its own opacity, blend mode and effects, which would stay on top of them.
let group: Vec<NodeId> = if stands { vec![target] } else { vec![] };
// When both objects come out as they were, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
super::overprint::edit_counted(s, if copy { "Copy Appearance" } else { "Move Appearance" }, |d| {
let src = d.node(source).cloned().ok_or(EngineError::NoNode(source))?;
let to = d.node_mut(target).ok_or(EngineError::NoNode(target))?;
let mut ap = src.appearance.clone();
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
ap.rebase_gradients(f, t);
d.node(source).ok_or(EngineError::NoNode(source))?;
let src = d.node(read).cloned().ok_or(EngineError::NoNode(read))?;
for id in &targets {
let to = d.node_mut(*id).ok_or(EngineError::NoNode(*id))?;
let mut ap = src.appearance.clone();
if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) {
ap.rebase_gradients(f, t);
}
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
if to.contents_label().is_none() {
ap.contents_index = None;
}
to.appearance = ap;
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) =
(src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
super::object::snap_if_aligned(to);
}
// Only groups, layers, type and images have a Contents (Characters) row to keep a slot for.
if to.contents_label().is_none() {
ap.contents_index = None;
clear_stood_for(d, &group);
for id in &cleared {
if let Some(n) = d.node_mut(*id) {
clear(n);
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
super::object::snap_if_aligned(n);
}
}
to.appearance = ap;
(to.opacity, to.blend, to.isolate, to.knockout, to.knockout_shape) = (src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
super::object::snap_if_aligned(to);
if !copy && let Some(n) = d.node_mut(source) {
clear(n);
(n.isolate, n.knockout, n.knockout_shape) = (false, Default::default(), false);
super::object::snap_if_aligned(n);
}
let changed = if copy { vec![target] } else { vec![source, target] };
let changed: Vec<NodeId> = cleared.iter().chain(&targets).copied().collect();
let kept = super::graph::capture_series_opacity(d, &both_kinds(&changed));
// The target last: on marks of one series, its paint is the one the series keeps.
// The targets last: on marks of one series, their paint is the one the series keeps.
let mut rows = top_paint_changed(&before, d, &changed);
rows.extend(painted_rows(d, both_kinds(&[target])));
rows.extend(painted_rows(d, both_kinds(&targets)));
let painted = super::graph::capture_series_top_paints(d, &rows);
let object = super::graph::capture_series_object_opacity(d, &changed);
Ok(count_changed(d, &before, &[source, target]) + usize::from(kept || painted || object))
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object))
})?;
s.active_appearance_item = None;
Ok(json!({ "source": source.0, "target": target.0 }))
@@ -772,7 +882,7 @@ fn is_group(n: &Node) -> bool {
}
fn reduce_basic(s: &mut Session, p: &Value) -> Result<Value> {
let ids = require_targets(s, p, "appearance.reduceToBasic")?;
let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?;
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// The Appearance panel's active row (a row of the first selected object's stack, and in each
@@ -828,7 +938,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
check_numbers(p, &["weight", "opacity"], "appearance.setItem")?;
check_switches(p, &["visible"], "appearance.setItem")?;
let paint = paint_from(s, p)?;
let ids = appearance_targets(s, p)?;
let ids = row_targets(s, p)?;
if ids.is_empty() {
return Err(bad("appearance.setItem", "select objects or give ids"));
}
@@ -1039,7 +1149,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
/// `appearance.showAllHidden`: shows every hidden fill, stroke and effect of the selected objects.
fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
let roots = require_targets(s, p, "appearance.showAllHidden")?;
let roots = require_whole_targets(s, p, "appearance.showAllHidden")?;
let before = s.doc()?.doc.clone();
let ids = s.edit("Show All Hidden Attributes", |d, _| {
let shown: Vec<NodeId> = roots
@@ -1069,11 +1179,16 @@ fn show_all_hidden(s: &mut Session, p: &Value) -> Result<Value> {
fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "appearance.moveItem";
let to = index_param(p, "to", C)?;
let ids = require_targets(s, p, C)?;
let aligned = aligned(p, C)?;
if p.get("from").and_then(Value::as_str) == Some("contents") {
// A graph series group's own Contents row, not its paths, which have none.
let ids = appearance_targets(s, p)?;
if ids.is_empty() {
return Err(bad(C, "select objects or give ids"));
}
return move_contents(s, &ids, to);
}
let ids = require_targets(s, p, C)?;
// Where an aligned row would go in each of several different stacks isn't one place.
if aligned && appearances_differ(&s.doc()?.doc, &ids) {
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
+56 -17
View File
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Guides",
[],
None,
"{} → [{index, vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), shown, editable (its layer shown and unlocked)}…] the ruler guides",
"{} → [{index, id (its node, which `layer.setProps` hides or locks on its own), vertical, pos, selected, artboard?: index (an artboard guide's), layer?: id (the layer it is on), hidden, locked (its own visibility and lock), shown, editable (it and its layer shown and unlocked)}…] the ruler guides",
has_doc,
guide_list
),
@@ -219,7 +219,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select Guides",
[],
None,
"{indexes: [index…], toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}",
"{indexes: [index…] (at most 10,000), toggle?: bool} select ruler guides on their own (deselecting the art); toggle adds or removes them instead, keeping the selected art (a Shift-click on a guide) → {selected: [index…]}",
guides_unlocked,
guide_select
),
@@ -228,7 +228,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Remove Guide",
[],
None,
"{index?} delete ruler guide `index`, else the selected ones (as Delete / edit.clear does) → {count}",
"{index?, indexes?: [index…] (at most 10,000)} delete ruler guide `index` (or guides `indexes`, as dragging their rows onto the Layers panel's trash does), else the selected ones (as Delete / edit.clear does), in one undo step; give `index` or `indexes`, not both, and an index given twice counts once; a hidden or locked guide, or one on a hidden or locked layer, is an error → {count}",
guides_unlocked,
guide_remove
),
@@ -246,7 +246,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Guide to Layer",
[],
None,
"{index?, indexes?: [index…], layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does → {count}",
"{index?, indexes?: [index…] (at most 10,000), layer: id} put ruler guide `index` (or guides `indexes`), else the selected guides, on layer `layer` (a layer or sublayer), as dragging their rows onto that layer's row in the Layers panel does; give `index` or `indexes`, not both, and an index given twice counts once → {count}",
guides_unlocked,
guide_set_layer
),
@@ -805,12 +805,17 @@ fn guide_list(s: &mut Session, _: &Value) -> Result<Value> {
let row = |(i, g): (usize, &Guide)| {
let selected = g.id.is_some_and(|id| st.selection.guides.contains(&id));
let mut r = json!({ "index": i, "vertical": g.vertical, "pos": g.pos, "selected": selected });
if let Some(id) = g.id {
r["id"] = json!(id.0);
}
if let Some(ab) = st.doc.artboards.iter().position(|a| Some(a.id) == g.artboard) {
r["artboard"] = json!(ab);
}
if let Some(l) = g.layer {
r["layer"] = json!(l.0);
}
r["hidden"] = json!(g.hidden);
r["locked"] = json!(g.locked);
r["shown"] = json!(st.doc.guide_shown(g));
r["editable"] = json!(st.doc.guide_editable(g));
r
@@ -824,27 +829,44 @@ fn guide_index_in(ids: &[NodeId], v: Option<&Value>, cmd: &str) -> Result<NodeId
ids.get(i).copied().ok_or_else(|| bad(cmd, format!("no guide {i}")))
}
/// The most guide indexes one `indexes` list may hold.
const MAX_GUIDE_INDEXES: usize = 10_000;
/// `indexes` as a list of at most [`MAX_GUIDE_INDEXES`] entries.
fn guide_index_list<'a>(v: &'a Value, cmd: &str) -> Result<&'a Vec<Value>> {
let list = v.as_array().ok_or_else(|| bad(cmd, "indexes must be an array of guide indexes"))?;
if list.len() > MAX_GUIDE_INDEXES {
return Err(bad(cmd, format!("indexes may hold at most {MAX_GUIDE_INDEXES} entries")));
}
Ok(list)
}
/// The id of ruler guide `index` of the active document (`index` validated).
fn guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
guide_index_in(&guide_ids(&s.doc()?.doc), v, cmd)
}
/// Is ruler guide `id` one that can be moved or deleted: not on a hidden or locked layer?
/// Is ruler guide `id` one that can be moved or deleted: not hidden or locked itself, nor on a
/// hidden or locked layer?
fn check_editable_guide(s: &Session, id: NodeId) -> Result<NodeId> {
let d = &s.doc()?.doc;
if !d.ruler_guide(id).is_some_and(|g| d.guide_editable(&g)) {
let guide = d.ruler_guide(id);
if guide.as_ref().is_some_and(|g| g.hidden || g.locked) {
return Err(EngineError::Other("the guide is hidden or locked".into()));
}
if !guide.is_some_and(|g| d.guide_editable(&g)) {
return Err(EngineError::Other("the guide is on a hidden or locked layer".into()));
}
Ok(id)
}
/// [`guide_index`] of a guide that can be moved or deleted: not on a hidden or locked layer.
/// [`guide_index`] of a guide that can be moved or deleted ([`check_editable_guide`]).
fn editable_guide_index(s: &Session, v: Option<&Value>, cmd: &str) -> Result<NodeId> {
check_editable_guide(s, guide_index(s, v, cmd)?)
}
fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
let list = p.get("indexes").and_then(Value::as_array).ok_or_else(|| bad("guide.select", "missing indexes"))?;
let list = guide_index_list(p.get("indexes").ok_or_else(|| bad("guide.select", "missing indexes"))?, "guide.select")?;
let ids = guide_ids(&s.doc()?.doc);
let picked = list.iter().map(|v| guide_index_in(&ids, Some(v), "guide.select")).collect::<Result<Vec<_>>>()?;
if switch_or(p, "toggle", false, "guide.select")? {
@@ -861,18 +883,30 @@ fn guide_select(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "selected": guide_indexes(&st.doc, &st.selection.guides) }))
}
/// Delete ruler guide `index`, else the selected guides, in one undo step → {count}.
/// Delete ruler guide `index` (or guides `indexes`), else the selected guides, in one undo step
/// → {count}.
pub(crate) fn guide_remove(s: &mut Session, p: &Value) -> Result<Value> {
let gone: Vec<NodeId> = match p.get("index") {
Some(v) => vec![editable_guide_index(s, Some(v), "guide.remove")?],
None => s.doc()?.selection.guides.clone(),
const C: &str = "guide.remove";
let mut gone: Vec<NodeId> = match (p.get("index"), p.get("indexes")) {
(Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")),
(Some(v), None) => vec![editable_guide_index(s, Some(v), C)?],
(None, Some(list)) => {
let list = guide_index_list(list, C)?;
let ids = guide_ids(&s.doc()?.doc);
// A set, so an index given twice deletes its guide once and the ids held never outnumber the guides.
let set = list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<BTreeSet<_>>>()?;
set.into_iter().collect()
}
(None, None) => s.doc()?.selection.guides.clone(),
};
gone.sort_unstable();
gone.dedup();
if gone.is_empty() {
return Err(bad("guide.remove", "no guide selected"));
return Err(bad(C, "no guide selected"));
}
let label = if gone.len() == 1 { "Delete Guide" } else { "Delete Guides" };
s.edit(label, |d, sel| {
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.binary_search(&id).is_ok()));
Ok(())
})?;
Ok(json!({ "count": gone.len() }))
@@ -888,14 +922,19 @@ fn guide_set_layer(s: &mut Session, p: &Value) -> Result<Value> {
if super::layer::locked_within(d, layer) {
return Err(EngineError::Other("the layer or group is locked".into()));
}
let moving: Vec<NodeId> = match (p.get("index"), p.get("indexes").and_then(Value::as_array)) {
(Some(v), _) => vec![editable_guide_index(s, Some(v), C)?],
let mut moving: Vec<NodeId> = match (p.get("index"), p.get("indexes")) {
(Some(_), Some(_)) => return Err(bad(C, "give index or indexes, not both")),
(Some(v), None) => vec![editable_guide_index(s, Some(v), C)?],
(None, Some(list)) => {
let list = guide_index_list(list, C)?;
let ids = guide_ids(&s.doc()?.doc);
list.iter().take(10_000).map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
list.iter().map(|v| check_editable_guide(s, guide_index_in(&ids, Some(v), C)?)).collect::<Result<Vec<_>>>()?
}
(None, None) => s.doc()?.selection.guides.clone(),
};
// An index given twice moves (and counts) its guide once; the others keep their order.
let mut seen = HashSet::new();
moving.retain(|id| seen.insert(*id));
if moving.is_empty() {
return Err(bad(C, "no guide selected (or give an index)"));
}
+1 -1
View File
@@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it",
has_doc,
freehand
),
+8 -2
View File
@@ -151,7 +151,11 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
}
let pen = PenRecord::of_samples(&samples);
let mut pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
let tol = number_or(p, "fidelity", 1.5, C)?.clamp(vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, 100.0);
let tol = number_or(p, "fidelity", 1.5, C)?;
let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE);
if !(lo..=hi).contains(&tol) {
return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt")));
}
// The tolerance the stroke is fitted at; with `fit: false` it is not fitted.
let fit_tol = switch_or(p, "fit", true, C)?.then_some(tol);
let closed = switch_or(p, "closed", false, C)?;
@@ -200,7 +204,9 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
}
None => None,
};
let close_tol = (tol * 4.0).max(6.0);
// An extending stroke that ends within four Fidelities of the path's other end closes it:
// at least 6 pt and at most 400 pt, whatever the Fidelity it is fitted at.
let close_tol = (tol * 4.0).clamp(6.0, 400.0);
let closing = connect.is_none() && sp.anchors.len() >= 2 && pts.last().is_some_and(|p| p.distance(first) <= close_tol);
if closing && let Some(l) = pts.last_mut() {
*l = first;
+3 -3
View File
@@ -1,5 +1,5 @@
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
//! Graphic) and mapped onto the planar faces of 3D objects (Extrude & Bevel's caps, a plane). The
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
//! also edits.
@@ -28,7 +28,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane), scale?: % (1..10000; default 100, or less so the graphic fits inside the object), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it; every object's 3D effect must be Extrude & Bevel (on a solid cap) or Rotate (the Plane type); one undo step → {ids, graphic}",
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
has_doc,
map_graphic
),
@@ -111,7 +111,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
};
if !effects::takes_graphics(&effect.id) {
return Err(bad(C, format!("object {}: Graphics map onto planar faces: use the Extrude or Plane object type", id.0)));
return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN)));
}
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
// but has no cap to show a new one on.
@@ -68,12 +68,37 @@ fn a_large_graphic_starts_inside_its_object() {
assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}");
}
#[test]
fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() {
let (mut s, id) = setup("threeD.revolve");
let plain = vectorcraft_render::effects::revolve_art_in(Some(&s.doc().unwrap().doc), s.doc().unwrap().doc.node(id).unwrap());
let history = undo_len(&s);
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}]));
assert_eq!(undo_len(&s), history + 1);
let d = &s.doc().unwrap().doc;
assert_ne!(vectorcraft_render::effects::revolve_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn");
// A large graphic starts inside the half of the side seen from the front: 100π around the
// axis (the square's far edge is 100 from it) and 300 along the profile (its edge on the axis
// sweeps nothing).
let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap();
let scale = graphics(&s, id)[1]["scale"].as_f64().unwrap();
assert!((scale - 100.0 * 100.0 * std::f64::consts::PI / 401.0).abs() < 1e-6, "{scale}");
// The side is its only face.
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("side"), "{e}");
assert_eq!(undo_len(&s), history);
}
#[test]
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
let (mut s, id) = setup("threeD.inflate");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Extrude or Plane"), "{e}");
assert!(e.contains("Plane, Extrude and Revolve"), "{e}");
let (mut s, id) = setup("threeD.rotate");
for (p, says) in [
(json!({"symbol": "Gone"}), "no symbol named"),
+32 -4
View File
@@ -18,8 +18,8 @@ use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint,
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer};
use vectorcraft_doc::live::GradientMesh;
use vectorcraft_doc::pattern::{PatternDef, place_art};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling};
use vectorcraft_geom::{Affine, PathData, Point, Rect, SubPath, Vec2, shapes};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Scaling, TextObject};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, SubPath, Vec2, shapes};
use super::dimension::EndedLink;
use super::edit::selected_roots;
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand Options",
[],
None,
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands, which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
"{} what each Expand option would change in the selection → {object, fill, stroke, gradient, appearance, symbolArt?: {fill, stroke, gradient}} (true: something to expand; gradient: a gradient fill that Fill expands (in type, on the outline Object makes of a character), which Expand Gradient To applies to; appearance: appearance attributes Expand Appearance expands first, for which Object › Expand… is dimmed in the menus; symbolArt, when the selection holds symbol instances that Object expands: true when only their art holds it, which Fill and Stroke reach only with Object on)",
has_selection,
|s, _| {
let roots = selected_roots(s)?;
@@ -197,7 +197,7 @@ impl Expandable {
// Once one is found, the next path is not measured.
e.gradient = e.gradient
|| match &c.kind {
NodeKind::Text(t) => t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))),
NodeKind::Text(t) => text_gradient_expands(d, t),
_ => shape && gradient_expands(d, c),
};
e.fill |= e.gradient;
@@ -247,6 +247,34 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
any
}
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline
/// graphics and color glyphs become other art. Leaves the document as it is and stops at the
/// first such path.
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
return false;
}
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let expands = |run: usize, outline: &BezPath| {
let style = t.runs.get(run).map(|r| &r.style);
if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) {
return false;
}
let path = PathData::from_bezpath(outline).transformed(t.xf);
if path.is_empty() {
return false;
}
let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance());
gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance))
};
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
|| lay.ruby.iter().any(|g| expands(g.run, &g.outline))
|| vectorcraft_text::decorations(&lay, vectorcraft_text::FontDb::global(), t).iter().any(|(run, bar)| expands(*run, bar))
}
/// [`gradient_expands`] for a path that no live-effect plug-in paints ([`expand_piece_fills`]).
fn piece_gradient_expands(d: &Document, l: &Node) -> bool {
if !l.appearance.items.iter().filter_map(gradient_fill).any(|(_, g)| g.gradient.is_spread()) {
+35 -7
View File
@@ -870,7 +870,10 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// read with [`jxlread`] and stored as PNG, with the ICC profile their colors are left in.
/// A PNG, JPEG, GIF, WebP or TIFF whose orientation ([`vectorcraft_doc::cmyk::exif_orientation`]) turns or flips it is
/// stored as it is shown, with its resolution's axes swapped when it turns a quarter; a CMYK JPEG
/// or TIFF keeps its inks, 8 bits each, as a CMYK TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]).
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA.
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let ppi = super::ppi::resolution(bytes);
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
@@ -933,35 +936,60 @@ pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let cms = vectorcraft_color::cms::active();
vectorcraft_doc::cmyk::extra_samples_tiff_rgba(bytes, |c| cms.cmyk_to_srgb(c, false))
};
// The ICC profile of the samples the image decoder reads; the other readers give sRGB pixels.
let mut icc = None;
let mut img = match (f.id == "tiff").then(extra_samples).flatten() {
Some(img) => image::DynamicImage::ImageRgba8(img),
None => match (f.id == "tiff").then(|| vectorcraft_doc::cmyk::group3_tiff_rgba(bytes)).flatten() {
Some(read) => image::DynamicImage::ImageRgba8(read.map_err(err)?),
None => {
use image::ImageDecoder as _;
let decoder = reader.into_decoder().map_err(err)?;
let mut decoder = reader.into_decoder().map_err(err)?;
// The allowance counts the decoded samples and the RGBA pixels they become (#1717).
let (w, h) = decoder.dimensions();
if decoder.total_bytes() > MAX_RASTER_ALLOC || u64::from(w) * u64::from(h) * 4 > MAX_RASTER_ALLOC {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
}
// A profile the decoder can't read leaves the image without one. The image decoder
// reads a TIFF's tags within the size of its pixels, so a small TIFF's profile is
// read by the TIFF decoder itself.
icc = match f.id {
"tiff" => vectorcraft_doc::cmyk::tiff_icc_profile(bytes),
_ => decoder.icc_profile().ok().flatten(),
};
image::DynamicImage::from_decoder(decoder).map_err(err)?
}
},
};
img.apply_orientation(orientation.unwrap_or(image::metadata::Orientation::NoTransforms));
let mut img = img.into_rgba8();
if f.id == "tga" {
let mut img = img.into_rgba8();
super::tgaread::fix_alpha(bytes, &mut img);
return as_png(img, None, shown_ppi);
}
as_png(img, None, shown_ppi)
use image::DynamicImage as D;
let img = match img {
D::ImageLuma8(_) | D::ImageLumaA8(_) | D::ImageRgb8(_) | D::ImageRgba8(_) => img,
D::ImageLuma16(_) | D::ImageLumaA16(_) | D::ImageRgb16(_) | D::ImageRgba16(_) => img,
other => D::ImageRgba8(other.into_rgba8()),
};
let icc = icc.filter(|icc| png_takes_icc(&img, icc));
as_png(img, icc, shown_ppi)
}
/// Can a PNG of `img`'s samples carry ICC profile `icc`? Its color space must be the samples':
/// `GRAY` for gray samples, `RGB ` for RGB ones.
fn png_takes_icc(img: &image::DynamicImage, icc: &[u8]) -> bool {
let want = if img.color().has_color() { *b"RGB " } else { *b"GRAY" };
vectorcraft_doc::cmyk::icc_color_space(icc) == Some(want)
}
/// `img` stored as a PNG that keeps the file's resolution and carries `icc`, the ICC profile its
/// colors are in.
pub(super) fn as_png(img: image::RgbaImage, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
/// colors are in. `img` has samples a PNG holds: 8 or 16 bits of gray or RGB, with or without alpha.
pub(super) fn as_png(img: impl Into<image::DynamicImage>, icc: Option<Vec<u8>>, ppi: Option<(f64, f64)>) -> Result<RasterImage> {
use image::ImageEncoder as _;
let size = img.dimensions();
let img: image::DynamicImage = img.into();
let size = (img.width(), img.height());
let mut png = Vec::new();
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc {
+3 -3
View File
@@ -98,8 +98,8 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
FormatOption {
name: "longPagesInPoints",
ty: "boolean",
default: "false",
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit)",
default: "true",
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit); false writes it with a UserUnit from PDF 1.6 on",
},
FormatOption {
name: "createLayers",
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdf Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art, as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMY Line truncated
has_doc,
export_pdf
),
+4
View File
@@ -730,6 +730,10 @@ fn encode_ai_pages(cmd: &str, f: &Format, doc: &Document, p: &Value, editing: bo
if o.get("standard").is_none_or(Value::is_null) {
o.entry("createLayers").or_insert(json!(true));
}
// A page longer than 14,400 pt keeps its `UserUnit` (PDF export writes it in points).
if o.get("longPagesInPoints").is_none_or(Value::is_null) {
o.insert("longPagesInPoints".into(), json!(false));
}
if let Some(c) = o.get("compress").and_then(Value::as_bool) {
let compression = o.entry("compression").or_insert_with(|| json!({}));
if let Some(m) = compression.as_object_mut() {
+210
View File
@@ -1171,6 +1171,216 @@ fn png_webp_and_rgb_tiff_turned_a_quarter_swap_their_resolution() {
}
}
/// A made-up ICC profile of `len` bytes (at least a header's 128) whose header names the color
/// space `space`; the bytes after the header differ from place to place.
fn icc_profile(space: &[u8; 4], len: usize) -> Vec<u8> {
let mut icc: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
icc[..4].copy_from_slice(&u32::try_from(len).unwrap().to_be_bytes());
icc[12..16].copy_from_slice(b"mntr");
icc[16..20].copy_from_slice(space);
icc[36..40].copy_from_slice(b"acsp");
icc
}
/// `tiff` (little-endian) with an ICCProfile tag (34675, of type UNDEFINED) holding `icc`: its first
/// directory copied to the end of the file with the tag added in order, as [`tiff_oriented`] adds
/// its tag.
fn tiff_with_icc(tiff: &[u8], icc: &[u8]) -> Vec<u8> {
let at = usize::try_from(u32::from_le_bytes(tiff[4..8].try_into().unwrap())).unwrap();
let n = usize::from(u16::from_le_bytes([tiff[at], tiff[at + 1]]));
let mut entries: Vec<Vec<u8>> = tiff[at + 2..at + 2 + 12 * n].chunks(12).map(<[u8]>::to_vec).collect();
let mut out = tiff.to_vec();
if out.len() % 2 == 1 {
out.push(0);
}
let data = u32::try_from(out.len()).unwrap();
out.extend(icc);
if out.len() % 2 == 1 {
out.push(0);
}
let i = entries.iter().position(|e| u16::from_le_bytes([e[0], e[1]]) > 34675).unwrap_or(n);
let count = u32::try_from(icc.len()).unwrap();
entries.insert(i, [&34675u16.to_le_bytes()[..], &7u16.to_le_bytes(), &count.to_le_bytes(), &data.to_le_bytes()].concat());
let ifd = u32::try_from(out.len()).unwrap();
out[4..8].copy_from_slice(&ifd.to_le_bytes());
out.extend(u16::try_from(n + 1).unwrap().to_le_bytes());
out.extend(entries.concat());
out.extend([0; 4]);
out
}
/// The ICC profile and pixels of a stored image, read by the image decoder for its format.
fn stored_pixels(what: &str, img: &RasterImage) -> (Option<Vec<u8>>, image::ExtendedColorType, image::DynamicImage) {
use image::ImageDecoder as _;
let bytes = Cursor::new(img.blob.bytes.as_slice());
let mut d: Box<dyn image::ImageDecoder> = match img.blob.mime.as_str() {
"image/png" => Box::new(image::codecs::png::PngDecoder::new(bytes).unwrap()),
"image/tiff" => Box::new(image::codecs::tiff::TiffDecoder::new(bytes).unwrap()),
other => panic!("{what}: stored as {other}"),
};
let icc = d.icc_profile().unwrap();
let color = d.original_color_type();
(icc, color, image::DynamicImage::from_decoder(d).unwrap())
}
/// An image turned by its orientation and stored as PNG keeps the gray or RGB ICC profile its file
/// carries, and its 16-bit samples at 16 bits, from a PNG, a JPEG, a WebP and a TIFF; a TIFF the
/// image decoder reads, stored as PNG without a turn, keeps them too. A profile of another color
/// space than the samples' is left out.
#[test]
fn images_stored_as_png_keep_their_icc_profile_and_16_bit_samples() {
use image::{DynamicImage, ImageEncoder as _};
let (rgb_icc, gray_icc, cmyk_icc) = (icc_profile(b"RGB ", 600), icc_profile(b"GRAY", 300), icc_profile(b"CMYK", 400));
// 3 × 2, every sample's low byte different.
let rgb16 = image::ImageBuffer::from_fn(3, 2, |x, y| {
let v = u16::try_from(x * 0x1111 + y * 0x2345).unwrap();
image::Rgb([0x1000 + v, 0x8001 + v, 0xF0F3 - v])
});
let rgb16 = DynamicImage::ImageRgb16(rgb16);
let gray16 = DynamicImage::ImageLuma16(image::ImageBuffer::from_fn(3, 2, |x, y| image::Luma([u16::try_from(x * 0x3001 + y * 0x0107).unwrap()])));
let rgb8 = DynamicImage::ImageRgb8(image::RgbImage::from_fn(3, 2, |x, y| image::Rgb([u8::try_from(x * 70 + y * 9).unwrap(), 200, 13])));
let png = |img: &DynamicImage, icc: &[u8], orientation: u16| {
let mut out = Vec::new();
let mut enc = image::codecs::png::PngEncoder::new(&mut out);
enc.set_icc_profile(icc.to_vec()).unwrap();
enc.set_exif_metadata(exif_block(orientation, (150, 150))).unwrap();
img.write_with_encoder(enc).unwrap();
out
};
let webp = {
let mut out = Vec::new();
let mut enc = image::codecs::webp::WebPEncoder::new_lossless(&mut out);
enc.set_icc_profile(rgb_icc.clone()).unwrap();
enc.set_exif_metadata(exif_block(6, (150, 150))).unwrap();
rgb8.write_with_encoder(enc).unwrap();
out
};
let tiff = |orientation: Option<u16>| {
let mut out = Vec::new();
let mut enc = image::codecs::tiff::TiffEncoder::new(Cursor::new(&mut out));
enc.set_icc_profile(rgb_icc.clone()).unwrap();
rgb16.write_with_encoder(enc).unwrap();
match orientation {
Some(o) => tiff_oriented(&out, o, false, None),
None => out,
}
};
// (what, file, the ICC profile to keep, the pixels as they show, 16 bits)
type Case<'a> = (&'a str, Vec<u8>, Option<&'a [u8]>, DynamicImage, bool);
let cases: Vec<Case> = vec![
("16-bit RGB PNG, orientation 6", png(&rgb16, &rgb_icc, 6), Some(&rgb_icc), rgb16.rotate90(), true),
("16-bit gray PNG, orientation 8", png(&gray16, &gray_icc, 8), Some(&gray_icc), gray16.rotate270(), true),
("8-bit RGB PNG, orientation 3", png(&rgb8, &rgb_icc, 3), Some(&rgb_icc), rgb8.rotate180(), false),
("RGB PNG with a CMYK profile, orientation 6", png(&rgb8, &cmyk_icc, 6), None, rgb8.rotate90(), false),
("WebP, orientation 6", webp, Some(&rgb_icc), rgb8.rotate90(), false),
("16-bit RGB TIFF, not turned", tiff(None), Some(&rgb_icc), rgb16.clone(), true),
("16-bit RGB TIFF, orientation 6", tiff(Some(6)), Some(&rgb_icc), rgb16.rotate90(), true),
];
for (what, file, icc, want, wide) in cases {
let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (want.width(), want.height(), "image/png"), "{what}");
let (kept, color, px) = stored_pixels(what, &img);
assert_eq!(kept.as_deref(), icc, "{what}: the ICC profile");
assert_eq!(color.bits_per_pixel() / u16::from(color.channel_count()), if wide { 16 } else { 8 }, "{what}: the sample depth");
if wide {
assert_eq!(px.to_rgb16(), want.to_rgb16(), "{what}: the samples");
} else {
assert_eq!(px.to_rgb8(), want.to_rgb8(), "{what}: the samples");
}
}
// A JPEG's samples change in encoding; its profile is kept.
let mut jpg = Vec::new();
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpg, 95);
enc.set_icc_profile(rgb_icc.clone()).unwrap();
rgb8.write_with_encoder(enc).unwrap();
let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (150, 150))].concat();
let mut turned = jpg[..2].to_vec();
turned.extend([0xff, 0xe1]);
turned.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
turned.extend(&exif);
turned.extend(&jpg[2..]);
let img = raster_image(&turned).unwrap();
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (2, 3, "image/png"), "JPEG");
assert_eq!(stored_pixels("JPEG", &img).0, Some(rgb_icc.clone()), "JPEG: the ICC profile");
// Not turned, a PNG keeps its own bytes.
let plain = png(&rgb16, &rgb_icc, 1);
assert_eq!(raster_image(&plain).unwrap().blob.bytes.as_slice(), plain.as_slice(), "a PNG as taken keeps its bytes");
}
/// A CMYK TIFF stored again, because it stores one plane per ink or because its orientation turns
/// it, keeps its ICC profile as tag 34675 and its 8 or 16 bits a sample, exactly; one that stores
/// its inks together and isn't turned keeps its own bytes.
#[test]
fn cmyk_tiffs_written_again_keep_their_icc_profile_and_depth() {
use image::DynamicImage;
let icc = icc_profile(b"CMYK", 900);
// 3 × 2, no black, every sample's low byte different.
let ink = |c: usize, p: usize| -> u16 { u16::try_from(0x0101 * (c * 5 + p + 1) + 0x10 * p + c).unwrap() };
for bits in [8u16, 16] {
let sample = |c: usize, p: usize| match (c, bits) {
(3, _) => 0,
(_, 16) => ink(c, p),
_ => ink(c, p) & 0xFF,
};
let channels: Vec<Vec<u16>> = (0..4).map(|c| (0..6).map(|p| sample(c, p)).collect()).collect();
// The image decoder shows a CMYK pixel without black as 1 - C, 1 - M, 1 - Y, exactly.
let full = if bits == 16 { 0xFFFF } else { 0xFF };
let shown: Vec<u16> = (0..6).flat_map(|p| (0..3).map(|c| full - channels[c][p]).collect::<Vec<_>>()).collect();
let shown = if bits == 16 {
DynamicImage::ImageRgb16(image::ImageBuffer::from_raw(3, 2, shown).unwrap())
} else {
DynamicImage::ImageRgb8(image::RgbImage::from_raw(3, 2, shown.iter().map(|v| u8::try_from(*v).unwrap()).collect()).unwrap())
};
for planar in [false, true] {
let file = tiff_with_icc(&hand_tiff(5, bits, &[], planar, &channels), &icc);
for (orientation, want) in [(None, shown.clone()), (Some(6), shown.rotate90()), (Some(3), shown.rotate180())] {
let what = format!("{bits} bits, planar {planar}, orientation {orientation:?}");
let file = orientation.map_or_else(|| file.clone(), |o| tiff_oriented(&file, o, false, Some(150)));
let img = raster_image(&file).unwrap_or_else(|e| panic!("{what}: {e}"));
if orientation.is_none() && !planar {
assert_eq!(img.blob.bytes.as_slice(), file.as_slice(), "{what}: kept as it is");
}
let (kept, color, px) = stored_pixels(&what, &img);
assert_eq!(kept.as_deref(), Some(icc.as_slice()), "{what}: the ICC profile");
let depth = if bits == 16 { image::ExtendedColorType::Cmyk16 } else { image::ExtendedColorType::Cmyk8 };
assert_eq!(color, depth, "{what}: the sample depth");
assert_eq!(px, want, "{what}: the samples");
}
}
}
}
/// A CMYK JPEG turned by its orientation and stored as a CMYK TIFF keeps its whole ICC profile,
/// put together from the two APP2 segments a profile larger than one segment is split into.
#[test]
fn a_turned_cmyk_jpeg_keeps_its_icc_profile_from_every_segment() {
use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions};
let icc = icc_profile(b"CMYK", 70_000);
let inks: Vec<u8> = (0..16u32 * 8).flat_map(|i| [u8::try_from(i).unwrap(), 0, 0, 40]).collect();
let o = JpegOptions { color_model: ColorModel::Cmyk, embed_icc: false, ..Default::default() };
let jpg = jpeg::encode(&inks, 16, 8, 100, None, &o).unwrap();
let exif = [b"Exif\0\0".as_slice(), &exif_block(6, (300, 300))].concat();
let mut file = jpg[..2].to_vec();
file.extend([0xff, 0xe1]);
file.extend(u16::try_from(exif.len() + 2).unwrap().to_be_bytes());
file.extend(&exif);
let chunks: Vec<&[u8]> = icc.chunks(65_519).collect();
assert_eq!(chunks.len(), 2, "the profile takes two segments");
for (i, chunk) in chunks.iter().enumerate() {
file.extend([0xff, 0xe2]);
file.extend(u16::try_from(chunk.len() + 16).unwrap().to_be_bytes());
file.extend(b"ICC_PROFILE\0");
file.extend([u8::try_from(i + 1).unwrap(), 2]);
file.extend(*chunk);
}
file.extend(&jpg[2..]);
let img = raster_image(&file).unwrap();
assert_eq!((img.width, img.height, img.blob.mime.as_str()), (8, 16, "image/tiff"));
let (kept, color, _) = stored_pixels("CMYK JPEG", &img);
assert_eq!(color, image::ExtendedColorType::Cmyk8);
assert!(kept.as_deref() == Some(icc.as_slice()), "the whole ICC profile: {:?} bytes", kept.map(|k| k.len()));
}
/// With `importer` named, a file up to the importer's limit is read whole and a larger one is an
/// error, whatever its content.
#[test]
+2 -1
View File
@@ -46,7 +46,8 @@ use generate::generate;
use series::default_series_color;
pub(crate) use series::{
capture_label_anti_alias, capture_label_paragraphs, capture_label_styles, capture_series_object_opacity, capture_series_opacity,
capture_series_paints, capture_series_top_paints, paint_targets, series_object_opacity_differs, shown_paint,
capture_series_paints, capture_series_top_paints, paint_targets, series_group_marks, series_group_marks_where, series_object_opacity_differs,
shown_paint,
};
#[cfg(test)]
+38 -1
View File
@@ -79,6 +79,11 @@ struct SeriesRef {
index: usize,
}
/// How many series groups `spec`'s graph has: a group whose index is past it (the index comes from the file) is not one.
fn series_count(spec: &GraphSpec) -> usize {
spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES)
}
/// Every node in a graph's series groups (the groups too), found in one pass over the document.
/// Axes, the legend and groups whose index is past the graph's series (the index comes from the
/// file) are left out.
@@ -86,7 +91,7 @@ fn series_members(doc: &Document) -> HashMap<NodeId, SeriesRef> {
let mut out = HashMap::new();
doc.walk(|n| {
let Some(spec) = n.extras().graph.as_deref() else { return };
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
let count = series_count(spec);
for group in n.children().into_iter().flatten() {
let Some(index) = group.extras().series_index.and_then(|i| usize::try_from(i).ok()).filter(|i| *i < count) else { continue };
let r = SeriesRef { graph: n.id, group: group.id, index };
@@ -124,6 +129,38 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
out
}
/// `ids` with each graph series group replaced by the paths directly inside it, as [`paint_targets`] reads a series
/// group: the graph draws its series groups again with no rows of their own. A series group with no such path, other
/// ids and the art of a graph design pass through, and the order of `ids` is kept.
pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
series_group_marks_where(doc, ids, |_| true)
}
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
// A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is
// looked up through its parent, with no pass over the document: the panels call this while they draw.
let is_series_group = |n: &Node| {
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
graph.is_some_and(|spec| index < series_count(spec))
};
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for id in ids {
match doc.node(*id) {
Some(group) if is_series_group(group) && stands(group) => {
let marks: Vec<NodeId> =
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
}
_ => out.push(*id),
}
}
out.retain(|id| seen.insert(*id));
out
}
/// Copy the paint just applied to generated series art into that series' fill or stroke. Called
/// inside the same document edit, so the visible paint and future regeneration undo together.
/// Gradients, patterns and swatch links are kept as [`Paint`], not reduced to a solid colour.
+358
View File
@@ -1804,6 +1804,364 @@ fn redefining_a_graphic_style_from_a_series_mark_keeps_the_paint_another_mark_st
assert_eq!(spec(&s, id).series_paints, was);
}
/// Series 0's group, and whether it is as the graph draws it: the group has no rows of its own and each path directly
/// inside it has rows.
fn series_0_group(s: &Session, id: NodeId) -> (NodeId, bool) {
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let g = series(&n, 0);
let drawn = g.appearance.items.is_empty() && g.children().unwrap().iter().all(|m| !m.appearance.items.is_empty());
(g.id, drawn)
}
/// `appearance.setItem` given a series group's id edits the paths directly inside it, so the graph stores the color and
/// opacity and every mark has them after the graph is drawn again. The group keeps no rows of its own.
#[test]
fn an_appearance_item_set_on_a_series_group_edits_its_marks() {
let (mut s, id, _, marks) = column_marks();
let (group, drawn) = series_0_group(&s, id);
assert!(drawn);
let was = spec(&s, id).series_paints;
let row = top_row(&s, marks[0], true);
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": row, "color": "#0000ff", "opacity": 40})).unwrap();
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
let blue = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill.clone(), kept.fill_opacity), (Some(blue.clone()), Some(0.4)));
let (stroke, weight) = {
let m = s.doc().unwrap().doc.node(marks[0]).unwrap().clone();
(m.appearance.stroke_paint(), m.appearance.stroke_width())
};
series_0_is(&mut s, id, (&blue, 0.4, &stroke, weight), &was);
}
/// The other Appearance commands given a series group's id, picked with Group Selection or given in `ids`, edit the
/// paths directly inside it, and the graph stores what they change: Add New Fill, Clear Appearance, Move Appearance onto
/// the group, and an opacity set on a row with `transparency.set`.
#[test]
fn appearance_commands_given_a_series_group_edit_its_marks() {
let (mut s, id, marks) = stored_red_stroke();
let (group, _) = series_0_group(&s, id);
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
assert!(series_0_group(&s, id).1, "Add New Fill on the selected group");
let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count();
assert_eq!(rows, 2, "each mark has a new fill row");
s.execute("edit.undo", &json!({})).unwrap();
let row = top_row(&s, marks[0], true);
s.execute("transparency.set", &json!({"ids": [group.0], "item": row, "opacity": 30})).unwrap();
assert!(series_0_group(&s, id).1);
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, Some(0.3));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap();
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
s.execute("edit.undo", &json!({})).unwrap();
let (rect, blue) = blue_style(&mut s, "Blue", false);
let was = spec(&s, id).series_paints;
s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 50})).unwrap();
s.execute("appearance.transfer", &json!({"source": rect.0, "target": group.0, "copy": true})).unwrap();
assert!(series_0_group(&s, id).1);
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().opacity, 1.0, "the appearance replaces the group's own opacity");
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None)));
series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was);
}
/// Moving the Contents row of a series group as the graph draws it, with no rows of its own, moves the group's own
/// row: the paths inside it have none.
#[test]
fn moving_a_series_groups_contents_row_moves_its_own_row() {
let (mut s, id, _, _) = column_marks();
let (group, drawn) = series_0_group(&s, id);
assert!(drawn);
let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": "contents", "to": 0})).unwrap();
assert_eq!(out["contents"], json!(0));
}
/// Add New Stroke, Duplicate Item, Reorder Appearance Item and Remove Item given a series group's id edit the rows of
/// the paths directly inside it, and the group keeps no rows of its own.
#[test]
fn row_commands_given_a_series_group_edit_its_marks_rows() {
let (mut s, id, _, marks) = column_marks();
let (group, _) = series_0_group(&s, id);
let count = |s: &Session, fill: bool| -> Vec<usize> {
let d = &s.doc().unwrap().doc;
marks.iter().map(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill() == fill).count()).collect()
};
let (fills, strokes) = (count(&s, true), count(&s, false));
s.execute("appearance.addStroke", &json!({"ids": [group.0]})).unwrap();
assert_eq!(count(&s, false), strokes.iter().map(|n| n + 1).collect::<Vec<_>>(), "each mark has a new stroke row");
let fill = top_row(&s, marks[0], true);
s.execute("appearance.duplicateItem", &json!({"ids": [group.0], "index": fill})).unwrap();
assert_eq!(count(&s, true), fills.iter().map(|n| n + 1).collect::<Vec<_>>(), "each mark has a copy of its fill row");
let rows = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.items.len();
let out = s.execute("appearance.moveItem", &json!({"ids": [group.0], "from": 0, "to": rows - 1})).unwrap();
assert_eq!(out["index"], json!(rows - 1));
s.execute("appearance.removeItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true)})).unwrap();
assert_eq!(count(&s, true), fills);
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
}
/// Reduce to Basic Appearance given a series group's id reduces the paths directly inside it and drops an effect the
/// group holds.
#[test]
fn reducing_a_series_group_reduces_its_marks_and_drops_its_own_effect() {
let (mut s, id, _, marks) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("appearance.addFill", &json!({"ids": [group.0]})).unwrap();
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
s.execute("appearance.reduceToBasic", &json!({"ids": [group.0]})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(group).unwrap().appearance.effects.is_empty(), "the group's effect is dropped");
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count() == 1));
assert!(series_0_group(&s, id).1);
}
/// A graphic style added on top (Alt-click) given a series group's id adds its rows to the paths directly inside the
/// group and unlinks a group that held a style link.
#[test]
fn a_graphic_style_added_to_a_series_group_adds_rows_to_its_marks_and_unlinks_the_group() {
let (mut s, id, _, marks) = column_marks();
let (group, _) = series_0_group(&s, id);
blue_style(&mut s, "Blue", false);
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id;
s.edit("Link", |d, _| {
d.node_mut(group).unwrap().extras_mut().graphic_style = Some(style);
Ok(())
})
.unwrap();
let fills = |s: &Session, m: NodeId| s.doc().unwrap().doc.node(m).unwrap().appearance.items.iter().filter(|it| it.is_fill()).count();
let was = fills(&s, marks[0]);
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0], "add": true})).unwrap();
assert!(marks.iter().all(|m| fills(&s, *m) == was + 1), "each mark has the style's fill on top");
assert!(series_0_group(&s, id).1, "the group takes no rows of the style");
assert_eq!(s.doc().unwrap().doc.node(group).unwrap().extras().graphic_style, None, "the group is unlinked");
}
/// Move Appearance from one of a series group's paths onto the group gives the other paths its look and leaves that
/// path as it was. When the path is the only one directly in the group, the command is refused and the group takes no
/// rows.
#[test]
fn moving_an_appearance_from_a_mark_onto_its_own_series_group_keeps_the_mark() {
let (mut s, id, _, marks) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap();
let green = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint();
s.execute("appearance.transfer", &json!({"source": marks[0].0, "target": group.0})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "every mark, the source too, is green");
assert_eq!(spec(&s, id).series_paints[0].fill, Some(green));
s.edit("One path", |d, _| {
d.children_mut(Some(group)).unwrap().truncate(1);
Ok(())
})
.unwrap();
let only = s.doc().unwrap().doc.node(group).unwrap().children().unwrap()[0].id;
let err = s.execute("appearance.transfer", &json!({"source": only.0, "target": group.0})).unwrap_err();
assert!(err.to_string().contains("only path"), "{err}");
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
}
/// A series group that holds an opacity and an effect of its own is read itself as a source, as any group is: a new
/// graphic style and Move Appearance take the group's opacity and effect, and the group, not a path, is linked.
#[test]
fn a_series_group_with_a_look_of_its_own_is_read_itself_as_a_source() {
let (mut s, id, _, marks) = column_marks();
let (group, _) = series_0_group(&s, id);
s.execute("transparency.set", &json!({"ids": [group.0], "opacity": 50, "item": null})).unwrap();
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap();
let d = &s.doc().unwrap().doc;
let style = d.graphic_style("Series").unwrap();
assert_eq!((style.opacity, style.appearance.effects.len()), (0.5, 1));
assert_eq!(d.node(group).unwrap().extras().graphic_style, Some(style.id));
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none()));
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0, "copy": true})).unwrap();
let r = s.doc().unwrap().doc.node(rect).unwrap().clone();
assert_eq!((r.opacity, r.appearance.effects.len()), (0.5, 1));
}
/// Clear Appearance and Show All Hidden Attributes given a series group's id also reach an effect the group holds, and
/// Break Link to Graphic Style unlinks the paths a style applied to the group linked.
#[test]
fn whole_appearance_commands_given_a_series_group_edit_the_group_and_its_marks() {
let (mut s, id, marks) = stored_red_stroke();
let (group, _) = series_0_group(&s, id);
let effects = |s: &Session| s.doc().unwrap().doc.node(group).unwrap().appearance.effects.clone();
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
s.execute("effect.setParams", &json!({"ids": [group.0], "index": 0, "visible": false, "item": null})).unwrap();
assert!(!effects(&s)[0].visible);
let shown = s.execute("appearance.showAllHidden", &json!({"ids": [group.0]})).unwrap();
assert_eq!(shown["ids"], json!([group.0]));
assert!(effects(&s)[0].visible);
s.execute("appearance.clear", &json!({"ids": [group.0]})).unwrap();
assert!(effects(&s).is_empty(), "the group's effect is cleared with its marks' rows");
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
s.execute("edit.undo", &json!({})).unwrap();
blue_style(&mut s, "Blue", false);
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap();
assert_eq!(s.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some(("Blue".into(), true)));
s.execute("graphicStyle.breakLink", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style.is_none()), "each mark is unlinked");
assert!(s.selection_graphic_style().is_none());
}
/// Redefine Graphic Style on a selected series group whose paths a style links takes the look of the topmost of them.
#[test]
fn redefining_a_graphic_style_from_a_selected_series_group_reads_its_topmost_mark() {
let (mut s, id, marks) = stored_red_stroke();
let (group, _) = series_0_group(&s, id);
blue_style(&mut s, "Blue", false);
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("graphicStyle.apply", &json!({"name": "Blue"})).unwrap();
let top = *marks.last().unwrap();
s.execute("appearance.setItem", &json!({"ids": [top.0], "index": top_row(&s, top, true), "color": "#00ff00"})).unwrap();
let green = s.doc().unwrap().doc.node(top).unwrap().appearance.fill_paint();
s.execute("graphicStyle.redefine", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.graphic_style("Blue").unwrap().appearance.fill_paint(), green);
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green), "the marks still linked follow");
}
/// A series group as the graph draws it, read as a source, gives the look of the topmost path directly inside it: New
/// Graphic Style keeps that path's fill and links it, Move Appearance copies it, and a move clears every path of the
/// group.
#[test]
fn a_series_group_read_as_a_source_gives_its_topmost_marks_look() {
let (mut s, id, marks) = stored_red_stroke();
let (group, _) = series_0_group(&s, id);
let top = *marks.last().unwrap();
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, marks[0], true), "color": "#0000ff", "opacity": 30})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [marks[0].0], "index": top_row(&s, marks[0], true), "color": "#00ff00"})).unwrap();
let look = s.doc().unwrap().doc.node(top).unwrap().appearance.clone();
assert_ne!(look.fill_paint(), s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.fill_paint());
s.execute("graphicStyle.new", &json!({"id": group.0, "name": "Series"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.graphic_style("Series").unwrap().appearance.fill_paint(), look.fill_paint());
assert_eq!(d.node(top).unwrap().extras().graphic_style, Some(d.graphic_style("Series").unwrap().id));
let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap());
s.execute("appearance.transfer", &json!({"source": group.0, "target": rect.0})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), look.fill_paint());
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == Paint::None), "the move clears each mark");
assert_eq!(spec(&s, id).series_paints[0].fill, Some(Paint::None));
}
/// A series group that has a row of its own, as a document saved earlier can hold, is edited itself: the Appearance
/// panel lists that row and edits it by its index.
#[test]
fn a_series_group_with_a_row_of_its_own_is_edited_itself() {
let (mut s, id, _, marks) = column_marks();
let (group, _) = series_0_group(&s, id);
s.edit("Row", |d, _| {
let g = d.node_mut(group).unwrap();
g.appearance = vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0).into();
Ok(())
})
.unwrap();
let was = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
s.execute("appearance.setItem", &json!({"ids": [group.0], "index": top_row(&s, group, true), "color": "#0000ff"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_ne!(d.node(group).unwrap().appearance.fill_paint(), Paint::None);
assert_eq!(d.node(marks[0]).unwrap().appearance, was, "the marks keep their rows");
}
/// A graphic style applied to a series group's id styles and links the paths directly inside it, and the graph stores
/// the style's fill and stroke.
#[test]
fn a_graphic_style_applied_to_a_series_group_styles_its_marks() {
let (mut s, id, marks) = stored_red_stroke();
let (group, _) = series_0_group(&s, id);
let (_, blue) = blue_style(&mut s, "Blue", false);
let was = spec(&s, id).series_paints;
let own = json!({"ids": [group.0], "opacity": 50, "blend": "multiply", "isolate": true, "knockout": "on", "item": null});
s.execute("transparency.set", &own).unwrap();
s.execute("effect.apply", &json!({"ids": [group.0], "effect": "distort.twist"})).unwrap();
let g = s.doc().unwrap().doc.node(group).unwrap().clone();
assert!(g.isolate && g.knockout != Default::default() && g.blend != vectorcraft_color::BlendMode::Normal);
s.execute("graphicStyle.apply", &json!({"name": "Blue", "ids": [group.0]})).unwrap();
assert!(series_0_group(&s, id).1, "the group takes no rows of the style");
let g = s.doc().unwrap().doc.node(group).unwrap().clone();
assert_eq!((g.opacity, g.isolate), (1.0, false), "the style replaces the group's own opacity and isolation");
assert_eq!((g.blend, g.knockout), (vectorcraft_color::BlendMode::Normal, Default::default()), "and its blend mode and knockout");
assert!(g.appearance.effects.is_empty(), "and its effects");
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().id;
let d = &s.doc().unwrap().doc;
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style)), "each mark is linked to the style");
assert_eq!(d.node(group).unwrap().extras().graphic_style, None);
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(blue.clone()), Some(0.5), Some(Paint::None)));
series_0_is(&mut s, id, (&blue, 0.5, &Paint::None, 0.0), &was);
}
/// Redefine Graphic Style on a series group linked to the style (as a file can hold it) restyles the paths directly
/// inside the group and links them, and the graph stores the new look; the group goes back to no rows of its own.
#[test]
fn redefining_a_graphic_style_restyles_the_marks_of_a_linked_series_group() {
let (mut s, id, marks) = stored_red_stroke();
let (group, _) = series_0_group(&s, id);
let (rect, _) = blue_style(&mut s, "Blue", false);
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
s.edit("Link", |d, _| {
let g = d.node_mut(group).unwrap();
g.appearance = style.appearance.clone().into();
g.extras_mut().graphic_style = Some(style.id);
Ok(())
})
.unwrap();
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint();
let was = spec(&s, id).series_paints;
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
assert!(series_0_group(&s, id).1, "the group has no rows of its own");
let d = &s.doc().unwrap().doc;
assert_eq!(d.node(group).unwrap().extras().graphic_style, None);
assert!(marks.iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
assert!(marks.iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green));
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill.clone(), kept.fill_opacity, kept.stroke), (Some(green.clone()), None, Some(Paint::None)));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(spec(&s, id).series_paints, was, "one undo takes back the redefinition and what the graph stored");
s.execute("edit.redo", &json!({})).unwrap();
series_0_is(&mut s, id, (&green, 1.0, &Paint::None, 0.0), &was);
}
/// Redefine Graphic Style on a linked series group leaves a path of the group that is linked to the style but no
/// longer has its look as it is, unlinked, and restyles the group's other paths.
#[test]
fn redefining_a_graphic_style_keeps_an_edited_mark_of_a_linked_series_group() {
let (mut s, id, _, marks) = column_marks();
let (group, _) = series_0_group(&s, id);
let (rect, _) = blue_style(&mut s, "Blue", false);
let style = s.doc().unwrap().doc.graphic_style("Blue").unwrap().clone();
s.edit("Link", |d, _| {
let g = d.node_mut(group).unwrap();
g.appearance = style.appearance.clone().into();
g.extras_mut().graphic_style = Some(style.id);
d.node_mut(marks[0]).unwrap().extras_mut().graphic_style = Some(style.id);
Ok(())
})
.unwrap();
let edited = s.doc().unwrap().doc.node(marks[0]).unwrap().appearance.clone();
s.execute("appearance.setItem", &json!({"ids": [rect.0], "index": top_row(&s, rect, true), "color": "#00ff00", "opacity": 100})).unwrap();
let green = s.doc().unwrap().doc.node(rect).unwrap().appearance.fill_paint();
s.execute("graphicStyle.redefine", &json!({"name": "Blue", "id": rect.0})).unwrap();
let d = &s.doc().unwrap().doc;
let first = d.node(marks[0]).unwrap();
assert_eq!((&first.appearance, first.extras().graphic_style), (&edited, None), "the edited mark keeps its look, unlinked");
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().appearance.fill_paint() == green));
assert!(marks[1..].iter().all(|m| d.node(*m).unwrap().extras().graphic_style == Some(style.id)));
}
/// Default Fill and Stroke on a series mark stores a white fill and a 1 pt black stroke, both opaque, on the graph.
#[test]
fn default_fill_and_stroke_on_a_series_mark_is_kept() {
+12 -6
View File
@@ -14,8 +14,8 @@ use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor
use vectorcraft_geom::{Affine, Rect};
use super::{
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, cmd, color_value, f64_or, has_doc,
has_selection, ids_param, index, object_param, ok, str_param, switch_or,
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd,
color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or,
};
use crate::EngineError;
@@ -83,7 +83,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Layer Options…",
["Window", "Layers"],
None,
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
"{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step",
has_doc,
set_props
),
@@ -210,11 +210,16 @@ pub fn specs() -> Vec<CommandSpec> {
/// The rows a panel command acts on: `ids` or `id`, else the highlighted rows, else the current
/// layer (capped at [`MAX_ROWS`]).
pub(crate) fn rows_param(s: &Session, p: &Value, command: &str) -> Result<Vec<NodeId>> {
rows_or_guides_param(s, p, command, false)
}
/// The rows [`rows_param`] reads; given ruler guide ids are taken too when `guides`, else refused.
fn rows_or_guides_param(s: &Session, p: &Value, command: &str, guides: bool) -> Result<Vec<NodeId>> {
// Presence is explicit intent: validate every target before fallback, truncation or edits.
let mut ids = if p.get("ids").is_some() {
checked_ids_param(s, p, "ids", command)?
checked_nodes_param(s, p, "ids", command, guides)?
} else if let Some(id) = p.get("id") {
vec![checked_id(s, id, command)?]
vec![checked_node(s, id, command, guides)?]
} else {
let st = s.doc()?;
let rows = st.highlighted_rows();
@@ -637,7 +642,8 @@ fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "layer.setProps";
let xml_id = s.prefs.identify_objects_by == "xmlId";
check_options(C, p, xml_id)?;
let ids = rows_param(s, p, C)?;
// A ruler guide's row takes visible and locked: its own eye and lock.
let ids = rows_or_guides_param(s, p, C, true)?;
if ids.is_empty() {
return Err(bad(C, "no rows"));
}
+28 -9
View File
@@ -169,28 +169,47 @@ pub(super) fn lock(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
/// The selected objects ([`selected_roots`]) that Lock › Selection and Hide › Selection change: in
/// isolation mode, only those inside the isolated object, where a path of the isolated compound
/// path is an object of its own.
/// The selected objects ([`selected_roots`]) and ruler guides that Lock › Selection and Hide ›
/// Selection change: in isolation mode, only the objects inside the isolated object, where a path
/// of the isolated compound path is an object of its own. A guide counts while it can be edited
/// (it and its layer shown and unlocked, and Lock Guides off).
fn selected_lock_hide_roots(s: &Session) -> Result<Vec<NodeId>> {
match crate::cmd::ordinary_isolation(s.doc()?) {
let st = s.doc()?;
match crate::cmd::ordinary_isolation(st) {
Some(root) => crate::cmd::edit::selected_roots_inside(s, root, false),
None => selected_roots(s),
None => {
let mut ids = selected_roots(s)?;
if !s.guides_locked() {
let d = &st.doc;
ids.extend(st.selection.guides.iter().copied().filter(|id| d.ruler_guide(*id).is_some_and(|g| d.guide_editable(&g))));
}
Ok(ids)
}
}
}
/// The objects and ruler guides in `d` that `f` picks (layers never).
fn collect_flag(d: &Document, f: impl Fn(&Node) -> bool) -> Vec<NodeId> {
let mut v = vec![];
d.walk(|n| {
if !n.is_layer() && !n.is_ruler_guide() && f(n) {
if !n.is_layer() && f(n) {
v.push(n.id)
}
});
v
}
/// Select what Unlock All or Show All changed (`ids`): the objects, and the ruler guides among
/// them as guides (a guide that still can't be edited is then dropped from the selection).
fn select_changed(d: &Document, sel: &mut vectorcraft_doc::Selection, ids: &[NodeId]) {
let guides: std::collections::HashSet<NodeId> = d.ruler_guides().into_iter().filter_map(|g| g.id).collect();
let (on_guides, objects): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| guides.contains(id));
sel.set(objects);
sel.guides = on_guides;
}
/// The objects that `f` picks for `object.unlockAll` and `object.showAll` (`cmd`): in the whole
/// document, inside the isolated object in isolation mode, or with `scope: "group"` inside the
/// document (its ruler guides included), inside the isolated object in isolation mode, or with `scope: "group"` inside the
/// groups that hold the selected objects (in isolation mode, only the objects of those groups
/// that are inside the isolated object). A selected group is the group that holds its own
/// members, and the objects of a group inside another such group are taken once. With
@@ -253,7 +272,7 @@ pub(super) fn unlock_all(s: &mut Session, p: &Value) -> Result<Value> {
n.locked = false;
}
}
sel.set(ids.iter().copied());
select_changed(d, sel, &ids);
Ok(())
})?;
Ok(json!({ "count": ids.len() }))
@@ -292,7 +311,7 @@ pub(super) fn show_all(s: &mut Session, p: &Value) -> Result<Value> {
n.visible = true;
}
}
sel.set(ids.iter().copied());
select_changed(d, sel, &ids);
Ok(())
})?;
Ok(json!({ "count": ids.len() }))
+7 -7
View File
@@ -7,7 +7,7 @@ use super::props::set_props;
use super::shape::{expand_shape, set_live_shape};
use super::transform::{move_cmd, nudge, reflect, rotate, scale, shear, transform, transform_again};
use super::{CommandSpec, cmd, has_doc, has_multi, has_selection, has_selection_or_guides};
use crate::cmd::has_selected_member;
use crate::cmd::has_selected_member_or_guide;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -151,8 +151,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Selection",
["Object", "Lock"],
Some("Cmd+2"),
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
has_selected_member,
"{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}",
has_selected_member_or_guide,
lock
),
cmd!(
@@ -160,7 +160,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Unlock All",
["Object"],
Some("Cmd+Alt+2"),
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them → {count}",
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} unlock the locked objects and select them; document scope outside isolation mode also unlocks ruler guides locked on their own → {count}",
has_doc,
unlock_all
),
@@ -169,8 +169,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Selection",
["Object", "Hide"],
Some("Cmd+3"),
"{ids?: [id…] (selected first; default: the selection; in isolation mode, only those inside the isolated object)}",
has_selected_member,
"{ids?: [id…] (selected first; default: the selection, selected ruler guides included; in isolation mode, only the objects inside the isolated object)}",
has_selected_member_or_guide,
hide
),
cmd!(
@@ -178,7 +178,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Show All",
["Object"],
Some("Cmd+Alt+3"),
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them → {count}",
"{scope?: \"document\"|\"group\" (default document, which in isolation mode is the isolated object; group: only the objects inside the groups that hold the selected objects, a selected group holding its own; the in-window menu item chosen with Shift+Alt)} show the hidden objects and select them; document scope outside isolation mode also shows ruler guides hidden on their own → {count}",
has_doc,
show_all
),
+54 -2
View File
@@ -12,7 +12,8 @@
//! `object.objectsOnPath.selectMember` chooses one object of a selected group (its Select/Move
//! widget), and `object.objectsOnPath.moveMember` moves one object to another's place along the
//! path, the objects between it and that place each moving one place toward where it was; hidden
//! and locked objects keep their places.
//! and locked objects keep their places. `object.objectsOnPath.detach` takes one object out of its
//! group, just above it, and the others move up the path.
//!
//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back
//! on its path: editing the path moves them, an object moved on its own goes back to its place,
@@ -21,7 +22,8 @@
//!
//! Behavior: <https://helpx.adobe.com/illustrator/using/objects-on-path.html> (the tool and
//! Object › Objects on Path › Attach; the order on the path, the attachment point, the distribution,
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Expand).
//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Detach and
//! the objects that move up the path after it; Expand).
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -75,6 +77,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
move_member
),
cmd!(
"object.objectsOnPath.detach",
"Detach Object from Path",
[],
None,
"{member?: id of an object of an Objects on Path group (default: the object chosen with the selected group's Select/Move widget); neither the object nor the group may be hidden or locked} take one object off the path, out of its group and just above the group in the Layers panel, where it stays as drawn and is selected alone. The group's other objects move up the path in their order: with Auto Space they spread evenly again, and a Space value and the start are kept. The group and its path stay, even with one object or none left → {group, member}",
has_doc,
detach
),
cmd!(
"object.objectsOnPath.expand",
"Expand",
@@ -383,6 +394,47 @@ fn move_member(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "group": g.0, "member": member.0, "index": index }))
}
// ---------- Detach ----------
/// The object chosen with the Select/Move widget of the one selected Objects on Path group.
fn chosen_member(s: &Session) -> Option<NodeId> {
let st = s.active()?;
match st.selection.objects[..] {
[_] => st.selection.on_path_member,
_ => None,
}
}
fn detach(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.objectsOnPath.detach";
const CHOOSE: &str = "choose the object to detach with its Select/Move widget";
let (g, member) = if p.get("member").is_none_or(Value::is_null) {
let chosen = chosen_member(s).ok_or_else(|| bad(C, CHOOSE))?;
let found = member_param(s, &json!({ "member": chosen.0 }), "member", C)?;
if s.active().is_none_or(|st| st.selection.objects[..] != [found.0]) {
return Err(bad(C, CHOOSE));
}
found
} else {
member_param(s, p, "member", C)?
};
// The object goes just above the group, in the group's parent, and keeps where it is drawn.
// When the group is itself an object on another group's path, the object goes above that
// group instead (and so on outward), so it does not join that path. The refresh after the edit
// removes it from the group's record and moves the others up the path.
s.edit("Detach Object from Path", |d, sel| {
let mut above = g;
while let Some(p) = d.parent_of(above).filter(|p| d.node(*p).is_some_and(is_objects_on_path)) {
above = p;
}
let (parent, index, _) = d.position(above).ok_or(EngineError::NoNode(above))?;
d.move_node(member, parent, index + 1)?;
sel.set([member]);
Ok(())
})?;
Ok(json!({ "group": g.0, "member": member.0 }))
}
// ---------- Expand ----------
fn expand(s: &mut Session, p: &Value) -> Result<Value> {
+3 -3
View File
@@ -6,7 +6,7 @@ use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
use super::appearance::{ItemTarget, appearance_targets, edit_items, edit_items_then, item_target};
use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets};
use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
use super::{
Affine, CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, leaf_targets, ok,
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Transparency",
["Window", "Transparency"],
None,
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series, the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
"{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, item?: appearance item index|null, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects; a gradient mesh point last clicked with the Mesh tool or Direct Selection takes the opacity itself). With an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, opacity and blend change that object for this instance only (isolate, knockout, knockoutShape, aligned and target are refused). On a path directly in a graph series (for a fill or stroke item, a series group's id stands for those paths), the graph also stores the opacity and blend mode of the object and of the topmost visible fill and stroke (exceptions: docs/mcp.md)",
has_doc,
transparency
),
@@ -1062,7 +1062,7 @@ fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
return s.execute("object.setProps", &Value::Object(q));
};
// Opacity and blend belong to the targeted fill/stroke; isolate/knockout/knockoutShape stay object-level.
let item_ids = if editing_mask { ids } else { appearance_targets(s, p)? };
let item_ids = if editing_mask { ids } else { row_targets(s, p)? };
if explicit {
let d = &s.doc()?.doc;
if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) {
+33 -15
View File
@@ -58,6 +58,9 @@ use crate::{EngineError, MAX_COORD};
const PLACE: &str = "file.place";
const QUEUE: &str = "file.place.queue";
/// The error of a file read apart from the session while another document is active, or after the
/// document it was read for closed ([`Session::place_read`], [`Session::place_queue_read`]).
const NOT_ACTIVE: &str = "the document it was prepared for is no longer active";
/// The most files one `file.place.queue` loads.
const MAX_QUEUE: usize = 100;
/// The longest thumbnail side `thumbnail` may ask for (px).
@@ -503,11 +506,13 @@ fn fit(natural: Rect, r: Rect) -> Affine {
Affine::translate(r.center().to_vec2()) * Affine::scale(k) * Affine::translate(-natural.center().to_vec2())
}
/// What `file.place` takes from the session before it reads the file: the params, the object
/// Replace swaps and the artboard under `at`, which a DXF drawing is laid out on
/// ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the session,
/// on any thread.
/// What `file.place` takes from the session before it reads the file: the document it places into,
/// the params, the object Replace swaps and the artboard under `at`, which a DXF drawing is laid
/// out on ([`Session::prepare_place`]). [`PlaceJob::read`] reads and decodes the file without the
/// session, on any thread.
pub struct PlaceJob {
/// The document it was prepared in (`DocState::uid`).
doc: u64,
params: Value,
old: Option<NodeId>,
/// The object Replace swaps as it was when Place started.
@@ -560,10 +565,14 @@ impl Session {
/// Run `file.place` with the params of `read` as a command (checked and journaled as any
/// other) that places the file `read` holds instead of reading it again → `file.place`'s
/// reply. The object Replace swaps must still be in the document as it was when Place started;
/// when the selection changed meanwhile, `select.set` selects that object again first, so a
/// replay of the journal replaces the same object.
/// reply. The document Place started in must be the active one, and the object Replace swaps
/// must still be in it as it was when Place started; when the selection changed meanwhile,
/// `select.set` selects that object again first, so a replay of the journal replaces the same
/// object.
pub fn place_read(&mut self, read: PlaceRead) -> Result<Value> {
if self.doc()?.uid != read.job.doc {
return Err(bad(PLACE, NOT_ACTIVE));
}
let params = read.job.params.clone();
if let Some(old) = read.job.old {
let st = self.doc()?;
@@ -615,7 +624,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
};
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
Ok(PlaceJob { params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
}
/// Place the file `read` holds in the active document.
@@ -755,6 +764,8 @@ fn queued_files(p: &Value) -> Result<Vec<Value>> {
/// ([`Session::prepare_place_queue`]). [`QueueJob::read`] reads them without the session, on any
/// thread.
pub struct QueueJob {
/// The document it was prepared in (`DocState::uid`).
doc: u64,
params: Value,
files: Vec<Value>,
}
@@ -762,6 +773,8 @@ pub struct QueueJob {
/// The files [`QueueJob::read`] read, which [`Session::place_queue_read`] loads the place cursor
/// with.
pub struct QueueRead {
/// The document the files were read for (`DocState::uid`).
doc: u64,
params: Value,
entries: Vec<Value>,
files: Vec<Value>,
@@ -776,13 +789,13 @@ impl QueueJob {
/// Read every file for its size and thumbnail, as `file.place.queue` does, without the session.
pub fn read(self) -> Result<QueueRead> {
read_queue(self.params, self.files)
read_queue(self.doc, self.params, self.files)
}
}
/// Read each of `queued`, the files of `file.place.queue` with params `p`, for its size and
/// thumbnail.
fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> {
/// Read each of `queued`, the files of `file.place.queue` with params `p` for the document `doc`,
/// for its size and thumbnail.
fn read_queue(doc: u64, p: Value, queued: Vec<Value>) -> Result<QueueRead> {
let thumbnail = p.get("thumbnail").and_then(Value::as_f64);
let (mut entries, mut files, mut skipped) = (vec![], vec![], vec![]);
for mut q in queued {
@@ -823,7 +836,7 @@ fn read_queue(p: Value, queued: Vec<Value>) -> Result<QueueRead> {
}
}
}
Ok(QueueRead { params: p, entries, files, skipped })
Ok(QueueRead { doc, params: p, entries, files, skipped })
}
impl Session {
@@ -834,12 +847,17 @@ impl Session {
has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?;
check_switches(params, &["link", "template"], QUEUE)?;
check_numbers(params, &["thumbnail"], QUEUE)?;
Ok(QueueJob { params: params.clone(), files: queued_files(params)? })
let files = queued_files(params)?;
Ok(QueueJob { doc: self.doc()?.uid, params: params.clone(), files })
}
/// Run `file.place.queue` with the params of `read` as a command that loads the place cursor
/// with the files `read` holds instead of reading them again → `file.place.queue`'s reply.
/// with the files `read` holds instead of reading them again → `file.place.queue`'s reply. The
/// document the files were read for must be the active one.
pub fn place_queue_read(&mut self, read: QueueRead) -> Result<Value> {
if self.doc()?.uid != read.doc {
return Err(bad(QUEUE, NOT_ACTIVE));
}
let params = read.params.clone();
self.queue_hand_off = Some(read);
let r = self.execute(QUEUE, &params);
@@ -314,6 +314,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.move",
"object.nudge",
"object.objectsOnPath.attach",
"object.objectsOnPath.detach",
"object.objectsOnPath.expand",
"object.objectsOnPath.moveMember",
"object.objectsOnPath.options",
+32 -12
View File
@@ -14,7 +14,7 @@
//! paint shows instead of the character colour under it.
use std::borrow::Cow;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
@@ -31,7 +31,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Graphic Style",
["Window", "Graphic Styles"],
None,
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
"{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions: docs/mcp.md). With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}",
has_doc,
style_apply
),
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Graphic Style",
["Window", "Graphic Styles"],
None,
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}",
"{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own stands for the topmost path directly in it; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}",
has_doc,
style_new
),
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Redefine Graphic Style",
["Window", "Appearance"],
None,
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}",
"{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it); the objects still linked to it update, and that object becomes linked. A linked graph series group passes the style to the paths directly in it, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md) → {name}",
has_doc,
style_redefine
),
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Break Link to Graphic Style",
["Window", "Graphic Styles"],
None,
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look",
"{ids?|id?, target?: \"object\"|\"contents\"} unlink the objects (default: the selection) from their graphic style; they keep their look. A graph series group's id stands for the group and the paths directly in it",
has_doc,
style_break_link
),
@@ -307,10 +307,11 @@ fn source<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(NodeId, &'a Node)
impl Session {
/// The graphic style of the first selected object: the one it was last linked to, and whether
/// it is still linked (still has that style's look).
/// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands
/// for the topmost path directly inside it, which a style applied to the group links.
pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> {
let st = self.active()?;
let n = st.doc.node(*st.selection.subjects().first()?)?;
let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?);
let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?;
Some((g, in_sync(n, g)))
}
@@ -331,7 +332,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
let i = style_index(&s.doc()?.doc, name)?;
let add = bool_or(p, "add", false);
let chars = s.prefs.override_char_color;
let ids = super::appearance::appearance_targets(s, p)?;
let own = super::appearance::appearance_targets(s, p)?;
let ids = super::appearance::rowless_series_marks(&s.doc()?.doc, &own);
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
// and a style added on top unlinks them.
let groups = super::appearance::stood_for(&own, &ids);
if ids.is_empty() {
if p.get("ids").is_some() || p.get("id").is_some() {
return Err(bad("graphicStyle.apply", "no such objects"));
@@ -353,6 +358,8 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
n.extras_mut().graphic_style = None;
}
}
// The series groups their paths stand for are unlinked with them.
set_link(d, &groups, None);
// The graph stores the rows of the kinds the style shows, now on top of each stack.
let shows = |kind: bool| g.appearance.items.iter().any(|it| it.is_fill() == kind && it.visible());
let kinds = (shows(true), shows(false));
@@ -364,6 +371,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
for id in &ids {
apply_style(d, *id, &g, &mut shared, chars);
}
super::appearance::clear_stood_for(d, &groups);
super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true);
}
Ok(())
@@ -372,8 +380,11 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
}
fn style_new(s: &mut Session, p: &Value) -> Result<Value> {
let (src, n) = source(s, p, "graphicStyle.new")?;
let (_, n) = source(s, p, "graphicStyle.new")?;
let d = &s.doc()?.doc;
// A series group that holds nothing of its own shows the look of its paths: the style is made from the topmost.
let n = super::appearance::look_holder(d, n);
let src = n.id;
let name = match str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) {
Some(n) => unique_name(n, |x| d.graphic_style(x).is_some()),
None => d.new_graphic_style_name(),
@@ -459,6 +470,9 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "graphicStyle.redefine";
let (src, n) = source(s, p, cmd)?;
let d = &s.doc()?.doc;
// A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links.
let n = super::appearance::look_holder(d, n);
let src = if n.id == src { src } else { n.id };
let i = match str_param(p, "name") {
Some(name) => style_index(d, name)?,
None => n
@@ -480,12 +494,18 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src);
let (follow, edited): (Vec<NodeId>, Vec<NodeId>) = linked.into_iter().partition(|nid| d.node(*nid).is_some_and(|n| in_sync(n, &old)));
set_link(d, &edited, None);
// A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and
// goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look.
let mut follow_marks = super::graph::series_group_marks(d, &follow);
let edited: HashSet<NodeId> = edited.into_iter().collect();
follow_marks.retain(|nid| *nid != src && !edited.contains(nid));
super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks));
let g = d.graphic_styles[i].clone();
let mut shared = None;
for nid in &follow {
for nid in &follow_marks {
apply_style(d, *nid, &g, &mut shared, chars);
}
super::appearance::capture_series_writes(&before, d, &follow, (true, true), (true, true), false, true);
super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true);
set_link(d, &[src], Some(id));
Ok(())
})?;
@@ -493,7 +513,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result<Value> {
}
fn style_break_link(s: &mut Session, p: &Value) -> Result<Value> {
let ids = super::appearance::appearance_targets(s, p)?;
let ids = super::appearance::whole_targets(s, p)?;
s.edit("Break Link to Graphic Style", |d, _| {
set_link(d, &ids, None);
Ok(())
+5
View File
@@ -164,6 +164,11 @@ pub(crate) const SELECTS_GIVEN_IDS: &[&str] = &[
"object.ungroup",
];
/// Commands whose `ids` (or `id`) may name ruler guide nodes as well as objects: the Layers panel's
/// eye and lock on a guide's row, and a drag down either column that passes guide rows. Every other
/// command given a ruler guide's id refuses it (the guide commands take guides by index).
pub(crate) const TAKES_GUIDE_IDS: &[&str] = &["layer.setProps"];
/// The non-empty `ids` given to a command whose params description names `ids` as a key (the
/// key callers outside the app may pass it, [`cmd::params::takes_key`]), or its `id` as `ids` of
/// one when no `ids` are given and the description takes `id` so
+35
View File
@@ -823,6 +823,34 @@ impl Host {
}
}
/// The file and line that line `line` of the source with tag `tag` came from, as `$.line` and
/// `$.stack` give them: the run's script, a file it included or a file `$.evalFile` gave, in
/// this run or in an earlier run of its named engine, with the run's name standing for a script
/// given as text. Code that `eval` or `Function` compiled has no map and keeps its own line,
/// named `[eval]`; code whose map is gone, such as one the named engine let go to stay within
/// [`KEPT_MAP_BYTES`], is at line 0 of `[unknown]`.
fn source_place(&self, tag: u32, line: u32) -> (String, u32) {
if tag == vectorcraft_js::UNKNOWN_SOURCE {
return ("[eval]".to_string(), line);
}
let named = |map: &include::SourceMap, script: Option<&Arc<str>>| {
let (index, file, line, _) = map.locate(line, 1);
match script {
Some(name) if index == 0 && file.is_empty() => (name.to_string(), line),
_ => (file.to_string(), line),
}
};
let script = self.script_tag.get();
let placed = match tag.checked_sub(script).filter(|_| script != vectorcraft_js::UNKNOWN_SOURCE) {
Some(0) => self.script_map.try_borrow().ok().map(|m| named(&m, Some(&self.report_name))),
Some(n) => self.eval_maps.try_borrow().ok().and_then(|maps| maps.get(n as usize - 1).map(|m| named(m, None))),
None => {
self.kept_maps.as_ref().and_then(|k| k.try_borrow().ok()).and_then(|k| k.get(tag).map(|kept| named(&kept.map, kept.script.as_ref())))
}
};
placed.unwrap_or_else(|| ("[unknown]".to_string(), 0))
}
/// `$.fileName` read by the code at `site`: the file that code is in, by the source map of the
/// source it came from (this run's script, a file `$.evalFile` gave, or code an earlier run of
/// the named engine compiled), so a function keeps the file it was defined in. Code from a file
@@ -1891,6 +1919,13 @@ impl Session {
Ok(expanded) => {
*host.script_map.borrow_mut() = expanded.map;
realm.set_strict_writes(expanded.strict == Some(true));
if fresh {
let l = link.clone();
realm.set_source_locator(Rc::new(move |tag, line| match current(&l) {
Ok(h) => h.source_place(tag, line),
Err(_) => ("[unknown]".to_string(), 0),
}));
}
(if fresh { realm.add_script_extensions() } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
+1 -1
View File
@@ -1,4 +1,4 @@
use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, given_ids, strip_replay_only, waits_for_tool_edit};
use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit};
use super::doc_state::DocState;
use super::error::{EngineError, Result};
use super::history::NamedStep;
+5 -4
View File
@@ -1,6 +1,6 @@
use super::{
CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, Value, cmd, find_command, given_ids, guard,
strip_replay_only, waits_for_tool_edit,
CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd, find_command,
given_ids, guard, strip_replay_only, waits_for_tool_edit,
};
/// A command's result `r` with the warnings of the previews that settling an interaction applied
@@ -115,7 +115,7 @@ impl Session {
if id == "effect.refreshDeferred" {
cmd::given_object_ids(params, id)?;
} else {
cmd::given_objects(self, params, id)?;
cmd::given_nodes(self, params, id, TAKES_GUIDE_IDS.contains(&id))?;
}
}
if SELECTS_GIVEN_IDS.contains(&id) {
@@ -134,7 +134,8 @@ impl Session {
// whichever tool is chosen.
let given = given_ids(spec.params, params);
// The guide commands take ruler guides by index; an object command given one's id is refused.
if let (Some(ids), Some(st)) = (&given, self.active())
if !TAKES_GUIDE_IDS.contains(&id)
&& let (Some(ids), Some(st)) = (&given, self.active())
&& let Some(guide) = ids.iter().find(|i| st.doc.node(**i).is_some_and(|n| n.is_ruler_guide()))
{
let value = guide.0;
+41
View File
@@ -542,6 +542,47 @@ fn dragging_a_blend_widget_is_one_undo_step_and_a_click_or_escape_none() {
assert_eq!(spec(&s, g).1.color_shift, 0.0);
}
/// A blend made without a spine has the Appearance widget alone: a drag of it with the Selection
/// tool or the Blend tool changes the color shift in one undo step, and there is no Easing widget
/// to drag.
#[test]
fn dragging_the_appearance_widget_of_a_blend_without_a_spine_is_one_undo_step() {
let mut s = session();
let (a, b) = (rect(&mut s, 0.0, 0.0, 40.0), rect(&mut s, 200.0, 0.0, 40.0));
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.blend.make", &json!({"steps": 3, "createSpine": "never", "orientation": "path"})).unwrap());
assert!(spec(&s, g).1.no_spine);
let v = ViewInfo::default();
let depth = |s: &Session| s.doc().unwrap().history.undo.len();
let ptr = |s: &mut Session, kind: PointerKind, x: f64, y: f64| {
s.pointer(&PointerEvent::new(kind, x, y), ViewInfo::default()).unwrap();
};
for (n, tool) in [(1.0, "selection"), (2.0, "blend")] {
s.select_tool(tool, v).unwrap();
sel(&mut s, &[g]);
let d0 = depth(&s);
// The Appearance widget sits 16 px above the halfway point (120, 20) of the line between
// the key centers.
ptr(&mut s, PointerKind::Down, 120.0, 4.0);
ptr(&mut s, PointerKind::Drag, 135.0, 4.0);
ptr(&mut s, PointerKind::Up, 135.0, 4.0);
let sp = spec(&s, g).1;
assert_eq!((sp.color_shift, sp.ease.ramp, depth(&s)), (15.0 * n, 0.0, d0 + 1), "{tool}");
assert_eq!(s.doc().unwrap().selection.objects, vec![g], "{tool}: the blend stays selected");
}
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(spec(&s, g).1.color_shift, 15.0, "each drag is its own undo step");
// 16 px below there is no widget: a drag there leaves the easing and the color shift alone.
s.select_tool("selection", v).unwrap();
sel(&mut s, &[g]);
let before = spec(&s, g).1;
ptr(&mut s, PointerKind::Down, 120.0, 36.0);
ptr(&mut s, PointerKind::Drag, 150.0, 36.0);
ptr(&mut s, PointerKind::Up, 150.0, 36.0);
let after = spec(&s, g).1;
assert_eq!((after.ease, after.color_shift), (before.ease, before.color_shift), "no Easing widget");
}
#[test]
fn native_blend_easing_values_clamp_and_non_finite_become_default() {
for (bad, ramp, shift) in [
+99 -5
View File
@@ -4717,6 +4717,12 @@ fn blob_anchors(s: &mut Session, fidelity: f64) -> usize {
/// [`blob_anchors`] with the blob scaled by `scale`: drawn the same on screen zoomed in 1 / `scale`
/// times.
fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize {
blob_anchors_through(s, "path.freehand", &json!({}), Some(fidelity), scale)
}
/// [`scaled_blob_anchors`] drawn with `command` and the params in `extra`, at `fidelity` (with none,
/// the command's default).
fn blob_anchors_through(s: &mut Session, command: &str, extra: &serde_json::Value, fidelity: Option<f64>, scale: f64) -> usize {
let pts: Vec<_> = (0..1200)
.map(|i| {
let a = i as f64 / 1200.0 * std::f64::consts::TAU;
@@ -4724,7 +4730,14 @@ fn scaled_blob_anchors(s: &mut Session, fidelity: f64, scale: f64) -> usize {
json!([(400.0 + r * a.cos()) * scale, (300.0 + r * a.sin()) * scale])
})
.collect();
let r = s.execute("path.freehand", &json!({"points": pts, "closed": true, "fidelity": fidelity, "keepSelected": false})).unwrap();
let mut p = json!({"points": pts, "closed": true, "keepSelected": false});
if let Some(f) = fidelity {
p["fidelity"] = json!(f);
}
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
p.extend(extra.clone());
}
let r = s.execute(command, &p).unwrap();
path(s, NodeId(r["id"].as_u64().unwrap())).subpaths.iter().map(|sp| sp.anchors.len()).sum()
}
@@ -4736,13 +4749,11 @@ fn pencil_fidelity_goes_down_to_a_hundredth_and_lower_keeps_more() {
assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}");
// Below the old floor of 0.05 the stroke keeps more of itself.
assert!(counts[4] > counts[2], "{counts:?}");
// Below the floor, the lowest Fidelity (0.01 px) at the highest zoom (64000 %), is read as the
// floor (#5729).
// The floor is the lowest Fidelity (0.01 px) at the highest zoom (64000 %) (#5729); below it,
// `pencil_takes_fidelity_within_its_range_and_rejects_the_rest`.
let floor = vectorcraft_tools::draw2::MIN_FIDELITY / 640.0;
let at_floor = blob_anchors(&mut s, floor);
assert!(at_floor >= counts[4], "{counts:?}");
assert_eq!(blob_anchors(&mut s, floor / 10.0), at_floor);
assert_eq!(blob_anchors(&mut s, 0.0), at_floor);
}
/// #5729: the tools send Fidelity / zoom, so a stroke drawn the same on screen zoomed in keeps as
@@ -4758,6 +4769,89 @@ fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_in() {
}
}
/// The tools send Fidelity / zoom up to the highest Fidelity (100 px) at the lowest zoom (3.13 %):
/// a stroke drawn the same on screen zoomed out keeps as many anchors as at 100 %, as a Pencil or a
/// Paintbrush stroke and through `brush.freehand` with a brush. A tolerance above
/// `MAX_FIT_TOLERANCE` is an error, and a stroke given no Fidelity is fitted at 1.5 pt.
#[test]
fn pencil_fit_keeps_its_anchors_on_a_stroke_drawn_zoomed_out() {
let mut s = session();
let max = vectorcraft_tools::draw2::MAX_FIT_TOLERANCE;
// The blob six times the size, so that 100 px still keeps some of its waves.
let big = 6.0;
for (command, extra) in [
("path.freehand", json!({})),
("path.freehand", json!({"style": "brush"})),
("brush.freehand", json!({"style": "brush", "brush": "3 pt. Round"})),
] {
for fidelity in [20.0, 100.0] {
let want = blob_anchors_through(&mut s, command, &extra, Some(fidelity), big);
for zoom in [0.2, 0.0313] {
let got = blob_anchors_through(&mut s, command, &extra, Some(fidelity / zoom), big / zoom);
assert_eq!(got, want, "{command} {extra}: {fidelity} px at {zoom}x");
// Fitted at 100 pt, the stroke on screen would keep the detail of a finer Fidelity.
if fidelity / zoom > 100.0 {
let at_100 = blob_anchors_through(&mut s, command, &extra, Some(100.0), big / zoom);
assert!(at_100 > want, "{command} {extra}: {fidelity} px at {zoom}x, 100 pt keeps {at_100} of {want}");
}
}
}
let mut p = json!({"points": [[0, 0], [100, 50], [200, 0]], "fidelity": max * 10.0});
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
p.extend(extra.clone());
}
let err = s.execute(command, &p).unwrap_err().to_string();
assert!(err.contains("`fidelity` must be from"), "{command} {extra}: {err}");
let default = blob_anchors_through(&mut s, command, &extra, None, 1.0);
assert_eq!(default, blob_anchors_through(&mut s, command, &extra, Some(1.5), 1.0), "{command} {extra}");
}
}
/// `path.freehand` and `brush.freehand` take a `fidelity` from `MIN_FIT_TOLERANCE` (the lowest
/// Fidelity at the highest zoom) to `MAX_FIT_TOLERANCE` (the highest at the lowest zoom), both ends
/// included, and reject a value just outside either end, a tenth of the lowest, 0, a negative one or
/// a huge one, leaving the document as it was.
#[test]
fn pencil_takes_fidelity_within_its_range_and_rejects_the_rest() {
let (lo, hi) = (vectorcraft_tools::draw2::MIN_FIT_TOLERANCE, vectorcraft_tools::draw2::MAX_FIT_TOLERANCE);
let points = json!([[0, 0], [100, 50], [200, 0], [300, 50]]);
for (command, extra) in [("path.freehand", json!({})), ("brush.freehand", json!({"style": "brush", "brush": "3 pt. Round"}))] {
let run = |s: &mut Session, fidelity: f64| {
let mut p = json!({"points": points, "fidelity": fidelity});
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
p.extend(extra.clone());
}
s.execute(command, &p)
};
let mut s = session();
for fidelity in [100.0 / 0.0313, hi, lo, 0.01 / 640.0] {
let r = run(&mut s, fidelity);
assert!(r.as_ref().is_ok_and(|r| r["id"].is_u64()), "{command}: {fidelity} pt: {r:?}");
}
let before = s.doc().unwrap().doc.clone();
for fidelity in [f64::from_bits(hi.to_bits() + 1), f64::from_bits(lo.to_bits() - 1), lo / 10.0, 0.0, -1.5, 1e300] {
let err = run(&mut s, fidelity).unwrap_err().to_string();
assert!(err.contains("`fidelity` must be from"), "{command}: {fidelity} pt: {err}");
}
assert_eq!(s.doc().unwrap().doc, before, "{command}");
}
}
/// A stroke that continues an open path closes it when it ends within four Fidelities of the path's
/// other end, at most 400 pt away: at the coarsest Fidelity one ending 1000 pt away leaves it open,
/// and one ending 300 pt away closes it.
#[test]
fn pencil_extend_closes_within_400_pt_at_any_fidelity() {
let mut s = session();
let max = vectorcraft_tools::draw2::MAX_FIT_TOLERANCE;
for (end, closed) in [([0, 1000], false), ([0, 300], true)] {
let l = line(&mut s, 0.0, 0.0, 2000.0, 0.0);
let points = json!([[2000, 0], [2000, 1000], [1000, 1500], end]);
s.execute("path.freehand", &json!({"points": points, "fidelity": max, "extend": {"id": l.0}, "keepSelected": false})).unwrap();
assert_eq!(path(&s, l).subpaths[0].closed, closed, "ending at {end:?}");
}
}
/// At Fidelity 0.01 short, one-point and repeated-point strokes still draw or are refused, never
/// crash, and what they draw has finite anchors.
#[test]
+135 -5
View File
@@ -4040,9 +4040,11 @@ fn ruler_guides_select_move_and_delete() {
assert!(selected(&s).is_empty());
assert_eq!(s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap()["selected"], json!([0, 1]));
let layer = s.doc().unwrap().current_layer().unwrap().0;
let id = s.doc().unwrap().doc.ruler_guides()[1].id.unwrap().0;
assert_eq!(
s.execute("guide.list", &json!({})).unwrap()[1],
json!({"index": 1, "vertical": false, "pos": 50.0, "selected": true, "layer": layer, "shown": true, "editable": true})
json!({"index": 1, "id": id, "vertical": false, "pos": 50.0, "selected": true, "layer": layer,
"hidden": false, "locked": false, "shown": true, "editable": true})
);
assert!(s.execute("guide.select", &json!({"indexes": [7]})).is_err());
// A move takes each selected guide along its own axis, in one undo step.
@@ -4323,11 +4325,14 @@ fn artboard_guides_go_with_their_artboard() {
s.execute("guide.add", &json!({"vertical": false, "pos": 100})).unwrap();
let list = |s: &mut Session| s.execute("guide.list", &json!({})).unwrap();
let layer = s.doc().unwrap().current_layer().unwrap().0;
let ids: Vec<u64> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect();
assert_eq!(
list(&mut s),
json!([
{"index": 0, "vertical": true, "pos": 1000.0, "selected": false, "artboard": 1, "layer": layer, "shown": true, "editable": true},
{"index": 1, "vertical": false, "pos": 100.0, "selected": false, "layer": layer, "shown": true, "editable": true},
{"index": 0, "id": ids[0], "vertical": true, "pos": 1000.0, "selected": false, "artboard": 1, "layer": layer,
"hidden": false, "locked": false, "shown": true, "editable": true},
{"index": 1, "id": ids[1], "vertical": false, "pos": 100.0, "selected": false, "layer": layer,
"hidden": false, "locked": false, "shown": true, "editable": true},
])
);
let spans = |s: &Session| {
@@ -4368,7 +4373,8 @@ fn artboard_guides_go_with_their_artboard() {
assert_eq!((guides(&s).len(), selected_guides(&s)), (3, vec![0, 1]));
assert_eq!(
list(&mut s)[0],
json!({"index": 0, "vertical": false, "pos": 100.0, "selected": true, "layer": layer, "shown": true, "editable": true})
json!({"index": 0, "id": ids[1], "vertical": false, "pos": 100.0, "selected": true, "layer": layer,
"hidden": false, "locked": false, "shown": true, "editable": true})
);
assert_eq!(undo_len(&s), n + 1);
s.execute("edit.undo", &json!({})).unwrap();
@@ -4412,9 +4418,11 @@ fn guides_dragged_out_of_a_ruler_snap_and_take_the_artboard_tool_s_artboard() {
s.ruler_guide(false, &ev(PointerKind::Drag, 1000.0, 50.0), true, v).unwrap();
s.ruler_guide(false, &ev(PointerKind::Up, 1000.0, 50.0), true, v).unwrap();
let layer = s.doc().unwrap().current_layer().unwrap().0;
let id = s.doc().unwrap().doc.ruler_guides()[1].id.unwrap().0;
assert_eq!(
s.execute("guide.list", &json!({})).unwrap()[1],
json!({"index": 1, "vertical": false, "pos": 50.0, "selected": false, "artboard": 1, "layer": layer, "shown": true, "editable": true})
json!({"index": 1, "id": id, "vertical": false, "pos": 50.0, "selected": false, "artboard": 1, "layer": layer,
"hidden": false, "locked": false, "shown": true, "editable": true})
);
}
@@ -4569,6 +4577,12 @@ fn ruler_guides_live_on_layers() {
assert!(s.doc().unwrap().doc.ruler_guides().iter().all(|g| g.layer == Some(first)));
s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap();
assert!(s.execute("guide.setLayer", &json!({"indexes": [7], "layer": first.0})).is_err());
// `indexes` that is not a list, or given with `index`, is an error; an index given twice counts once.
assert!(s.execute("guide.setLayer", &json!({"indexes": 0, "layer": first.0})).is_err());
assert!(s.execute("guide.setLayer", &json!({"index": 0, "indexes": [1], "layer": first.0})).is_err());
assert!(s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.layer).eq([Some(first), Some(second)]));
assert_eq!(s.execute("guide.setLayer", &json!({"indexes": [1, 1], "layer": first.0})).unwrap()["count"], 1);
s.execute("guide.setLayer", &json!({"indexes": [1], "layer": second.0})).unwrap();
// Deleting a layer deletes its guides; undo brings them back.
s.execute("layer.delete", &json!({"ids": [second.0]})).unwrap();
assert_eq!(guides(&s), [(true, 200.0)]);
@@ -4606,6 +4620,122 @@ fn guides_on_hidden_or_locked_layers_are_left_alone() {
assert_eq!(guides(&s).len(), 3);
}
/// A guide hidden or locked on its own can't be moved, deleted or moved to another layer, and the
/// error names the guide, not its layer; a guide on a hidden or locked layer names the layer.
#[test]
fn a_guide_hidden_or_locked_on_its_own_is_named_in_the_error() {
let mut s = session();
let first = s.doc().unwrap().current_layer().unwrap();
for pos in [100.0, 200.0] {
s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap();
}
let second = id_of(&s.execute("layer.new", &json!({})).unwrap());
let ids: Vec<u64> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect();
s.execute("layer.setProps", &json!({"ids": [ids[0]], "locked": true})).unwrap();
s.execute("layer.setProps", &json!({"ids": [ids[1]], "visible": false})).unwrap();
let own = "the guide is hidden or locked";
for i in [0, 1] {
assert_eq!(s.execute("guide.move", &json!({"index": i, "pos": 50})).unwrap_err().to_string(), own, "{i}");
assert_eq!(s.execute("guide.remove", &json!({"index": i})).unwrap_err().to_string(), own, "{i}");
assert_eq!(s.execute("guide.remove", &json!({"indexes": [i]})).unwrap_err().to_string(), own, "{i}");
let p = json!({"index": i, "layer": second.0});
assert_eq!(s.execute("guide.setLayer", &p).unwrap_err().to_string(), own, "{i}");
}
// Shown and unlocked, but on a locked layer: the error names the layer.
s.execute("layer.setProps", &json!({"ids": [ids[0]], "locked": false})).unwrap();
s.execute("layer.setProps", &json!({"ids": [first.0], "locked": true})).unwrap();
let e = s.execute("guide.move", &json!({"index": 0, "pos": 50})).unwrap_err().to_string();
assert_eq!(e, "the guide is on a hidden or locked layer");
}
/// Object › Lock › Selection and Hide › Selection lock and hide a selected ruler guide on its own,
/// with the selected art, in one undo step; Unlock All and Show All unlock and show it again and
/// select it as a guide. While Lock Guides is on nothing selects it, and in isolation mode Lock
/// leaves it alone.
#[test]
fn lock_hide_unlock_and_show_all_reach_ruler_guides() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
for pos in [100.0, 200.0] {
s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap();
}
let flags = |s: &Session| s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.hidden, g.locked)).collect::<Vec<_>>();
let undo = |s: &Session| s.doc().unwrap().history.undo.len();
let clear = (false, false);
// A guide selected on its own: Lock locks it alone and deselects it.
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
let n = undo(&s);
s.execute("object.lock", &json!({})).unwrap();
assert_eq!((flags(&s), undo(&s)), (vec![(false, true), clear], n + 1));
assert!(selected_guides(&s).is_empty());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((flags(&s), selected_guides(&s)), (vec![clear, clear], vec![0]));
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(flags(&s)[0], (false, true));
// A guide and art selected together: Hide hides both, in one step.
sel(&mut s, &[a]);
s.execute("guide.select", &json!({"indexes": [1], "toggle": true})).unwrap();
let n = undo(&s);
s.execute("object.hide", &json!({})).unwrap();
assert_eq!((flags(&s), undo(&s)), (vec![(false, true), (true, false)], n + 1));
assert!(!s.doc().unwrap().doc.node(a).unwrap().visible);
// Unlock All and Show All reach the guides and select them as guides.
assert_eq!(s.execute("object.unlockAll", &json!({})).unwrap()["count"], 1);
assert_eq!((flags(&s)[0], selected_guides(&s), selected(&s)), (clear, vec![0], vec![]));
assert_eq!(s.execute("object.showAll", &json!({})).unwrap()["count"], 2);
assert_eq!((flags(&s), selected_guides(&s), selected(&s)), (vec![clear, clear], vec![1], vec![a]));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(flags(&s)[1], (true, false), "Show All is one undo step");
s.execute("edit.redo", &json!({})).unwrap();
// With Lock Guides on, Unlock All unlocks a guide but leaves it unselected.
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("view.guides.lock", &json!({"locked": true})).unwrap();
s.execute("object.unlockAll", &json!({})).unwrap();
assert_eq!((flags(&s)[0], selected_guides(&s)), (clear, vec![]));
s.execute("view.guides.lock", &json!({"locked": false})).unwrap();
// In isolation mode Lock takes only the objects inside the isolated group.
let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0);
sel(&mut s, &[a, b]);
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
sel(&mut s, &[a]);
let _ = s.execute("guide.select", &json!({"indexes": [0], "toggle": true}));
s.execute("object.lock", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(a).unwrap().locked);
assert_eq!(flags(&s)[0], clear);
}
/// `guide.remove` with `indexes` deletes those guides in one undo step, an index given twice
/// once; a locked guide among them, or an unknown index, deletes nothing.
#[test]
fn guide_remove_takes_several_indexes() {
let mut s = session();
for pos in [100.0, 200.0, 300.0] {
s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap();
}
let id = s.doc().unwrap().doc.ruler_guides()[2].id.unwrap();
s.execute("layer.setProps", &json!({"ids": [id.0], "locked": true})).unwrap();
assert!(s.execute("guide.remove", &json!({"indexes": [0, 2]})).is_err());
assert!(s.execute("guide.remove", &json!({"indexes": [0, 7]})).is_err());
assert!(s.execute("guide.remove", &json!({"indexes": 0})).is_err());
assert!(s.execute("guide.remove", &json!({"index": 0, "indexes": [1]})).is_err());
// A list longer than 10,000 entries is refused by every guide command that takes one.
let long = json!(vec![0; 10_001]);
assert!(s.execute("guide.remove", &json!({"indexes": long})).is_err());
assert!(s.execute("guide.select", &json!({"indexes": long})).is_err());
let layer = s.doc().unwrap().doc.layers[0].id;
assert!(s.execute("guide.setLayer", &json!({"indexes": long, "layer": layer.0})).is_err());
assert_eq!(s.execute("guide.select", &json!({"indexes": vec![0; 10_000]})).unwrap()["selected"], json!([0]));
s.execute("select.none", &json!({})).unwrap();
assert_eq!(guides(&s).len(), 3);
let n = s.doc().unwrap().history.undo.len();
assert_eq!(s.execute("guide.remove", &json!({"indexes": [1, 0, 1]})).unwrap()["count"], 2);
assert_eq!((guides(&s), s.doc().unwrap().history.undo.len()), (vec![(true, 300.0)], n + 1));
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(guides(&s).len(), 3);
}
/// Guides follow their layers through Duplicate, Merge Selected and Flatten Artwork, in one undo
/// step each.
#[test]
+194
View File
@@ -681,3 +681,197 @@ fn the_space_saves_and_reopens_and_goes_with_a_copy() {
let copy = s.doc().unwrap().selection.objects.to_vec();
assert_eq!(space(&s, copy[0]), (Some(40.0), 25.0));
}
/// Where `id` is in the tree: its parent and its index there (0 at the bottom).
fn place_of(s: &Session, id: NodeId) -> (Option<NodeId>, usize) {
let (parent, index, _) = s.doc().unwrap().doc.position(id).unwrap();
(parent, index)
}
#[test]
fn detach_takes_the_chosen_object_off_the_path_and_the_others_move_up_in_one_undo_step() {
let mut s = session();
let ([left, middle, right], path) = squares_and_line(&mut s);
let g = attach(&mut s, path, &[left, middle, right], json!({"rotate": 30}));
let (layer, at) = place_of(&s, g);
s.execute("object.objectsOnPath.selectMember", &json!({"member": middle.0})).unwrap();
let drawn = s.doc().unwrap().doc.node(middle).unwrap().clone();
let steps = s.doc().unwrap().history.undo.len();
let v = s.execute("object.objectsOnPath.detach", &json!({})).unwrap();
assert_eq!(v, json!({"group": g.0, "member": middle.0}));
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step");
let (on_path, children) = orders(&s, g);
assert_eq!(on_path, [left, right]);
assert!(children.len() == 3 && !children.contains(&middle), "{children:?}");
assert_eq!(place_of(&s, middle), (layer, at + 1), "just above the group, in its layer");
assert_eq!(s.doc().unwrap().doc.node(middle), Some(&drawn), "the object keeps its art, place and rotation");
let sel = &s.doc().unwrap().selection;
assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[middle][..], None), "the detached object alone is selected");
// The two left stay on the ends of the path; the path stays.
assert_eq!(center(&s, left), Point::new(50.0, 300.0));
assert_eq!(center(&s, right), Point::new(350.0, 300.0));
assert_eq!(s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().unwrap().path, path);
// The detached object is free: moving it moves it, and the group does not take it back.
s.execute("object.move", &json!({"ids": [middle.0], "dx": 0, "dy": -100})).unwrap();
assert_eq!(center(&s, middle), Point::new(200.0, 200.0));
assert_eq!(orders(&s, g).0, [left, right]);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let (on_path, children) = orders(&s, g);
assert_eq!(on_path, [left, middle, right], "undo puts it back on the path");
assert!(children.contains(&middle), "{children:?}");
assert_eq!(center(&s, middle), Point::new(200.0, 300.0));
assert_eq!(center(&s, right), Point::new(350.0, 300.0));
let sel = &s.doc().unwrap().selection;
assert_eq!((sel.objects.as_slice(), sel.on_path_member), (&[g][..], Some(middle)), "and the choice back");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(orders(&s, g).0, [left, right]);
assert_eq!(place_of(&s, middle), (layer, at + 1));
}
#[test]
fn after_the_first_object_is_detached_the_second_takes_the_start() {
let mut s = session();
let ([left, middle, right], path) = squares_and_line(&mut s);
let g = attach(&mut s, path, &[left, middle, right], json!({}));
select(&mut s, &[]);
let v = s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap();
assert_eq!(v, json!({"group": g.0, "member": left.0}));
assert_eq!(orders(&s, g).0, [middle, right]);
assert_eq!(center(&s, middle), Point::new(50.0, 300.0), "the second object moves up to the start");
assert_eq!(center(&s, right), Point::new(350.0, 300.0));
assert_eq!(center(&s, left), Point::new(50.0, 300.0), "the detached object stays where it was drawn");
assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [left]);
}
#[test]
fn detach_on_a_closed_path_spreads_the_others_all_the_way_round_again() {
let mut s = session();
let ids: Vec<NodeId> = (0..4).map(|i| rect(&mut s, 10.0 + 40.0 * f64::from(i), 0.0, 10.0, 10.0)).collect();
let ring = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let g = attach(&mut s, ring, &ids, json!({}));
s.execute("object.objectsOnPath.detach", &json!({"member": ids[1].0})).unwrap();
assert_eq!(orders(&s, g).0, [ids[0], ids[2], ids[3]]);
let data = s.doc().unwrap().doc.node(ring).unwrap().path_data().unwrap().clone();
let stops = vectorcraft_doc::objects_on_path::stops(&data, 3, None, 0.0).unwrap();
for (id, (p, _)) in [ids[0], ids[2], ids[3]].iter().zip(stops) {
let c = center(&s, *id);
assert!((c.x - p.x).abs() < 1e-3 && (c.y - p.y).abs() < 1e-3, "a third of the way round apart: {c:?} {p:?}");
}
}
#[test]
fn detach_keeps_a_space_value_and_the_start() {
let mut s = session();
let (g, [a, b, c], _) = three_on_a_line(&mut s);
s.execute("object.objectsOnPath.options", &json!({"start": 20})).unwrap();
s.execute("object.objectsOnPath.detach", &json!({"member": a.0})).unwrap();
assert_eq!(space(&s, g), (Some(100.0), 20.0));
assert_eq!(center(&s, b), Point::new(70.0, 300.0), "the second object moves up to the first place");
assert_eq!(center(&s, c), Point::new(170.0, 300.0));
// A Space value the path is too short for stays, and two objects get more of the path.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("object.objectsOnPath.options", &json!({"spacing": 200, "start": 0})).unwrap();
assert_eq!(center(&s, c), Point::new(350.0, 300.0), "three objects drawn 150 pt apart");
s.execute("object.objectsOnPath.detach", &json!({"member": b.0})).unwrap();
assert_eq!(space(&s, g), (Some(200.0), 0.0));
assert_eq!(center(&s, a), Point::new(50.0, 300.0));
assert_eq!(center(&s, c), Point::new(250.0, 300.0), "two objects 200 pt apart");
}
#[test]
fn the_group_and_its_path_stay_with_one_object_or_none_left() {
let mut s = session();
let ([left, middle, _], path) = squares_and_line(&mut s);
let g = attach(&mut s, path, &[left, middle], json!({"pivot": 7}));
s.execute("object.objectsOnPath.options", &json!({"spacing": 30})).unwrap();
s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap();
assert_eq!(orders(&s, g), (vec![middle], vec![path, middle]));
let b = bounds(&s, middle);
assert!((b.center().x - 50.0).abs() < 1e-6 && (b.y1 - 300.0).abs() < 1e-6, "the one left on the start, by its Pivot: {b:?}");
s.execute("object.objectsOnPath.detach", &json!({"member": middle.0})).unwrap();
let n = s.doc().unwrap().doc.node(g).unwrap().clone();
let rec = n.extras().objects_on_path.as_deref().unwrap();
assert_eq!((rec.path, rec.members.len(), rec.pivot, rec.spacing), (path, 0, 7, Some(30.0)), "a live group with no objects");
assert_eq!(orders(&s, g).1, [path]);
// An object moved back in joins the path.
s.execute("layer.move", &json!({"ids": [left.0], "target": g.0, "place": "inside"})).unwrap();
assert_eq!(orders(&s, g).0, [left]);
}
#[test]
fn detach_refuses_what_is_not_one_chosen_editable_object_on_a_path() {
let mut s = session();
let (g, [a, b, c], path) = three_on_a_line(&mut s);
let loose = rect(&mut s, 300.0, 20.0, 10.0, 10.0);
let err = |s: &mut Session, p: Value| s.execute("object.objectsOnPath.detach", &p).unwrap_err().to_string();
let choose = "choose the object to detach with its Select/Move widget";
let steps = s.doc().unwrap().history.undo.len();
select(&mut s, &[g]);
assert!(err(&mut s, json!({})).contains(choose), "the group without a chosen object");
select(&mut s, &[]);
assert!(err(&mut s, json!({})).contains(choose), "nothing selected");
assert!(err(&mut s, json!({"member": path.0})).contains("`member` must name an object attached"), "the path");
assert!(err(&mut s, json!({"member": g.0})).contains("`member` must name"), "the group itself");
assert!(err(&mut s, json!({"member": loose.0})).contains("`member` must name"), "an object on no path");
assert!(err(&mut s, json!({"member": 99999})).contains("no such object"));
assert!(err(&mut s, json!({"member": "a"})).contains("invalid object id"));
// Hidden and locked objects stay; a locked group keeps all of its objects.
select(&mut s, &[c]);
s.execute("object.lock", &json!({})).unwrap();
assert!(err(&mut s, json!({"member": c.0})).contains("`member` names an object that is hidden or locked"));
s.execute("object.unlockAll", &json!({})).unwrap();
select(&mut s, &[b]);
s.execute("object.hide", &json!({})).unwrap();
assert!(err(&mut s, json!({"member": b.0})).contains("hidden or locked"), "a hidden object");
s.execute("object.showAll", &json!({})).unwrap();
select(&mut s, &[g]);
s.execute("object.lock", &json!({})).unwrap();
assert!(err(&mut s, json!({"member": a.0})).contains("the Objects on Path group is hidden or locked"));
s.execute("object.unlockAll", &json!({})).unwrap();
assert_eq!(orders(&s, g).0, [a, b, c], "nothing refused detached anything");
let undone = s.doc().unwrap().history.undo.len();
assert_eq!(undone, steps + 6, "only the lock, hide and show steps");
}
#[test]
fn an_object_detached_from_a_group_on_another_path_does_not_join_that_path() {
let mut s = session();
let ([left, middle, right], path) = squares_and_line(&mut s);
let inner = attach(&mut s, path, &[left, middle], json!({}));
let outer_line = line(&mut s, (20.0, 380.0), (380.0, 380.0));
let outer = attach(&mut s, outer_line, &[inner, right], json!({}));
let outer_members = orders(&s, outer).0;
s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap();
assert_eq!(orders(&s, inner).0, [middle]);
assert_eq!(orders(&s, outer).0, outer_members, "the outer path keeps its objects and takes no new one");
let (layer, at) = place_of(&s, outer);
assert_eq!(place_of(&s, left), (layer, at + 1), "above the outer group");
}
#[test]
fn hidden_and_locked_objects_left_on_the_path_move_up_too() {
let mut s = session();
let ([left, middle, right], path) = squares_and_line(&mut s);
let g = attach(&mut s, path, &[left, middle, right], json!({}));
select(&mut s, &[right]);
s.execute("object.lock", &json!({})).unwrap();
select(&mut s, &[middle]);
s.execute("object.hide", &json!({})).unwrap();
s.execute("object.objectsOnPath.detach", &json!({"member": left.0})).unwrap();
assert_eq!(orders(&s, g).0, [middle, right]);
assert_eq!(center(&s, middle), Point::new(50.0, 300.0), "the hidden object moves up to the start");
assert_eq!(center(&s, right), Point::new(350.0, 300.0));
}
#[test]
fn objects_moved_out_together_in_the_layers_panel_all_leave_the_path() {
let mut s = session();
let ([left, middle, right], path) = squares_and_line(&mut s);
let g = attach(&mut s, path, &[left, middle, right], json!({}));
s.execute("layer.move", &json!({"ids": [left.0, middle.0], "target": g.0, "place": "above"})).unwrap();
assert_eq!(orders(&s, g), (vec![right], vec![path, right]));
assert_eq!(center(&s, right), Point::new(50.0, 300.0), "the one left takes the start");
let (layer, at) = place_of(&s, g);
assert_eq!((place_of(&s, left), place_of(&s, middle)), ((layer, at + 1), (layer, at + 2)), "above the group, in their order");
}
+83
View File
@@ -629,6 +629,89 @@ fn a_spread_gradient_with_more_runs_than_written_stays_a_gradient() {
}
}
/// Selected type "Hi" at 48 pt, its characters filled with a gradient that repeats 100 times along
/// a vector `len` pt long.
fn spread_gradient_type(s: &mut Session, len: f64) -> u64 {
let t = run(s, "text.create", json!({"x": 50, "y": 100, "text": "Hi", "size": 48}))["id"].as_u64().unwrap();
run(s, "select.set", json!({"ids": [t]}));
run(
s,
"paint.setFill",
json!({"gradient": {"kind": "linear", "spread": "repeat", "repeats": 100, "start": [50, 100], "end": [50.0 + len, 100],
"stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 1, "color": "#004080"}]}}),
);
t
}
/// How many objects in the document have a gradient fill, and how many are type.
fn gradients_and_type(s: &Session) -> (usize, usize) {
let (mut gradients, mut texts) = (0, 0);
s.doc().unwrap().doc.walk(|n| {
gradients += usize::from(matches!(n.appearance.fill_paint(), Paint::Gradient(_)));
texts += usize::from(matches!(n.kind, NodeKind::Text(_)));
});
(gradients, texts)
}
/// Type is outlined before its fills expand, and each glyph's gradient fits that glyph's own box:
/// `object.expand.info` reports a gradient (and a fill) only when a glyph's box needs no more runs
/// than are written, so Expand turns it into art. Both Expand Gradient To options leave the
/// glyphs whose gradient needs more runs with their gradient, and Object still outlines the type.
/// The query leaves the document and its history as they are.
#[test]
fn type_whose_gradient_needs_more_runs_than_written_reports_no_gradient() {
// 0.2 pt runs (100 repeats over 20 pt) across glyphs about 30 pt wide: under the limit.
// 0.02 pt runs (over 2 pt): far over it.
for (len, expands) in [(20.0, true), (2.0, false)] {
let mut s = session();
spread_gradient_type(&mut s, len);
let before = (s.doc().unwrap().revision, s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.layers.clone());
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["gradient"].clone(), info["fill"].clone(), info["object"].clone()), (json!(expands), json!(expands), json!(true)), "{len}");
assert!(
before == (s.doc().unwrap().revision, s.doc().unwrap().history.undo.len(), s.doc().unwrap().doc.layers.clone()),
"{len}: the query changed the document"
);
for to in [json!({}), json!({"gradient": "mesh"})] {
let mut s = session();
spread_gradient_type(&mut s, len);
run(&mut s, "object.expand", to.clone());
let (gradients, texts) = gradients_and_type(&s);
assert_eq!(texts, 0, "{len} {to}: outlined");
assert_eq!(gradients == 0, expands, "{len} {to}: {gradients} gradient fills left");
}
}
}
/// One glyph whose box needs more runs than are written does not hide another that Expand turns
/// into art: the 200 pt "H" keeps its gradient, the 48 pt "i" expands, and the query reports it.
#[test]
fn type_reports_a_gradient_when_any_glyph_expands() {
let mut s = session();
let t = spread_gradient_type(&mut s, 20.0);
run(&mut s, "text.setRangeStyle", json!({"id": t, "start": 0, "end": 1, "size": 200}));
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!((info["gradient"].clone(), info["fill"].clone()), (json!(true), json!(true)));
run(&mut s, "object.expand", json!({}));
assert_eq!(gradients_and_type(&s), (1, 0), "the large glyph keeps its gradient");
}
/// The same rule for type in the art of a symbol instance that Object expands. The symbol's art
/// is the type scaled down (its "i" about 2.5 pt wide), so its glyphs need more runs than are
/// written with 0.002 pt runs (over a 0.2 pt vector).
#[test]
fn type_in_symbol_art_reports_a_gradient_only_when_it_expands() {
for (len, expands) in [(20.0, true), (0.2, false)] {
let mut s = session();
spread_gradient_type(&mut s, len);
let inst = run(&mut s, "symbol.new", json!({"name": "Hi"}))["id"].as_u64().unwrap();
run(&mut s, "select.set", json!({"ids": [inst]}));
let info = run(&mut s, "object.expand.info", json!({}));
assert_eq!(info["gradient"], json!(expands), "{len}");
assert_eq!((info["symbolArt"]["gradient"].clone(), info["symbolArt"]["fill"].clone()), (json!(expands), json!(expands)), "{len}: {info}");
}
}
#[test]
fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() {
for gradient in [
+31 -22
View File
@@ -123,40 +123,49 @@ fn presets_export_and_import_round_trip() {
assert!(is_bad_params(Session::new().execute("pdf.preset.export", &json!({}))), "nothing saved to export");
}
/// `longPagesInPoints` is saved with a preset, comes back through a presets file and the
/// preferences, shows in `document.pdfSettings`, and a 10 m page exported with it reopens at 10 m.
/// A value that isn't a boolean is refused.
/// `longPagesInPoints` is on by default: a 10 m page exported without options is written in
/// points and reopens at 10 m. Turned off, it is saved with a preset, comes back through a presets
/// file and the preferences, shows in `document.pdfSettings`, and the page exported with it has a
/// `UserUnit` and reopens at 10 m. A value that isn't a boolean is refused.
#[test]
fn long_pages_in_points_round_trips_through_presets_and_reopens_at_full_size() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 28_346.456_692_913_386, "height": 2_834.645_669_291_338_5})).unwrap();
s.execute("pdf.preset.save", &json!({"name": "Banner", "longPagesInPoints": true, "preserveEditing": false})).unwrap();
assert!(s.prefs.pdf_presets[0].settings.long_pages_in_points);
let reopened = |bytes: &[u8]| {
let mut o = Session::new();
o.execute("document.open", &json!({"name": "banner.pdf", "dataBase64": vectorcraft_format::base64_encode(bytes)})).unwrap();
let rect = o.doc().unwrap().doc.artboards[0].rect;
assert!((rect.width() - 28_346.46).abs() < 0.01 && (rect.height() - 2_834.65).abs() < 0.01, "{rect:?}");
};
let warned = |v: &Value, end: &str| v["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().ends_with(end));
// By default the page is written in points.
assert_eq!(s.execute("document.pdfSettings", &json!({})).unwrap()["settings"]["longPagesInPoints"], json!(true));
let v = s.execute("document.exportPdf", &json!({"preserveEditing": false})).unwrap();
let bytes = pdf(&v);
assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit"));
assert!(warned(&v, "written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in"), "{v}");
reopened(&bytes);
// Off in a preset.
s.execute("pdf.preset.save", &json!({"name": "Banner", "longPagesInPoints": false, "preserveEditing": false})).unwrap();
assert!(!s.prefs.pdf_presets[0].settings.long_pages_in_points);
let back: crate::Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
assert_eq!(back.pdf_presets, s.prefs.pdf_presets);
let text = s.execute("pdf.preset.export", &json!({"names": ["Banner"]})).unwrap()["data"].as_str().unwrap().to_string();
let mut t = session();
t.execute("pdf.preset.import", &json!({"data": text})).unwrap();
assert_eq!(t.prefs.pdf_presets, s.prefs.pdf_presets);
let v = s.execute("document.pdfSettings", &json!({"longPagesInPoints": true})).unwrap();
assert_eq!((&v["settings"]["longPagesInPoints"], &v["changed"]), (&json!(true), &json!([{"option": "longPagesInPoints", "value": true}])), "{v}");
assert_eq!(s.execute("document.pdfSettings", &json!({})).unwrap()["settings"]["longPagesInPoints"], json!(false));
// The preset writes the page in points; the file reopens at 10 m.
let v = s.execute("document.exportPdf", &json!({"preset": "Banner"})).unwrap();
let bytes = pdf(&v);
assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit"));
assert!(
v["warnings"]
.as_array()
.unwrap()
.iter()
.any(|w| w.as_str().unwrap().ends_with("written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in")),
let v = s.execute("document.pdfSettings", &json!({"longPagesInPoints": false})).unwrap();
assert_eq!(
(&v["settings"]["longPagesInPoints"], &v["changed"]),
(&json!(false), &json!([{"option": "longPagesInPoints", "value": false}])),
"{v}"
);
let mut o = Session::new();
o.execute("document.open", &json!({"name": "banner.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap();
let rect = o.doc().unwrap().doc.artboards[0].rect;
assert!((rect.width() - 28_346.46).abs() < 0.01 && (rect.height() - 2_834.65).abs() < 0.01, "{rect:?}");
// The preset writes the page with a `UserUnit`; the file reopens at 10 m.
let v = s.execute("document.exportPdf", &json!({"preset": "Banner"})).unwrap();
let bytes = pdf(&v);
assert!(String::from_utf8_lossy(&bytes).contains("/UserUnit 1.969"));
assert!(warned(&v, "it is written with a UserUnit of 1.969, so apps that ignore UserUnit show it that many times smaller"), "{v}");
reopened(&bytes);
for bad in [json!("yes"), json!(1)] {
assert!(is_bad_params(s.execute("document.exportPdf", &json!({"longPagesInPoints": bad}))), "{bad}");
assert!(is_bad_params(s.execute("pdf.preset.save", &json!({"name": "Bad", "longPagesInPoints": bad}))), "{bad}");
+89
View File
@@ -365,6 +365,95 @@ fn a_file_read_apart_from_the_session_replaces_what_was_selected_when_place_star
}
}
/// Every open document with its art, selection and undo steps, and the journal, tool and tool
/// options: what a refused hand-off leaves as it was.
type Snapshot = (Vec<(u64, Arc<vectorcraft_doc::Document>, Vec<NodeId>, usize)>, usize, &'static str, Value);
fn snapshot(s: &Session) -> Snapshot {
let docs = s.documents().iter().map(|d| (d.uid, d.doc.clone(), d.selection.objects.clone(), d.history.undo.len())).collect();
(docs, s.journal.len(), s.tool_id(), s.tool_options())
}
/// A file read apart from the session is placed only in the document Place started in: with
/// another document active, Replace included when that document holds the same object under the
/// same id, or after the document closed, nothing changes in any document; with the document
/// active again, the file is placed in it.
#[test]
fn a_file_read_apart_from_the_session_is_placed_only_in_the_document_it_was_read_for() {
let blue = file("blue.png", &png(8, 8, [0, 0, 255, 255], None));
let not_active = "the document it was prepared for is no longer active";
for replace in [false, true] {
let p = with(blue.clone(), json!({"replace": replace}));
let mut s = session();
let square = json!({"x": 10, "y": 10, "width": 20, "height": 20});
let a = s.execute("shape.rectangle", &square).unwrap()["id"].clone();
let read = s.prepare_place(&p).unwrap().read().unwrap();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let b = s.execute("shape.rectangle", &square).unwrap()["id"].clone();
assert_eq!(a, b, "the other document holds an object with the same id");
assert!(node(&s, &b) == s.documents()[0].doc.node(NodeId(a.as_u64().unwrap())).unwrap().clone(), "and the same content");
let before = snapshot(&s);
let err = s.place_read(read).unwrap_err();
assert!(err.to_string().contains(not_active), "replace {replace}: {err}");
assert!(snapshot(&s) == before, "replace {replace}: nothing placed, selected or journaled in either document");
// Active again, the document Place started in takes the file.
let read = {
s.execute("document.activate", &json!({"index": 0})).unwrap();
s.prepare_place(&p).unwrap().read().unwrap()
};
s.execute("document.activate", &json!({"index": 1})).unwrap();
s.execute("document.activate", &json!({"index": 0})).unwrap();
let r = s.place_read(read).unwrap();
assert_eq!(s.active_index(), Some(0));
assert!(s.doc().unwrap().doc.node(NodeId(r["ids"][0].as_u64().unwrap())).is_some(), "replace {replace}: placed in the first document");
let others = s.documents()[1].doc.layers.last().unwrap().children().unwrap().len();
assert_eq!(others, 1, "replace {replace}: the other document keeps its one object");
}
// The document Place started in closed: refused in the document left open, and with none left.
let mut s = session();
let read = s.prepare_place(&blue).unwrap().read().unwrap();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("file.close", &json!({"index": 0})).unwrap();
let before = snapshot(&s);
assert!(s.place_read(read).unwrap_err().to_string().contains(not_active));
assert!(snapshot(&s) == before, "nothing placed in the document left open");
let read = s.prepare_place(&blue).unwrap().read().unwrap();
s.execute("file.close", &json!({})).unwrap();
let journal = s.journal.len();
assert!(s.place_read(read).is_err() && s.journal.len() == journal, "no document left: refused");
}
/// Files read for the place cursor apart from the session load it only in the document they were
/// read for: with another document active, or after that document closed, its tool and queue stay
/// as they were; with the document active again, the cursor is loaded.
#[test]
fn files_read_for_the_place_cursor_apart_from_the_session_load_it_only_in_their_document() {
let p = json!({"files": [file("a.png", &png(40, 20, [9, 9, 9, 255], None))], "link": false});
let not_active = "the document it was prepared for is no longer active";
let mut s = session();
let read = s.prepare_place_queue(&p).unwrap().read().unwrap();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let before = snapshot(&s);
assert!(s.place_queue_read(read).unwrap_err().to_string().contains(not_active));
assert!(snapshot(&s) == before && s.tool_id() == "selection", "the other document's tool and queue stay");
let read = {
s.execute("document.activate", &json!({"index": 0})).unwrap();
s.prepare_place_queue(&p).unwrap().read().unwrap()
};
s.execute("document.activate", &json!({"index": 1})).unwrap();
s.execute("document.activate", &json!({"index": 0})).unwrap();
assert_eq!(s.place_queue_read(read).unwrap()["count"], 1);
assert_eq!(s.tool_id(), "place");
// The document they were read for closed.
let mut s = session();
let read = s.prepare_place_queue(&p).unwrap().read().unwrap();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("file.close", &json!({"index": 0})).unwrap();
let before = snapshot(&s);
assert!(s.place_queue_read(read).unwrap_err().to_string().contains(not_active));
assert!(snapshot(&s) == before, "the document left open keeps its tool");
}
/// A linked image keeps the preview its file was read with ([`cmd::place::PlaceJob::read`] makes
/// it), so placing the read file does not decode the image again; an embedded image has none.
#[test]
+284 -12
View File
@@ -796,30 +796,269 @@ fn expanding_a_pattern_fill_keeps_each_piece_s_own_paint() {
assert_eq!(patterns, 0, "the tiles are objects");
}
/// Two painted effects on one fill, the first returning a piece with two fills: the second replaces
/// the first of them and the other fill stays over it.
/// A path's bounds and the paints of its fills and strokes, each stroke with its weight.
type PaintedPath = (Option<vectorcraft_geom::Rect>, Vec<(Paint, Option<f64>)>);
/// The paths of `id`'s reshaped art that paint, in paint order, each with the fills and strokes of
/// it that paint.
fn painted_paths(s: &Session, id: NodeId) -> Vec<PaintedPath> {
let st = s.doc().unwrap();
let art = vectorcraft_render::effects::reshape(Some(&st.doc), st.doc.node(id).unwrap(), None).unwrap();
let mut paths = vec![];
art.walk(&mut |n| {
if let Some(p) = n.path_data() {
let items: Vec<_> = n
.appearance
.items
.iter()
.map(|i| match i {
vectorcraft_doc::AppearanceItem::Fill(f) => (f.paint.clone(), None),
vectorcraft_doc::AppearanceItem::Stroke(st) => (st.paint.clone(), Some(st.width)),
})
.filter(|(paint, _)| !paint.is_none())
.collect();
if !items.is_empty() {
paths.push((p.bounds(), items));
}
}
});
paths
}
fn paint(hex: &str) -> Paint {
Paint::solid(Color::from_hex(hex).unwrap())
}
/// Two painted effects on one fill, the first returning a piece with two fills: the second runs on
/// each of them, told which fill it is on. On the second fill it returns a blue square at 80 pt; on
/// the first it returns a result that is refused, which leaves only that fill, red, on the square at
/// 40 pt.
#[test]
fn a_second_painted_effect_on_a_fill_keeps_the_piece_s_other_fills() {
fn a_later_painted_effect_runs_on_every_fill_a_piece_returns() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string();
let one = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff")]}]}).to_string();
let blue = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#0000ff")]}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.twofills", true), &two));
install_wat(&mut s, &tpl::returning(&painting("test.engine.onefill", true), &one));
install_wat(&mut s, &tpl::when_given(&painting("test.engine.onsecond", true), tpl::Given::Params, r#""item":{"fill":1}"#, &blue));
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.twofills", "item": fill}));
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.onefill", "item": fill}));
assert_eq!(drawn(&s).pixel(50, 50), GREEN, "the other fill paints over the replaced one");
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.onsecond", "item": fill}));
let img = drawn(&s);
assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (RED, BLUE), "the first fill as it was, the second moved and blue");
let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds());
assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#ff0000"), None)]), (b, vec![(paint("#0000ff"), None)])]);
// The same result for both fills: each is replaced.
let one = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff")]}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.onsecond", true), &one));
assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#0000ff"), None)]), (a, vec![(paint("#0000ff"), None)])]);
}
/// On a stroke, a later painted effect runs on each stroke the first returns, with its own weight
/// and place among them, and keeps their order.
#[test]
fn a_later_painted_effect_runs_on_every_stroke_a_piece_returns() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
run(&mut s, "paint.setStroke", json!({"ids": [id.0], "color": "#000000"}));
let two = json!({"objects": [{"path": square_at(40.0), "strokes": [{"paint": solid("#ff0000"), "width": 2}, {"paint": solid("#00ff00"), "width": 6}]}]})
.to_string();
let blue = json!({"objects": [{"path": square_at(80.0), "strokes": [{"paint": solid("#0000ff"), "width": 4}]}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.twostrokes", true), &two));
install_wat(&mut s, &tpl::when_given(&painting("test.engine.onsecondstroke", true), tpl::Given::Params, r#""item":{"stroke":1}"#, &blue));
let stroke = node(&s, id).appearance.items.iter().position(|i| !i.is_fill()).unwrap();
for effect in ["plugin.test.engine.twostrokes", "plugin.test.engine.onsecondstroke"] {
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": stroke}));
}
let stroked: Vec<_> = painted_paths(&s, id).into_iter().filter(|(_, items)| items.iter().any(|(_, w)| w.is_some())).collect();
let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds());
assert_eq!(stroked, [(a, vec![(paint("#ff0000"), Some(2.0))]), (b, vec![(paint("#0000ff"), Some(4.0))])]);
}
/// A third painted effect runs on every fill the second returned, for each fill the first returned.
#[test]
fn a_third_painted_effect_visits_every_fill_from_the_second() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let first = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string();
let second = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#0000ff"), solid("#00ffff")]}]}).to_string();
let third = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#ffff00")]}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.third.a", true), &first));
install_wat(&mut s, &tpl::returning(&painting("test.engine.third.b", true), &second));
install_wat(&mut s, &tpl::when_given(&painting("test.engine.third.c", true), tpl::Given::Params, r#""item":{"fill":1}"#, &third));
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
for effect in ["a", "b", "c"] {
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": format!("plugin.test.engine.third.{effect}"), "item": fill}));
}
let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds());
let pair = [(a, vec![(paint("#0000ff"), None)]), (b, vec![(paint("#ffff00"), None)])];
assert_eq!(painted_paths(&s, id), [pair.clone(), pair].concat());
}
/// A later live effect that changes geometry only runs on each fill a painted effect returned, told
/// which fill it is on: on the second it moves the square to 80 pt, and the first stays at 40 pt.
#[test]
fn a_later_geometry_effect_uses_each_generated_fill_s_context() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string();
let moved = json!({"objects": [{"path": square_at(80.0)}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.geomfills", true), &two));
install_wat(&mut s, &tpl::when_given(&painting("test.engine.geomsecond", false), tpl::Given::Params, r#""item":{"fill":1}"#, &moved));
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
for effect in ["plugin.test.engine.geomfills", "plugin.test.engine.geomsecond"] {
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill}));
}
let (a, b) = (square_at(40.0).bounds(), square_at(80.0).bounds());
assert_eq!(painted_paths(&s, id), [(a, vec![(paint("#ff0000"), None)]), (b, vec![(paint("#00ff00"), None)])]);
}
/// A later Outline Stroke effect runs on each stroke a painted effect returned, with that stroke's
/// weight: the 2 pt stroke's outline is 22 pt wide and the 6 pt stroke's 26 pt, in their order.
#[test]
fn a_later_outline_stroke_uses_each_generated_stroke_s_weight() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
run(&mut s, "paint.setStroke", json!({"ids": [id.0], "color": "#000000"}));
let two = json!({"objects": [{"path": square_at(40.0), "strokes": [{"paint": solid("#ff0000"), "width": 2}, {"paint": solid("#00ff00"), "width": 6}]}]})
.to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.outlinestrokes", true), &two));
let stroke = node(&s, id).appearance.items.iter().position(|i| !i.is_fill()).unwrap();
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.outlinestrokes", "item": stroke}));
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "path.outlineStroke", "params": {}, "item": stroke}));
let st = s.doc().unwrap();
let art = vectorcraft_render::effects::reshape(Some(&st.doc), st.doc.node(id).unwrap(), None).unwrap();
let mut paints = vec![];
// Each outline is a compound path (the ring around the square): its width and its strokes.
let mut outlines = vec![];
art.walk(&mut |n| {
if n.path_data().is_some() {
paints.push(n.appearance.items.iter().filter(|i| i.is_fill()).map(|i| i.paint().clone()).collect::<Vec<_>>());
if let vectorcraft_doc::NodeKind::Compound { children, .. } = &n.kind {
let bounds = children.iter().filter_map(|c| c.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b));
let strokes: Vec<_> = n
.appearance
.items
.iter()
.filter_map(|i| match i {
vectorcraft_doc::AppearanceItem::Stroke(st) => Some((st.paint.clone(), st.width)),
vectorcraft_doc::AppearanceItem::Fill(_) => None,
})
.collect();
outlines.push((bounds.map(|b| (b.width() * 1000.0).round() / 1000.0), strokes));
}
});
let fill = |hex: &str| Paint::solid(Color::from_hex(hex).unwrap());
assert!(paints.contains(&vec![fill("#0000ff"), fill("#00ff00")]), "{paints:?}");
assert_eq!(
outlines,
[(Some(22.0), vec![(paint("#ff0000"), 2.0)]), (Some(26.0), vec![(paint("#00ff00"), 6.0)])],
"each stroke is outlined at its own weight"
);
}
/// A later painted effect's runs on the fills a piece returned share the effects' budget: each run
/// that fits gives all its pieces, and once the budget is spent the remaining fills stay together
/// on the piece's path, with none of their run's pieces.
#[test]
fn painted_fills_share_the_budget_without_partial_results() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let fills = vec![solid("#ff0000"); vectorcraft_plugins::objects::MAX_ITEMS];
let first = json!({"objects": [{"path": square_at(40.0), "fills": fills}]}).to_string();
let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true));
let many = json!({"objects": vec![json!({"path": tiny}); 400]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.budget.fills", true), &first));
install_wat(&mut s, &tpl::returning(&painting("test.engine.budget.many", true), &many));
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
for effect in ["plugin.test.engine.budget.fills", "plugin.test.engine.budget.many"] {
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill}));
}
let paths = painted_paths(&s, id);
let tinies = paths.iter().filter(|(b, _)| *b == tiny.bounds()).count();
let kept: Vec<_> = paths.iter().filter(|(b, _)| *b == square_at(40.0).bounds()).collect();
assert_eq!(kept.len(), 1, "the fills left out stay together");
let ran = vectorcraft_plugins::objects::MAX_ITEMS - kept[0].1.len();
assert!(ran > 1 && !kept[0].1.is_empty(), "{ran} runs gave their pieces");
assert_eq!(tinies, ran * 400, "every run that fit gave all its pieces");
assert!(paths.len() <= vectorcraft_plugins::objects::MAX_OBJECTS, "{} paths", paths.len());
}
/// A later painted effect runs on each of 256 fills a painted effect returned on an 8,000-anchor
/// path, although 256 copies of that path would pass the effects' budget, when what it returns
/// fits.
#[test]
fn a_later_painted_effect_runs_on_many_fills_of_a_large_piece_when_its_results_fit() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let zigzag: Vec<Point> = (0..8_000).map(|i| Point::new(40.0 + f64::from(i) * 20.0 / 8_000.0, if i % 2 == 0 { 40.0 } else { 60.0 })).collect();
let large = PathData::single(SubPath::polyline(&zigzag, true));
let fills = vec![solid("#ff0000"); vectorcraft_plugins::objects::MAX_ITEMS];
let first = json!({"objects": [{"path": large, "fills": fills}]}).to_string();
let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true));
let small = json!({"objects": [{"path": tiny}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.large.fills", true), &first));
install_wat(&mut s, &tpl::returning(&painting("test.engine.large.small", true), &small));
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
for effect in ["plugin.test.engine.large.fills", "plugin.test.engine.large.small"] {
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill}));
}
let paths = painted_paths(&s, id);
let tinies = paths.iter().filter(|(b, _)| *b == tiny.bounds()).count();
assert_eq!(tinies, vectorcraft_plugins::objects::MAX_ITEMS, "every fill's run");
assert!(paths.iter().all(|(b, _)| *b != large.bounds()), "no fill left on the large path");
}
/// An open path of `curves` tall curves, each drawn with about 5,200 lines.
fn tall_curves(curves: u32) -> PathData {
let h = 3_000_000.0;
let anchors = (0..=curves)
.map(|i| {
let x = 40.0 + f64::from(i);
vectorcraft_geom::Anchor::with_handles(Point::new(x, 0.0), Point::new(x, -h), Point::new(x, h))
})
.collect();
PathData::single(SubPath::new(anchors, false))
}
/// A later painted effect's run on the first of two fills a painted effect returned on a path that
/// takes most of the effects' budget gives its result when it and the second fill's result fit
/// together, although the result and another copy of the path would not.
#[test]
fn a_later_painted_run_counts_the_results_after_it_before_keeping_room_for_its_input() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let (large, result) = (tall_curves(1_000), tall_curves(600));
let tiny = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.1, 0.0), Point::new(0.0, 0.1)], true));
let two = json!({"objects": [{"path": large, "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string();
let on_first = json!({"objects": [{"path": result}]}).to_string();
let on_second = json!({"objects": [{"path": tiny}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.tall.fills", true), &two));
let second = painting("test.engine.tall.each", true);
install_wat(&mut s, &tpl::when_given_else(&second, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_second));
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
for effect in ["plugin.test.engine.tall.fills", "plugin.test.engine.tall.each"] {
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill}));
}
let want = [(result.bounds(), vec![(paint("#ff0000"), None)]), (tiny.bounds(), vec![(paint("#00ff00"), None)])];
assert_eq!(painted_paths(&s, id), want, "both runs give their results");
}
/// When the results of a later painted effect's runs on the two fills of a large path do not fit
/// together, and the first fill's result and another copy of the path do not fit either, the first
/// fill stays on the path and the second fill's result, which fits beside the path, is drawn.
#[test]
fn a_later_painted_run_that_did_not_fit_beside_an_earlier_result_fits_once_that_is_left_out() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let (large, first, second) = (tall_curves(577), tall_curves(1_058), tall_curves(770));
let two = json!({"objects": [{"path": large, "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string();
let on_first = json!({"objects": [{"path": first}]}).to_string();
let on_second = json!({"objects": [{"path": second}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.refit.fills", true), &two));
let each = painting("test.engine.refit.each", true);
install_wat(&mut s, &tpl::when_given_else(&each, tpl::Given::Params, r#""item":{"fill":0}"#, &on_first, &on_second));
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
for effect in ["plugin.test.engine.refit.fills", "plugin.test.engine.refit.each"] {
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": fill}));
}
let want = [(large.bounds(), vec![(paint("#ff0000"), None)]), (second.bounds(), vec![(paint("#00ff00"), None)])];
assert_eq!(painted_paths(&s, id), want, "the second fill's result is drawn");
}
/// A Transform effect before a painted effect on a fill moves the fill's placed gradient: a piece
@@ -1183,6 +1422,39 @@ fn the_first_view_defers_plug_in_effects_past_its_budget() {
assert_eq!(fx_c.take_report(), Some(0));
}
/// A later painted effect deferred on the fills a piece returned is listed once, at its place among
/// the object's fill's effects, and a refresh of the object runs it on each of them.
#[test]
fn deferred_runs_on_the_fills_a_piece_returned_keep_the_fill_s_stage() {
let mut s = session();
let id = rect(&mut s, 10.0, "#ff0000");
let two = json!({"objects": [{"path": square_at(40.0), "fills": [solid("#ff0000"), solid("#00ff00")]}]}).to_string();
let blue = json!({"objects": [{"path": square_at(80.0), "fills": [solid("#0000ff")]}]}).to_string();
install_wat(&mut s, &tpl::returning(&painting("test.engine.deferred.two", true), &two));
install_wat(&mut s, &tpl::returning(&painting("test.engine.deferred.later", true), &blue));
let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap();
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.deferred.two", "item": fill}));
// The first effect's result is kept from a drawing outside a view's budget.
assert_eq!(drawn(&s).pixel(50, 50), GREEN);
run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.deferred.later", "item": fill}));
let step = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(3_000));
let fx = vectorcraft_plugins::deferred::Deferrals::with_clock(stepping_clock(&step));
s.doc_mut().unwrap().plugin_effects = fx.clone();
let img = fx.view(|| drawn(&s));
assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (GREEN, WHITE), "the fills on the first effect's piece");
let places = run(&mut s, "effect.deferredStatus", json!({}))["effects"]
.as_array()
.unwrap()
.iter()
.map(|e| (e["objectId"].as_u64().unwrap(), e["item"].as_u64(), e["effectIndex"].as_u64().unwrap()))
.collect::<Vec<_>>();
assert_eq!(places, [(id.0, Some(fill as u64), 1)], "the fill's stage, listed once");
step.store(0, std::sync::atomic::Ordering::Relaxed);
assert_eq!(run(&mut s, "effect.refreshDeferred", json!({"ids": [id.0]})), json!({"refreshed": 1, "stillDeferred": 0, "failed": 0}));
let img = fx.view(|| drawn(&s));
assert_eq!((img.pixel(50, 50), img.pixel(90, 50)), (WHITE, BLUE), "both fills replaced");
}
/// Deferred stages are listed where their effects are: after an effect that changes no geometry,
/// and on a fill after a Transform effect that reaches its appearance, each of two instances of
/// one plug-in at its own place.
+26
View File
@@ -789,3 +789,29 @@ fn units_and_ruler_guides_survive_save_and_reopen() {
}
let _ = std::fs::remove_dir_all(d);
}
/// A ruler guide hidden or locked on its own (the Layers panel's eye and lock on its row,
/// `layer.setProps` on its node) stays so through Save, Close and Open, and the other guide stays
/// visible and unlocked.
#[test]
fn a_guide_hidden_or_locked_on_its_own_survives_save_and_reopen() {
let d = dir("guide-flags");
for ext in ["vectorcraft", "pdf", "ai", "eps"] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
for pos in [10, 20, 30] {
s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap();
}
rect(&mut s);
let ids: Vec<u64> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| g.id.unwrap().0).collect();
s.execute("layer.setProps", &json!({"ids": [ids[1]], "visible": false})).unwrap();
s.execute("layer.setProps", &json!({"ids": [ids[2]], "locked": true})).unwrap();
let p = path(&d, &format!("a.{ext}"));
s.execute("document.save", &json!({"path": p})).unwrap();
s.execute("file.close", &json!({})).unwrap();
s.execute("document.open", &json!({"path": p})).unwrap();
let flags: Vec<_> = s.doc().unwrap().doc.ruler_guides().iter().map(|g| (g.pos, g.hidden, g.locked)).collect();
assert_eq!(flags, [(10.0, false, false), (20.0, true, false), (30.0, false, true)], "{ext}");
}
let _ = std::fs::remove_dir_all(d);
}
+2 -2
View File
@@ -63,7 +63,7 @@ fn each_member_has_its_value() {
("$.memCache", json!(0)),
("$.os", json!(os)),
("$.screens.length", json!(0)),
("$.stack", json!("[global]:1\n")),
("$.stack", json!("[global]@t.js:1\n")),
("$.strict", json!(false)),
("$.version", json!(version)),
("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")),
@@ -165,7 +165,7 @@ fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() {
fn error_line_and_stack_follow_the_running_code() {
let mut s = Session::new();
let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());";
assert_eq!(logged(&mut s, source)[0], json!([3, "[global]:5\nwhere:3\n", true]));
assert_eq!(logged(&mut s, source)[0], json!([3, "[global]@t.js:5\nwhere@t.js:3\n", true]));
assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one");
}
+38
View File
@@ -276,6 +276,44 @@ fn an_engine_keeps_the_newest_places_within_its_budget() {
assert_eq!((d_place.0, d_place.1, d_place.2), (None, 0, 0), "a map larger than the budget is not kept");
}
/// `$.line` and `$.stack` in code an earlier run of a named engine compiled give the line of that
/// run's file: its script, or a file it included; a script given as text is named by that run's
/// name. Code `eval` and `Function` compiled keeps its own line, in `[eval]`, and code whose place
/// the engine did not keep is at line 0 of `[unknown]`.
#[test]
fn the_line_and_the_stack_of_code_an_earlier_run_kept_are_at_that_runs_files() {
use super::script_include::short_stack;
let base: PathBuf = std::env::temp_dir().join(format!("vc-script-engines-line-stack-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(&base).unwrap();
std::fs::write(base.join("inc.jsxinc"), "\n\nfunction fromInclude() {\n return [$.line, $.stack];\n}").unwrap();
let def = base.join("def.jsx");
std::fs::write(&def, "#targetengine e\nvar pad = 1;\n#include \"inc.jsxinc\"\nfunction fromMain() {\n return fromInclude();\n}").unwrap();
let mut s = Session::new();
s.execute("script.run", &json!({"path": def.to_string_lossy()})).unwrap();
run(&mut s, "#targetengine e\n\nfunction fromText() {\n return $.stack;\n}").unwrap();
let call = |s: &mut Session, code: &str| {
let r = s.execute("script.run", &json!({"source": format!("#targetengine e\n\n{code}"), "name": "caller.js"}));
r.unwrap_or_else(|e| panic!("{code}: {e}"))["log"][0].clone()
};
let r = call(&mut s, "vc.log(fromMain());");
assert_eq!(r[0], 4, "{r}");
assert_eq!(short_stack(&r[1]), "[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n");
assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[global]@caller.js:3\nfromText@t.js:4\n");
assert_eq!(call(&mut s, "vc.log(eval('\\n\\n$.line'));"), 3);
assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[global]@caller.js:3\n[global]@[eval]:2\n");
let r = call(&mut s, "vc.log(new Function('\\nreturn $.stack;')());");
assert_eq!(r, "[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles");
// A map larger than the budget is not kept.
TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1)));
let lost = run(&mut s, "#targetengine e\n\n\nfunction lost() {\n return [$.line, $.stack];\n}");
let r = lost.map(|_| call(&mut s, "vc.log(lost());"));
TEST_KEPT_MAP_BYTES.with(|b| b.set(None));
let r = r.unwrap();
assert_eq!(r, json!([0, "[global]@caller.js:3\nlost@[unknown]:0\n"]));
let _ = std::fs::remove_dir_all(base);
}
/// A run of a named engine whose script does not compile defines no code, so it keeps no place
/// and pushes out none of the places kept before. An included file without a preprocessor line is
/// first parsed with the script it joins, so its syntax error ends the run as it starts.
+43
View File
@@ -496,6 +496,49 @@ fn script_included_error_has_local_file_and_line() {
let _ = std::fs::remove_dir_all(base);
}
/// `$.stack`'s text with each frame's file cut to its name: `function@name:line` a line.
pub(crate) fn short_stack(stack: &Value) -> String {
let stack = stack.as_str().unwrap_or_else(|| panic!("a stack: {stack}"));
stack
.lines()
.map(|frame| match (frame.split_once('@'), frame.rsplit_once(':')) {
(Some((name, _)), Some((place, line))) => {
let file = place.split_once('@').map_or(place, |(_, f)| f).rsplit(['/', '\\']).next().unwrap_or_default();
format!("{name}@{file}:{line}\n")
}
_ => format!("{frame}\n"),
})
.collect()
}
/// `$.line` and `$.stack` give the line of the file the running code is in: the script, a file it
/// included (and a file that one included) or a file `$.evalFile` gave and the files it included,
/// whatever lines come before it in the run's expanded source.
#[test]
fn script_line_and_stack_are_at_the_line_of_each_file() {
let base = folder("line-stack");
write(
&base.join("main/lib.jsxinc"),
"\nfunction libWhere() {\n return [$.line, $.stack];\n}\nvar libLine = $.line;\n#include \"deep.jsxinc\"\n",
);
write(&base.join("main/deep.jsxinc"), "\n\nvar deepLine = $.line;\nfunction deepStack() {\n return $.stack;\n}");
write(&base.join("main/sub/ev.jsx"), "#include \"inc.jsxinc\"\nfunction evWhere() {\n return incWhere();\n}\nevWhere();");
write(&base.join("main/sub/inc.jsxinc"), "\n\nfunction incWhere() {\n return [$.line, $.stack];\n}");
let text = "var a = 1;\nvar b = 2;\n#include \"lib.jsxinc\"\nvar mainLine = $.line;\nvc.log([libLine, deepLine, mainLine]);\n\
vc.log(libWhere());\nvc.log(deepStack());\nvc.log($.evalFile('sub/ev.jsx'));";
let log = run(&base, text).unwrap()["log"].clone();
assert_eq!(log[0], json!([5, 3, 4]), "{log}");
assert_eq!(log[1][0], 3, "{log}");
assert_eq!(short_stack(&log[1][1]), "[global]@main.jsx:6\nlibWhere@lib.jsxinc:3\n");
assert_eq!(short_stack(&log[2]), "[global]@main.jsx:7\ndeepStack@deep.jsxinc:5\n");
assert_eq!(log[3][0], 4, "{log}");
assert_eq!(short_stack(&log[3][1]), "[global]@main.jsx:8\n[global]@ev.jsx:5\nevWhere@ev.jsx:3\nincWhere@inc.jsxinc:4\n");
// The file a frame names is the one `$.fileName` gives while that file runs.
let log = run(&base, "vc.log($.stack.slice(9, -3) === $.fileName);").unwrap()["log"].clone();
assert_eq!(log, json!([true]));
let _ = std::fs::remove_dir_all(base);
}
/// Pumps the run in the app until it ends or waits at a dialog (`None`).
fn pump(s: &mut Session) -> Option<Result<Value>> {
for _ in 0..10_000 {
+4 -2
View File
@@ -103,10 +103,12 @@ fn ruler_guides_are_not_art_to_select_paint_or_inspect() {
let layer_row = s.execute("document.inspect", &json!({"ids": [layer.0]})).unwrap();
let listed = layer_row.to_string();
assert!(guides.iter().all(|g| !listed.contains(&format!("\"id\":{}", g.0))), "{listed}");
// Unlock All does not reach a locked guide.
// Unlock All unlocks a guide locked on its own and selects it as a guide, not as art.
Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(guides[0]).unwrap().locked = true;
s.execute("object.unlockAll", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.node(guides[0]).unwrap().locked);
let st = s.doc().unwrap();
assert!(!st.doc.node(guides[0]).unwrap().locked);
assert_eq!((st.selection.guides.clone(), st.selection.objects.clone()), (vec![guides[0]], vec![]));
}
#[test]
+21 -4
View File
@@ -388,18 +388,33 @@ fn last_error(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<V
}
fn line(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
let line = interp.script_frames().last().map_or(0, |(code, pc, _)| code.line_column(pc.saturating_sub(1)).0);
let line = interp.script_frames().last().map_or(0, |(code, pc, _)| place(interp.locator.as_ref(), code, pc).1);
Ok(Value::Number(f64::from(line)))
}
/// Where the instruction before `pc` in `code` came from: the file the realm's locator names
/// (`None` without one) and the line there, or the line in the compiled source without a locator.
fn place(locator: Option<&crate::realm::SourceLocator>, code: &Code, pc: usize) -> (Option<String>, u32) {
let line = code.line_column(pc.saturating_sub(1)).0;
match locator {
Some(locate) => {
let (file, line) = locate(code.source.tag, line);
(Some(file), line)
}
None => (None, line),
}
}
/// The most frames `$.stack` lists, and the most characters of a function's name it shows.
const STACK_FRAMES: usize = 64;
const STACK_NAME_UNITS: usize = 64;
/// The script's frames, outermost first, one a line: the function's name and the line it is at.
/// The script's frames, outermost first, one a line: the function's name and the line it is at,
/// as `name:line`, or as `name@file:line` with the file the realm's locator names.
fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
let frames: Vec<(Rc<Code>, usize, bool)> = interp.script_frames().map(|(c, pc, f)| (c.clone(), pc, f)).collect();
let skip = frames.len().saturating_sub(STACK_FRAMES);
let locator = interp.locator.clone();
let mut text = String::new();
if skip > 0 {
text.push_str("…\n");
@@ -407,8 +422,10 @@ fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value>
for (code, pc, function) in frames.iter().skip(skip) {
interp.use_fuel()?;
let name = if *function { function_name(code) } else { "[global]".to_string() };
let line = code.line_column(pc.saturating_sub(1)).0;
text.push_str(&format!("{name}:{line}\n"));
match place(locator.as_ref(), code, *pc) {
(Some(file), line) => text.push_str(&format!("{name}@{file}:{line}\n")),
(None, line) => text.push_str(&format!("{name}:{line}\n")),
}
}
let mut out = Builder::new();
out.push_str(interp, &text)?;
+26
View File
@@ -219,6 +219,32 @@ fn script_items_read_the_global_object_the_last_error_the_line_and_the_stack() {
assert!(thrown(&mut r, "'use strict'; h.line = 1").starts_with("TypeError"), "the items cannot be assigned");
}
#[test]
fn the_line_and_the_stack_give_the_place_the_source_locator_maps_each_frame_to() {
let mut r = realm();
let items = [("line", ScriptItem::Line), ("stack", ScriptItem::Stack)].into_iter().map(|(n, i)| (n.to_string(), HostItem::Script(i))).collect();
r.define_host_object("h", items).unwrap();
let asked: Rc<RefCell<Vec<(u32, u32)>>> = Rc::default();
let seen = asked.clone();
r.set_source_locator(Rc::new(move |tag, line| {
seen.borrow_mut().push((tag, line));
let file = if tag == UNKNOWN_SOURCE { "[eval]".to_string() } else { format!("f{tag}") };
(file, line + 100)
}));
let source = "function inner() {\n return h.stack;\n}\n\ninner()";
let stack = text(&mut r, source);
let tag = r.script_tag();
assert_eq!(stack, format!("[global]@f{tag}:105\ninner@f{tag}:102\n"));
assert_eq!(*asked.borrow(), [(tag, 5), (tag, 2)], "each frame's tag and its line in the compiled source");
assert_eq!(r.run("\n\n h.line").unwrap(), JsValue::Number(103.0));
let tag = r.script_tag();
let stack = text(&mut r, "\neval('\\n\\nh.stack')");
assert_eq!(stack, format!("[global]@f{}:102\n[global]@[eval]:103\n", tag + 1), "code eval compiles has no tag of its own");
let deep = "function d(n) { return n ? d(n - 1) : h.stack; } var s = d(100).split('\\n'); s.length + ',' + s[0] + ',' + s[1]";
let tag = r.script_tag() + 1;
assert_eq!(text(&mut r, deep), format!("66,…,d@f{tag}:101"), "the frames past 64 are still left out");
}
#[test]
fn a_host_property_reads_its_getter_and_gives_assignments_to_its_setter() {
let mut r = Realm::new();
+3
View File
@@ -232,6 +232,8 @@ pub(crate) struct Interp {
pub(crate) evaluated: u32,
/// The tag of the source the last run's error was raised in.
pub(crate) error_tag: u32,
/// Where `$.line` and `$.stack` find the file and line of a compiled line.
pub(crate) locator: Option<crate::realm::SourceLocator>,
/// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is
/// propagating.
pub(crate) thrown_mark: Option<u32>,
@@ -469,6 +471,7 @@ impl Interp {
source_tag: crate::realm::UNKNOWN_SOURCE,
evaluated: 0,
error_tag: crate::realm::UNKNOWN_SOURCE,
locator: None,
thrown_mark: None,
finally_marks: Vec::new(),
finally_sites: Vec::new(),
+1 -1
View File
@@ -83,7 +83,7 @@ pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction};
pub use lexer::{Goal, Lexer};
pub use number::to_string as number_to_string;
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, UNKNOWN_SOURCE};
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE};
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
/// How a script is read.
+11
View File
@@ -63,6 +63,10 @@ pub enum LimitKind {
/// evaluator's: code that `eval` or `Function` compiled, or an error with no place.
pub const UNKNOWN_SOURCE: u32 = u32::MAX;
/// The file and line that line `line` of the source with tag `tag` ([`Realm::error_tag`]) came
/// from, as `$.line` and `$.stack` give them ([`Realm::set_source_locator`]).
pub type SourceLocator = std::rc::Rc<dyn Fn(u32, u32) -> (String, u32)>;
/// The source tag after `tag`. Once the tags are used up, every later source gets
/// [`UNKNOWN_SOURCE`], so no two sources share a tag.
pub(crate) fn next_tag(tag: u32) -> u32 {
@@ -395,6 +399,13 @@ impl Realm {
self.interp.interrupt = interrupt.0.clone();
}
/// Has `$.line` give the line `locate` maps the running line to, and `$.stack` give each
/// frame's line that way, after the file `locate` names: `function@file:line`. Without a
/// locator they give the line of the compiled source, and `$.stack` names no file.
pub fn set_source_locator(&mut self, locate: SourceLocator) {
self.interp.locator = Some(locate);
}
/// Which source the last error's `line` and `column` are in: 0 for the script last given to
/// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a
/// [`crate::HostItem::Evaluator`] gave since then, and [`UNKNOWN_SOURCE`] otherwise, which
+185 -86
View File
@@ -8,8 +8,8 @@ use crate::builtins::{arg, constructor, data, method, native};
use crate::heap::{
Class, ENUMERABLE, Key, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, WRITABLE, XmlKind, XmlName, XmlNs, key, string_bytes,
};
use crate::interp::{Abrupt, Interp, JsResult};
use crate::string_builtins::{new_array, set_element};
use crate::interp::{Abrupt, HeldBytes, Interp, JsResult};
use crate::string_builtins::{flat_charged, new_array, push_held, reserve_units, set_element};
use crate::value::{Str, Value};
use crate::xml::{
Access, Content, NameRef, RESERVED_NS_BINDING, STAR, Xv, canonical_index, is_ncname, is_script_xml_name, ns_binding_allowed, xml_name_writable,
@@ -184,6 +184,13 @@ fn as_qname(interp: &Interp, v: &Value) -> Option<(XmlName, bool)> {
}
}
/// The code units of `v` as a string. A rope is flattened only after the bytes of its copy are
/// reserved.
fn str_arg(interp: &mut Interp, v: &Value) -> JsResult<Key> {
let s = interp.to_str(v)?;
flat_charged(interp, &s)
}
/// The namespace `new Namespace(...)` makes from its arguments (ECMA-357 section 13.2.2).
fn build_namespace(interp: &mut Interp, args: &[Value]) -> JsResult<XmlNs> {
match args {
@@ -197,7 +204,7 @@ fn build_namespace(interp: &mut Interp, args: &[Value]) -> JsResult<XmlNs> {
{
return Ok(XmlNs { prefix: name.prefix, uri: u });
}
let u = interp.to_str(uri)?.flat();
let u = str_arg(interp, uri)?;
let prefix = if u.is_empty() { Some(empty()) } else { None };
Ok(XmlNs { prefix, uri: u })
}
@@ -205,7 +212,7 @@ fn build_namespace(interp: &mut Interp, args: &[Value]) -> JsResult<XmlNs> {
let qname_uri = as_qname(interp, uri).and_then(|(n, _)| n.uri);
let u = match qname_uri {
Some(u) => u,
None => interp.to_str(uri)?.flat(),
None => str_arg(interp, uri)?,
};
if u.is_empty() {
if matches!(prefix_value, Value::Undefined) || interp.to_str(prefix_value)?.len() == 0 {
@@ -216,7 +223,7 @@ fn build_namespace(interp: &mut Interp, args: &[Value]) -> JsResult<XmlNs> {
if matches!(prefix_value, Value::Undefined) {
return Ok(XmlNs { prefix: None, uri: u });
}
let p = interp.to_str(prefix_value)?.flat();
let p = str_arg(interp, prefix_value)?;
Ok(XmlNs { prefix: is_ncname(&p).then_some(p), uri: u })
}
}
@@ -256,7 +263,7 @@ fn build_qname(interp: &mut Interp, args: &[Value]) -> JsResult<(XmlName, bool)>
} else if matches!(name_value, Value::Undefined) {
empty()
} else {
interp.to_str(&name_value)?.flat()
str_arg(interp, &name_value)?
};
let (uri, prefix) = match namespace {
Some(Value::Undefined) | None => {
@@ -290,7 +297,16 @@ fn qname_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
let Some((name, attribute)) = as_qname(interp, &this) else {
return Err(interp.type_error("QName.prototype.toString needs a QName"));
};
let mut units: Vec<u16> = Vec::new();
let uri_len = match &name.uri {
None => 3,
Some(u) if !u.is_empty() => u.len().saturating_add(2),
_ => 0,
};
let len = usize::from(attribute).saturating_add(uri_len).saturating_add(name.local.len());
let bytes = string_bytes(len);
interp.reserve_heap(bytes)?;
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
let mut units: Vec<u16> = Vec::with_capacity(len);
if attribute {
units.push(0x40);
}
@@ -303,9 +319,6 @@ fn qname_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js
_ => {}
}
units.extend_from_slice(&name.local);
let bytes = string_bytes(units.len());
interp.reserve_heap(bytes)?;
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
Ok(Value::String(Str::from_units(units)))
}
@@ -324,7 +337,7 @@ fn to_xml(interp: &mut Interp, v: &Value) -> JsResult<ObjId> {
Err(interp.type_error("an XMLList converts to XML only when it has one item"))
}
Xv::Other => {
let text = if v.is_nullish() { empty() } else { interp.to_str(v)?.flat() };
let text = if v.is_nullish() { empty() } else { str_arg(interp, v)? };
interp.xml_from_text(&text)
}
}
@@ -355,7 +368,7 @@ fn xml_list_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool)
Xv::Node(n) => i.list_push(out, n)?,
_ if v.is_nullish() => {}
_ => {
let text = i.to_str(&v)?.flat();
let text = str_arg(i, &v)?;
for node in i.xml_parse(&text)? {
i.list_push(out, node)?;
}
@@ -366,7 +379,7 @@ fn xml_list_ctor(interp: &mut Interp, _: Value, args: &[Value], construct: bool)
}
fn is_xml_name(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
let s = interp.to_str(&arg(args, 0))?.flat();
let s = str_arg(interp, &arg(args, 0))?;
Ok(Value::Bool(is_script_xml_name(&s)))
}
@@ -440,10 +453,16 @@ fn this_id(interp: &mut Interp, this: &Value) -> JsResult<ObjId> {
}
}
fn nodes_of(interp: &mut Interp, this: &Value) -> JsResult<Vec<ObjId>> {
/// The nodes of `this`: the node itself, or a copy of the items of an XMLList, whose bytes `held`
/// holds against the heap limit first.
fn nodes_of(interp: &mut Interp, held: &mut HeldBytes, this: &Value) -> JsResult<Vec<ObjId>> {
match interp.classify(this) {
Xv::Node(n) => Ok(vec![n]),
Xv::List(l) => Ok(interp.xml_list(l)?.items.clone()),
Xv::List(l) => interp.rooted(std::slice::from_ref(this), |interp| {
let count = interp.xml_list(l)?.items.len();
held.add(interp, count.saturating_mul(size_of::<ObjId>()))?;
Ok(interp.xml_list(l)?.items.clone())
}),
Xv::Other => Err(not_xml_method(interp)),
}
}
@@ -464,8 +483,14 @@ fn attribute_name(interp: &mut Interp, v: &Value) -> JsResult<NameRef> {
if matches!(v, Value::Undefined | Value::Null | Value::Bool(_) | Value::Number(_)) {
return Err(interp.type_error("the value is not an XML attribute name"));
}
let local = interp.to_str(v)?.flat();
let local = local.strip_prefix(&[0x40u16]).map_or_else(|| local.clone(), Rc::from);
let local = str_arg(interp, v)?;
let local = match local.strip_prefix(&[0x40u16]) {
Some(rest) => {
reserve_units(interp, rest.len())?;
Rc::from(rest)
}
None => local,
};
let uri = if *local == *STAR { None } else { Some(empty()) };
Ok(NameRef { uri, local, attribute: true })
}
@@ -510,7 +535,8 @@ fn child(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<
match interp.xml_access(&p)? {
Access::Name(n) => Ok(Value::Object(interp.xml_select(id, &n)?)),
Access::Index(i) => {
let nodes = nodes_of(interp, &this)?;
let mut held = HeldBytes::new(interp);
let nodes = nodes_of(interp, &mut held, &this)?;
interp.rooted(std::slice::from_ref(&this), |it| {
let out = it.new_xml_list(Some(id), None)?;
it.xml_keep(out);
@@ -535,7 +561,8 @@ fn select_children(
keep: impl Fn(&Interp, ObjId) -> JsResult<bool>,
) -> JsResult<Value> {
let id = this_id(interp, this)?;
let nodes = nodes_of(interp, this)?;
let mut held = HeldBytes::new(interp);
let nodes = nodes_of(interp, &mut held, this)?;
interp.rooted(std::slice::from_ref(this), |it| {
let out = it.new_xml_list(Some(id), target_name)?;
it.xml_keep(out);
@@ -666,34 +693,64 @@ fn has_simple_content(interp: &mut Interp, this: Value, _: &[Value], _: bool) ->
}
}
/// The namespaces in scope at `x`, nearest declarations first, one for each prefix. Takes one unit
/// of fuel for each node it climbs through and for each declaration it reads.
pub(crate) fn scope_of(interp: &mut Interp, x: Option<ObjId>) -> JsResult<Vec<XmlNs>> {
let mut out: Vec<XmlNs> = Vec::new();
let mut seen: HashSet<Option<Key>> = HashSet::new();
let mut cur = x;
while let Some(y) = cur {
interp.use_fuel()?;
let (list, parent) = {
let node = interp.xml_node(y)?;
(node.ns.clone(), node.parent)
};
for ns in list {
interp.use_fuel()?;
if seen.insert(ns.prefix.clone()) {
out.push(ns);
}
}
cur = parent;
}
Ok(out)
/// The namespaces in scope at a node, nearest declarations first, one for each prefix. The bytes of
/// the list and of the table of prefixes that built it stay held against the heap limit until the
/// scope is dropped.
pub(crate) struct Scope {
pub(crate) list: Vec<XmlNs>,
_held: HeldBytes,
}
fn namespaces_array(interp: &mut Interp, list: Vec<XmlNs>) -> JsResult<Value> {
/// Holds the bytes of a full hash table of `len` entries of `entry` bytes each, and returns how
/// many more entries to reserve room for. Each new entry is counted four times with a control
/// byte, which covers the empty slots the table keeps and the old table while it is rehashed.
fn grow_table(interp: &mut Interp, held: &mut HeldBytes, len: usize, entry: usize) -> JsResult<usize> {
let more = len.max(4);
held.add(interp, more.saturating_mul(4).saturating_mul(entry.saturating_add(1)).saturating_add(16))?;
Ok(more)
}
/// The namespace `y` declares at index `i`.
fn declared_at(interp: &mut Interp, y: ObjId, i: usize) -> JsResult<Option<XmlNs>> {
Ok(interp.xml_node(y)?.ns.get(i).cloned())
}
/// The namespaces in scope at `x`, nearest declarations first, one for each prefix. Takes one unit
/// of fuel for each node it climbs through and for each declaration it reads.
pub(crate) fn scope_of(interp: &mut Interp, x: Option<ObjId>) -> JsResult<Scope> {
let root: Vec<Value> = x.map(Value::Object).into_iter().collect();
interp.rooted(&root, |interp| {
let mut held = HeldBytes::new(interp);
let mut out: Vec<XmlNs> = Vec::new();
let mut seen: HashSet<Option<Key>> = HashSet::new();
let mut cur = x;
while let Some(y) = cur {
interp.use_fuel()?;
let mut i = 0;
while let Some(ns) = declared_at(interp, y, i)? {
interp.use_fuel()?;
i += 1;
if seen.contains(&ns.prefix) {
continue;
}
if seen.len() == seen.capacity() {
let more = grow_table(interp, &mut held, seen.len(), size_of::<Option<Key>>())?;
seen.reserve(more);
}
seen.insert(ns.prefix.clone());
push_held(interp, &mut held, &mut out, ns)?;
}
cur = interp.xml_node(y)?.parent;
}
Ok(Scope { list: out, _held: held })
})
}
fn namespaces_array(interp: &mut Interp, list: &[XmlNs]) -> JsResult<Value> {
interp.rooted(&[], |i| {
let a = new_array(i);
for (at, ns) in list.into_iter().enumerate() {
let v = new_namespace(i, ns)?;
for (at, ns) in list.iter().enumerate() {
let v = new_namespace(i, ns.clone())?;
set_element(i, a, at, v)?;
}
Ok(Value::Object(a))
@@ -702,28 +759,46 @@ fn namespaces_array(interp: &mut Interp, list: Vec<XmlNs>) -> JsResult<Value> {
fn in_scope_namespaces(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
let x = this_node(interp, &this)?;
let list = scope_of(interp, Some(x))?;
namespaces_array(interp, list)
let scope = scope_of(interp, Some(x))?;
namespaces_array(interp, &scope.list)
}
fn namespace_declarations(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
let x = this_node(interp, &this)?;
if interp.xml_kind(x)? != XmlKind::Element {
return namespaces_array(interp, Vec::new());
return namespaces_array(interp, &[]);
}
let parent = interp.xml_node(x)?.parent;
let ancestors: HashMap<Option<Key>, Key> = scope_of(interp, parent)?.into_iter().map(|a| (a.prefix, a.uri)).collect();
let declared: Vec<XmlNs> = interp.xml_node(x)?.ns.iter().filter(|ns| ancestors.get(&ns.prefix) != Some(&ns.uri)).cloned().collect();
namespaces_array(interp, declared)
interp.rooted(&[Value::Object(x)], |interp| {
let parent = interp.xml_node(x)?.parent;
let scope = scope_of(interp, parent)?;
let mut held = HeldBytes::new(interp);
let mut ancestors: HashMap<Option<Key>, Key> = HashMap::new();
for a in &scope.list {
if ancestors.len() == ancestors.capacity() {
let more = grow_table(interp, &mut held, ancestors.len(), size_of::<(Option<Key>, Key)>())?;
ancestors.reserve(more);
}
ancestors.insert(a.prefix.clone(), a.uri.clone());
}
let mut declared: Vec<XmlNs> = Vec::new();
let mut i = 0;
while let Some(ns) = declared_at(interp, x, i)? {
i += 1;
if ancestors.get(&ns.prefix) != Some(&ns.uri) {
push_held(interp, &mut held, &mut declared, ns)?;
}
}
namespaces_array(interp, &declared)
})
}
fn namespace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let x = this_node(interp, &this)?;
let scope = scope_of(interp, Some(x))?;
if let Some(p) = args.first() {
let p = interp.to_str(p)?.flat();
return match scope.into_iter().find(|ns| ns.prefix.as_deref() == Some(&*p)) {
Some(ns) => new_namespace(interp, ns),
let p = str_arg(interp, p)?;
return match scope.list.iter().find(|ns| ns.prefix.as_deref() == Some(&*p)) {
Some(ns) => new_namespace(interp, ns.clone()),
None => Ok(Value::Undefined),
};
}
@@ -734,9 +809,10 @@ fn namespace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRes
let Some(name) = node.name.clone() else { return Ok(Value::Null) };
let uri = name.uri.clone().unwrap_or_else(empty);
let found = scope
.list
.iter()
.find(|ns| ns.uri == uri && ns.prefix == name.prefix)
.or_else(|| scope.iter().find(|ns| ns.uri == uri))
.or_else(|| scope.list.iter().find(|ns| ns.uri == uri))
.cloned()
.unwrap_or(XmlNs { prefix: name.prefix, uri });
new_namespace(interp, found)
@@ -777,7 +853,8 @@ fn node_kind(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult
}
fn normalize(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
for node in nodes_of(interp, &this)? {
let mut held = HeldBytes::new(interp);
for node in nodes_of(interp, &mut held, &this)? {
if interp.xml_kind(node)? == XmlKind::Element {
interp.node_normalize(node)?;
}
@@ -806,7 +883,7 @@ fn parent(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Va
fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let p = arg(args, 0);
let s = interp.to_str(&p)?.flat();
let s = str_arg(interp, &p)?;
match interp.classify(&this) {
Xv::Node(_) => Ok(Value::Bool(canonical_index(&s) == Some(0))),
Xv::List(l) => Ok(Value::Bool(canonical_index(&s).is_some_and(|i| (i as usize) < interp.list_len(l).unwrap_or(0)))),
@@ -814,6 +891,11 @@ fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: b
}
}
/// The attribute `x` holds at index `i`.
fn attr_at(interp: &mut Interp, x: ObjId, i: usize) -> JsResult<Option<ObjId>> {
Ok(interp.xml_node(x)?.attrs.get(i).copied())
}
/// [[AddInScopeNamespace]] (ECMA-357 section 9.1.1.13).
fn add_in_scope(interp: &mut Interp, x: ObjId, ns: XmlNs) -> JsResult<()> {
if interp.xml_kind(x)? != XmlKind::Element {
@@ -823,16 +905,14 @@ fn add_in_scope(interp: &mut Interp, x: ObjId, ns: XmlNs) -> JsResult<()> {
if !ns_binding_allowed(&prefix, &ns.uri) {
return Err(interp.type_error(RESERVED_NS_BINDING));
}
let node = interp.xml_node(x)?;
if prefix.is_empty() && node.name.as_ref().and_then(|n| n.uri.as_ref()).is_some_and(|u| u.is_empty()) {
if prefix.is_empty() && interp.xml_node(x)?.name.as_ref().and_then(|n| n.uri.as_ref()).is_some_and(|u| u.is_empty()) {
return Ok(());
}
if !node.ns.iter().any(|m| m.prefix.as_ref() == Some(&prefix)) {
if !interp.xml_node(x)?.ns.iter().any(|m| m.prefix.as_ref() == Some(&prefix)) {
let bytes = crate::heap::XML_NS_BYTES;
interp.reserve_heap(bytes)?;
interp.heap.bytes = interp.heap.bytes.saturating_add(bytes);
}
let attrs = interp.xml_node(x)?.attrs.clone();
let node = interp.xml_node_mut(x)?;
node.ns.retain(|m| m.prefix.as_ref() != Some(&prefix));
node.ns.push(ns);
@@ -841,8 +921,10 @@ fn add_in_scope(interp: &mut Interp, x: ObjId, ns: XmlNs) -> JsResult<()> {
{
name.prefix = None;
}
for a in attrs {
let mut i = 0;
while let Some(a) = attr_at(interp, x, i)? {
interp.use_fuel()?;
i += 1;
if let Some(name) = &mut interp.xml_node_mut(a)?.name
&& name.prefix.as_ref() == Some(&prefix)
{
@@ -915,25 +997,31 @@ fn insert_child_before(interp: &mut Interp, this: Value, args: &[Value], _: bool
insert_relative(interp, this, args, false)
}
/// One element of a `removeNamespace` walk; true when the walk goes on to its children.
fn remove_ns_from(interp: &mut Interp, x: ObjId, ns: &XmlNs) -> JsResult<bool> {
let node = interp.xml_node(x)?;
let attrs = node.attrs.clone();
if node.name.as_ref().and_then(|n| n.uri.as_ref()) == Some(&ns.uri) {
return Ok(false);
/// Whether the name of element `x` or of one of its attributes is in `ns`, which keeps `ns` on `x`
/// and its descendants in a `removeNamespace` walk.
fn ns_in_use(interp: &mut Interp, x: ObjId, ns: &XmlNs) -> JsResult<bool> {
if interp.xml_node(x)?.name.as_ref().and_then(|n| n.uri.as_ref()) == Some(&ns.uri) {
return Ok(true);
}
for a in attrs {
let mut i = 0;
while let Some(a) = attr_at(interp, x, i)? {
interp.use_fuel()?;
i += 1;
if interp.xml_node(a)?.name.as_ref().and_then(|n| n.uri.as_ref()) == Some(&ns.uri) {
return Ok(false);
return Ok(true);
}
}
Ok(false)
}
/// Removes `ns` from the declarations of element `x`.
fn remove_ns_from(interp: &mut Interp, x: ObjId, ns: &XmlNs) -> JsResult<()> {
let list = &mut interp.xml_node_mut(x)?.ns;
match &ns.prefix {
None => list.retain(|m| m.uri != ns.uri),
Some(p) => list.retain(|m| !(m.uri == ns.uri && m.prefix.as_ref() == Some(p))),
}
Ok(true)
Ok(())
}
fn remove_namespace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
@@ -942,23 +1030,31 @@ fn remove_namespace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -
return Ok(this);
}
let ns = build_namespace(interp, std::slice::from_ref(&arg(args, 0)))?;
if !remove_ns_from(interp, x, &ns)? {
return Ok(this);
}
let mut stack = vec![(x, 0usize)];
while let Some(&(node, next)) = stack.last() {
interp.use_fuel()?;
let Some(c) = interp.xml_node(node)?.children.get(next).copied() else {
stack.pop();
continue;
};
if let Some(frame) = stack.last_mut() {
frame.1 += 1;
interp.rooted(&[Value::Object(x)], |interp| {
if ns_in_use(interp, x, &ns)? {
return Ok(());
}
if interp.xml_kind(c)? == XmlKind::Element && remove_ns_from(interp, c, &ns)? {
stack.push((c, 0));
let mut held = HeldBytes::new(interp);
let mut stack = Vec::new();
push_held(interp, &mut held, &mut stack, (x, 0usize))?;
remove_ns_from(interp, x, &ns)?;
while let Some(&(node, next)) = stack.last() {
interp.use_fuel()?;
let Some(c) = interp.xml_node(node)?.children.get(next).copied() else {
stack.pop();
continue;
};
if let Some(frame) = stack.last_mut() {
frame.1 += 1;
}
if interp.xml_kind(c)? != XmlKind::Element || ns_in_use(interp, c, &ns)? {
continue;
}
push_held(interp, &mut held, &mut stack, (c, 0))?;
remove_ns_from(interp, c, &ns)?;
}
}
Ok(())
})?;
Ok(this)
}
@@ -989,6 +1085,9 @@ fn replace(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResul
};
let matched = i.xml_select(x, &NameRef { attribute: false, ..n })?;
i.xml_keep(matched);
let mut held = HeldBytes::new(i);
let count = i.xml_list(matched)?.items.len();
held.add(i, count.saturating_mul(size_of::<ObjId>()))?;
let items = i.xml_list(matched)?.items.clone();
if items.is_empty() {
return Ok(());
@@ -1020,7 +1119,7 @@ fn set_local_name(interp: &mut Interp, this: Value, args: &[Value], _: bool) ->
let v = arg(args, 0);
let local = match as_qname(interp, &v) {
Some((n, _)) => n.local,
None => interp.to_str(&v)?.flat(),
None => str_arg(interp, &v)?,
};
checked_local(interp, &local)?;
if kind == XmlKind::Attribute
+139 -1
View File
@@ -351,6 +351,10 @@ fn the_xml_methods_behave_as_specified() {
"var x = <a xmlns:p='u'><b/></a>; x.b[0].inScopeNamespaces().length === 1 && x.namespaceDeclarations()[0].prefix === 'p' && x.b[0].namespaceDeclarations().length === 0",
);
truth("var x = <a xmlns:p='u'/>; x.namespace('p').uri === 'u' && x.namespace('q') === undefined && x.namespace().uri === ''");
truth(
"var x = <a xmlns:p='u' xmlns:q='v'><b xmlns:p='w' xmlns:q='v'><c/></b></a>; var c = x.b.c[0]; var s = c.inScopeNamespaces(); var d = x.b[0].namespaceDeclarations(); \
s.length === 2 && c.namespace('p').uri === 'w' && c.namespace('q').uri === 'v' && c.namespace('z') === undefined && d.length === 1 && d[0].prefix === 'p' && d[0].uri === 'w'",
);
truth("var x = <a/>; x.addNamespace(new Namespace('p', 'u')); x.namespace('p').uri === 'u'");
truth("var x = <a xmlns:p='u'/>; x.removeNamespace(new Namespace('p', 'u')); x.namespace('p') === undefined");
truth("var x = <a xmlns:p='u' p:q='1'/>; x.removeNamespace(new Namespace('p', 'u')); x.namespace('p').uri === 'u'");
@@ -1488,7 +1492,12 @@ fn comparing_xml_values_is_charged_to_the_heap() {
/// Runs `setup` with no limit, then `action` in the same realm, and returns how `action` ended.
fn after_setup(setup: &str, action: &str) -> Result<JsValue, RunErrorKind> {
let mut r = realm();
after_setup_with(e4x(), setup, action)
}
/// [`after_setup`] in a realm with `options`.
fn after_setup_with(options: Options, setup: &str, action: &str) -> Result<JsValue, RunErrorKind> {
let mut r = Realm::with_options(options, Limits::default());
let interp = r.interp();
let global = interp.global;
assert!(crate::builtins::method(interp, global, "squeeze", squeeze, 1).is_ok());
@@ -1512,6 +1521,135 @@ fn namespace_declarations_and_qname_strings_are_charged_to_the_heap() {
assert_eq!(after_setup(long, action), heap);
}
#[test]
fn namespace_scopes_are_charged_to_the_heap() {
let heap = Err(RunErrorKind::Limit(LimitKind::Heap));
let setup = "var x = <r><b><c/></b></r>; for (var i = 0; i < 2000; i++) x.addNamespace(new Namespace('p' + i, 'u' + i)); \
var b = x.b[0]; b.c[0].setNamespace(new Namespace('u7'));";
for (action, ample) in [
("b.namespace('p1999').uri", JsValue::String("u1999".into())),
("b.namespaceDeclarations().length", JsValue::Number(0.0)),
("b.inScopeNamespaces().length", JsValue::Number(2000.0)),
("x.xpath('b[namespace::p1999]').length()", JsValue::Number(1.0)),
("b.xpath('p5:c').length()", JsValue::Number(0.0)),
("b.xpath(\"*[name() = 'p7:c']\").length()", JsValue::Number(1.0)),
] {
assert_eq!(after_setup(setup, &format!("squeeze(16384); {action}")), heap, "{action}");
assert_eq!(after_setup(setup, action), Ok(ample.clone()), "{action}");
// The scope reads the same bindings after the script has left garbage to collect.
let churn = format!("squeeze(2000000); for (var i = 0; i < 3000; i++) [i]; {action}");
assert_eq!(after_setup(setup, &churn), Ok(ample), "{action}");
}
}
#[test]
fn namespace_edits_read_attributes_in_place_and_charge_their_walk() {
let heap = Err(RunErrorKind::Limit(LimitKind::Heap));
let wide = "var s = '<r xmlns:q=\"v\"'; for (var i = 0; i < 4000; i++) s += ' a' + i + '=\"v\"'; var x = new XML(s + '/>'); \
var n = new Namespace('q', 'v'); var m = new Namespace('s', 'w');";
let deep = "var s = '<r xmlns:q=\"v\">'; for (var i = 0; i < 2000; i++) s += '<d>'; for (var i = 0; i < 2000; i++) s += '</d>'; \
var x = new XML(s + '</r>'); var n = new Namespace('q', 'v');";
let removed = "x.removeNamespace(n); x.namespace('q') === undefined";
// An element's attributes are read where they are, so 4,000 of them need no room; the walk of a
// deep tree is held against the limit.
for (tree, setup, action, ample, squeezed) in [
("wide", wide, "x.addNamespace(m); x.namespace('s').uri", JsValue::String("w".into()), false),
("wide", wide, removed, JsValue::Bool(true), false),
("deep", deep, removed, JsValue::Bool(true), true),
] {
let options = Options { max_depth: 1_000_000, ..e4x() };
let want = if squeezed { heap.clone() } else { Ok(ample.clone()) };
assert_eq!(after_setup_with(options.clone(), setup, &format!("squeeze(4096); {action}")), want, "{tree}: {action}");
assert_eq!(after_setup_with(options, setup, action), Ok(ample), "{tree}: {action}");
}
}
#[test]
fn xml_list_methods_charge_their_copies_to_the_heap() {
let heap = Err(RunErrorKind::Limit(LimitKind::Heap));
let setup = "var x = <r/>; for (var i = 0; i < 4000; i++) x.appendChild(<a/>); var l = x.a;";
for (action, ample) in [
("l.child(0).length()", JsValue::Number(0.0)),
("l.comments().length()", JsValue::Number(0.0)),
("l.normalize().length()", JsValue::Number(4000.0)),
] {
assert_eq!(after_setup(setup, &format!("squeeze(4096); {action}")), heap, "{action}");
assert_eq!(after_setup(setup, action), Ok(ample), "{action}");
}
}
/// The least spare heap, found by bisection, at which `action` ends without the heap limit after
/// `setup`.
fn least_spare(setup: &str, action: &str) -> usize {
let (mut lo, mut hi) = (0usize, 1usize << 22);
assert!(after_setup(setup, &format!("squeeze({hi}); {action}")).is_ok(), "{action}");
while lo < hi {
let mid = lo + (hi - lo) / 2;
match after_setup(setup, &format!("squeeze({mid}); {action}")) {
Ok(_) => hi = mid,
Err(RunErrorKind::Limit(LimitKind::Heap)) => lo = mid + 1,
Err(e) => panic!("{action}: {e:?}"),
}
}
lo
}
#[test]
fn replace_charges_its_copy_of_the_matches_to_the_heap() {
let setup = "var x = <r/>; for (var i = 0; i < 4000; i++) x.appendChild(<a/>);";
let action = "x.replace('a', 'z'); x.children().length()";
let select = least_spare(setup, "x.a.length()");
let replace = least_spare(setup, action);
assert!(replace >= select + 4000 * 4, "select {select}, replace {replace}");
assert_eq!(after_setup(setup, action), Ok(JsValue::Number(1.0)));
}
#[test]
fn xpath_qualified_names_are_charged_to_the_heap() {
let setup = "var s = 'a'; for (var i = 0; i < 14; i++) s += s; var x = <r xmlns:p='u'><c/></r>; var c = x.c[0]; \
c.setLocalName(s); c.setNamespace(new Namespace('u'));";
let action = "x.xpath('*[string-length(name()) = 16386]').length()";
assert_eq!(after_setup(setup, &format!("squeeze(16384); {action}")), Err(RunErrorKind::Limit(LimitKind::Heap)));
assert_eq!(after_setup(setup, action), Ok(JsValue::Number(1.0)));
}
#[test]
fn xml_methods_charge_the_strings_they_flatten() {
let heap = Err(RunErrorKind::Limit(LimitKind::Heap));
// `s` and `t` are ropes of 32,768 and 49,152 units; `f` is a flat string that starts with `@`.
let setup = "var s = 'a'; for (var i = 0; i < 15; i++) s += s; var t = 'a b'; for (var i = 0; i < 14; i++) t += t; \
var f = '@' + s; isXMLName(f); var x = <r><c/></r>; var c = x.c[0];";
let mut wrong = Vec::new();
for (action, ample) in [
("x.addNamespace(s); 1", JsValue::Number(1.0)),
("new Namespace(t, 'u').prefix", JsValue::Undefined),
("c.setName(s); 1", JsValue::Number(1.0)),
("isXMLName(s)", JsValue::Bool(true)),
("x.attribute(s).length()", JsValue::Number(0.0)),
("x.attribute(f).length()", JsValue::Number(0.0)),
("x.namespace(s) === undefined", JsValue::Bool(true)),
("x.propertyIsEnumerable(s)", JsValue::Bool(false)),
("c.setLocalName(s); 1", JsValue::Number(1.0)),
] {
let squeezed = after_setup(setup, &format!("squeeze(16384); {action}"));
if squeezed != heap {
wrong.push(format!("{action} with 16384 spare: {squeezed:?}"));
}
assert_eq!(after_setup(setup, action), Ok(ample), "{action}");
}
// Parsing a rope needs room for its flat copy on top of what parsing the same flat text needs.
let text = "var k = 'x'; for (var i = 0; i < 15; i++) k += k; var s = '<a><!--' + k + '--></a>'; \
var g = '<a><!--' + k + '--></a>'; isXMLName(g);";
for ctor in ["XML", "XMLList"] {
let rope = least_spare(text, &format!("new {ctor}(s); 1"));
let flat = least_spare(text, &format!("new {ctor}(g); 1"));
if rope < flat + 32768 {
wrong.push(format!("new {ctor} needs {rope} spare for a rope and {flat} for flat text"));
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
#[test]
fn an_interrupt_stops_serialization() {
let mut r = realm();
+27 -23
View File
@@ -1472,13 +1472,14 @@ impl<'p> Ev<'p> {
let xml = key("xml");
let mut at = 0u32;
let mut has_xml = false;
for ns in scope_of(interp, Some(*x))? {
let Some(prefix) = ns.prefix else { continue };
let scope = scope_of(interp, Some(*x))?;
for ns in &scope.list {
let Some(prefix) = ns.prefix.clone() else { continue };
if prefix.is_empty() && ns.uri.is_empty() {
continue;
}
has_xml |= prefix == xml;
self.add(interp, out, axis, test, XNode::Ns { owner: *x, at, prefix, uri: ns.uri })?;
self.add(interp, out, axis, test, XNode::Ns { owner: *x, at, prefix, uri: ns.uri.clone() })?;
at += 1;
}
if !has_xml {
@@ -1867,7 +1868,7 @@ impl<'p> Ev<'p> {
prefix
}
}
Some(XNode::Node(x)) => node_name(interp, f, x)?,
Some(XNode::Node(x)) => return node_name(interp, f, x),
};
Ok(Text::plain(interp, units))
}
@@ -2179,7 +2180,7 @@ impl<'p> Ev<'p> {
let uri = if units_are(p, "xml") {
key(XML_URI)
} else {
match scope.iter().find(|ns| ns.prefix.as_ref() == Some(p)) {
match scope.list.iter().find(|ns| ns.prefix.as_ref() == Some(p)) {
Some(ns) if !ns.uri.is_empty() => ns.uri.clone(),
_ => {
let shown = String::from_utf16_lossy(p);
@@ -2213,24 +2214,26 @@ impl<'p> Ev<'p> {
}
}
fn node_name(interp: &mut Interp, f: Func, x: ObjId) -> JsResult<Key> {
fn node_name(interp: &mut Interp, f: Func, x: ObjId) -> JsResult<Text> {
let node = interp.xml_node(x)?;
let (kind, parent) = (node.kind, node.parent);
let Some(name) = node.name.clone() else { return Ok(empty()) };
match (f, kind) {
(_, XmlKind::Text | XmlKind::Comment) => Ok(empty()),
(Func::NamespaceUri, XmlKind::Pi) => Ok(empty()),
(Func::NamespaceUri, _) => Ok(Rc::from(name_uri(&name))),
(Func::LocalName, _) | (_, XmlKind::Pi) => Ok(name.local),
_ => qualified_name(interp, x, parent, &name, kind == XmlKind::Attribute),
}
let Some(name) = node.name.clone() else { return Ok(Text::plain(interp, empty())) };
let units = match (f, kind) {
(_, XmlKind::Text | XmlKind::Comment) => empty(),
(Func::NamespaceUri, XmlKind::Pi) => empty(),
(Func::NamespaceUri, _) => Rc::from(name_uri(&name)),
(Func::LocalName, _) | (_, XmlKind::Pi) => name.local,
_ => return qualified_name(interp, x, parent, &name, kind == XmlKind::Attribute),
};
Ok(Text::plain(interp, units))
}
/// An element's or attribute's name as a QName, with a prefix declared for its namespace.
fn qualified_name(interp: &mut Interp, x: ObjId, parent: Option<ObjId>, name: &XmlName, attribute: bool) -> JsResult<Key> {
/// An element's or attribute's name as a QName, with a prefix declared for its namespace. The units
/// of a prefixed name are held against the heap limit while the text lives.
fn qualified_name(interp: &mut Interp, x: ObjId, parent: Option<ObjId>, name: &XmlName, attribute: bool) -> JsResult<Text> {
let uri = name_uri(name);
if uri.is_empty() {
return Ok(name.local.clone());
return Ok(Text::plain(interp, name.local.clone()));
}
let prefix = if units_are(uri, XML_URI) {
key("xml")
@@ -2240,17 +2243,18 @@ fn qualified_name(interp: &mut Interp, x: ObjId, parent: Option<ObjId>, name: &X
_ => {
let scope = scope_of(interp, if attribute { parent } else { Some(x) })?;
let usable = |ns: &XmlNs| *ns.uri == *uri && ns.prefix.as_ref().is_some_and(|p| !(attribute && p.is_empty()));
scope.into_iter().find(usable).and_then(|ns| ns.prefix).unwrap_or_else(empty)
scope.list.iter().find(|ns| usable(ns)).and_then(|ns| ns.prefix.clone()).unwrap_or_else(empty)
}
}
};
if prefix.is_empty() {
return Ok(name.local.clone());
return Ok(Text::plain(interp, name.local.clone()));
}
let mut units = prefix.to_vec();
units.push(COLON);
units.extend_from_slice(&name.local);
Ok(Rc::from(units))
let mut buf = TextBuf::new(interp);
buf.push(interp, &prefix)?;
buf.push(interp, &[COLON])?;
buf.push(interp, &name.local)?;
Ok(buf.finish())
}
/// The first index where `needle` occurs in `hay`. Every position tried takes fuel.
+78
View File
@@ -313,6 +313,84 @@ fn window_captures_take_max_side() {
assert!(r["content"][0]["text"].as_str().unwrap().contains("`scale`"), "{r}");
}
/// The path an app from before `ui.screenshot {data}` was sent, with the mode of the folder holding
/// it on unix (`None` elsewhere).
type SeenPaths = std::sync::Arc<std::sync::Mutex<Vec<(String, Option<u32>)>>>;
/// An app from before `ui.screenshot {data}`: it writes `png` (nothing when `None`) to the `path`
/// it is sent, keeps the path in `seen` and answers `reply`. A capture without a path is answered
/// with its size alone.
struct OldWindow {
png: Option<Vec<u8>>,
reply: Result<Value, String>,
seen: SeenPaths,
}
impl Backend for OldWindow {
fn call(&mut self, method: &str, p: Value) -> Result<Value, String> {
if method != "ui.screenshot" {
return Err(format!("unexpected {method}"));
}
// Without a path it ignores `data` and sends the size alone.
let Some(path) = p["path"].as_str().map(str::to_owned) else { return Ok(json!({"width": 2, "height": 1})) };
#[cfg(unix)]
let mode = {
use std::os::unix::fs::PermissionsExt as _;
std::path::Path::new(&path).parent().and_then(|d| std::fs::metadata(d).ok()).map(|m| m.permissions().mode() & 0o777)
};
#[cfg(not(unix))]
let mode = None;
self.seen.lock().unwrap().push((path.clone(), mode));
if let Some(png) = &self.png {
std::fs::write(&path, png).map_err(|e| format!("{path}: {e}"))?;
}
self.reply.clone()
}
fn has_ui(&self) -> bool {
true
}
fn describe(&self) -> String {
"old window".into()
}
}
/// An app without `ui.screenshot {data}` writes the window capture to a file in a new folder of its
/// own inside the system's temporary folder (owner-only on unix), never to a fixed name in the
/// shared folder itself. The folder is removed after the capture is read, and also when the app
/// fails after writing it or the file can't be read.
#[test]
fn an_old_app_captures_the_window_in_a_new_private_folder() {
let temp = std::env::temp_dir();
let png = b"window capture".to_vec();
let size = json!({"width": 2, "height": 1});
let mut folders = Vec::new();
for (written, reply, ok) in [
(Some(png.clone()), Ok(size.clone()), true),
(Some(png.clone()), Ok(size.clone()), true),
(Some(png.clone()), Err("the capture failed".to_string()), false),
(None, Ok(size.clone()), false),
] {
let seen = SeenPaths::default();
let mut s = Server::new(Box::new(OldWindow { png: written, reply, seen: seen.clone() }));
let r = call(&mut s, "screenshot", json!({"window": true}));
assert_eq!(r["isError"], !ok, "{r}");
if ok {
assert_eq!(vectorcraft_format::base64_decode(r["content"][0]["data"].as_str().unwrap()).unwrap(), png, "{r}");
}
let seen = seen.lock().unwrap().clone();
let [(path, mode)] = seen.as_slice() else { panic!("one capture: {seen:?}") };
let dir = std::path::Path::new(path).parent().unwrap().to_path_buf();
assert_eq!(dir.parent(), Some(temp.as_path()), "{path} is in a folder of its own inside {}", temp.display());
assert!(!dir.exists(), "{} is removed", dir.display());
if cfg!(unix) {
assert_eq!(*mode, Some(0o700), "{path}");
}
folders.push(dir);
}
folders.sort();
folders.dedup();
assert_eq!(folders.len(), 4, "each capture has a new folder: {folders:?}");
}
/// Each tool with another name for the same call names it in its description.
#[test]
fn alias_tools_name_their_pair() {
+40 -6
View File
@@ -437,18 +437,52 @@ pub(super) fn screenshot(b: &mut dyn Backend, a: &Args) -> Result<ToolResult, St
}
}
/// The window of an app from before `ui.screenshot {data}`, captured through a temporary file.
/// The window of an app from before `ui.screenshot {data}`, captured through a temporary file in a
/// new folder of its own inside the system's temporary folder ([`new_capture_folder`]). The folder
/// and everything in it are removed once the capture is read, and also when the app or the read
/// fails.
fn old_window_capture(b: &mut dyn Backend, max: Option<u32>) -> Result<ToolResult, String> {
let tmp = std::env::temp_dir().join(format!("vectorcraft-window-{}.png", std::process::id())).to_string_lossy().to_string();
let r = b.call("ui.screenshot", json!({"path": tmp}))?;
let png = std::fs::read(&tmp).map_err(|e| format!("read {tmp}: {e}"))?;
// Best effort: a temporary file left behind is harmless.
std::fs::remove_file(&tmp).ok();
let dir = new_capture_folder(&std::env::temp_dir())?;
let tmp = dir.join("window.png").to_string_lossy().to_string();
let captured = b.call("ui.screenshot", json!({"path": tmp})).and_then(|r| Ok((std::fs::read(&tmp).map_err(|e| format!("read {tmp}: {e}"))?, r)));
// Best effort: a folder that can't be removed holds only this capture, and on unix only its
// owner can open it.
let _ = std::fs::remove_dir_all(&dir);
let (png, r) = captured?;
let mut info = json!({"window": true, "width": r.get("width"), "height": r.get("height"), "path": Value::Null});
let png = fit_capture(png, max, &mut info)?;
Ok(image_result(&png, info))
}
/// A new folder in `parent` named `vectorcraft-window-` followed by the process id, `-` and a count
/// of the process's captures; on unix only its owner can open it. A name that is already taken, by
/// an earlier process with the same id or by anyone else, is skipped for the next count.
fn new_capture_folder(parent: &std::path::Path) -> Result<std::path::PathBuf, String> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
loop {
let dir = parent.join(format!("vectorcraft-window-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
match private_folder().create(&dir) {
Ok(()) => return Ok(dir),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(format!("{}: {e}", dir.display())),
}
}
}
/// A builder for folders that only their owner can read, write or open (mode 0o700).
#[cfg(unix)]
fn private_folder() -> std::fs::DirBuilder {
let mut b = std::fs::DirBuilder::new();
std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);
b
}
/// A builder for folders: a plain one outside unix.
#[cfg(not(unix))]
fn private_folder() -> std::fs::DirBuilder {
std::fs::DirBuilder::new()
}
/// `max_side`: absent, or an integer in 1..4096.
pub(super) fn max_side(a: &Args) -> Result<Option<u32>, String> {
match a.get("max_side") {
+1 -1
View File
@@ -1258,7 +1258,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.smoothAuto",
"Auto-Smooth",
"",
"{} the open Smooth slider (Object › Path › Smooth opens 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 and the canvas context menu'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",
),
(
"ui.simplifyMoreOptions",
+31 -4
View File
@@ -5,8 +5,11 @@
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::{Path, PathBuf};
mod common;
use std::path::Path;
use common::TempFolder;
use serde_json::{Value, json};
use vectorcraft_engine::file_access::AutomationRoots;
use vectorcraft_mcp::{Headless, Server};
@@ -14,9 +17,10 @@ use vectorcraft_mcp::{Headless, Server};
const SVG: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="30"><rect width="20" height="10" fill="red"/></svg>"#;
/// A folder holding `in` (the read root, with `a.svg`), `out` (the write root), `outside` (with
/// `b.svg`) and `in2`, and a server confined to `in` and `out` (either may be left out).
fn confined(tag: &str, read: bool, write: bool) -> (Server, PathBuf) {
let base = vectorcraft_testkit::temp_dir(&format!("roots-{tag}"));
/// `b.svg`) and `in2`, and a server confined to `in` and `out` (either may be left out). The
/// folder is removed when the returned [`TempFolder`] is dropped.
fn confined(tag: &str, read: bool, write: bool) -> (Server, TempFolder) {
let base = TempFolder::new(&format!("roots-{tag}"));
for d in ["in", "out", "outside", "in2"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
@@ -55,6 +59,29 @@ fn refused(server: &mut Server, name: &str, args: Value, why: &str) {
assert!(error && text.contains(why), "{name} {args} should be refused ({why}): {text}");
}
/// A `TempFolder` is removed with the files and folders in it when dropped, also when the test
/// that holds it panics.
#[test]
fn temp_folders_are_removed_when_dropped() {
let dir = TempFolder::new("roots-drop-check");
std::fs::create_dir(dir.join("sub")).unwrap();
std::fs::write(dir.join("sub/a.svg"), SVG).unwrap();
let path = dir.to_path_buf();
drop(dir);
assert!(!path.exists(), "{} is removed", path.display());
let mut held = None;
let panicked = vectorcraft_testkit::catch_quiet(|| {
let dir = TempFolder::new("roots-panic-check");
std::fs::write(dir.join("a.svg"), SVG).unwrap();
held = Some(dir.to_path_buf());
panic!("the test fails with {} in use", dir.display());
});
assert!(panicked.is_err());
let path = held.unwrap();
assert!(!path.exists(), "{} is removed after a panic", path.display());
}
#[test]
fn files_open_only_from_inside_the_read_root() {
let (mut server, base) = confined("open", true, true);
+28
View File
@@ -0,0 +1,28 @@
//! Shared helpers for the MCP integration tests.
use std::path::{Path, PathBuf};
/// A test's own folder, made by [`vectorcraft_testkit::temp_dir`] (with its checks against a
/// folder made by someone else) and removed with everything in it when dropped, also when the
/// test panics. A removal that fails (a file still open) is ignored. Tests that run at the same
/// time use different tags.
pub struct TempFolder(PathBuf);
impl TempFolder {
pub fn new(tag: &str) -> Self {
Self(vectorcraft_testkit::temp_dir(tag))
}
}
impl std::ops::Deref for TempFolder {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
impl Drop for TempFolder {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
+5 -2
View File
@@ -4,6 +4,9 @@
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod common;
use common::TempFolder;
use proptest::prelude::*;
use serde_json::{Value, json};
use vectorcraft_doc::Document;
@@ -98,7 +101,7 @@ fn tool_definitions_are_valid() {
#[test]
fn every_tool_survives_empty_and_junk_arguments() {
let dir = vectorcraft_testkit::temp_dir("mcp-junk");
let dir = TempFolder::new("mcp-junk");
let safe = dir.join("junk.vectorcraft").to_string_lossy().to_string();
let mut failures = vec![];
for t in tool_definitions() {
@@ -169,7 +172,7 @@ proptest! {
tail in junk_tail(),
tool in prop::sample::select(vec!["open_file", "save_file", "export", "screenshot"]),
) {
let base = vectorcraft_testkit::temp_dir("mcp-confined");
let base = TempFolder::new("mcp-confined");
let root = base.join("a/b/c/root");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(base.join("outside")).unwrap();
+476 -80
View File
@@ -3,7 +3,7 @@
//! nearly closed paths; [`near_point_groups`] finds anchors to snap together, and [`rejoin`] welds
//! open pieces whose ends meet back into paths.
use std::collections::HashMap;
use std::collections::{BTreeSet, HashMap};
use kurbo::{Point, Vec2};
use vectorcraft_geom::{Anchor, AnchorKind, EPS, SubPath};
@@ -23,24 +23,64 @@ fn moved(p: Point, a_p: Point, h: Point) -> Point {
/// Remove the corner anchors (no handles, straight segments both sides) where a straight run goes
/// on in the same direction: the sine of the angle it turns there is at most `tolerance`. Open ends
/// stay, and a subpath keeps two anchors (three when closed) → how many went.
///
/// Each anchor is tested once, first to last, against the nearest anchors still kept on either
/// side. On a closed subpath, an anchor with none kept before it has the last anchor as its
/// previous neighbor, and the last anchor has the first one kept as its next neighbor. The kept
/// anchors move into place once at the end, so the work grows linearly with the number of anchors.
pub fn remove_collinear_anchors(sp: &mut SubPath, tolerance: f64) -> usize {
let mut removed = 0;
let mut i = 0;
while i < sp.anchors.len() && sp.anchors.len() > min_anchors(sp) {
let n = sp.anchors.len();
let inner = sp.closed || (i > 0 && i + 1 < n);
let (Some(prev), Some(cur), Some(next)) = (sp.anchors.get((i + n - 1) % n), sp.anchors.get(i), sp.anchors.get((i + 1) % n)) else { break };
let n = sp.anchors.len();
let min = min_anchors(sp);
if n <= min {
return 0;
}
let mut keep = vec![true; n];
let (mut left, mut first_kept, mut last_kept) = (n, None, None);
#[cfg(test)]
let mut work = 0;
for i in 0..n {
if left <= min {
break;
}
#[cfg(test)]
{
work += 1;
}
// Every anchor after `i` is still there, the last one included.
let p = last_kept.unwrap_or(n - 1);
let q = if i + 1 < n { i + 1 } else { first_kept.unwrap_or(i) };
let inner = sp.closed || (last_kept.is_some() && i + 1 < n);
let (Some(prev), Some(cur), Some(next)) = (sp.anchors.get(p), sp.anchors.get(i), sp.anchors.get(q)) else { break };
let straight = !prev.has_out() && !cur.has_in() && !cur.has_out() && !next.has_in();
let (a, b) = (cur.p - prev.p, next.p - cur.p);
let len = a.hypot() * b.hypot();
if inner && straight && len > EPS && a.dot(b) > 0.0 && a.cross(b).abs() / len <= tolerance {
sp.anchors.remove(i);
removed += 1;
if let Some(k) = keep.get_mut(i) {
*k = false;
}
left -= 1;
} else {
i += 1;
first_kept.get_or_insert(i);
last_kept = Some(i);
}
}
removed
if left < n {
let mut kept = keep.iter();
sp.anchors.retain(|_| kept.next().copied().unwrap_or(true));
#[cfg(test)]
{
work += n;
}
}
#[cfg(test)]
COLLINEAR_WORK.with(|w| w.set(work));
n - left
}
#[cfg(test)]
thread_local! {
/// Anchors tested plus anchors moved by the last [`remove_collinear_anchors`] on this thread.
static COLLINEAR_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Merge each anchor lying within `distance` of the one before it (and a closed subpath's last
@@ -101,58 +141,203 @@ pub fn close_nearly_closed(sp: &mut SubPath, distance: f64) -> bool {
true
}
/// The cell of a grid of `size`-wide squares that `p` lies in.
fn grid_cell(p: Point, size: f64) -> (i64, i64) {
((p.x / size).floor() as i64, (p.y / size).floor() as i64)
}
/// The cell `(x, y)` and the cells around it, each once.
fn around((x, y): (i64, i64)) -> Vec<(i64, i64)> {
let mut out: Vec<(i64, i64)> = [-1, 0, 1].into_iter().flat_map(|dx| [-1, 0, 1].map(|dy| (x.saturating_add(dx), y.saturating_add(dy)))).collect();
out.sort_unstable();
out.dedup();
out
}
/// The root of `i`'s set in the union-find forest `parent`.
fn root(parent: &mut [usize], mut i: usize) -> usize {
while let Some(&p) = parent.get(i).filter(|&&p| p != i) {
let up = parent.get(p).copied().unwrap_or(p);
if let Some(slot) = parent.get_mut(i) {
*slot = up;
}
i = p;
}
i
}
/// Groups of `points` to snap together: points within `distance` of one another (and so on, one
/// to the next) that aren't all at the same place, skipping the pairs `linked` names (such as
/// neighbouring anchors of one path). Each group lists its points in order; snapping them all to
/// the first one makes them coincide. Non-finite points and a distance that isn't a positive number
/// find nothing.
///
/// Two points are compared when their cells of a `distance`-wide grid touch. Each group grows from
/// one point at a time, which looks only at points no group has taken yet, so a cluster of points
/// all within `distance` of one another is grouped with work that grows linearly with its size.
pub fn near_point_groups(points: &[Point], distance: f64, linked: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> {
if !(distance > 0.0 && distance.is_finite()) {
return vec![];
}
let cell = |p: Point| ((p.x / distance).floor() as i64, (p.y / distance).floor() as i64);
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
for (i, p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) {
grid.entry(cell(*p)).or_default().push(i);
}
let mut parent: Vec<usize> = (0..points.len()).collect();
fn root(parent: &mut [usize], mut i: usize) -> usize {
while let Some(&p) = parent.get(i).filter(|&&p| p != i) {
let up = parent.get(p).copied().unwrap_or(p);
if let Some(slot) = parent.get_mut(i) {
*slot = up;
}
i = p;
let mut cells = buckets(points, distance);
let mut near = Near {
distance,
linked,
parent: (0..points.len()).collect(),
taken: points.iter().map(|p| !p.is_finite()).collect(),
queue: vec![],
#[cfg(test)]
work: 0,
};
for (start, &p) in points.iter().enumerate() {
if near.taken.get(start) != Some(&false) {
continue;
}
i
}
for (&(cx, cy), members) in &grid {
for (dx, dy) in [(0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] {
let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue };
for &i in members {
for &j in others.iter().filter(|&&j| (dx, dy) != (0, 0) || j > i) {
let (Some(a), Some(b)) = (points.get(i), points.get(j)) else { continue };
let d = a.distance(*b);
if d <= distance && d > 0.0 && !linked(i.min(j), i.max(j)) {
let (ri, rj) = (root(&mut parent, i), root(&mut parent, j));
if let Some(slot) = parent.get_mut(ri.max(rj)) {
*slot = ri.min(rj);
}
}
}
}
if let Some(t) = near.taken.get_mut(start) {
*t = true;
}
let mut at = Some((start, p));
while let Some((i, p)) = at {
near.reach(&mut cells, i, p);
at = near.queue.pop().and_then(|j| Some((j, *points.get(j)?)));
}
}
#[cfg(test)]
NEAR_WORK.with(|w| w.set(near.work));
// Only pairs that aren't at the same place were joined, so no group is all at one place.
let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
for i in 0..points.len() {
groups.entry(root(&mut parent, i)).or_default().push(i);
groups.entry(root(&mut near.parent, i)).or_default().push(i);
}
let mut out: Vec<Vec<usize>> = groups.into_values().filter(|g| g.len() > 1).collect();
out.sort_unstable();
out
}
#[cfg(test)]
thread_local! {
/// Buckets, places and points looked at by the last [`near_point_groups`] on this thread.
static NEAR_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The finite points of one cell of a grid that lie in one square a quarter of a cell wide, with
/// the box around them.
struct Bucket {
lo: Point,
hi: Point,
/// Each place (bit for bit) and the points there that no group has taken yet, though some of
/// them may have been taken since.
places: Vec<(Point, Vec<usize>)>,
}
impl Bucket {
/// Whether [`Point::distance`] puts every point here further than `distance` from `p`: one
/// coordinate alone differs by more. The square of a `distance` of 1e-150 or more does not
/// underflow, so the measured distance is at least that difference.
fn beyond(&self, p: Point, distance: f64) -> bool {
distance >= 1e-150 && [self.lo.x - p.x, p.x - self.hi.x, self.lo.y - p.y, p.y - self.hi.y].into_iter().any(|g| g > distance)
}
}
/// The finite `points` in buckets, by grid cell.
fn buckets(points: &[Point], distance: f64) -> HashMap<(i64, i64), Vec<Bucket>> {
let quarter = distance / 4.0;
let mut cells: HashMap<(i64, i64), Vec<Bucket>> = HashMap::new();
// Each bucket by its cell and square, and each place by its cell, bucket and coordinates.
let mut bucket_at: HashMap<[i64; 4], usize> = HashMap::new();
let mut place_at: HashMap<(usize, [i64; 2], [u64; 2]), usize> = HashMap::new();
for (i, &p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) {
let c = grid_cell(p, distance);
let list = cells.entry(c).or_default();
let square = grid_cell(p, quarter);
let b = *bucket_at.entry([c.0, c.1, square.0, square.1]).or_insert_with(|| {
list.push(Bucket { lo: p, hi: p, places: vec![] });
list.len() - 1
});
let Some(bucket) = list.get_mut(b) else { continue };
bucket.lo = Point::new(bucket.lo.x.min(p.x), bucket.lo.y.min(p.y));
bucket.hi = Point::new(bucket.hi.x.max(p.x), bucket.hi.y.max(p.y));
let at = *place_at.entry((b, [c.0, c.1], [p.x.to_bits(), p.y.to_bits()])).or_insert_with(|| {
bucket.places.push((p, vec![]));
bucket.places.len() - 1
});
if let Some((_, here)) = bucket.places.get_mut(at) {
here.push(i);
}
}
cells
}
/// The grouping behind [`near_point_groups`].
struct Near<F> {
distance: f64,
linked: F,
/// The union-find forest of the groups.
parent: Vec<usize>,
/// Whether each point is in a group being grown or grown already (non-finite ones never are).
taken: Vec<bool>,
/// Points taken into the group being grown whose own neighbors are still to be looked at.
queue: Vec<usize>,
#[cfg(test)]
work: usize,
}
impl<F: Fn(usize, usize) -> bool> Near<F> {
/// Take into `i`'s group every point no group has taken yet that lies within the distance of
/// `p`, `i`'s place, in the cells around it, at a different place and not linked to `i`.
fn reach(&mut self, cells: &mut HashMap<(i64, i64), Vec<Bucket>>, i: usize, p: Point) {
for c in around(grid_cell(p, self.distance)) {
let Some(buckets) = cells.get_mut(&c) else { continue };
buckets.retain_mut(|b| {
#[cfg(test)]
{
self.work += 1;
}
if !b.beyond(p, self.distance) {
b.places.retain_mut(|place| {
self.visit(i, p, place);
!place.1.is_empty()
});
}
!b.places.is_empty()
});
}
}
/// Take into `i`'s group the points at `place` that `i` joins, and drop the ones taken.
fn visit(&mut self, i: usize, p: Point, (at, here): &mut (Point, Vec<usize>)) {
#[cfg(test)]
{
self.work += 1;
}
let d = p.distance(*at);
if !(d <= self.distance && d > 0.0) {
return;
}
here.retain(|&j| {
if self.taken.get(j) != Some(&false) {
return false;
}
#[cfg(test)]
{
self.work += 1;
}
if (self.linked)(i.min(j), i.max(j)) {
return true;
}
let (ri, rj) = (root(&mut self.parent, i), root(&mut self.parent, j));
if let Some(slot) = self.parent.get_mut(ri.max(rj)) {
*slot = ri.min(rj);
}
if let Some(t) = self.taken.get_mut(j) {
*t = true;
}
self.queue.push(j);
false
});
}
}
/// Open pieces welded into one path by [`rejoin`]: `members` index the pieces in the order they
/// run along `path`.
#[derive(Clone, Debug, PartialEq)]
@@ -179,6 +364,12 @@ fn outward(sp: &SubPath, last: bool) -> Option<Vec2> {
/// Each junction keeps the earlier piece's anchor and the later piece's out handle. Pieces that are
/// closed, have fewer than two anchors or a non-finite coordinate stay out. → the chains of two or
/// more pieces, and the single pieces that closed.
///
/// Two ends are compared when their cells of a `gap`-wide grid touch, and pairs are taken in order
/// of the turn, then the distance, then the order of the ends. Each end looks for its first
/// partner in that order among the ends still free, searching outward from the reverse of its own
/// direction, and two ends that are each other's first partner meet; these are the pairs that
/// taking every pair in that order gives.
pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec<Rejoined> {
if !(gap >= 0.0 && gap.is_finite()) {
return vec![];
@@ -187,7 +378,7 @@ pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec<Rejoined> {
!sp.closed && sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite())
};
// Each usable end: where it is and the way out of its piece there.
let ends: Vec<(End, Point, Vec2)> = pieces
let ends: Vec<EndAt> = pieces
.iter()
.enumerate()
.filter(|(_, sp)| usable(sp))
@@ -197,49 +388,254 @@ pub fn rejoin(pieces: &[SubPath], gap: f64) -> Vec<Rejoined> {
Some(((i, last), a.p, outward(sp, last)?))
})
.collect();
let points: Vec<Point> = ends.iter().map(|e| e.1).collect();
// Every pair of ends within the gap, by the turn across the junction.
let mut pairs: Vec<(f64, f64, End, End)> = vec![];
for (a, b) in candidate_pairs(&points, gap.max(1e-9)) {
let (Some(&(ea, pa, oa)), Some(&(eb, pb, ob))) = (ends.get(a), ends.get(b)) else { continue };
// A piece's own two ends meet only when closing it leaves a shape (three anchors).
if ea.0 == eb.0 && pieces.get(ea.0).is_none_or(|sp| sp.anchors.len() < 3) {
continue;
}
let d = pa.distance(pb);
if d <= gap {
pairs.push((oa.dot(-ob).clamp(-1.0, 1.0).acos(), d, ea, eb));
}
}
pairs.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1)));
let mut link: HashMap<End, End> = HashMap::new();
for (_, _, a, b) in pairs {
if !link.contains_key(&a) && !link.contains_key(&b) {
link.insert(a, b);
link.insert(b, a);
}
}
let link = Weld::new(pieces, &ends, gap).link();
chains(pieces, &link)
}
/// Pairs (a < b) of `points` that may lie within `gap`: those in neighbouring grid cells.
fn candidate_pairs(points: &[Point], gap: f64) -> Vec<(usize, usize)> {
let cell = |p: Point| ((p.x / gap).floor() as i64, (p.y / gap).floor() as i64);
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
for (i, p) in points.iter().enumerate() {
grid.entry(cell(*p)).or_default().push(i);
}
let mut out = vec![];
for (i, p) in points.iter().enumerate() {
let (cx, cy) = cell(*p);
for dx in -1..=1 {
for dy in -1..=1 {
let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue };
out.extend(others.iter().filter(|&&j| j > i).map(|&j| (i, j)));
/// An end, where it lies and the unit direction pointing out of its piece there.
type EndAt = (End, Point, Vec2);
/// Where a pair of ends (`a` < `b` in the list of ends) comes in the order [`rejoin`] takes pairs:
/// the turn across the junction, the distance between the ends, `a`, the place of `b`'s grid cell
/// among the cells around `a`'s, and `b`.
type Order = (f64, f64, usize, usize, usize);
/// Whether pair `x` comes before pair `y`.
fn earlier(x: &Order, y: &Order) -> bool {
x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1)).then((x.2, x.3, x.4).cmp(&(y.2, y.3, y.4))).is_lt()
}
/// The place of cell `to` among the cells around `from`, listed by x step and then y step from -1
/// to 1 (cells past the end of the grid repeat their neighbor; the first place counts).
fn listed_at(from: (i64, i64), to: (i64, i64)) -> usize {
let mut steps = [-1, 0, 1].into_iter().flat_map(|dx| [-1, 0, 1].map(|dy| (from.0.saturating_add(dx), from.1.saturating_add(dy))));
steps.position(|c| c == to).unwrap_or(9)
}
/// `angle` as an integer in the same order.
fn angle_key(angle: f64) -> i64 {
let bits = angle.to_bits() as i64;
bits ^ (((bits >> 63) as u64) >> 1) as i64
}
/// The angle between the directions at angles `a` and `b`, from 0 to π.
fn apart(a: f64, b: f64) -> f64 {
let d = (a - b).abs();
d.min(std::f64::consts::TAU - d)
}
/// How far past the turn of the best pair found so far [`Weld::first_partner`] still looks. The
/// turn [`rejoin`] measures (the arc cosine of a dot product of unit vectors) is within 1e-7 of
/// the angle between the directions, and the angles the search sorts by are within 1e-14 of it.
const TURN_SLACK: f64 = 1e-6;
/// Ends in one grid cell at one place with one outward direction (bit for bit): every other end
/// pairs with each of them at the same turn and distance.
struct Class {
at: Point,
angle: f64,
/// The ends here no pair has taken yet.
free: BTreeSet<usize>,
}
/// The pairing behind [`rejoin`].
struct Weld<'a> {
pieces: &'a [SubPath],
ends: &'a [EndAt],
gap: f64,
/// The width of the grid's cells.
size: f64,
classes: Vec<Class>,
/// Each end's class.
class_of: Vec<usize>,
/// Each grid cell's classes with free ends, by the angle of their direction.
cells: HashMap<(i64, i64), BTreeSet<(i64, usize)>>,
/// Whether each end is still free.
free: Vec<bool>,
/// Whether each end has looked for its first partner. Another end's first partner in a class
/// is one of the class's first three free ends, so the ends after those cannot meet next and
/// look only once they move up.
awake: Vec<bool>,
/// Each awake end's first partner, and where that pair comes in the order.
first: Vec<Option<(Order, usize)>>,
/// The ends whose first partner each end is (some may have moved on since).
wanted_by: Vec<Vec<usize>>,
/// Ends to check for a partner whose first partner they are.
todo: Vec<usize>,
#[cfg(test)]
work: std::cell::Cell<usize>,
}
impl<'a> Weld<'a> {
fn new(pieces: &'a [SubPath], ends: &'a [EndAt], gap: f64) -> Self {
let size = gap.max(1e-9);
let (mut classes, mut class_of, mut cells) = (vec![], vec![], HashMap::new());
let mut class_at: HashMap<((i64, i64), [u64; 4]), usize> = HashMap::new();
for (i, &(_, p, out)) in ends.iter().enumerate() {
let c = grid_cell(p, size);
let k = *class_at.entry((c, [p.x, p.y, out.x, out.y].map(f64::to_bits))).or_insert_with(|| {
let angle = out.y.atan2(out.x);
cells.entry(c).or_insert_with(BTreeSet::new).insert((angle_key(angle), classes.len()));
classes.push(Class { at: p, angle, free: BTreeSet::new() });
classes.len() - 1
});
if let Some(class) = classes.get_mut(k) {
class.free.insert(i);
}
class_of.push(k);
}
let n = ends.len();
Weld {
pieces,
ends,
gap,
size,
classes,
class_of,
cells,
free: vec![true; n],
awake: vec![false; n],
first: vec![None; n],
wanted_by: vec![vec![]; n],
todo: vec![],
#[cfg(test)]
work: std::cell::Cell::new(0),
}
}
out
/// The links between the ends that meet: two free ends that are each other's first partner
/// meet, and the ends that wanted either of them look again, until no such pair is left.
fn link(mut self) -> HashMap<End, End> {
for k in 0..self.classes.len() {
self.wake(k);
}
let mut link: HashMap<End, End> = HashMap::new();
while let Some(v) = self.todo.pop() {
let Some(w) = self.partner(v) else { continue };
if self.free.get(v) != Some(&true) || self.free.get(w) != Some(&true) || self.partner(w) != Some(v) {
continue;
}
let (Some(&(ev, ..)), Some(&(ew, ..))) = (self.ends.get(v), self.ends.get(w)) else { continue };
link.insert(ev, ew);
link.insert(ew, ev);
self.take(v);
self.take(w);
for e in [v, w] {
if let Some(&k) = self.class_of.get(e) {
self.wake(k);
}
}
let waiting: Vec<usize> = [v, w].iter().flat_map(|&e| self.wanted_by.get_mut(e).map(std::mem::take).unwrap_or_default()).collect();
for x in waiting {
if self.free.get(x) == Some(&true) && matches!(self.partner(x), Some(p) if p == v || p == w) {
self.look(x);
}
}
}
#[cfg(test)]
REJOIN_WORK.with(|w| w.set(self.work.get()));
link
}
/// End `v`'s first partner, once it has looked.
fn partner(&self, v: usize) -> Option<usize> {
self.first.get(v).and_then(|f| f.as_ref()).map(|f| f.1)
}
/// Have the first three free ends of class `k` that have not looked for a partner look.
fn wake(&mut self, k: usize) {
let Some(class) = self.classes.get(k) else { return };
let sleeping: Vec<usize> = class.free.iter().take(3).copied().filter(|&e| self.awake.get(e) == Some(&false)).collect();
for e in sleeping {
if let Some(a) = self.awake.get_mut(e) {
*a = true;
}
self.look(e);
}
}
/// Find free end `e`'s first partner, and queue `e` to check whether that end wants it too.
fn look(&mut self, e: usize) {
let next = self.first_partner(e);
if let Some(list) = next.as_ref().and_then(|f| self.wanted_by.get_mut(f.1)) {
list.push(e);
}
if let Some(f) = self.first.get_mut(e) {
*f = next;
}
self.todo.push(e);
}
/// End `e` has met another: it is no longer free.
fn take(&mut self, e: usize) {
if let Some(f) = self.free.get_mut(e) {
*f = false;
}
let Some(&k) = self.class_of.get(e) else { return };
let Some(class) = self.classes.get_mut(k) else { return };
class.free.remove(&e);
if class.free.is_empty()
&& let Some(&(_, p, _)) = self.ends.get(e)
&& let Some(set) = self.cells.get_mut(&grid_cell(p, self.size))
{
set.remove(&(angle_key(class.angle), k));
}
}
/// The free end `v` meets first, and where that pair comes in the order: the classes in the
/// cells around `v`'s are looked at by how far their direction is from the reverse of `v`'s,
/// until that is more than [`TURN_SLACK`] past the best turn found.
fn first_partner(&self, v: usize) -> Option<(Order, usize)> {
let &((piece, _), p, out) = self.ends.get(v)?;
let toward = (-out.y).atan2(-out.x);
let split = (angle_key(toward), 0);
let mut best: Option<(Order, usize)> = None;
for c in around(grid_cell(p, self.size)) {
let Some(set) = self.cells.get(&c) else { continue };
// Both ways round from `toward`; between them they meet every class once.
let mut up = set.range(split..).chain(set.range(..split)).peekable();
let mut down = set.range(..split).rev().chain(set.range(split..).rev()).peekable();
let turn = |e: Option<&&(i64, usize)>| e.and_then(|e| self.classes.get(e.1)).map_or(f64::INFINITY, |k| apart(k.angle, toward));
for _ in 0..set.len() {
let (tu, td) = (turn(up.peek()), turn(down.peek()));
if best.as_ref().is_some_and(|b| tu.min(td) > b.0.0 + TURN_SLACK) {
break;
}
let Some(&(_, k)) = (if tu <= td { up.next() } else { down.next() }) else { break };
if let Some(pair) = self.pair_with(v, p, piece, k)
&& best.as_ref().is_none_or(|b| earlier(&pair.0, &b.0))
{
best = Some(pair);
}
}
}
best
}
/// The first free end of class `k` that free end `v` (at `p`, on `piece`) may meet, and where
/// that pair comes in the order. Within a class the pairs differ only in the ends' order, so
/// the end listed first comes first.
fn pair_with(&self, v: usize, p: Point, piece: usize, k: usize) -> Option<(Order, usize)> {
#[cfg(test)]
self.work.set(self.work.get() + 1);
let class = self.classes.get(k)?;
if p.distance(class.at) > self.gap {
return None;
}
// A piece's own two ends meet only when closing it leaves a shape (three anchors).
let short = self.pieces.get(piece).is_none_or(|sp| sp.anchors.len() < 3);
let u = *class.free.iter().find(|&&u| u != v && !(short && self.ends.get(u).is_some_and(|e| e.0.0 == piece)))?;
let (a, b) = (v.min(u), v.max(u));
let (&(_, pa, oa), &(_, pb, ob)) = (self.ends.get(a)?, self.ends.get(b)?);
let at = listed_at(grid_cell(pa, self.size), grid_cell(pb, self.size));
Some(((oa.dot(-ob).clamp(-1.0, 1.0).acos(), pa.distance(pb), a, at, b), u))
}
}
#[cfg(test)]
thread_local! {
/// Classes of ends looked at by the last [`rejoin`] on this thread.
static REJOIN_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Walk the links between piece ends into chains.
+414 -3
View File
@@ -1,7 +1,12 @@
use kurbo::{Point, Vec2};
use vectorcraft_geom::{Anchor, AnchorKind, SubPath};
use std::collections::HashMap;
use super::{close_nearly_closed, merge_duplicate_anchors, near_point_groups, rejoin, remove_collinear_anchors, retract_tiny_handles};
use kurbo::{Point, Vec2};
use vectorcraft_geom::{Anchor, AnchorKind, EPS, SubPath};
use super::{
End, Rejoined, chains, close_nearly_closed, merge_duplicate_anchors, near_point_groups, outward, rejoin, remove_collinear_anchors,
retract_tiny_handles, root,
};
fn line(pts: &[(f64, f64)], closed: bool) -> SubPath {
SubPath::polyline(&pts.iter().map(|&p| p.into()).collect::<Vec<Point>>(), closed)
@@ -30,6 +35,174 @@ fn collinear_anchors_go_and_corners_stay() {
assert_eq!(remove_collinear_anchors(&mut bend, 0.005), 1);
}
/// The collinear-anchor removal done one `Vec::remove` at a time, testing the anchor that moves
/// into the gap next: the result [`remove_collinear_anchors`] gives.
fn one_at_a_time(sp: &mut SubPath, tolerance: f64) -> usize {
let min = if sp.closed { 3 } else { 2 };
let mut removed = 0;
let mut i = 0;
while i < sp.anchors.len() && sp.anchors.len() > min {
let n = sp.anchors.len();
let inner = sp.closed || (i > 0 && i + 1 < n);
let (prev, cur, next) = (sp.anchors[(i + n - 1) % n], sp.anchors[i], sp.anchors[(i + 1) % n]);
let straight = !prev.has_out() && !cur.has_in() && !cur.has_out() && !next.has_in();
let (a, b) = (cur.p - prev.p, next.p - cur.p);
let len = a.hypot() * b.hypot();
if inner && straight && len > EPS && a.dot(b) > 0.0 && a.cross(b).abs() / len <= tolerance {
sp.anchors.remove(i);
removed += 1;
} else {
i += 1;
}
}
removed
}
/// A subpath's closed flag and every anchor's coordinates bit for bit, with its kind.
fn bits(sp: &SubPath) -> (bool, Vec<([u64; 6], AnchorKind)>) {
let anchors = sp.anchors.iter().map(|a| ([a.p.x, a.p.y, a.h_in.x, a.h_in.y, a.h_out.x, a.h_out.y].map(f64::to_bits), a.kind));
(sp.closed, anchors.collect())
}
/// Check that [`remove_collinear_anchors`] gives `sp` the count and anchors [`one_at_a_time`] does.
fn same_as_one_at_a_time(sp: &SubPath, tolerance: f64) {
let (mut fast, mut slow) = (sp.clone(), sp.clone());
let got = remove_collinear_anchors(&mut fast, tolerance);
let want = one_at_a_time(&mut slow, tolerance);
assert_eq!(got, want, "count at tolerance {tolerance} for {sp:?}");
assert_eq!(bits(&fast), bits(&slow), "anchors at tolerance {tolerance} for {sp:?}");
}
/// xorshift64: the same numbers on every run.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn pick<T: Copy>(&mut self, xs: &[T]) -> T {
xs[(self.next() % xs.len() as u64) as usize]
}
}
/// A subpath of `n` anchors stepping mostly straight along one direction, with repeated points,
/// small and large bends, reversals, short and long handles and non-finite or huge coordinates.
fn generated(r: &mut Rng, n: usize, closed: bool) -> SubPath {
let dir = r.pick(&[Vec2::new(1.0, 0.0), Vec2::new(0.0, -1.0), Vec2::new(0.6, 0.8), Vec2::new(-1.0, 1.0)]);
let side = Vec2::new(-dir.y, dir.x);
let mut at = Point::new(r.pick(&[0.0, 3.0, -7.5]), r.pick(&[0.0, 2.0]));
let anchors = (0..n)
.map(|_| {
at += dir * r.pick(&[1.0, 1.0, 1.0, 2.0, 0.5, 0.0, -1.0]);
let bend = r.pick(&[0.0, 0.0, 0.0, 0.0, 1e-3, 0.004, 0.005, 0.006, 1.0]);
let mut p = at + side * bend;
match r.next() % 40 {
0 => p.x = f64::NAN,
1 => p.y = f64::INFINITY,
2 => p.x = f64::NEG_INFINITY,
3 => p = Point::new(p.x * 1e300, p.y * 1e300),
4 => p = Point::new(1e-300, -1e-300),
_ => {}
}
let handle = |r: &mut Rng| p + Vec2::new(r.pick(&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1e-10, 1.0]), 0.0);
let (h_in, h_out) = (handle(r), handle(r));
Anchor { p, h_in, h_out, kind: r.pick(&[AnchorKind::Corner, AnchorKind::Corner, AnchorKind::Smooth]) }
})
.collect();
SubPath::new(anchors, closed)
}
const TOLERANCES: [f64; 12] = [-1.0, -0.0, 0.0, 1e-9, 0.001, 0.005, 0.5, 1.0, 2.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY];
#[test]
fn collinear_anchors_go_as_when_removed_one_at_a_time() {
let mut r = Rng(0x9e37_79b9_7f4a_7c15);
for n in (0..40).chain([64, 100, 257]) {
for _ in 0..40 {
for closed in [false, true] {
let sp = generated(&mut r, n, closed);
for tolerance in TOLERANCES {
same_as_one_at_a_time(&sp, tolerance);
}
}
}
}
}
#[test]
fn collinear_anchors_keep_their_neighbors_order_and_ends() {
let ring = |pts: &[(f64, f64)]| line(pts, true);
let cases = [
// A closed run whose first anchor goes: the last anchor's next neighbor is then the second.
ring(&[(5.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)]),
ring(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0), (5.0, 0.0), (2.0, 4.0)]),
// Every anchor on one line: the path stops at three (closed) or two (open) anchors.
ring(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0)]),
line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (3.0, 0.0), (4.0, 0.0)], false),
// The last anchor lies between the first one kept and the one before it.
ring(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 5.0)]),
// Repeated and zero-length points.
line(&[(0.0, 0.0), (0.0, 0.0), (1.0, 0.0), (1.0, 0.0), (2.0, 0.0)], false),
ring(&[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)]),
// Products of huge coordinates overflow; tiny ones underflow.
line(&[(0.0, 0.0), (1e200, 1e200), (2e200, 2e200), (f64::MAX, f64::MAX)], false),
line(&[(0.0, 0.0), (1e-200, 0.0), (2e-200, 0.0)], false),
line(&[(0.0, 0.0), (f64::NAN, 0.0), (2.0, 0.0), (f64::INFINITY, 0.0), (5.0, 0.0)], false),
];
for sp in &cases {
for tolerance in TOLERANCES {
same_as_one_at_a_time(sp, tolerance);
}
}
let mut first = cases[0].clone();
assert_eq!(remove_collinear_anchors(&mut first, 0.0), 1);
assert_eq!(points(&first), [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)]);
let (mut closed, mut open) = (cases[2].clone(), cases[3].clone());
assert_eq!((remove_collinear_anchors(&mut closed, 0.0), closed.anchors.len()), (2, 3));
assert_eq!(remove_collinear_anchors(&mut open, 0.0), 3);
assert_eq!(points(&open), [(0.0, 0.0), (4.0, 0.0)], "open ends stay");
// A handle on either side of either segment keeps the anchor between them.
for side in 0..4 {
let mut sp = line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0)], false);
let (i, h) = [(0, 1), (1, 0), (1, 1), (2, 0)][side];
for kind in [AnchorKind::Corner, AnchorKind::Smooth] {
let a = &mut sp.anchors[i];
a.kind = kind;
*(if h == 0 { &mut a.h_in } else { &mut a.h_out }) = a.p + Vec2::new(0.0, 1.0);
same_as_one_at_a_time(&sp, 0.005);
assert_eq!(remove_collinear_anchors(&mut sp.clone(), 0.005), 0, "handle {h} on anchor {i}");
}
}
}
#[test]
fn collinear_anchors_at_the_tolerance_go_and_just_past_it_stay() {
let sp = line(&[(0.0, 0.0), (100.0, 0.1), (200.0, 0.0)], false);
let (a, b) = (sp.anchors[1].p - sp.anchors[0].p, sp.anchors[2].p - sp.anchors[1].p);
let sine = a.cross(b).abs() / (a.hypot() * b.hypot());
for (tolerance, removed) in [(sine, 1), (sine.next_down(), 0), (sine.next_up(), 1)] {
same_as_one_at_a_time(&sp, tolerance);
assert_eq!(remove_collinear_anchors(&mut sp.clone(), tolerance), removed, "{tolerance}");
}
}
#[test]
fn collinear_anchors_go_in_linear_work() {
for (n, closed) in [(10_000, false), (20_000, false), (20_000, true)] {
let pts: Vec<Point> = (0..n).map(|i| Point::new(i as f64, 0.0)).collect();
let mut sp = SubPath::polyline(&pts, closed);
let removed = remove_collinear_anchors(&mut sp, 0.005);
// A closed straight run stops at three anchors; an open one keeps its two ends.
assert_eq!((removed, sp.anchors.len()), if closed { (n - 3, 3) } else { (n - 2, 2) });
let work = super::COLLINEAR_WORK.with(std::cell::Cell::get);
assert!(work <= 2 * n, "{n} anchors took {work} steps");
}
}
#[test]
fn duplicate_anchors_merge_keeping_the_outer_handles() {
let mut sp = SubPath::new(
@@ -89,6 +262,244 @@ fn near_points_group_but_linked_and_equal_ones_do_not() {
assert!(near_point_groups(&far, 1e-300, |_, _| false).is_empty());
}
/// Nearly Coincident Anchors' grouping comparing every pair of points in touching grid cells: the
/// groups [`near_point_groups`] gives.
fn near_groups_pair_by_pair(points: &[Point], distance: f64, linked: impl Fn(usize, usize) -> bool) -> Vec<Vec<usize>> {
if !(distance > 0.0 && distance.is_finite()) {
return vec![];
}
let cell = |p: Point| ((p.x / distance).floor() as i64, (p.y / distance).floor() as i64);
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
for (i, p) in points.iter().enumerate().filter(|(_, p)| p.is_finite()) {
grid.entry(cell(*p)).or_default().push(i);
}
let mut parent: Vec<usize> = (0..points.len()).collect();
for (&(cx, cy), members) in &grid {
for (dx, dy) in [(0, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] {
let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue };
for &i in members {
for &j in others.iter().filter(|&&j| (dx, dy) != (0, 0) || j > i) {
let d = points[i].distance(points[j]);
if d <= distance && d > 0.0 && !linked(i.min(j), i.max(j)) {
let (ri, rj) = (root(&mut parent, i), root(&mut parent, j));
parent[ri.max(rj)] = ri.min(rj);
}
}
}
}
}
let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
for i in 0..points.len() {
groups.entry(root(&mut parent, i)).or_default().push(i);
}
let mut out: Vec<Vec<usize>> = groups.into_values().filter(|g| g.len() > 1).collect();
out.sort_unstable();
out
}
/// Points around a few spots on a lattice, many at the same place, with signed zeros, huge, tiny
/// and non-finite coordinates.
fn generated_points(r: &mut Rng, n: usize, distance: f64) -> Vec<Point> {
let spots: Vec<Point> = (0..1 + r.next() % 6).map(|_| Point::new((r.next() % 5) as f64 * distance, (r.next() % 5) as f64 * distance)).collect();
(0..n)
.map(|_| {
let jitter = |r: &mut Rng| r.pick(&[0.0, 0.0, -0.0, 0.1, 0.3, 0.5, 0.7, 0.99, 1.0, 1.01, 2.0, -0.5, -1.0]) * distance;
let at = r.pick(&spots);
let p = Point::new(at.x + jitter(r), at.y + jitter(r));
match r.next() % 50 {
0 => Point::new(f64::NAN, p.y),
1 => Point::new(p.x, f64::INFINITY),
2 => Point::new(-0.0, -0.0),
3 => Point::new(p.x * 1e300, p.y),
4 => Point::new(1e-300, 1e-300),
_ => p,
}
})
.collect()
}
#[test]
fn near_points_group_as_when_every_pair_is_compared() {
let mut r = Rng(0x2545_f491_4f6c_dd1d);
let linked: [fn(usize, usize) -> bool; 5] =
[|_, _| false, |a, b| b == a + 1, |a, b| (a * 31 + b * 17) % 5 == 0, |a, b| (a + b) % 2 == 0, |_, _| true];
for n in (0..30).chain([64, 150, 300]) {
for _ in 0..12 {
for distance in [0.01, 0.5, 1.0, 3.0, 1e-200, 1e300] {
let pts = generated_points(&mut r, n, distance);
for (k, linked) in linked.iter().enumerate() {
let want = near_groups_pair_by_pair(&pts, distance, linked);
assert_eq!(near_point_groups(&pts, distance, linked), want, "linked {k} at {distance} for {pts:?}");
}
}
}
}
}
/// A tight cluster of `n` points around `at`, no two at the same place.
fn cluster(at: Point, radius: f64, n: usize) -> Vec<Point> {
(0..n).map(|i| at + Vec2::from_angle(i as f64 * 2.399_963) * (radius * ((i + 1) as f64 / n as f64).sqrt())).collect()
}
#[test]
fn near_points_in_a_dense_cell_group_in_linear_work() {
let n = 4_000;
let neighbours = |a: usize, b: usize| b == a + 1;
let one_cluster = cluster(Point::new(0.005, 0.005), 0.004, n);
let mut two_clusters = cluster(Point::new(0.001, 0.001), 0.0009, n / 2);
two_clusters.extend(cluster(Point::new(0.019, 0.019), 0.0009, n / 2));
let same_place = vec![Point::new(0.005, 0.005); n];
let cases = [(&one_cluster, 1, n), (&two_clusters, 2, n / 2), (&same_place, 0, 0)];
for (pts, count, size) in cases {
let groups = near_point_groups(pts, 0.01, neighbours);
let work = super::NEAR_WORK.with(std::cell::Cell::get);
assert_eq!(groups, near_groups_pair_by_pair(pts, 0.01, neighbours));
assert_eq!(groups.len(), count);
assert!(groups.iter().all(|g| g.len() == size), "{:?}", groups.iter().map(Vec::len).collect::<Vec<_>>());
assert!(work <= 4 * n, "{n} points took {work} steps");
}
}
/// One pair of ends (`a` < `b` in the list of ends) for [`rejoin_sorting_every_pair`]: the turn,
/// the distance, and the two ends.
type Pair = (f64, f64, End, End);
/// Rejoin listing every pair of ends in touching grid cells and sorting them by turn and then
/// distance: the joins [`rejoin`] makes.
fn rejoin_sorting_every_pair(pieces: &[SubPath], gap: f64) -> Vec<Rejoined> {
if !(gap >= 0.0 && gap.is_finite()) {
return vec![];
}
let usable = |sp: &&SubPath| {
!sp.closed && sp.anchors.len() >= 2 && sp.anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite())
};
let ends: Vec<(End, Point, Vec2)> = pieces
.iter()
.enumerate()
.filter(|(_, sp)| usable(sp))
.flat_map(|(i, sp)| [(i, sp, false), (i, sp, true)])
.filter_map(|(i, sp, last)| {
let a = if last { sp.anchors.last() } else { sp.anchors.first() }?;
Some(((i, last), a.p, outward(sp, last)?))
})
.collect();
let size = gap.max(1e-9);
let cell = |p: Point| ((p.x / size).floor() as i64, (p.y / size).floor() as i64);
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
for (i, e) in ends.iter().enumerate() {
grid.entry(cell(e.1)).or_default().push(i);
}
let mut pairs: Vec<Pair> = vec![];
for (a, &(ea, pa, oa)) in ends.iter().enumerate() {
let (cx, cy) = cell(pa);
for dx in -1..=1 {
for dy in -1..=1 {
let Some(others) = grid.get(&(cx.saturating_add(dx), cy.saturating_add(dy))) else { continue };
for &b in others.iter().filter(|&&b| b > a) {
let (eb, pb, ob) = ends[b];
if ea.0 == eb.0 && pieces[ea.0].anchors.len() < 3 {
continue;
}
let d = pa.distance(pb);
if d <= gap {
pairs.push((oa.dot(-ob).clamp(-1.0, 1.0).acos(), d, ea, eb));
}
}
}
}
}
pairs.sort_by(|x, y| x.0.total_cmp(&y.0).then(x.1.total_cmp(&y.1)));
let mut link: HashMap<End, End> = HashMap::new();
for (_, _, a, b) in pairs {
if !link.contains_key(&a) && !link.contains_key(&b) {
link.insert(a, b);
link.insert(b, a);
}
}
chains(pieces, &link)
}
/// Check that [`rejoin`] joins `pieces` as [`rejoin_sorting_every_pair`] does, bit for bit.
fn same_as_sorting_every_pair(pieces: &[SubPath], gap: f64) {
let (got, want) = (rejoin(pieces, gap), rejoin_sorting_every_pair(pieces, gap));
let shape = |out: &[Rejoined]| out.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::<Vec<_>>();
assert_eq!(shape(&got), shape(&want), "gap {gap} for {pieces:?}");
}
/// Pieces of two to four anchors whose ends sit on or near a few lattice points, often at the
/// same place, some curving, closed or non-finite.
fn generated_pieces(r: &mut Rng, n: usize, gap: f64) -> Vec<SubPath> {
let spot = |r: &mut Rng| {
let near = r.pick(&[0.0, 0.0, 0.0, 0.25, 0.5, 1.0, 1.5]) * gap;
Point::new((r.next() % 3) as f64 + near, (r.next() % 3) as f64 + r.pick(&[0.0, 0.0, near, -near]))
};
(0..n)
.map(|_| {
let count = 2 + (r.next() % 3) as usize;
let mut pts: Vec<Point> = (0..count).map(|_| spot(r)).collect();
if r.next().is_multiple_of(30) {
pts[0].x = f64::NAN;
}
let mut sp = SubPath::polyline(&pts, r.next().is_multiple_of(15));
if r.next().is_multiple_of(4) {
let a = &mut sp.anchors[0];
a.h_out = a.p + r.pick(&[Vec2::new(0.3, 0.1), Vec2::new(0.0, -0.2), Vec2::new(-0.1, -0.1)]);
}
sp
})
.collect()
}
#[test]
fn rejoin_joins_as_when_every_pair_is_sorted() {
let mut r = Rng(0xd1b5_4a32_d192_ed03);
for n in (0..25).chain([40, 80, 160]) {
for _ in 0..15 {
for gap in [0.0, 0.05, 0.1, 0.5, 1.0, 3.0] {
same_as_sorting_every_pair(&generated_pieces(&mut r, n, gap), gap);
}
}
}
// Ends meeting from directions that tie: a plus sign, a doubled star and stacked copies.
let plus: Vec<SubPath> = [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (0.0, -1.0)].map(|(x, y)| line(&[(0.0, 0.0), (x, y)], false)).to_vec();
let mut doubled = plus.clone();
doubled.extend(plus.iter().map(|sp| {
let mut sp = sp.clone();
sp.reverse();
sp
}));
let stacked = vec![line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 1.0)], false); 7];
for pieces in [&plus, &doubled, &stacked] {
for gap in [0.0, 0.1, 5.0] {
same_as_sorting_every_pair(pieces, gap);
}
}
}
#[test]
fn rejoin_pairs_coincident_ends_in_near_linear_work() {
let n = 2_000;
let ray = |angle: f64| {
let tip = Vec2::from_angle(angle) * 100.0;
line(&[(0.0, 0.0), (tip.x, tip.y)], false)
};
let star: Vec<SubPath> = (0..n).map(|i| ray(i as f64 * std::f64::consts::TAU / n as f64)).collect();
let mut r = Rng(0x9e37_79b9_7f4a_7c15);
let scattered: Vec<SubPath> = (0..n).map(|_| ray((r.next() % 1_000_000) as f64 * 1e-6 * std::f64::consts::TAU)).collect();
let stacked = vec![line(&[(0.0, 0.0), (10.0, 0.0)], false); n];
for (name, pieces) in [("star", &star), ("scattered", &scattered), ("stacked", &stacked)] {
let out = rejoin(pieces, 0.1);
let work = super::REJOIN_WORK.with(std::cell::Cell::get);
let want = rejoin_sorting_every_pair(pieces, 0.1);
assert_eq!(
out.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::<Vec<_>>(),
want.iter().map(|j| (j.members.clone(), bits(&j.path))).collect::<Vec<_>>(),
"{name}"
);
assert!(work <= 20 * n, "{name}: {n} pieces took {work} steps");
}
}
#[test]
fn rejoin_welds_pieces_within_the_gap() {
// Three pieces of one zig-zag, the middle one drawn backwards, plus one too far away.
+27 -4
View File
@@ -217,7 +217,7 @@ choice! {
}
/// Save PDF settings (the dialog's sections; what a preset stores).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct PdfSettings {
pub standard: Standard,
@@ -237,9 +237,9 @@ pub struct PdfSettings {
/// `create_layers` is on).
pub include_non_printing: bool,
/// Write a page with a side longer than 14,400 pt (200 in) at its size in points, without a
/// `UserUnit`, at every PDF version, in files without a standard (off, and in PDF/A files:
/// PDF 1.6 and later files that aren't PDF/X files write it with a `UserUnit`, and PDF 1.5
/// files are written as PDF 1.6 for it).
/// `UserUnit`, at every PDF version, in files without a standard (on by default; off, and in
/// PDF/A files: PDF 1.6 and later files that aren't PDF/X files write it with a `UserUnit`,
/// and PDF 1.5 files are written as PDF 1.6 for it).
pub long_pages_in_points: bool,
pub compression: CompressionSettings,
pub marks: MarkSettings,
@@ -253,6 +253,29 @@ pub struct PdfSettings {
pub flattener_preset: String,
}
impl Default for PdfSettings {
fn default() -> Self {
Self {
standard: Standard::default(),
compatibility: Compatibility::default(),
preserve_editing: false,
thumbnails: false,
fast_web_view: false,
view_after_saving: false,
create_layers: false,
include_non_printing: false,
long_pages_in_points: true,
compression: CompressionSettings::default(),
marks: MarkSettings::default(),
bleed: BleedSettings::default(),
output: OutputSettings::default(),
advanced: AdvancedSettings::default(),
security: SecuritySettings::default(),
flattener_preset: String::new(),
}
}
}
/// Resampling and compression of one kind of image.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
+32 -25
View File
@@ -105,8 +105,9 @@ fn units_and_media(bytes: &[u8]) -> Vec<(f32, Rect)> {
}
/// A page with a side longer than ISO 32000-1's 14,400 units is written in larger units (its
/// `UserUnit`), so that its sides are 14,400 units at most, and reads back at its size in points.
/// Pages up to 14,400 pt, files before PDF 1.6 and PDF/X files keep their sizes in points.
/// `UserUnit`), so that its sides are 14,400 units at most, and reads back at its size in points,
/// with `longPagesInPoints` off. Pages up to 14,400 pt, files before PDF 1.6 and PDF/X files keep
/// their sizes in points.
#[test]
fn a_page_past_14400_pt_is_written_with_a_user_unit_and_reads_back_at_its_size() {
let mut d = doc();
@@ -117,7 +118,7 @@ fn a_page_past_14400_pt_is_written_with_a_user_unit_and_reads_back_at_its_size()
small.rect = Rect::new(0.0, 12_000.0, 20_000.0, 12_001.0);
d.artboards.push(small);
let near = |a: Rect, b: Rect| [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.01);
let bytes = pdf(&d, json!({}));
let bytes = pdf(&d, json!({"longPagesInPoints": false}));
let pages = units_and_media(&bytes);
// 20,000 / 14,400 = 1.3889, rounded up to 1.389: the page is 14,398.85 × 7,199.42 units.
assert_eq!(pages[0].0, 1.389, "{pages:?}");
@@ -155,6 +156,12 @@ fn report(d: &Document, set: PdfSettings) -> Result<ExportReport, PdfError> {
export_with_report(d, &PdfOptions { settings: set, created: Some(1_791_200_000), ..PdfOptions::uncompressed() })
}
/// The default settings with `long_pages_in_points` off: long pages from PDF 1.6 on get a
/// `UserUnit`.
fn user_units() -> PdfSettings {
PdfSettings { long_pages_in_points: false, ..PdfSettings::default() }
}
/// The numbers that follow `key` in the file's bytes (`/MediaBox [0 0 w h]`, `/UserUnit u`), read
/// as text, without the PDF reader: none when the file has no `key`.
fn raw_numbers(bytes: &[u8], key: &str, count: usize) -> Vec<f64> {
@@ -178,13 +185,13 @@ fn long_page_warnings(r: &ExportReport) -> Vec<&String> {
r.warnings.iter().filter(|w| w.contains("page limit of 14,400 pt")).collect()
}
/// A 20 m page at PDF 1.7 (the default) is written with a `UserUnit` of 3.938, reads back at 20 m
/// from the file's bytes, through the PDF reader and through the import, and the export says how
/// it is written.
/// A 20 m page at PDF 1.7 (the default) with `long_pages_in_points` off is written with a
/// `UserUnit` of 3.938, reads back at 20 m from the file's bytes, through the PDF reader and
/// through the import, and the export says how it is written.
#[test]
fn a_20_m_page_keeps_its_size_with_a_user_unit_and_the_export_says_so() {
let d = sized(TWENTY_M, TWENTY_M / 20.0);
let r = report(&d, PdfSettings::default()).unwrap();
let r = report(&d, user_units()).unwrap();
assert!(r.bytes.starts_with(b"%PDF-1.7"));
assert_eq!(
long_page_warnings(&r),
@@ -209,7 +216,7 @@ fn a_20_m_page_keeps_its_size_with_a_user_unit_and_the_export_says_so() {
/// Every built-in preset and every PDF version keeps a 20 m page at its size, or refuses it with
/// the reason: PDF 1.3 and 1.4 files (PDF/X-1a and PDF/X-3 among them) have no `UserUnit` and
/// hold no real number past 32,767, PDF 1.5 is written as PDF 1.6 to have one, and PDF/X-4 pages
/// at PDF 1.5 or 1.6 stay in points with a warning.
/// at PDF 1.5 or 1.6 stay in points with a warning (with `long_pages_in_points` off).
#[test]
fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() {
let d = sized(TWENTY_M, TWENTY_M / 20.0);
@@ -223,7 +230,7 @@ fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() {
};
for preset in crate::builtin_presets() {
let name = preset.name.as_str();
match report(&d, preset.settings.clone()) {
match report(&d, PdfSettings { long_pages_in_points: false, ..preset.settings.clone() }) {
Err(e) if matches!(name, "PDF/X-1a:2001" | "PDF/X-3:2002") => refused(e, name),
Err(e) => panic!("{name}: {e}"),
Ok(r) if name == "PDF/X-4:2010" => {
@@ -241,7 +248,7 @@ fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() {
}
}
for c in Compatibility::ALL.iter().copied() {
let set = PdfSettings { compatibility: c, ..PdfSettings::default() };
let set = PdfSettings { compatibility: c, ..user_units() };
match (c, report(&d, set)) {
(Compatibility::Pdf13 | Compatibility::Pdf14, Err(e)) => refused(e, c.label()),
(Compatibility::Pdf13 | Compatibility::Pdf14, Ok(_)) => panic!("{} is refused", c.label()),
@@ -362,7 +369,7 @@ fn the_error_names_the_long_page_whose_art_needs_a_larger_real() {
#[test]
fn a_page_too_narrow_for_its_user_unit_keeps_3_units_on_its_short_side() {
const MM: f64 = 72.0 / 25.4;
for set in [PdfSettings::default(), PdfSettings { standard: Standard::PdfA2b, ..PdfSettings::default() }] {
for set in [user_units(), PdfSettings { standard: Standard::PdfA2b, ..PdfSettings::default() }] {
let r = report(&sized(TWENTY_M * 5.0, 4.0 * MM), set).unwrap();
assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.779]);
let media = raw_numbers(&r.bytes, "/MediaBox", 4);
@@ -377,11 +384,11 @@ fn a_page_too_narrow_for_its_user_unit_keeps_3_units_on_its_short_side() {
assert!(long_page_warnings(&r).is_empty(), "{:?}", r.warnings);
}
// A short side of 3 units or more at the long side's unit keeps that unit.
let r = report(&sized(TWENTY_M * 5.0, 60.0), PdfSettings::default()).unwrap();
let r = report(&sized(TWENTY_M * 5.0, 60.0), user_units()).unwrap();
assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [19.686]);
let media = raw_numbers(&r.bytes, "/MediaBox", 4);
assert!(media[3] - media[1] >= 3.0, "{media:?}");
let r = report(&sized(TWENTY_M * 5.0, 2.0), PdfSettings::default()).unwrap();
let r = report(&sized(TWENTY_M * 5.0, 2.0), user_units()).unwrap();
assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [19.686]);
}
@@ -389,7 +396,7 @@ fn a_page_too_narrow_for_its_user_unit_keeps_3_units_on_its_short_side() {
/// the Save PDF dialog shows it.
#[test]
fn a_pdf_1_5_file_written_as_1_6_keeps_rc4_encryption() {
let mut set = PdfSettings { compatibility: Compatibility::Pdf15, ..PdfSettings::default() };
let mut set = PdfSettings { compatibility: Compatibility::Pdf15, ..user_units() };
set.security.open_password = "secret".into();
let has = |bytes: &[u8], s: &[u8]| bytes.windows(s.len()).any(|w| w == s);
let r = report(&sized(TWENTY_M, 300.0), set).unwrap();
@@ -408,7 +415,7 @@ fn the_long_page_warning_rounds_the_size_up() {
/// point longer gets a `UserUnit` of 1.001 and the warning, and stays in points at PDF 1.4.
#[test]
fn a_page_of_14400_pt_stays_in_points_and_one_point_more_does_not() {
let at = |side: f64, c: Compatibility| report(&sized(side, 300.0), PdfSettings { compatibility: c, ..PdfSettings::default() });
let at = |side: f64, c: Compatibility| report(&sized(side, 300.0), PdfSettings { compatibility: c, ..user_units() });
for c in [Compatibility::Pdf14, Compatibility::Pdf15, Compatibility::Pdf17] {
let r = at(14_400.0, c).unwrap();
assert!(long_page_warnings(&r).is_empty() && !r.warnings.iter().any(|w| w.contains("UserUnit")), "{}: {:?}", c.label(), r.warnings);
@@ -455,13 +462,14 @@ fn a_page_within_14400_pt_is_written_as_before_at_every_version() {
/// 10 m in points.
const TEN_M: f64 = 10.0 / 0.0254 * 72.0;
/// With `long_pages_in_points`, a 10 m page at PDF 1.7 is written at its size in points, with no
/// `UserUnit`, the warning says so, and the page reads back at 10 m. Without it the page keeps
/// its `UserUnit`.
/// With `long_pages_in_points` (on by default), a 10 m page at PDF 1.7 is written at its size in
/// points, with no `UserUnit`, the warning says so, and the page reads back at 10 m. Without it the
/// page keeps its `UserUnit`.
#[test]
fn long_pages_in_points_writes_a_10_m_page_in_points() {
let d = sized(TEN_M, TEN_M / 10.0);
let r = report(&d, PdfSettings { long_pages_in_points: true, ..PdfSettings::default() }).unwrap();
assert!(settings(json!({})).long_pages_in_points, "on by default");
let r = report(&d, PdfSettings::default()).unwrap();
assert!(r.bytes.starts_with(b"%PDF-1.7"));
assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::<f64>::new());
let media = raw_numbers(&r.bytes, "/MediaBox", 4);
@@ -479,13 +487,12 @@ fn long_pages_in_points_writes_a_10_m_page_in_points() {
let back = import(&r.bytes).unwrap();
let rect = back.artboards[0].rect;
assert!((rect.width() - TEN_M).abs() < 0.01 && (rect.height() - TEN_M / 10.0).abs() < 0.01, "{rect:?}");
// Off (the default), the page has a `UserUnit` of 28,346.46 / 14,400, rounded up.
let off = report(&d, PdfSettings::default()).unwrap();
// Off, the page has a `UserUnit` of 28,346.46 / 14,400, rounded up.
let off = report(&d, user_units()).unwrap();
assert_eq!(raw_numbers(&off.bytes, "/UserUnit", 1), [1.969]);
assert!(
long_page_warnings(&off)[0].ends_with("it is written with a UserUnit of 1.969, so apps that ignore UserUnit show it that many times smaller")
);
assert!(!settings(json!({})).long_pages_in_points, "off by default");
}
/// With `long_pages_in_points`, every PDF version writes a 10 m page in points: PDF 1.5 stays
@@ -496,7 +503,7 @@ fn long_pages_in_points_keeps_every_version_and_changes_nothing_where_pages_are_
let d = sized(TEN_M, TEN_M / 10.0);
let with = |set: &PdfSettings| PdfSettings { long_pages_in_points: true, ..set.clone() };
for c in Compatibility::ALL.iter().copied() {
let set = PdfSettings { compatibility: c, ..PdfSettings::default() };
let set = PdfSettings { compatibility: c, ..user_units() };
let r = report(&d, with(&set)).unwrap();
assert!(r.bytes.starts_with(format!("%PDF-{}", c.id()).as_bytes()), "{}", c.label());
assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::<f64>::new(), "{}", c.label());
@@ -520,7 +527,7 @@ fn pdfa2b_long_page_stays_within_14400_units() {
let d = sized(TEN_M, TEN_M / 10.0);
for s in Standard::ALL.iter().copied().filter(|s| *s != Standard::None && !s.is_pdfx()) {
for c in Compatibility::ALL.iter().copied().filter(|c| s.allows(*c)) {
let off = PdfSettings { standard: s, compatibility: c, ..PdfSettings::default() };
let off = PdfSettings { standard: s, compatibility: c, ..user_units() };
let on = PdfSettings { long_pages_in_points: true, ..off.clone() };
let (on, off) = (report(&d, on).unwrap(), report(&d, off).unwrap());
assert_eq!(on.bytes, off.bytes, "{} {}", s.label(), c.label());
@@ -540,7 +547,7 @@ fn pdfa2b_long_page_stays_within_14400_units() {
fn long_pages_in_points_leaves_a_page_within_14400_pt_as_it_is() {
let d = sized(14_400.0, 300.0);
for c in Compatibility::ALL.iter().copied() {
let off = PdfSettings { compatibility: c, ..PdfSettings::default() };
let off = PdfSettings { compatibility: c, ..user_units() };
let on = PdfSettings { long_pages_in_points: true, ..off.clone() };
let (off, on) = (report(&d, off).unwrap(), report(&d, on).unwrap());
assert_eq!(on.bytes, off.bytes, "{}", c.label());
+24 -3
View File
@@ -127,11 +127,31 @@ const NEEDLE_AT: usize = 0x8000;
/// its input unchanged otherwise. A live effect made from it draws one shape or the other, so a
/// test sees from the geometry whether the host handed the plug-in something.
pub fn when_given(manifest: &str, given: Given, needle: &str, output: &str) -> String {
given_or(manifest, given, needle, output, None)
}
/// A plug-in that returns `output` when what it is given (`given`) holds the text `needle`, and
/// `otherwise` when it does not.
pub fn when_given_else(manifest: &str, given: Given, needle: &str, output: &str, otherwise: &str) -> String {
given_or(manifest, given, needle, output, Some(otherwise))
}
/// [`when_given`], returning `otherwise` in place of the input when it is given.
fn given_or(manifest: &str, given: Given, needle: &str, output: &str, otherwise: Option<&str>) -> String {
let (src, len) = match given {
Given::Input => ("$in", "$il"),
Given::Params => ("$pp", "$pl"),
};
let n = needle.len();
// `otherwise` sits right after `output`.
let other_at = OUTPUT_AT + output.len();
let (none, other) = match otherwise {
Some(o) => (
format!("(i64.or (i64.shl (i64.const {}) (i64.const 32)) (i64.const {other_at}))", o.len()),
format!(r#" (data (i32.const {other_at}) "{}")"#, string(o)),
),
None => (ECHO.to_string(), String::new()),
};
// For each place `$i` the needle fits, compare it byte by byte (`$j`).
let run = format!(
r#"(local $i i32) (local $j i32)
@@ -149,12 +169,13 @@ pub fn when_given(manifest: &str, given: Given, needle: &str, output: &str) -> S
(br $cmp)))
(local.set $i (i32.add (local.get $i) (i32.const 1)))
(br $at)))
(return {ECHO}))
(return {none}))
(i64.or (i64.shl (i64.const {out}) (i64.const 32)) (i64.const {OUTPUT_AT}))"#,
out = output.len(),
);
let extra = format!(r#"(data (i32.const {NEEDLE_AT}) "{}") (data (i32.const {OUTPUT_AT}) "{}")"#, string(needle), string(output));
module(manifest, &run, &extra, (OUTPUT_AT + output.len()).div_ceil(0x1_0000) as u32 + 1)
let extra = format!(r#"(data (i32.const {NEEDLE_AT}) "{}") (data (i32.const {OUTPUT_AT}) "{}"){other}"#, string(needle), string(output));
let end = other_at + otherwise.map_or(0, str::len);
module(manifest, &run, &extra, end.div_ceil(0x1_0000) as u32 + 1)
}
/// The manifest of a test plug-in `id` of `kind` with `params` (a JSON object of specs).
+179 -40
View File
@@ -73,6 +73,67 @@ fn poly_intervals(polys: &[Vec<Point>], y: f64) -> Vec<(f64, f64)> {
xs.as_chunks::<2>().0.iter().map(|c| (c[0], c[1])).collect()
}
/// The part of the horizontal line at `y` closer than `r` to the segment `a`–`b`: the line's
/// intersection with the segment's two end disks and the band between them, which together make
/// a convex shape, so the result is one interval.
fn near_segment(a: Point, b: Point, y: f64, r: f64) -> Option<(f64, f64)> {
if y <= a.y.min(b.y) - r || y >= a.y.max(b.y) + r {
return None;
}
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
for p in [a, b] {
let h = r * r - (y - p.y) * (y - p.y);
if h > 0.0 {
lo = lo.min(p.x - h.sqrt());
hi = hi.max(p.x + h.sqrt());
}
}
let d = b - a;
let len = d.hypot();
if len > 0.0 {
let n = kurbo::Vec2::new(-d.y, d.x) * (r / len);
let band = [a + n, b + n, b - n, a - n];
for i in 0..4 {
let (p, q) = (band[i], band[(i + 1) % 4]);
if (p.y <= y) != (q.y <= y) {
let x = p.x + (y - p.y) / (q.y - p.y) * (q.x - p.x);
lo = lo.min(x);
hi = hi.max(x);
}
}
}
(hi > lo).then_some((lo, hi))
}
/// The x at which some point of the band `top..bottom` (`top <= bottom`) is closer than `r` to the
/// segment `a`–`b`. The points closer than `r` to the segment make a convex shape, so within the
/// band its leftmost and rightmost points lie on the band's top or bottom or beside an end of the
/// segment inside the band, and the result is one interval.
fn near_segment_in_band(a: Point, b: Point, top: f64, bottom: f64, r: f64) -> Option<(f64, f64)> {
let ends = [a, b].into_iter().filter(|p| p.y >= top && p.y <= bottom).map(|p| (p.x - r, p.x + r));
let (lo, hi) = [near_segment(a, b, top, r), near_segment(a, b, bottom, r)]
.into_iter()
.flatten()
.chain(ends)
.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), (c, d)| (lo.min(c), hi.max(d)));
(hi > lo).then_some((lo, hi))
}
/// [`band_intervals`] less every x at which some point of the band `top..bottom` is closer than
/// `inset` to an edge of `polys` (holes included), measured from the edge itself.
fn band_inset_intervals(polys: &[Vec<Point>], top: f64, bottom: f64, inset: f64) -> Vec<(f64, f64)> {
let iv = band_intervals(polys, top, bottom);
if inset <= 0.0 || iv.is_empty() {
return iv;
}
if !inset.is_finite() {
return vec![];
}
let (top, bottom) = (top.min(bottom), top.max(bottom));
let near = polys.iter().flat_map(|p| (0..p.len()).filter_map(move |i| near_segment_in_band(p[i], p[(i + 1) % p.len()], top, bottom, inset)));
subtract_intervals(&iv, &union_intervals(near.collect()))
}
/// Union of sorted-or-not intervals.
fn union_intervals(mut v: Vec<(f64, f64)>) -> Vec<(f64, f64)> {
v.sort_by(|a, b| a.0.total_cmp(&b.0));
@@ -355,14 +416,18 @@ impl Region {
/// `iv` minus every x at which a wrap object lies somewhere in the band `top..bottom` (or the x
/// inside it over the whole band, for Invert Wrap). Offsets grow each wrap shape vertically
/// and horizontally.
/// and horizontally. Along the line, the text also keeps the inset beside each wrap object
/// (outside it, or inside it for Invert Wrap); above and below a wrap object only its offset
/// applies.
fn wrapped(&self, mut iv: Vec<(f64, f64)>, top: f64, bottom: f64) -> Vec<(f64, f64)> {
let (top, bottom) = (top.min(bottom), top.max(bottom));
let inset = self.inset;
for (polys, off, invert) in self.wraps.iter() {
if iv.is_empty() {
break;
}
let grow = |v: Vec<(f64, f64)>| union_intervals(v.into_iter().map(|(a, b)| (a - off, b + off)).collect());
let shrink = |v: Vec<(f64, f64)>| v.into_iter().map(|(a, b)| (a + inset, b - inset)).filter(|(a, b)| b > a).collect::<Vec<_>>();
iv = if *invert {
// The band is cut into pieces. Each height of a piece `y0..y1` is within the offset
// of some height from `y0` plus the offset to `y1` less the offset, so an x the
@@ -395,14 +460,15 @@ impl Region {
for w in cuts.windows(2) {
let (a, b) = (w[0] + off, w[1] - off);
let held = if a <= b { band_intervals(polys, a, b) } else { band_cover_closed(polys, b, a) };
iv = intersect_intervals(&iv, &grow(held));
iv = intersect_intervals(&iv, &shrink(grow(held)));
if iv.is_empty() {
break;
}
}
iv
} else {
subtract_intervals(&iv, &grow(band_cover(polys, top - off, bottom + off, false)))
let w = grow(band_cover(polys, top - off, bottom + off, false));
subtract_intervals(&iv, &union_intervals(w.into_iter().map(|(a, b)| (a - inset, b + inset)).collect()))
};
}
iv
@@ -416,8 +482,10 @@ impl Region {
/// Every horizontal span inside the frame (and the cell) over the band `top..bottom`, left to
/// right (text wraps on both sides of an object).
pub(super) fn spans(&self, top: f64, bottom: f64) -> Vec<(f64, f64)> {
// The inset from the cell's edges; `band_inset_intervals` already keeps it from the frame's
// edges and `wrapped` beside the wrap objects.
let clip = |(a, b): (f64, f64)| {
let (a, b) = (a.max(self.cell.x0) + self.inset, b.min(self.cell.x1) - self.inset);
let (a, b) = (a.max(self.cell.x0 + self.inset), b.min(self.cell.x1 - self.inset));
(b > a).then_some((a, b))
};
let plain = self.polys.is_empty() || self.rect;
@@ -433,7 +501,7 @@ impl Region {
};
// `max` then `min` rather than `clamp`, which panics on a frame less than 2e-4 tall.
let clamp = |y: f64| if plain { y } else { y.max(fb.y0 + 1e-4).min(fb.y1 - 1e-4) };
let free = if plain { vec![(self.cell.x0, self.cell.x1)] } else { band_intervals(&self.polys, clamp(top), clamp(bottom)) };
let free = if plain { vec![(self.cell.x0, self.cell.x1)] } else { band_inset_intervals(&self.polys, clamp(top), clamp(bottom), self.inset) };
// Wrap objects split lines: keep what is free of them over the whole band.
let free = if self.wraps.is_empty() { free } else { self.wrapped(free, clamp(top), clamp(bottom)) };
free.into_iter().filter_map(clip).collect()
@@ -455,12 +523,13 @@ fn the_cells_of_a_frame_share_its_polygons_and_the_wrap_shapes() {
assert!(cells.iter().all(|c| c.polys.as_ptr() == first.polys.as_ptr() && c.wraps.as_ptr() == first.wraps.as_ptr()));
}
/// A path with one closed subpath through each list of points.
#[cfg(test)]
fn polygon_path(contours: &[&[(f64, f64)]]) -> BezPath {
fn closed(subpaths: &[&[(f64, f64)]]) -> BezPath {
let mut path = BezPath::new();
for c in contours {
path.move_to(c[0]);
for &p in &c[1..] {
for pts in subpaths {
path.move_to(pts[0]);
for &p in &pts[1..] {
path.line_to(p);
}
path.close_path();
@@ -468,10 +537,18 @@ fn polygon_path(contours: &[&[(f64, f64)]]) -> BezPath {
path
}
/// The spans of every cell of `path` over the band `top..bottom`.
#[cfg(test)]
fn cell_spans(path: &BezPath, opts: &LayoutOptions, wrap: &[vectorcraft_doc::WrapShape], top: f64, bottom: f64) -> Vec<Vec<(f64, f64)>> {
Region::cells(path, opts, wrap).iter().map(|c| c.spans(top, bottom)).collect()
}
#[cfg(test)]
fn assert_spans(got: &[(f64, f64)], want: &[(f64, f64)]) {
assert_eq!(got.len(), want.len(), "{got:?} != {want:?}");
assert!(got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9), "{got:?} != {want:?}");
for (g, w) in got.iter().zip(want) {
assert!((g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9, "{got:?} != {want:?}");
}
}
/// A line stays inside a frame whose right edge pinches in to a point between any fixed heights of
@@ -479,9 +556,8 @@ fn assert_spans(got: &[(f64, f64)], want: &[(f64, f64)]) {
#[cfg(test)]
#[test]
fn a_line_stays_inside_a_frame_that_pinches_in_within_its_band() {
let notch = |tip: (f64, f64), (y0, y1): (f64, f64)| {
polygon_path(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, y0), tip, (100.0, y1), (100.0, 100.0), (0.0, 100.0)]])
};
let notch =
|tip: (f64, f64), (y0, y1): (f64, f64)| closed(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, y0), tip, (100.0, y1), (100.0, 100.0), (0.0, 100.0)]]);
let far = PathData::from_bezpath(&Rect::new(300.0, 0.0, 310.0, 100.0).to_path(0.1));
let far = vectorcraft_doc::WrapShape { path: far, wrap: Default::default() };
for (frame, x) in
@@ -503,7 +579,7 @@ fn a_line_stays_inside_a_frame_that_pinches_in_within_its_band() {
fn a_line_stays_clear_of_a_wrap_object_that_reaches_into_its_band() {
let frame = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1);
let spans = |shape: &[(f64, f64)], offset: f64, invert: bool| {
let path = PathData::from_bezpath(&polygon_path(&[shape]));
let path = PathData::from_bezpath(&closed(&[shape]));
let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset, invert } };
let cells = Region::cells(&frame, &LayoutOptions::default(), &[wrap]);
assert!(cells[0].rect);
@@ -513,7 +589,7 @@ fn a_line_stays_clear_of_a_wrap_object_that_reaches_into_its_band() {
assert_spans(&spans(&[(100.0, 47.0), (40.0, 47.5), (100.0, 48.0)], 1.0, false), &[(0.0, 39.0)]);
// Two contours that cancel each other (even-odd) hold no area and leave the line whole.
let band: &[(f64, f64)] = &[(0.0, 45.0), (100.0, 45.0), (100.0, 55.0), (0.0, 55.0)];
let path = PathData::from_bezpath(&polygon_path(&[band, band]));
let path = PathData::from_bezpath(&closed(&[band, band]));
let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert: false } };
assert_spans(&Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(40.0, 60.0), &[(0.0, 100.0)]);
let notch = [(0.0, 0.0), (100.0, 0.0), (100.0, 45.0), (60.0, 47.5), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)];
@@ -524,19 +600,19 @@ fn a_line_stays_clear_of_a_wrap_object_that_reaches_into_its_band() {
// An Invert Wrap shape that steps sideways within the band keeps the room its offset bridges.
let upper: &[(f64, f64)] = &[(0.0, 0.0), (40.0, 0.0), (40.0, 50.0), (0.0, 50.0)];
let lower: &[(f64, f64)] = &[(45.0, 50.0), (85.0, 50.0), (85.0, 100.0), (45.0, 100.0)];
let path = PathData::from_bezpath(&polygon_path(&[upper, lower]));
let path = PathData::from_bezpath(&closed(&[upper, lower]));
let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 5.0, invert: true } };
assert_spans(&Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(40.0, 60.0), &[(40.0, 45.0)]);
// An Invert Wrap shape of two parts whose offsets meet across the gap between them (45.25 + 5
// reaches past 55.125 - 5) keeps the whole line.
let upper: &[(f64, f64)] = &[(0.0, 0.0), (100.0, 0.0), (100.0, 45.25), (0.0, 45.25)];
let lower: &[(f64, f64)] = &[(0.0, 55.125), (100.0, 55.125), (100.0, 100.0), (0.0, 100.0)];
let path = PathData::from_bezpath(&polygon_path(&[upper, lower]));
let path = PathData::from_bezpath(&closed(&[upper, lower]));
let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 5.0, invert: true } };
assert_spans(&Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(40.0, 60.0), &[(0.0, 100.0)]);
// A gap the offsets do not bridge (45 + 5 stops short of 55.125 - 5) holds no line.
let upper: &[(f64, f64)] = &[(0.0, 0.0), (100.0, 0.0), (100.0, 45.0), (0.0, 45.0)];
let path = PathData::from_bezpath(&polygon_path(&[upper, lower]));
let path = PathData::from_bezpath(&closed(&[upper, lower]));
let wrap = vectorcraft_doc::WrapShape { path, wrap: vectorcraft_doc::TextWrap { offset: 5.0, invert: true } };
assert!(Region::cells(&frame, &LayoutOptions::default(), &[wrap])[0].spans(40.0, 60.0).is_empty());
}
@@ -546,7 +622,7 @@ fn a_line_stays_clear_of_a_wrap_object_that_reaches_into_its_band() {
#[cfg(test)]
#[test]
fn a_hole_inside_a_band_splits_the_line() {
let frame = polygon_path(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], &[(40.0, 52.0), (60.0, 52.0), (60.0, 58.0), (40.0, 58.0)]]);
let frame = closed(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], &[(40.0, 52.0), (60.0, 52.0), (60.0, 58.0), (40.0, 58.0)]]);
let cells = Region::cells(&frame, &LayoutOptions::default(), &[]);
assert!(!cells[0].rect);
assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 40.0), (60.0, 100.0)]);
@@ -564,48 +640,42 @@ fn a_hole_inside_a_band_splits_the_line() {
#[cfg(test)]
#[test]
fn lines_cross_an_edge_two_contours_share() {
let seam = polygon_path(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], &[(0.0, 50.0), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)]]);
let seam = closed(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], &[(0.0, 50.0), (100.0, 50.0), (100.0, 100.0), (0.0, 100.0)]]);
let cells = Region::cells(&seam, &LayoutOptions::default(), &[]);
assert!(!cells[0].rect);
assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]);
let step = polygon_path(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], &[(0.0, 50.0), (50.0, 50.0), (50.0, 100.0), (0.0, 100.0)]]);
let step = closed(&[&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)], &[(0.0, 50.0), (50.0, 50.0), (50.0, 100.0), (0.0, 100.0)]]);
let cells = Region::cells(&step, &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 50.0)]);
// Contours that meet along a seam that bends within the band, one drawn each way along it.
let bent = polygon_path(&[
let bent = closed(&[
&[(0.0, 0.0), (50.0, 0.0), (70.0, 47.5), (50.0, 100.0), (0.0, 100.0)],
&[(50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0), (70.0, 47.5)],
]);
let cells = Region::cells(&bent, &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]);
// Contours side by side, meeting along a vertical edge.
let side = polygon_path(&[&[(0.0, 0.0), (50.0, 0.0), (50.0, 100.0), (0.0, 100.0)], &[(50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0)]]);
let side = closed(&[&[(0.0, 0.0), (50.0, 0.0), (50.0, 100.0), (0.0, 100.0)], &[(50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0)]]);
let cells = Region::cells(&side, &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]);
// The same, with an extra anchor on one side of the shared edge.
let split = polygon_path(&[
&[(0.0, 0.0), (50.0, 0.0), (50.0, 50.0), (50.0, 100.0), (0.0, 100.0)],
&[(50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0)],
]);
let split =
closed(&[&[(0.0, 0.0), (50.0, 0.0), (50.0, 50.0), (50.0, 100.0), (0.0, 100.0)], &[(50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (50.0, 100.0)]]);
let cells = Region::cells(&split, &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]);
// A slanted shared edge with an extra anchor on one side.
let slanted = polygon_path(&[
&[(0.0, 0.0), (40.0, 0.0), (50.0, 50.0), (60.0, 100.0), (0.0, 100.0)],
&[(40.0, 0.0), (100.0, 0.0), (100.0, 100.0), (60.0, 100.0)],
]);
let slanted =
closed(&[&[(0.0, 0.0), (40.0, 0.0), (50.0, 50.0), (60.0, 100.0), (0.0, 100.0)], &[(40.0, 0.0), (100.0, 0.0), (100.0, 100.0), (60.0, 100.0)]]);
let cells = Region::cells(&slanted, &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 100.0)]);
// Slanted edges of two contours 1e-7 pt apart are not one edge: the line stops at each.
let near = polygon_path(&[
&[(0.0, 0.0), (40.0, 0.0), (60.0, 100.0), (0.0, 100.0)],
&[(40.0 + 1e-7, 0.0), (100.0, 0.0), (100.0, 100.0), (60.0 + 1e-7, 100.0)],
]);
let near =
closed(&[&[(0.0, 0.0), (40.0, 0.0), (60.0, 100.0), (0.0, 100.0)], &[(40.0 + 1e-7, 0.0), (100.0, 0.0), (100.0, 100.0), (60.0 + 1e-7, 100.0)]]);
let cells = Region::cells(&near, &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(40.0, 60.0), &[(0.0, 48.0), (52.0 + 1e-7, 100.0)]);
// The same 1e-6 pt apart, 1e8 pt from the origin.
let (x, y) = (1e8, 1e8);
let far = polygon_path(&[
let far = closed(&[
&[(x, y), (x + 40.0, y), (x + 60.0, y + 100.0), (x, y + 100.0)],
&[(x + 40.0 + 1e-6, y), (x + 100.0, y), (x + 100.0, y + 100.0), (x + 60.0 + 1e-6, y + 100.0)],
]);
@@ -614,14 +684,14 @@ fn lines_cross_an_edge_two_contours_share() {
assert!(spans.len() == 2 && spans[0].1 < x + 48.001 && spans[1].0 > x + 51.999, "{spans:?}");
// A real gap of 0.01 pt between contours far from the origin stays a gap.
let x = 1e8;
let apart = polygon_path(&[
let apart = closed(&[
&[(x, 0.0), (x + 50.0, 0.0), (x + 50.0, 100.0), (x, 100.0)],
&[(x + 50.01, 0.0), (x + 100.0, 0.0), (x + 100.0, 100.0), (x + 50.01, 100.0)],
]);
let cells = Region::cells(&apart, &LayoutOptions::default(), &[]);
assert_spans(&cells[0].spans(40.0, 60.0), &[(x, x + 50.0), (x + 50.01, x + 100.0)]);
// So does a gap of 1e-7 pt between vertical edges there, a few units of rounding wide.
let apart = polygon_path(&[
let apart = closed(&[
&[(x, 0.0), (x + 50.0, 0.0), (x + 50.0, 100.0), (x, 100.0)],
&[(x + 50.0 + 1e-7, 0.0), (x + 100.0, 0.0), (x + 100.0, 100.0), (x + 50.0 + 1e-7, 100.0)],
]);
@@ -637,7 +707,7 @@ fn many_overlapping_edges_in_a_band_hold_no_line_outside_the_frame() {
let strips: Vec<Vec<(f64, f64)>> =
(0..200).map(|i| f64::from(i) * 2.0).map(|x| vec![(x, 0.0), (x + 1.0, 0.0), (x + 501.0, 100.0), (x + 500.0, 100.0)]).collect();
let strips: Vec<&[(f64, f64)]> = strips.iter().map(Vec::as_slice).collect();
let cells = Region::cells(&polygon_path(&strips), &LayoutOptions::default(), &[]);
let cells = Region::cells(&closed(&strips), &LayoutOptions::default(), &[]);
assert!(cells[0].spans(40.0, 60.0).is_empty());
assert!(!cells[0].spans(50.0, 50.0).is_empty());
}
@@ -648,7 +718,7 @@ fn many_overlapping_edges_in_a_band_hold_no_line_outside_the_frame() {
#[test]
fn flat_frames_and_rectangles_keep_their_spans() {
for height in [0.0, 1e-5] {
let flat = polygon_path(&[&[(0.0, 0.0), (10.0, 0.0), (0.0, height)], &[(20.0, 0.0), (30.0, 0.0), (20.0, height)]]);
let flat = closed(&[&[(0.0, 0.0), (10.0, 0.0), (0.0, height)], &[(20.0, 0.0), (30.0, 0.0), (20.0, height)]]);
let cells = Region::cells(&flat, &LayoutOptions::default(), &[]);
assert!(!cells[0].rect);
assert!(cells[0].spans(-5.0, 5.0).iter().all(|&(a, b)| b - a < 1e-3));
@@ -659,3 +729,72 @@ fn flat_frames_and_rectangles_keep_their_spans() {
assert_eq!((cells[0].top(), cells[0].bottom()), (10.0, 90.0));
assert_spans(&cells[0].spans(40.0, 60.0), &[(10.0, 90.0)]);
}
/// On a triangle, the inset keeps the line 10 pt from the sloped edge, measured from the edge
/// itself (x + y <= 100 - 10√2 at the band's bottom), not 10 pt along the line.
#[cfg(test)]
#[test]
fn inset_on_a_shaped_frame_is_measured_from_its_sloped_edge() {
let triangle = closed(&[&[(0.0, 0.0), (100.0, 0.0), (0.0, 100.0)]]);
let inset = |inset| cell_spans(&triangle, &LayoutOptions { inset, ..LayoutOptions::default() }, &[], 40.0, 60.0);
assert_spans(&inset(10.0)[0], &[(10.0, 40.0 - 10.0 * std::f64::consts::SQRT_2)]);
assert_spans(&inset(0.0)[0], &[(0.0, 40.0)]);
}
/// A rectangular frame keeps its inset from each side, and its first line starts the inset below
/// its top.
#[cfg(test)]
#[test]
fn a_rectangular_frame_keeps_its_inset_from_each_side() {
let cells = Region::cells(&Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1), &LayoutOptions { inset: 10.0, ..LayoutOptions::default() }, &[]);
assert!(cells[0].rect);
assert_eq!((cells[0].top(), cells[0].bottom()), (10.0, 90.0));
assert_spans(&cells[0].spans(40.0, 60.0), &[(10.0, 90.0)]);
}
/// The inset keeps text clear of a hole's sloped edges too.
#[cfg(test)]
#[test]
fn inset_keeps_text_clear_of_a_hole_s_sloped_edges() {
let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
let diamond = [(50.0, 30.0), (70.0, 50.0), (50.0, 70.0), (30.0, 50.0)];
let spans = cell_spans(&closed(&[&square, &diamond]), &LayoutOptions { inset: 5.0, ..LayoutOptions::default() }, &[], 40.0, 44.0);
let clear = 5.0 * std::f64::consts::SQRT_2;
assert_spans(&spans[0], &[(5.0, 36.0 - clear), (64.0 + clear, 95.0)]);
}
/// In a frame of columns, the inset is kept once from a column's inner edge and once from the
/// frame's sloped edge.
#[cfg(test)]
#[test]
fn inset_applies_once_at_a_column_s_edge_and_at_the_frame_s_edge() {
let triangle = closed(&[&[(0.0, 0.0), (100.0, 0.0), (0.0, 100.0)]]);
let spans = cell_spans(&triangle, &LayoutOptions { inset: 10.0, columns: 2, gutter: 0.0, ..LayoutOptions::default() }, &[], 10.0, 20.0);
assert_spans(&spans[0], &[(10.0, 40.0)]);
assert_spans(&spans[1], &[(60.0, 80.0 - 10.0 * std::f64::consts::SQRT_2)]);
}
/// An inset wider than a shaped frame leaves no room for text, whatever its size.
#[cfg(test)]
#[test]
fn an_inset_wider_than_a_shaped_frame_leaves_no_room() {
let triangle = closed(&[&[(0.0, 0.0), (100.0, 0.0), (0.0, 100.0)]]);
for inset in [40.0, 1e300, f64::INFINITY] {
let cells = Region::cells(&triangle, &LayoutOptions { inset, ..LayoutOptions::default() }, &[]);
assert!(cells[0].spans(40.0, 60.0).is_empty() && cells[0].span(40.0, 60.0).is_none(), "inset {inset}");
}
}
/// Along the line, text keeps the inset beside a wrap object, around it and, with Invert Wrap,
/// inside it.
#[cfg(test)]
#[test]
fn text_keeps_the_inset_beside_a_wrap_object_along_the_line() {
let frame = Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1);
let shape = PathData::from_bezpath(&Rect::new(40.0, 40.0, 60.0, 60.0).to_path(0.1));
let opts = LayoutOptions { inset: 5.0, ..LayoutOptions::default() };
for (invert, want) in [(false, vec![(5.0, 35.0), (65.0, 95.0)]), (true, vec![(45.0, 55.0)])] {
let wrap = vectorcraft_doc::WrapShape { path: shape.clone(), wrap: vectorcraft_doc::TextWrap { offset: 0.0, invert } };
assert_spans(&cell_spans(&frame, &opts, &[wrap], 45.0, 55.0)[0], &want);
}
}
+311 -7
View File
@@ -23,7 +23,8 @@ pub use mesh::{Mesh, extrude_mesh, inflate_meshes, plane_mesh, revolve_mesh};
mod shadow;
pub use shadow::{MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, TOO_COMPLEX_SHADOW};
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2, kurbo::ParamCurveDeriv};
use vectorcraft_geom::kurbo::{ParamCurveArclen, ParamCurveDeriv};
use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Shape, Vec2};
/// Resource limits shared by desktop, CLI and browser evaluation.
const MAX_PROFILE_POINTS: usize = 16_384;
@@ -104,6 +105,10 @@ pub struct Revolve {
/// Samples for each curved profile segment, from [`revolve_curve_samples`] for the surfaces of
/// one object. `None` plans them from the profile alone.
pub curve_samples: Option<usize>,
/// Graphics are mapped onto the side: its faces carry a [`SurfaceCell`], and a closed profile
/// that does not touch the axis takes an anchor where its side is cut. Off by default, which
/// leaves the faces as they are without graphics.
pub map_surface: bool,
}
/// The default light's Rotation and Height: the light of the earlier default direction (45° to the
@@ -133,6 +138,7 @@ impl Default for Revolve {
smooth_shading: true,
cap_ends: true,
curve_samples: None,
map_surface: false,
}
}
}
@@ -362,6 +368,235 @@ pub struct Face {
pub cap: bool,
/// Bounded radial strips for a body face joining two curved endpoint rings.
pub visibility_pieces: Option<Vec<Vec<Point>>>,
/// For a face of the swept side (not an end cap): where its corners lie on the side surface,
/// for a graphic mapped onto it.
pub surface: Option<SurfaceCell>,
}
/// Where a face of Revolve's swept side lies on the side surface, unrolled flat: x runs around the
/// axis and y along the profile, in points. x is the angle from the middle of the surface times the
/// point's own distance from the axis, so a graphic keeps its size at every distance and wraps
/// farther around the axis where the profile comes closer to it. y is the length along the profile
/// from its middle, increasing toward the profile's lower end; on a closed contour that does not
/// touch the axis the middle is where its outer side crosses the middle height of its bounds. The
/// middle of the surface around the axis is the side that faces the viewer before the rotation
/// ([`surface_middle`]). Only the faces of the longest contour of a compound profile carry a cell.
#[derive(Clone, Debug, PartialEq)]
pub struct SurfaceCell {
/// The corners of the face on the page: its `points` before an edge along an end cap's ring
/// is curved.
pub page: Vec<Point>,
/// The surface point of each of `page`, in the same order.
pub uv: Vec<Point>,
/// The face shows the outside of the surface (the side away from the axis, or out of the
/// region a closed profile encloses) to the viewer.
pub outward: bool,
}
/// The size of Revolve's side surface unrolled ([`SurfaceCell`]), which is the side of the
/// profile's longest contour: its width around the axis at that contour's largest distance from it
/// over the part of the sweep a viewer can see from the front ([`surface_span`]: half a turn at
/// most), and the contour's length. `None` when the profile has no length or lies on the axis.
pub fn revolve_surface_size(path: &PathData, bounds: Rect, options: Revolve) -> Option<(f64, f64)> {
let o = options.sanitized();
let axis = revolve_projection(bounds, o).origin.x;
let sp = path.subpaths.get(longest_contour(path, axis)?)?;
let length = swept_length(sp, axis);
let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) };
let radius = (0..segments).map(|i| sp.segment(i).bounding_box()).fold(0.0f64, |r, b| r.max((b.x0 - axis).abs()).max((b.x1 - axis).abs()));
let width = surface_span(o.angle.to_radians(), o.edge) * radius;
(width.is_finite() && length.is_finite() && width > 0.0 && length > 0.0).then_some((width, length))
}
/// The length of contour `sp` that sweeps a surface about `axis`: every segment but those that lie
/// wholly on the axis.
fn swept_length(sp: &vectorcraft_geom::SubPath, axis: f64) -> f64 {
let segments = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) };
(0..segments)
.map(|i| {
// A segment sweeps nothing only when the whole of it lies on the axis: its control
// points as well as its ends.
let c = sp.segment(i);
let on_axis = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| (p.x - axis).abs() <= 1e-9);
if on_axis { 0.0 } else { ParamCurveArclen::arclen(&c, 1e-3) }
})
.sum()
}
/// The contour of `path` with the longest [`swept_length`] about `axis` (the first of equal ones),
/// which carries Revolve's graphics. `None` when no contour sweeps a surface.
fn longest_contour(path: &PathData, axis: f64) -> Option<usize> {
path.subpaths
.iter()
.map(|sp| swept_length(sp, axis))
.enumerate()
.filter(|(_, l)| l.is_finite() && *l > 0.0)
.fold(None, |best: Option<(usize, f64)>, (k, l)| if best.is_some_and(|(_, top)| top >= l) { best } else { Some((k, l)) })
.map(|(k, _)| k)
}
/// The angle of a Revolve sweep of `sweep` radians, about an axis on the profile's `edge`, at the
/// middle of its side surface ([`SurfaceCell`]). Before the rotation the viewer looks straight at
/// the angle 90° with the axis on the left and 270° with it on the right, and sees the half turn
/// around it. The middle is the middle of the part of the sweep in that half turn, or half the
/// sweep when no part is in it.
fn surface_middle(sweep: f64, edge: Edge) -> f64 {
use std::f64::consts::{FRAC_PI_2, PI};
match edge {
Edge::Left => FRAC_PI_2.min(sweep / 2.0),
Edge::Right if sweep > PI => (3.0 * FRAC_PI_2).min((PI + sweep) / 2.0),
Edge::Right => sweep / 2.0,
}
}
/// The angle of a Revolve sweep of `sweep` radians about an axis on `edge` that a viewer sees from
/// the front before the rotation, about [`surface_middle`]: the part of the sweep in the half turn
/// facing the viewer, or the whole sweep when no part is in it.
fn surface_span(sweep: f64, edge: Edge) -> f64 {
use std::f64::consts::PI;
match edge {
Edge::Right if sweep > PI => (sweep - PI).min(PI),
_ => sweep.min(PI),
}
}
/// The surface y ([`SurfaceCell`]) of each end of each piece of a contour's profile `profile`
/// about `axis`: the length along the profile from its middle, counted from just after the
/// pieces that lie on the axis (which sweep no surface and add no length) on a closed contour.
fn along_profile(profile: &[Point], axis: f64, closed: bool) -> Vec<[f64; 2]> {
let n = profile.len().saturating_sub(1);
if n == 0 {
return vec![];
}
let on_axis = |k: usize| match (profile.get(k), profile.get(k + 1)) {
(Some(a), Some(b)) => (a.x - axis).abs() <= 1e-9 && (b.x - axis).abs() <= 1e-9,
_ => true,
};
if closed
&& !(0..n).any(&on_axis)
&& let Some(out) = around_ring(profile, axis, n)
{
return out;
}
let start = if closed { (0..n).find(|&k| on_axis((k + n - 1) % n) && !on_axis(k)).unwrap_or(0) } else { 0 };
let mut out = vec![[0.0; 2]; n];
let mut length = 0.0;
for step in 0..n {
let k = (start + step) % n;
let piece = if on_axis(k) { 0.0 } else { profile.get(k).zip(profile.get(k + 1)).map_or(0.0, |(a, b)| a.distance(*b)) };
if let Some(slot) = out.get_mut(k) {
*slot = [length, length + piece];
}
length += piece;
}
// y increases toward the profile's lower end on the page: the end of an open contour, or the
// point half way along a closed one.
let middle = length / 2.0;
let first = profile.get(start).map_or(0.0, |p| p.y);
let end = if closed {
(0..n)
.map(|step| (start + step) % n)
.find_map(|k| {
let [a, b] = *out.get(k)?;
let (p, q) = (profile.get(k)?, profile.get(k + 1)?);
(b >= middle).then(|| p.y + (q.y - p.y) * if b > a { (middle - a) / (b - a) } else { 0.0 })
})
.unwrap_or(first)
} else {
profile.last().map_or(first, |p| p.y)
};
let sign = if end >= first { 1.0 } else { -1.0 };
out.into_iter().map(|[a, b]| [(a - middle) * sign, (b - middle) * sign]).collect()
}
/// [`along_profile`] of a closed contour `profile` of `n` pieces with none on `axis`: y is 0 where
/// the contour's outer side (its crossing farthest from the axis) crosses the middle height of its
/// bounds and increases from there in the direction that runs down the page. The contour is cut at
/// its anchor nearest half way around from there, on its far side. `None` when the contour has no
/// height or no length.
fn around_ring(profile: &[Point], axis: f64, n: usize) -> Option<Vec<[f64; 2]>> {
let RingFrame { ends, length, at, sign } = ring_frame(profile, axis, n)?;
// The cut is at the anchor nearest half way around from the crossing, so no piece runs across
// it: the pieces run on from there, once around. [`ring_cut`] puts an anchor there.
let opposite = at + length / 2.0;
let round = |d: f64| {
let d = d.rem_euclid(length);
d.min(length - d)
};
let cut = ends
.iter()
.map(|[a, _]| *a)
.fold(None, |best: Option<f64>, a| if best.is_some_and(|b| round(b - opposite) <= round(a - opposite)) { best } else { Some(a) })?;
let first = (cut - at).rem_euclid(length) - length;
Some(
ends.into_iter()
.map(|[a, b]| {
let s = first + (a - cut).rem_euclid(length);
[s * sign, (s + (b - a)) * sign]
})
.collect(),
)
}
/// Where a closed contour `profile` with no piece on `axis` is cut for [`around_ring`]: the piece
/// that the point half way around from its outer crossing lies inside, and how far along it, when
/// that point is not an anchor already. `None` otherwise, or for a contour that [`around_ring`]
/// does not measure.
fn ring_cut(profile: &[Point], axis: f64) -> Option<(usize, f64)> {
let n = profile.len().saturating_sub(1);
let on_axis = |k: usize| match (profile.get(k), profile.get(k + 1)) {
(Some(a), Some(b)) => (a.x - axis).abs() <= 1e-9 && (b.x - axis).abs() <= 1e-9,
_ => true,
};
if n == 0 || (0..n).any(on_axis) {
return None;
}
let RingFrame { ends, length, at, .. } = ring_frame(profile, axis, n)?;
let opposite = (at + length / 2.0).rem_euclid(length);
ends.iter().enumerate().find_map(|(k, [a, b])| {
let t = if b > a { (opposite - a) / (b - a) } else { return None };
(t > 1e-9 && t < 1.0 - 1e-9).then_some((k, t))
})
}
/// The pieces of a closed contour, measured for [`around_ring`].
struct RingFrame {
/// Each piece's length along the contour from its first anchor, at each end.
ends: Vec<[f64; 2]>,
/// The contour's length.
length: f64,
/// The length along the contour of its crossing farthest from the axis at the middle height
/// of its bounds.
at: f64,
/// 1 when the contour runs down the page there, -1 when it runs up.
sign: f64,
}
/// [`RingFrame`] of closed contour `profile` of `n` pieces about `axis`. `None` when the contour
/// has no height or no length.
fn ring_frame(profile: &[Point], axis: f64, n: usize) -> Option<RingFrame> {
let (top, bottom) = profile.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(t, b), p| (t.min(p.y), b.max(p.y)));
let mid = (top + bottom) / 2.0;
let mut ends = Vec::with_capacity(n);
let mut length = 0.0;
// The crossing farthest from the axis: its distance from it, its length along the contour
// and the direction down the page there.
let mut crossing: Option<(f64, f64, f64)> = None;
for k in 0..n {
let (p, q) = (profile.get(k)?, profile.get(k + 1)?);
let piece = p.distance(*q);
if (p.y - mid) * (q.y - mid) <= 0.0 && p.y != q.y {
let t = (mid - p.y) / (q.y - p.y);
let distance = (p.x + (q.x - p.x) * t - axis).abs();
if crossing.is_none_or(|(far, ..)| distance > far) {
crossing = Some((distance, length + piece * t, if q.y > p.y { 1.0 } else { -1.0 }));
}
}
ends.push([length, length + piece]);
length += piece;
}
let (_, at, sign) = crossing?;
(length.is_finite() && length > 0.0).then_some(RingFrame { ends, length, at, sign })
}
impl Face {
@@ -471,6 +706,7 @@ fn project_face(vertices: &[V3], normals: Option<&[V3]>, o: Revolve, origin: Poi
outline: None,
cap: false,
visibility_pieces: None,
surface: None,
}))
}
@@ -703,6 +939,13 @@ fn revolve_projection(bounds: Rect, o: Revolve) -> shadow::Projection {
shadow::Projection { view: o, origin: Point::new(axis, center_y), eye }
}
/// The most faces one Revolve surface with sanitized options `o` holds. With graphics mapped, a
/// closed contour may take one more edge where its side is cut ([`ring_cut`]): the surface may
/// hold that edge's faces past [`MAX_REVOLVE_FACES`], which the profile was planned within.
fn revolve_face_limit(o: Revolve) -> usize {
MAX_REVOLVE_FACES + if o.map_surface { o.steps().saturating_mul(2) } else { 0 }
}
/// [`revolve`], or with `mesh` the surface's faces before projection, kept there instead of drawn,
/// each turned out of the region `rule` fills.
fn revolve_faces(
@@ -720,10 +963,11 @@ fn revolve_faces(
// For a mesh, each piece of a closed contour's edge is cut where it crosses another contour, so
// each part's normal turns toward a hole only where it walls one.
let mut search = if mesh.is_some() { Some(HoleSearch::new(path, rule)?) } else { None };
let face_limit = revolve_face_limit(o);
// A face kept for a mesh: its normal follows from its corners.
let keep = |mesh: &mut Vec<solid::Face3>, face: Vec<V3>, normal: V3| {
mesh.push((vec![face], normal));
if mesh.len() > MAX_REVOLVE_FACES { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) }
if mesh.len() > face_limit { Err(TOO_COMPLEX_SURFACE.to_string()) } else { Ok(()) }
};
if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite() && v.abs() <= 1e8) {
return Err("Revolve requires finite profile coordinates within 100 million points".into());
@@ -734,6 +978,27 @@ fn revolve_faces(
let smooth = o.shade && o.smooth_shading;
let [lx, ly, lz] = o.light_direction();
let light = V3(lx, ly, lz);
// The side surface's angle at each end of step `j` ([`SurfaceCell`]): from the middle of the
// surface, increasing to the viewer's right. The middle is the middle of the part of the sweep
// that faces the viewer before the rotation, and at most the angle that faces the viewer
// straight on: 90° with the axis on the profile's left, 270° with it on the right. A sweep
// with no part facing the viewer has its middle at half the sweep. A full turn is cut at the
// back, at the edge between two steps nearest half a turn from the middle: each step is placed
// by its own middle, within half a turn of the surface's middle, so the steps meet edge to
// edge on either side of the cut.
let middle = surface_middle(sweep, o.edge);
let full = o.angle >= 360.0;
let surface_angle = |j: usize| {
let (from, to) = (sweep * j as f64 / steps as f64, sweep * (j + 1) as f64 / steps as f64);
let half = (to - from) / 2.0;
let mut start = middle - from;
if full {
start = (start - half + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI + half;
}
[start, start - (to - from)]
};
// Only the longest contour of a compound profile carries the graphics.
let surface_contour = o.map_surface.then(|| longest_contour(path, axis)).flatten();
let mut faces = Vec::new();
let vertex = |p: Point, step: usize| {
let (s, c) = (sweep * step as f64 / steps as f64).sin_cos();
@@ -748,7 +1013,7 @@ fn revolve_faces(
if let Some(face) = face {
faces.push(face);
mesh_cost += cost;
if mesh_cost > MAX_REVOLVE_FACES {
if mesh_cost > face_limit {
return Err(TOO_COMPLEX_SURFACE.into());
}
}
@@ -833,9 +1098,26 @@ fn revolve_faces(
let area: f64 = ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.0 * q.1 - q.0 * p.1).sum();
if area < 0.0 { -1.0 } else { 1.0 }
};
// A closed contour that does not touch the axis has its side cut opposite the middle of its
// outer side; an anchor goes there, so no face runs across the cut. That one anchor is not
// counted against the limit on the profile's points.
if sp.closed
&& surface_contour == Some(contour)
&& let Some((k, t)) = ring_cut(&profile, axis)
&& let (Some(a), Some(b), Some([ta, tb]), Some(hole)) =
(profile.get(k), profile.get(k + 1), tangents.get(k).copied(), hole_edges.get(k).copied())
{
let point = *a + (*b - *a) * t;
let middle = ta + (tb - ta) * t;
profile.insert(k + 1, point);
tangents.splice(k..=k, [[ta, middle], [middle, tb]]);
hole_edges.insert(k + 1, hole);
}
let along = along_profile(&profile, axis, sp.closed);
for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(tangents).zip(hole_edges).enumerate() {
let [a, b] = pair else { continue };
let turn = if hole { -turn } else { turn };
let [va, vb] = along.get(i).copied().unwrap_or_default();
if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) {
return Err("Revolve profile contains invalid coordinates".into());
}
@@ -851,20 +1133,42 @@ fn revolve_faces(
}
let first = (i == 0).then(|| rings.first().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten();
let last = (i + 2 == profile.len()).then(|| rings.last().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten();
let projected = |vertices: &[V3], normals: Option<&[V3]>, edges: &[(usize, &caps::RingArc, bool)]| {
// Where the corners lie on the unrolled side surface, and whether the face shows
// its outside: the edge's outward normal swept to the middle of the step.
// x is the angle times the corner's own distance from the axis.
let [t0, t1] = surface_angle(j);
let (ra, rb) = ((a.x - axis).abs(), (b.x - axis).abs());
let corners = [Point::new(t0 * ra, va), Point::new(t0 * rb, vb), Point::new(t1 * rb, vb), Point::new(t1 * ra, va)];
let on_surface = surface_contour == Some(contour);
let outward = {
let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn);
let (s, c) = (sweep * (j as f64 + 0.5) / steps as f64).sin_cos();
let n = o.rotate(V3(dy * c, -dr, dy * s));
let middle = [v0, v1, v2, v3].iter().fold(V3::default(), |m, v| V3(m.0 + v.0 / 4.0, m.1 + v.1 / 4.0, m.2 + v.2 / 4.0));
let toward = eye.map_or(V3(0.0, 0.0, 1.0), |e| V3(-middle.0, -middle.1, e - middle.2));
n.dot(toward) > 0.0
};
let projected = |vertices: &[V3], normals: Option<&[V3]>, edges: &[(usize, &caps::RingArc, bool)], uv: &[usize]| {
let mut face = project_face(vertices, normals, o, Point::new(axis, center_y), eye, light)?;
if let Some(face) = &mut face {
let page = face.points.clone();
caps::curve_edges(face, edges);
if on_surface {
let uv = uv.iter().filter_map(|k| corners.get(*k).copied()).collect();
face.surface = Some(SurfaceCell { page, uv, outward });
}
}
Ok::<_, String>(face)
};
if smooth {
let [n0, n1, n2, n3] = [normal(ta, j), normal(tb, j), normal(tb, j + 1), normal(ta, j + 1)];
emit(projected(&[v0, v1, v2], Some(&[n0, n1, n2]), &last.map(|arc| (1, arc, false)).into_iter().collect::<Vec<_>>())?, 1)?;
emit(projected(&[v0, v2, v3], Some(&[n0, n2, n3]), &first.map(|arc| (2, arc, true)).into_iter().collect::<Vec<_>>())?, 1)?;
let last: Vec<_> = last.map(|arc| (1, arc, false)).into_iter().collect();
let first: Vec<_> = first.map(|arc| (2, arc, true)).into_iter().collect();
emit(projected(&[v0, v1, v2], Some(&[n0, n1, n2]), &last, &[0, 1, 2])?, 1)?;
emit(projected(&[v0, v2, v3], Some(&[n0, n2, n3]), &first, &[0, 2, 3])?, 1)?;
} else {
let edges: Vec<_> = last.map(|arc| (1, arc, false)).into_iter().chain(first.map(|arc| (3, arc, true))).collect();
emit(projected(&[v0, v1, v2, v3], None, &edges)?, 1)?;
emit(projected(&[v0, v1, v2, v3], None, &edges, &[0, 1, 2, 3])?, 1)?;
}
}
}
+184
View File
@@ -184,6 +184,190 @@ fn perspective_runs_0_to_160_degrees_with_the_eye_outside_the_object() {
assert_eq!(wide, revolve(&p, b, Revolve { rotation_x: -30.0, perspective: 400.0, ..Default::default() }).unwrap());
}
#[test]
fn side_faces_lie_on_the_unrolled_surface_and_caps_do_not() {
let (p, b) = cylinder();
// Without graphics no face carries a place on the surface.
let plain = revolve(&p, b, Revolve { rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap();
assert!(plain.iter().all(|f| f.surface.is_none()));
let faces = revolve(&p, b, Revolve { map_surface: true, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap();
assert_eq!(faces.len(), plain.len());
assert!(faces.iter().filter(|f| f.cap).all(|f| f.surface.is_none()));
let side: Vec<_> = faces.iter().filter(|f| !f.cap).collect();
assert!(!side.is_empty() && side.iter().all(|f| f.surface.as_ref().is_some_and(|c| c.uv.len() == c.page.len() && c.uv.len() == 3)));
for f in &side {
let cell = f.surface.as_ref().unwrap();
// Straight on, x around the axis is the angle from the front times the radius 40: a corner
// at page x lies at 40 asin(x / 40) on the front half; y runs 40 each way from the middle,
// downward.
for (q, uv) in cell.page.iter().zip(&cell.uv) {
assert!((uv.y - (q.y - 50.0)).abs() < 1e-9, "{q:?} {uv:?}");
if cell.outward {
assert!((uv.x - 40.0 * (q.x / 40.0).clamp(-1.0, 1.0).asin()).abs() < 1e-6, "{q:?} {uv:?}");
}
}
// The outside faces the viewer on the front half only.
let mean = cell.uv.iter().map(|p| p.x).sum::<f64>() / cell.uv.len() as f64;
assert_eq!(cell.outward, mean.abs() < 40.0 * std::f64::consts::FRAC_PI_2, "{mean}");
}
// A quarter sweep's middle is the middle of the sweep, 45° around the axis.
let quarter = revolve(&p, b, Revolve { map_surface: true, angle: 90.0, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap();
let xs: Vec<f64> = quarter.iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter().map(|p| p.x)).collect();
let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x)));
let reach = 40.0 * std::f64::consts::FRAC_PI_4;
assert!((lo + reach).abs() < 1e-9 && (hi - reach).abs() < 1e-9, "{lo} {hi}");
let (w, h) = revolve_surface_size(&p, b, Revolve::default()).unwrap();
assert!((w - 40.0 * std::f64::consts::PI).abs() < 1e-9 && (h - 80.0).abs() < 1e-3, "{w} {h}");
assert_eq!(revolve_surface_size(&p, Rect::new(40.0, 10.0, 40.0, 90.0), Revolve::default()), None);
// A curve that starts and ends on the axis but bows away from it sweeps a side with a length.
let mut bow = BezPath::new();
bow.move_to((0.0, 0.0));
bow.curve_to((40.0, 0.0), (40.0, 80.0), (0.0, 80.0));
let (w, h) = revolve_surface_size(&PathData::from_bezpath(&bow), Rect::new(0.0, 0.0, 30.0, 80.0), Revolve::default()).unwrap();
assert!((w - 30.0 * std::f64::consts::PI).abs() < 1e-9 && h > 80.0, "{w} {h}");
}
#[test]
fn the_side_keeps_its_length_around_the_axis_at_every_distance_from_it() {
// A step: 40 from the axis, 20 between y 40 and 60, then 40 again.
let mut bp = BezPath::new();
bp.move_to((40.0, 10.0));
for p in [(40.0, 40.0), (20.0, 40.0), (20.0, 60.0), (40.0, 60.0), (40.0, 90.0)] {
bp.line_to(p);
}
let (p, b) = (PathData::from_bezpath(&bp), Rect::new(0.0, 10.0, 40.0, 90.0));
let faces = revolve(&p, b, Revolve { map_surface: true, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap();
let (mut narrow, mut wide) = (0.0f64, 0.0f64);
for cell in faces.iter().filter_map(|f| f.surface.as_ref()).filter(|c| c.outward) {
// The faces of the narrow part run from y 40 to 60; those of the wide parts reach past
// them; the steps between lie at y 40 or 60 only.
let at = |y: f64| cell.page.iter().any(|q| (q.y - y).abs() < 1e-9);
let radius = if at(40.0) && at(60.0) {
Some(20.0)
} else if cell.page.iter().any(|q| q.y < 40.0 - 1e-9 || q.y > 60.0 + 1e-9) {
Some(40.0)
} else {
None
};
for (q, uv) in cell.page.iter().zip(&cell.uv) {
// Straight on, a corner at page x that is r from the axis lies r asin(x / r) around it.
let fits = |r: f64| (uv.x - r * (q.x / r).clamp(-1.0, 1.0).asin()).abs() < 1e-6;
match radius {
Some(r) => {
assert!(fits(r), "{r}: {q:?} {uv:?}");
let reach = if r < 30.0 { &mut narrow } else { &mut wide };
*reach = reach.max(uv.x.abs());
}
None => assert!(fits(20.0) || fits(40.0), "{q:?} {uv:?}"),
}
}
}
// The half seen from the front reaches a quarter turn each way: 10π at 20 from the axis, 20π
// at 40.
let quarter = std::f64::consts::FRAC_PI_2;
assert!((narrow - 20.0 * quarter).abs() < 1.0 && (wide - 40.0 * quarter).abs() < 2.0, "{narrow} {wide}");
}
#[test]
fn with_the_axis_on_the_right_the_middle_of_the_side_faces_the_viewer() {
let mut bp = BezPath::new();
bp.move_to((0.0, 10.0));
bp.line_to((0.0, 90.0));
let (p, b) = (PathData::from_bezpath(&bp), Rect::new(0.0, 10.0, 40.0, 90.0));
let q = 40.0 * std::f64::consts::FRAC_PI_4;
// The side's reach around the axis either way of its middle: for 270° the middle is 225°, in
// the middle of the part from 180° to 270° that faces the viewer; a quarter turn faces away,
// and its middle is half the sweep.
for (angle, lo_expected, hi_expected) in [(270.0, -q, 5.0 * q), (90.0, -q, q)] {
let o = Revolve { map_surface: true, edge: Edge::Right, angle, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() };
let xs: Vec<f64> = revolve(&p, b, o).unwrap().iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter().map(|p| p.x)).collect();
let (lo, hi) = xs.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x)));
assert!((lo - lo_expected).abs() < 1e-6 && (hi - hi_expected).abs() < 1e-6, "{angle}: {lo} {hi}");
}
// A new graphic fits the part of the sweep that faces the viewer: 90° of a 270° sweep, 20° of
// a 200° one, all of a quarter turn that faces away.
for (angle, seen) in [(270.0f64, 90.0f64), (200.0, 20.0), (90.0, 90.0), (360.0, 180.0)] {
let (w, _) = revolve_surface_size(&p, b, Revolve { edge: Edge::Right, angle, ..Default::default() }).unwrap();
assert!((w - 40.0 * seen.to_radians()).abs() < 1e-9, "{angle}: {w}");
}
// A full turn: straight on, the axis is at x 40, a corner at page x lies 40 asin((x - 40) / 40)
// around it, and the front half shows its outside.
let faces = revolve(&p, b, Revolve { map_surface: true, edge: Edge::Right, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap();
let cells: Vec<_> = faces.iter().filter_map(|f| f.surface.as_ref()).collect();
assert!(cells.iter().any(|c| c.outward));
for cell in &cells {
let mean = cell.uv.iter().map(|p| p.x).sum::<f64>() / cell.uv.len() as f64;
assert_eq!(cell.outward, mean.abs() < 40.0 * std::f64::consts::FRAC_PI_2, "{mean}");
if cell.outward {
for (q, uv) in cell.page.iter().zip(&cell.uv) {
assert!((uv.x - 40.0 * ((q.x - 40.0) / 40.0).clamp(-1.0, 1.0).asin()).abs() < 1e-6, "{q:?} {uv:?}");
}
}
}
}
#[test]
fn only_the_longest_contour_of_a_compound_profile_carries_the_side_surface() {
let mut bp = BezPath::new();
bp.move_to((40.0, 10.0));
bp.line_to((40.0, 90.0));
bp.move_to((20.0, 30.0));
bp.line_to((20.0, 50.0));
let (p, b) = (PathData::from_bezpath(&bp), Rect::new(0.0, 10.0, 40.0, 90.0));
let faces = revolve(&p, b, Revolve { map_surface: true, rotation_x: 0.0, rotation_y: 0.0, ..Default::default() }).unwrap();
let short = |f: &Face| f.points.iter().all(|q| q.y > 29.0 && q.y < 51.0);
assert!(faces.iter().any(|f| !f.cap && short(f)) && faces.iter().any(|f| !f.cap && !short(f)));
for f in faces.iter().filter(|f| !f.cap) {
assert_eq!(f.surface.is_some(), !short(f), "{:?}", f.points);
}
// The side's size is that contour's: with the longest contour 10 from the axis and a shorter
// one 40 from it, the width is half a turn at 10 and the length the longest contour's 80.
let mut bp = BezPath::new();
bp.move_to((10.0, 10.0));
bp.line_to((10.0, 90.0));
bp.move_to((40.0, 30.0));
bp.line_to((40.0, 50.0));
let (w, h) = revolve_surface_size(&PathData::from_bezpath(&bp), b, Revolve::default()).unwrap();
assert!((w - 10.0 * std::f64::consts::PI).abs() < 1e-9 && (h - 80.0).abs() < 1e-3, "{w} {h}");
}
/// The square ring of [`a_ring_profile_is_measured_from_its_outer_side_at_mid_height`] with an
/// anchor in the middle of its inner side.
fn split_square() -> [Point; 6] {
[(20.0, 30.0), (40.0, 30.0), (40.0, 50.0), (20.0, 50.0), (20.0, 40.0), (20.0, 30.0)].map(|(x, y)| Point::new(x, y))
}
#[test]
fn a_ring_profile_is_measured_from_its_outer_side_at_mid_height() {
// A square from 20 to 40 from the axis, starting at its top inner corner and running to the
// right first (down the outer side).
let ring = [(20.0, 30.0), (40.0, 30.0), (40.0, 50.0), (20.0, 50.0), (20.0, 30.0)].map(|(x, y)| Point::new(x, y));
assert_eq!(along_profile(&ring, 0.0, true), vec![[-30.0, -10.0], [-10.0, 10.0], [10.0, 30.0], [30.0, 50.0]]);
// Wound the other way the outer side still runs down the page as y increases. The cut is at
// an inner corner, so each piece's y runs one way across it.
let back = [(20.0, 30.0), (20.0, 50.0), (40.0, 50.0), (40.0, 30.0), (20.0, 30.0)].map(|(x, y)| Point::new(x, y));
assert_eq!(along_profile(&back, 0.0, true), vec![[50.0, 30.0], [30.0, 10.0], [10.0, -10.0], [-10.0, -30.0]]);
// The cut falls half way along a long inner side: Revolve puts an anchor there first, and y
// then runs half the contour's length each way.
let tall = [(20.0, 0.0), (40.0, 0.0), (40.0, 100.0), (20.0, 100.0), (20.0, 0.0)].map(|(x, y)| Point::new(x, y));
assert_eq!(ring_cut(&tall, 0.0), Some((3, 0.5)));
assert_eq!(ring_cut(&ring, 0.0), Some((3, 0.5)));
assert_eq!(ring_cut(&split_square(), 0.0), None);
assert_eq!(along_profile(&split_square(), 0.0, true), vec![[-30.0, -10.0], [-10.0, 10.0], [10.0, 30.0], [30.0, 40.0], [-40.0, -30.0]]);
let split = [(20.0, 0.0), (40.0, 0.0), (40.0, 100.0), (20.0, 100.0), (20.0, 50.0), (20.0, 0.0)].map(|(x, y)| Point::new(x, y));
assert_eq!(along_profile(&split, 0.0, true), vec![[-70.0, -50.0], [-50.0, 50.0], [50.0, 70.0], [70.0, 120.0], [-120.0, -70.0]]);
let mut bp = BezPath::new();
bp.move_to((20.0, 0.0));
for p in [(40.0, 0.0), (40.0, 100.0), (20.0, 100.0)] {
bp.line_to(p);
}
bp.close_path();
let (path, bounds, o) =
(PathData::from_bezpath(&bp), Rect::new(20.0, 0.0, 40.0, 100.0), Revolve { map_surface: true, offset: 20.0, ..Default::default() });
let faces = revolve(&path, bounds, o).unwrap();
// Without graphics the profile takes no anchor at the cut: its inner side stays one edge.
let plain = revolve(&path, bounds, Revolve { map_surface: false, ..o }).unwrap();
assert!(plain.len() < faces.len() && plain.iter().all(|f| f.surface.is_none()), "{} {}", plain.len(), faces.len());
let ys: Vec<f64> = faces.iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter().map(|p| p.y)).collect();
assert!(!ys.is_empty() && ys.iter().all(|y| y.abs() <= 120.0 + 1e-9), "{ys:?}");
let (w, h) = revolve_surface_size(&path, bounds, o).unwrap();
assert!((h - 240.0).abs() < 1e-6 && (w - 40.0 * std::f64::consts::PI).abs() < 1e-9, "{w} {h}");
}
#[test]
fn malformed_and_degenerate_inputs_are_bounded() {
let (p, b) = cylinder();
let f = revolve(&p, b, Revolve { segments: usize::MAX, angle: f64::NAN, offset: f64::INFINITY, ..Default::default() }).unwrap();
@@ -103,6 +103,35 @@ fn the_profiles_of_one_object_share_one_budget() {
assert_eq!(revolve_curve_samples([&both], o), Err(refused));
}
#[test]
fn with_graphics_a_ring_at_the_face_limit_still_takes_the_edge_its_cut_adds() {
// A closed many-sided ring, 50 clear of the axis, with the middle of an edge at the middle of
// its outer side and, with an even number of edges, at the middle of its inner side.
let ring = |edges: usize| {
let anchors = (0..edges)
.map(|i| {
let (s, c) = ((i as f64 + 0.5) * std::f64::consts::TAU / edges as f64).sin_cos();
Anchor::corner(Point::new(300.0 + 100.0 * c, 100.0 * s))
})
.collect();
PathData::new(vec![SubPath::new(anchors, true)])
};
// Tilted, so the flat edges at the top and bottom draw faces too.
let plain = Revolve { offset: 50.0, rotation_x: -20.0, ..Revolve::default() };
let mapped = Revolve { map_surface: true, ..plain };
// 1,280 edges of 128 faces each are the most that fit, with graphics or without.
for o in [plain, mapped] {
assert_eq!(revolve_curve_samples([&ring(1280)], o), Ok(CURVE_SAMPLES));
assert!(revolve_curve_samples([&ring(1281)], o).unwrap_err().contains("reduce Segments"));
}
let faces = revolved(&ring(1280), plain).unwrap();
assert_eq!(faces.len(), MAX_REVOLVE_FACES);
assert!(faces.iter().all(|f| f.surface.is_none()));
// With graphics the side is cut in the middle of the inner edge, which makes one edge more:
// its faces are taken past the limit.
assert_eq!(revolved(&ring(1280), mapped).unwrap().len(), MAX_REVOLVE_FACES + 128);
}
#[test]
fn deeply_nested_contours_stop_the_search_for_holes() {
// Concentric triangles: each tests every contour outside it.
+1
View File
@@ -302,6 +302,7 @@ mod tests {
outline: None,
cap: false,
visibility_pieces: None,
surface: None,
}
}
+67 -11
View File
@@ -5,8 +5,11 @@
//! the canvas draws from the halfway point to the widget grows with it. The upper one sets the
//! blend's color shift (`colorShift`, -100 to 100) and the lower one its easing strength (`ramp`,
//! 0 to 100). The lower one shows only when the steps follow a spine (a replaced or edited spine,
//! or Align to Path), where easing moves them; a blend made without a spine shows neither. A drag along the spine's direction at the press
//! changes the value by one per screen pixel, starting from the value at the press, and the arrow
//! or Align to Path), where easing moves them. A blend made without a spine shows the upper one
//! alone, placed in the same way against the straight lines between its key centers that its steps
//! are laid out along ([`blend_layout_line`]); the canvas does not draw those lines. A drag along
//! the spine's direction at the press changes the value by one per screen pixel, starting from the
//! value at the press, and the arrow
//! keys during the drag change it by one (Shift: by ten); Escape or a switch to another tool
//! cancels the drag and puts the value back. Each drag previews
//! `object.blend.setEasing` and is one undo step, or none when the value ends where it started; a
@@ -14,7 +17,7 @@
//! from the same geometry.
use serde_json::json;
use vectorcraft_doc::live::{Spine, blend_spine};
use vectorcraft_doc::live::{Spine, blend_layout_line};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection};
use vectorcraft_geom::{Point, Rect, Vec2};
@@ -69,7 +72,8 @@ impl BlendControl {
pub struct BlendWidget {
pub id: NodeId,
pub control: BlendControl,
/// The spine's halfway point, in the document.
/// The spine's halfway point, in the document (for a blend without a spine, the halfway point of
/// the line its steps are laid out along).
pub on: Point,
/// The widget's center in the document: [`OFFSET_PX`] from `on`, or further out where other
/// artwork crowds that spot.
@@ -84,9 +88,10 @@ impl BlendWidget {
/// The widgets of the selection at `zoom` (screen px per document point), with `up` the
/// document direction of the screen's up: the Appearance widget, then the Easing widget. Empty
/// unless the selection is one whole blend, visible and unlocked, with two or more keys and a
/// spine of some length, and no anchors are selected. Each widget sits at the first spot out
/// from the spine, in [`OFFSET_PX`] steps, that the boxes of fewer than three other visible
/// objects hold, at most nine steps out; where every spot is crowded it stays at the first.
/// spine (or, without one, a step layout line) of some length, and no anchors are selected.
/// Each widget sits at the first spot out from the spine, in [`OFFSET_PX`] steps, that the
/// boxes of fewer than three other visible objects hold, at most nine steps out; where every
/// spot is crowded it stays at the first.
pub fn of(doc: &Document, selection: &Selection, zoom: f64, up: Vec2) -> Vec<Self> {
let up_len = up.hypot();
let usable = |v: f64| v.is_finite() && v > 0.0;
@@ -98,7 +103,7 @@ impl BlendWidget {
if children.len() < 2 || !doc.is_editable(*id) {
return vec![];
}
let Some(spine) = blend_spine(children, spec).and_then(|(path, _)| Spine::new(&path)) else { return vec![] };
let Some(spine) = blend_layout_line(children, spec).and_then(|path| Spine::new(&path)) else { return vec![] };
if !usable(spine.length()) {
return vec![];
}
@@ -430,9 +435,60 @@ mod tests {
// One key.
let (d, _, s) = blend_doc(&[(100.0, 200.0)], eased());
assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "one key");
// A blend made without a spine (Create Spine › Never), Align to Path included.
let (d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], BlendSpec { no_spine: true, ..eased() });
assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "no spine");
// Without a spine: locked or hidden, or keys on one spot.
let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], BlendSpec { no_spine: true, ..eased() });
for hide in [false, true] {
let mut d = d.clone();
let n = d.node_mut(id).unwrap();
(n.visible, n.locked) = (!hide, !hide);
assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "no spine, hidden: {hide}");
}
let (d, _, s) = blend_doc(&[(100.0, 200.0), (100.0, 200.0)], BlendSpec { no_spine: true, ..eased() });
assert!(BlendWidget::of(&d, &s, 1.0, UP).is_empty(), "no spine, no length");
}
/// A blend made without a spine (Create Spine › Never), Align to Path included, shows the
/// Appearance widget alone, at the halfway point by length of the straight lines between its
/// key centers.
#[test]
fn a_blend_without_a_spine_shows_the_appearance_widget_alone() {
let no_spine = || BlendSpec { no_spine: true, ..eased() };
let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], no_spine());
let w = BlendWidget::of(&d, &s, 1.0, UP);
assert_eq!(w.iter().map(|w| w.control).collect::<Vec<_>>(), [BlendControl::Appearance], "{w:?}");
assert!(w[0].id == id && near(w[0].on, Point::new(200.0, 200.0)) && near(w[0].at, Point::new(200.0, 184.0)), "{w:?}");
assert_eq!(w[0].value, -20.0);
// Halfway along by length, not the middle key: (0, 0), (100, 0), (100, 300) is 400 long.
let (d, _, s) = blend_doc(&[(0.0, 0.0), (100.0, 0.0), (100.0, 300.0)], no_spine());
let w = BlendWidget::of(&d, &s, 1.0, UP);
assert!(w.len() == 1 && near(w[0].on, Point::new(100.0, 100.0)), "{w:?}");
// There the line runs down, so a drag down adds.
assert!(near(Point::new(w[0].along.x, w[0].along.y), Point::new(0.0, 1.0)), "{w:?}");
// Two keys on one spot and a third away: the line still has length.
let (d, _, s) = blend_doc(&[(100.0, 200.0), (100.0, 200.0), (300.0, 200.0)], no_spine());
let w = BlendWidget::of(&d, &s, 1.0, UP);
assert!(w.len() == 1 && near(w[0].on, Point::new(200.0, 200.0)), "{w:?}");
}
/// With the Selection or the Blend tool, a drag of a spineless blend's Appearance widget
/// previews the color shift alone, in one undo step.
#[test]
fn dragging_the_appearance_widget_of_a_blend_without_a_spine() {
let (d, id, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], BlendSpec { no_spine: true, ..eased() });
let p = paint();
let c = cx(&d, &s, &p);
let at = Point::new(200.0, 184.0);
assert!(over_widget(&c, at) && !over_widget(&c, Point::new(200.0, 216.0)), "no Easing widget below");
let tools: [Box<dyn Tool>; 2] = [Box::new(SelectionTool::default()), Box::new(crate::meshblend::BlendTool::default())];
for mut t in tools {
assert!(t.pointer(&c, &ev(PointerKind::Down, at)).is_empty());
let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(30.0, 0.0)));
assert_eq!(
a,
vec![Action::Begin(LABEL.into()), Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "colorShift": 10.0}))]
);
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at + Vec2::new(30.0, 0.0))), vec![Action::Commit]);
}
}
/// A drag of the Easing widget along the spine changes the ramp by one per pixel from its
+5
View File
@@ -34,6 +34,11 @@ pub const MIN_FIDELITY: f64 = 0.01;
/// Fidelity at the highest zoom (64000 %), whose screen pixels the tools send in points (#5729).
pub const MIN_FIT_TOLERANCE: f64 = MIN_FIDELITY / 640.0;
/// The coarsest tolerance (points) `path.freehand` fits a Pencil or Paintbrush stroke at: the highest
/// Fidelity the tools and their Tool Options take (100 px) at the lowest zoom (3.13 %), about 3195 pt.
/// A change to either range changes this bound with it.
pub const MAX_FIT_TOLERANCE: f64 = 100.0 / 0.0313;
/// The lowest Fidelity (points) the Smooth tool takes.
pub const SMOOTH_MIN_FIDELITY: f64 = 0.05;
+9 -2
View File
@@ -42,6 +42,13 @@ const PREVIEW_FIDELITY_PX: f64 = 0.5;
/// The Smooth tool's Fidelity until Smooth Tool Options sets another.
const SMOOTH_FIDELITY: f64 = 2.5;
/// The `fidelity` (points) the Pencil and the Paintbrush send `path.freehand` for `px` screen pixels
/// at the current zoom, within the range the command takes
/// ([`super::MIN_FIT_TOLERANCE`]..[`super::MAX_FIT_TOLERANCE`]).
fn fit_tolerance(cx: &ToolContext, px: f64) -> f64 {
cx.tol(px).clamp(super::MIN_FIT_TOLERANCE, super::MAX_FIT_TOLERANCE)
}
pub struct GestureTool {
/// How many points the last preview of the stroke had ([`crate::previews_at`]); 0 when it was
/// fitted coarser than the stroke kept ([`PREVIEW_FIDELITY_PX`]).
@@ -460,7 +467,7 @@ impl GestureTool {
pub fn freehand_params(&self, cx: &ToolContext, closed: bool) -> Value {
let mut v = json!({
"points": self.stroke_json(),
"fidelity": cx.tol(self.fidelity),
"fidelity": fit_tolerance(cx, self.fidelity),
"closed": closed,
"style": if self.id == "paintbrush" { "brush" } else { "pencil" },
"fill": self.fill,
@@ -654,7 +661,7 @@ impl Tool for GestureTool {
if self.previews() && crate::previews_at(self.points.len()) {
let mut v = self.freehand_params(cx, false);
let fidelity = self.fidelity.max(PREVIEW_FIDELITY_PX);
v["fidelity"] = json!(cx.tol(fidelity));
v["fidelity"] = json!(fit_tolerance(cx, fidelity));
// A preview fitted coarser than the stroke kept is stale (`deactivate`).
self.previewed = if fidelity > self.fidelity { 0 } else { self.points.len() };
if !self.live_fit {
+46
View File
@@ -215,6 +215,52 @@ fn fidelity_is_in_screen_pixels_at_any_zoom() {
}
}
/// The highest Fidelity (100 px) at the lowest zoom (3.13 %) is sent, while the stroke is drawn and
/// at its release, as [`crate::draw2::MAX_FIT_TOLERANCE`], the coarsest tolerance `path.freehand`
/// reads.
#[test]
fn highest_fidelity_at_the_lowest_zoom_sends_the_coarsest_tolerance() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let mut cx = cx(&d, &s, &p);
cx.zoom = 0.0313;
let stroke: Vec<_> = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)].iter().map(|&(x, y)| (x / cx.zoom, y / cx.zoom)).collect();
for id in ["pencil", "paintbrush"] {
let mut t = GestureTool::new(id);
t.set_option("fidelity", &json!(100.0));
let acts = drag(&mut t, &cx, &stroke, Mods::default());
let sent: Vec<_> =
acts.concat().into_iter().filter_map(|a| if let Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }).collect();
assert_eq!(sent, [crate::draw2::MAX_FIT_TOLERANCE; 4], "{id}");
}
}
/// `path.freehand` rejects a `fidelity` outside `MIN_FIT_TOLERANCE..=MAX_FIT_TOLERANCE`, so at a zoom
/// beyond the view's range the Pencil and the Paintbrush send the nearer end of it, while the stroke
/// is drawn and at its release.
#[test]
fn fidelity_sent_stays_within_what_path_freehand_takes() {
let (d, _) = doc_with_rect();
let s = Selection::default();
let p = paint();
let mut cx = cx(&d, &s, &p);
let (lo, hi) = (crate::draw2::MIN_FIT_TOLERANCE, crate::draw2::MAX_FIT_TOLERANCE);
for (zoom, fidelity, release) in [(0.01, 100.0, hi), (1000.0, 0.01, lo)] {
cx.zoom = zoom;
let stroke: Vec<_> = [(0.0, 0.0), (40.0, 20.0), (80.0, 0.0), (120.0, 20.0)].iter().map(|&(x, y)| (x / zoom, y / zoom)).collect();
for id in ["pencil", "paintbrush"] {
let mut t = GestureTool::new(id);
t.set_option("fidelity", &json!(fidelity));
let acts = drag(&mut t, &cx, &stroke, Mods::default());
let sent: Vec<_> =
acts.concat().into_iter().filter_map(|a| if let Action::Preview(_, v) = a { v["fidelity"].as_f64() } else { None }).collect();
assert!(sent.iter().all(|f| (lo..=hi).contains(f)), "{id} at {zoom}x: {sent:?}");
assert_eq!(sent.last(), Some(&release), "{id} at {zoom}x: {sent:?}");
}
}
}
/// The Blob Brush's Fidelity stays in points (#5729 is the Pencil's and the Paintbrush's): its
/// stroke, and another tool chosen while it is drawn, send it as set at any zoom.
#[test]
+274 -2
View File
@@ -12,6 +12,8 @@
//! An image with hard edges (a GIF, a 1-bit scan) says nothing more than the cracks do: every crack
//! moves by the same amount. There the staircase is read the classic way: a one-pixel step between
//! two runs is a point of a sloped edge (its middle is on the edge, the corners beside it are not).
//! A staircase of longer steps is read the same way where a smooth area was split into bands (see
//! [`outline`]).
use kurbo::Vec2;
use vectorcraft_geom::Point;
@@ -119,6 +121,10 @@ pub(crate) fn low_contrast(steps: &[[f64; 5]]) -> bool {
/// flat (see [`low_contrast`]).
const FLAT: f64 = 12.0;
/// The longest step (px) of a staircase read as the slope through it in a smooth area (see
/// [`outline`]). An edge longer than this keeps its corners.
const STAIR_MAX: usize = 8;
/// What `across` says of a crack that is an edge whatever the image does there: a crack on the
/// image's border, or one that the image's pixels cannot be read across (see [`low_contrast`]).
pub(crate) const EDGE_STEP: [f64; 5] = [1.0, 1.0, f64::NAN, f64::NAN, f64::NAN];
@@ -233,6 +239,50 @@ pub(crate) fn outline(
if junctions[edges[i % n].first].is_some() { 0 } else { (a.0 * b.1 - a.1 * b.0).signum() }
};
let step: Vec<bool> = (0..n).map(|i| edges[i].len == 1 && turn(i) * turn(i + 1) < 0).collect();
// A staircase of longer steps, where a smooth area was split into bands: a run of three or more
// edges of one to `STAIR_MAX` pixels, each turning one way where it starts and the other where
// it ends, with no junction on it, whose cracks read as the contour of a smooth area (see
// `low_contrast`, applied to the run's own cracks; a run is cut at any step whose own cracks
// show half the step between the colors or more). Its edges are steps: no corner where two of
// them meet, and each gives one point, its middle. Where a run meets an edge that is not a
// step, that corner stays. A sharp edge drawn as a staircase keeps its corners. (The runs are
// the same from either side: they depend only on the edges, their turns and the junctions,
// which every region around a pixel corner shares.)
let stair = {
let candidate: Vec<bool> = (0..n)
.map(|i| {
let e = &edges[i];
(1..=STAIR_MAX).contains(&e.len) && turn(i) * turn(i + 1) < 0 && !(0..=e.len).any(|k| junction((e.first + k) % cracks))
})
.collect();
let own = |i: usize| (0..edges[i].len).filter_map(|j| steps.get(edges[i].first + j).copied()).collect::<Vec<_>>();
// Whether a step's own cracks show under half of the step between the two colors, as a
// contour does (an edge shows nearly all of it): a staircase that runs on from a contour
// into an edge is cut there. (Summed in sorted order: the same from either side.)
let gentle = |i: usize| {
let mut near: Vec<f64> = own(i).iter().map(|s| s[0]).filter(|s| !s.is_nan()).collect();
near.sort_by(f64::total_cmp);
!near.is_empty() && near.iter().sum::<f64>() < 0.5 * near.len() as f64
};
let mut stair = vec![false; n];
// A loop turns once round in all, so some edge is not a candidate: runs start after it.
if let Some(s0) = (0..n).find(|&i| !candidate[i]) {
let mut k = 1;
while k < n {
let run: Vec<usize> = (k..n).map(|j| (s0 + j) % n).take_while(|&i| candidate[i] && gentle(i)).collect();
k += run.len().max(1);
if run.len() < 3 {
continue;
}
if low_contrast(&run.iter().flat_map(|&i| own(i)).collect::<Vec<_>>()) {
for &i in &run {
stair[i] = true;
}
}
}
}
stair
};
let outward = |d: (i32, i32)| Vec2::new(f64::from(d.1), f64::from(-d.0));
// The pixel at a corner of the shape lies on both of the corner's edges, and what it lacks of
// the inside's colour is the doing of both: read as one edge's alone it dents the corner. The
@@ -242,7 +292,7 @@ pub(crate) fn outline(
let mut shifts = shifts;
for i in 0..n {
let (b, e) = ((i + n - 1) % n, i);
if step[b] || step[e] || turn(i) == 0 {
if step[b] || step[e] || (stair[b] && stair[e]) || turn(i) == 0 {
continue;
}
let (before, edge) = (&edges[b], &edges[e]);
@@ -276,6 +326,9 @@ pub(crate) fn outline(
&& edges[b].len >= 3
&& edges[s1].dir == edges[b].dir
&& edges[s2].dir == edges[a].dir
// The edges of a staircase of longer steps (see `stair`) make no corner here.
&& !stair[a]
&& !stair[b]
&& free(s1)
&& free(s2)
&& free(b)
@@ -311,7 +364,7 @@ pub(crate) fn outline(
if k == 0 && first.is_some() {
// The junction itself: the one point every region around it has.
pts.push(junctions[crack].unwrap_or(corner));
} else if along_edge == 0 && !step[i] && !step[(i + n - 1) % n] {
} else if along_edge == 0 && !step[i] && !step[(i + n - 1) % n] && !(stair[i] && stair[(i + n - 1) % n]) {
// A true corner: where its two edges, each moved by its own shift, meet.
let before = &edges[(i + n - 1) % n];
pts.push(corner + outward(before.dir) * shifts[(crack + cracks - 1) % cracks] + outward(e.dir) * shifts[crack]);
@@ -319,6 +372,13 @@ pub(crate) fn outline(
if !hard && let Some(sharp) = notch[i] {
// A corner whose own pixel went to the other side: the corner, not the two steps.
pts.extend(sharp);
} else if stair[i] {
if along_edge == e.len / 2 {
// The middle of the step, moved by its cracks' mean shift (multiples of 1/1024,
// so the same sum from either side).
let shift = (0..e.len).map(|j| shifts[e.first + j]).sum::<f64>() / e.len as f64;
pts.push(at(i) + Vec2::new(f64::from(e.dir.0), f64::from(e.dir.1)) * (e.len as f64 / 2.0) + outward(e.dir) * shift);
}
} else if step[i] || !hard {
pts.push(corner + Vec2::new(f64::from(e.dir.0), f64::from(e.dir.1)) * 0.5 + outward(e.dir) * shifts[crack]);
}
@@ -494,6 +554,218 @@ mod tests {
}
}
#[test]
fn a_staircase_of_longer_steps_in_a_smooth_area_becomes_the_slope_through_its_steps() {
// Left and right regions meet along a staircase of steps two pixels across and three down
// (rows 0 to 8), a straight run of ten rows, and the same staircase again (rows 19 to 27).
// The cracks above row 9 read as the contour of a smooth area, the others as an edge, so
// the piece as a whole is no contour.
let (w, h) = (18, 28);
let edge = |y: usize| match y {
0..9 => 2 + 2 * (y / 3),
9..19 => 8,
_ => 10 + 2 * ((y - 19) / 3),
};
let left: Vec<bool> = (0..w * h).map(|i| i % w < edge(i / w)).collect();
let right: Vec<bool> = left.iter().map(|b| !b).collect();
let step = |c: Crack| if c.at(0).unwrap().min(c.at(1).unwrap()) / w < 9 { [0.1, 0.3, 4.0, 4.0, 4.0] } else { [1.0, 1.0, 40.0, 40.0, 0.0] };
let a = outline(&loop_of(&left, w, h), w, h, &|c| (0.0, 1, step(c)), &grid);
let b = outline(&loop_of(&right, w, h), w, h, &|c| (0.0, 2, step(c)), &grid);
let inner = |pieces: &[Piece]| {
pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone()
};
let (mut ours, theirs) = (inner(&a), inner(&b));
assert!(!ours.contour);
ours.pts.reverse();
assert_eq!(ours, theirs);
let pts = &theirs.pts;
// The upper staircase: the middle of each of its steps, on one line, and none of its corners.
let middles = [(3.0, 3.0), (4.0, 4.5), (5.0, 6.0), (6.0, 7.5), (7.0, 9.0)].map(Point::from);
assert!(middles.iter().all(|m| pts.contains(m)), "{pts:?}");
assert!([(4.0, 3.0), (4.0, 6.0), (6.0, 6.0), (6.0, 9.0)].map(Point::from).iter().all(|c| !pts.contains(c)), "{pts:?}");
// The straight run keeps the corners at both its ends, so it stays straight.
assert!([(8.0, 9.0), (8.0, 19.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}");
// The lower one is a sharp edge: it keeps its corners.
assert!([(8.0, 19.0), (10.0, 19.0), (10.0, 22.0), (12.0, 22.0), (12.0, 25.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}");
// Steps longer than STAIR_MAX keep their corners, in a smooth area too.
let (w, h) = (40, 40);
let left: Vec<bool> = (0..w * h).map(|i| i % w < 5 + 10 * (i / w / 10)).collect();
let pieces = outline(&loop_of(&left, w, h), w, h, &|_| (0.0, 1, [0.1, 0.3, 4.0, 4.0, 4.0]), &grid);
let pts = &inner(&pieces).pts;
assert!([(15.0, 10.0), (15.0, 20.0), (25.0, 20.0), (25.0, 30.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}");
}
#[test]
fn a_staircase_that_runs_on_from_a_smooth_area_into_an_edge_keeps_the_edges_corners() {
// One staircase of steps two pixels across and three down, from the top of the image to its
// bottom: its cracks above row 18 read as the contour of a smooth area, the others as an
// edge. Read as a whole, the run would pass as a contour.
let (w, h) = (20, 27);
let left: Vec<bool> = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect();
let right: Vec<bool> = left.iter().map(|b| !b).collect();
let step = |c: Crack| if c.at(0).unwrap().min(c.at(1).unwrap()) / w < 18 { [0.1, 0.3, 4.0, 4.0, 4.0] } else { [1.0, 1.0, 40.0, 40.0, 0.0] };
let a = outline(&loop_of(&left, w, h), w, h, &|c| (0.0, 1, step(c)), &grid);
let b = outline(&loop_of(&right, w, h), w, h, &|c| (0.0, 2, step(c)), &grid);
let inner = |pieces: &[Piece]| {
pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone()
};
let (mut ours, theirs) = (inner(&a), inner(&b));
ours.pts.reverse();
assert_eq!(ours, theirs);
let pts = &theirs.pts;
assert!([(3.0, 3.0), (4.0, 4.5), (9.0, 12.0), (11.0, 15.0), (12.0, 16.5)].map(Point::from).iter().all(|m| pts.contains(m)), "{pts:?}");
assert!([(4.0, 3.0), (10.0, 15.0)].map(Point::from).iter().all(|c| !pts.contains(c)), "{pts:?}");
// The corner where the staircase meets the edge's first step stays.
assert!([(14.0, 18.0), (14.0, 21.0), (16.0, 21.0), (16.0, 24.0), (18.0, 24.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}");
}
#[test]
fn a_staircase_whose_cracks_do_not_read_as_a_contour_keeps_its_corners() {
// Each step's cracks show a tenth of the step near them, but nothing changes within either
// side: two flat colors, not a smooth area.
let (w, h) = (20, 27);
let left: Vec<bool> = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect();
let right: Vec<bool> = left.iter().map(|b| !b).collect();
let flat = [0.1, 0.3, 4.0, 4.0, 0.0];
let a = outline(&loop_of(&left, w, h), w, h, &|_| (0.0, 1, flat), &grid);
let b = outline(&loop_of(&right, w, h), w, h, &|_| (0.0, 2, flat), &grid);
let inner = |pieces: &[Piece]| {
pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone()
};
let (mut ours, theirs) = (inner(&a), inner(&b));
ours.pts.reverse();
assert_eq!(ours, theirs);
let pts = &theirs.pts;
assert!([(4.0, 3.0), (4.0, 6.0), (6.0, 6.0), (10.0, 15.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}");
assert!([(4.0, 4.5), (9.0, 12.0)].map(Point::from).iter().all(|m| !pts.contains(m)), "{pts:?}");
}
#[test]
fn a_staircase_step_moves_by_the_mean_shift_of_its_cracks() {
// The staircase of steps two pixels across and three down, in a smooth area. Down a step,
// its cracks move 0, 1/8 and 1/4 px; across one, 0 and 1/8 px (out of the left region; the
// right region sees them negated).
let (w, h) = (20, 27);
let left: Vec<bool> = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect();
let right: Vec<bool> = left.iter().map(|b| !b).collect();
let shift = |c: Crack| {
let (p, q) = (c.at(0).unwrap(), c.at(1).unwrap());
let v = if p / w == q / w { 0.125 * (p / w % 3) as f64 } else { 0.125 * (p % w % 2) as f64 };
if left[p] { v } else { -v }
};
let gentle = [0.1, 0.3, 4.0, 4.0, 4.0];
let a = outline(&loop_of(&left, w, h), w, h, &|c| (shift(c), 1, gentle), &grid);
let b = outline(&loop_of(&right, w, h), w, h, &|c| (shift(c), 2, gentle), &grid);
let inner = |pieces: &[Piece]| {
pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone()
};
let (mut ours, theirs) = (inner(&a), inner(&b));
assert!(!ours.hard);
ours.pts.reverse();
assert_eq!(ours, theirs);
let pts = &theirs.pts;
// A step down at x = 4 moves right by 1/8 px; the step across at y = 6 moves up by 1/16 px.
assert!([(4.125, 4.5), (5.0, 5.9375), (6.125, 7.5), (7.0, 8.9375)].map(Point::from).iter().all(|m| pts.contains(m)), "{pts:?}");
}
#[test]
fn a_staircase_of_mixed_one_pixel_and_longer_steps_is_one_slope_without_a_notch() {
// Per four rows: three down, one across, one down, three across. Each three-pixel step meets
// the next one with no one-pixel step between them, and the one-pixel steps are a notch
// between two longer ones. All of it is the contour of a smooth area, and the cracks move by
// different amounts.
let (w, h) = (26, 24);
let edge = |y: usize| 2 + 4 * (y / 4) + usize::from(y % 4 == 3);
let left: Vec<bool> = (0..w * h).map(|i| i % w < edge(i / w)).collect();
let right: Vec<bool> = left.iter().map(|b| !b).collect();
let shift = |c: Crack| {
let (p, q) = (c.at(0).unwrap(), c.at(1).unwrap());
let v = 0.125 * ((p + q) % 3) as f64 - 0.125;
if left[p] { v } else { -v }
};
let gentle = [0.1, 0.3, 4.0, 4.0, 4.0];
let a = outline(&loop_of(&left, w, h), w, h, &|c| (shift(c), 1, gentle), &grid);
let b = outline(&loop_of(&right, w, h), w, h, &|c| (shift(c), 2, gentle), &grid);
let inner = |pieces: &[Piece]| {
pieces.iter().find(|p| p.pts.iter().any(|q| q.x > 0.0 && q.x < w as f64 && q.y > 0.0 && q.y < h as f64)).unwrap().clone()
};
let (mut ours, theirs) = (inner(&a), inner(&b));
assert!(!ours.hard);
ours.pts.reverse();
assert_eq!(ours, theirs);
let pts = &theirs.pts;
let near = |x: f64, y: f64, d: f64| pts.iter().any(|p| (p.x - x).hypot(p.y - y) < d);
for k in 1..5 {
let (c, y) = ((2 + 4 * k) as f64, (4 * k) as f64);
// The middle of each step, and no point at the corner where the three-pixel steps
// meet or at the corner the notch would make.
assert!(near(c, y + 1.5, 0.2) && near(c + 2.5, y + 4.0, 0.2), "{k}: {pts:?}");
assert!(!near(c, y, 0.4) && !near(c, y + 4.0, 0.4), "{k}: {pts:?}");
}
}
/// Every point of every piece that `mask` and the region around it get in a smooth area, with
/// `junction_at` and the near share of each crack from `near`.
fn both_sides(
mask: &[bool],
w: usize,
h: usize,
near: &dyn Fn(Crack) -> [f64; 5],
junction_at: &dyn Fn(i32, i32) -> Option<Point>,
) -> [Vec<Point>; 2] {
let other: Vec<bool> = mask.iter().map(|b| !b).collect();
[(mask, 1), (&other[..], 2)]
.map(|(m, id)| outline(&loop_of(m, w, h), w, h, &|c| (0.0, id, near(c)), junction_at).into_iter().flat_map(|p| p.pts).collect())
}
#[test]
fn a_run_of_two_steps_keeps_its_corners() {
// Ten rows down, two across, three down, ten across: only two edges are short enough to
// be steps.
let (w, h) = (20, 20);
let edge = |y: usize| match y {
0..10 => 2,
10..13 => 4,
_ => 14,
};
let left: Vec<bool> = (0..w * h).map(|i| i % w < edge(i / w)).collect();
for pts in both_sides(&left, w, h, &|_| [0.1, 0.3, 4.0, 4.0, 4.0], &grid) {
assert!([(2.0, 10.0), (4.0, 10.0), (4.0, 13.0), (14.0, 13.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}");
assert!(!pts.contains(&Point::new(4.0, 11.5)), "{pts:?}");
}
}
#[test]
fn a_junction_on_a_step_ends_the_staircase_there() {
// The staircase of steps two pixels across and three down, in a smooth area, with a
// junction at (8, 10), on the step down from (8, 9) to (8, 12).
let (w, h) = (20, 27);
let left: Vec<bool> = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect();
let junction_at = |x: i32, y: i32| (x == 8 && y == 10).then(|| Point::new(8.0, 10.0));
for pts in both_sides(&left, w, h, &|_| [0.1, 0.3, 4.0, 4.0, 4.0], &junction_at) {
// The step keeps the corners at both its ends; the steps on either side of it are slopes.
assert!([(8.0, 9.0), (8.0, 10.0), (8.0, 12.0), (5.0, 6.0), (11.0, 15.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}");
assert!(!pts.contains(&Point::new(8.0, 10.5)) && !pts.contains(&Point::new(6.0, 6.0)), "{pts:?}");
}
}
#[test]
fn a_step_whose_cracks_read_as_an_edge_ends_the_staircase_there() {
// The same staircase in a smooth area, but the cracks of the step down from (8, 9) to
// (8, 12) cannot be read across.
let (w, h) = (20, 27);
let left: Vec<bool> = (0..w * h).map(|i| i % w < 2 + 2 * (i / w / 3)).collect();
let near = |c: Crack| {
let (p, q) = (c.at(0).unwrap(), c.at(1).unwrap());
if p / w == q / w && (9..12).contains(&(p / w)) && (p % w).max(q % w) == 8 { EDGE_STEP } else { [0.1, 0.3, 4.0, 4.0, 4.0] }
};
for pts in both_sides(&left, w, h, &near, &grid) {
assert!([(8.0, 9.0), (8.0, 12.0), (5.0, 6.0), (11.0, 15.0)].map(Point::from).iter().all(|c| pts.contains(c)), "{pts:?}");
assert!(!pts.contains(&Point::new(8.0, 10.5)) && !pts.contains(&Point::new(6.0, 6.0)), "{pts:?}");
}
}
#[test]
fn a_shift_that_is_not_a_number_moves_nothing() {
let mask = [true, true, false, false, true, true, false, false];
+2
View File
@@ -344,6 +344,8 @@ impl VectorcraftApp {
screen_color::poll(self, ctx);
self.poll_finished_work();
crate::script_runs::poll(self);
// A panel's, a dialog's or the text input's commit journaled in the frame before.
crate::panels::actions::after_journaled_edit(self);
crate::scripts_menu::poll(self, ctx);
if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() {
// A script in `$.sleep` goes on when its time is up; until then the app can idle.
+5 -8
View File
@@ -224,13 +224,10 @@ impl VectorcraftApp {
}
// While an action records, a command that the recording would keep as a step runs only
// when the step fits in the action.
let recorded = match panels::actions::before_recorded_command(self, id, &params) {
Ok(recorded) => recorded,
Err(e) => {
self.ui.status = e.clone();
return Err(e);
}
};
if let Err(e) = panels::actions::before_recorded_command(self, id, &params) {
self.ui.status = e.clone();
return Err(e);
}
// A command that changes the edited text is an application edit (undo, a panel or menu
// edit, a control request). Capture the bounded committed context around it so `Other`
// dominates the frame even if an IME receipt follows. Selection/view commands that leave
@@ -240,7 +237,7 @@ impl VectorcraftApp {
let ime_before = crate::ime::stamp(&mut self.session, ime_view);
let cursor_settings = (self.session.caps_lock, self.session.prefs.use_precise_cursors);
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
let r = panels::actions::after_recorded_command(self, recorded, r);
let r = panels::actions::after_recorded_command(self, r);
if r.is_ok() && cursor_settings != (self.session.caps_lock, self.session.prefs.use_precise_cursors) {
self.canvas.hover_cursor = None;
}
+4 -1
View File
@@ -399,7 +399,9 @@ fn pressed_with(app: &mut VectorcraftApp, index: Option<usize>, pos: Point, tool
}
}
/// Act on what a tool event asked the UI for (dialogs, tool switches), or show its error.
/// Act on what a tool event asked the UI for (dialogs, tool switches), or show its error. When an
/// edit the tool committed or ran no longer fits in the action being recorded, the edit stays and
/// the status bar names the limit ([`crate::panels::actions::after_journaled_edit`]).
pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Vec<vectorcraft_engine::UiRequest>>) {
match r {
Ok(reqs) => {
@@ -420,6 +422,7 @@ pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Ve
}
}
}
crate::panels::actions::after_journaled_edit(app);
}
Err(e) => app.status(e.to_string()),
}
+3 -1
View File
@@ -252,7 +252,9 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf:
/// The Appearance and Easing widgets of one selected blend (Selection and Blend tools), each joined
/// by a line to the spine's halfway point: the Appearance widget hollow above it, the Easing widget
/// filled below it. Drawn with the edges hidden too, as they are controls.
/// filled below it. For a blend without a spine the line goes to the halfway point of the straight
/// lines between its key centers, which are not drawn. Drawn with the edges hidden too, as they are
/// controls.
pub(super) fn blend_widgets_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) {
use vectorcraft_tools::blendwidget::{BlendControl, BlendWidget, RADIUS_PX};
if !matches!(app.session.tool_id(), "selection" | "blend") {
+23 -12
View File
@@ -9,17 +9,11 @@ use std::time::{Duration, Instant};
use vectorcraft_engine::cmd::clipboard::PASTE_ORDER;
use crate::sysclip::ClipboardProbeFactory;
use crate::sysclip::{CLIPBOARD_PROBE_STOP_WAIT as STOP_WAIT, ClipboardProbeFactory};
/// How often the worker looks at the clipboard while the UI wants to know.
const PROBE_INTERVAL: Duration = Duration::from_millis(250);
/// How long dropping the probe (when the app quits) waits for the worker to let go of its clipboard
/// handle (VectorCraft's own bound). arboard's X11 reads wait up to 4 s for each text format they
/// ask for; when a look is still waiting after this bound, the app quits without waiting longer,
/// and what it copied may not reach the clipboard manager.
const STOP_WAIT: Duration = Duration::from_secs(5);
/// The background clipboard check ([`crate::VectorcraftApp`]'s `clipboard_probe`).
pub(crate) struct Probe {
/// Tells the worker whether Paste depends on the system clipboard; dropped to stop it.
@@ -28,8 +22,14 @@ pub(crate) struct Probe {
verdicts: Receiver<bool>,
/// The worker's last verdict.
last: bool,
/// How `Drop` waits for the worker: [`wait_for_worker`], or a controllable clock in tests.
pub(crate) stop: StopWait,
}
/// Waits on the worker's verdicts, from the quit to the deadline [`stop_by`] gives, until the worker
/// is gone or the deadline passes.
pub(crate) type StopWait = Box<dyn FnMut(&Receiver<bool>, Instant, Instant) + Send>;
impl Probe {
/// Start the worker. `None` on wasm, or when the thread can't be spawned: the caller then falls
/// back to the in-line check.
@@ -65,13 +65,14 @@ impl Probe {
Err(RecvTimeoutError::Disconnected) => break,
}
}
// The handle goes before the app stops waiting (`Drop`): on X11 the last one alive
// hands what the app copied to the clipboard manager, which must finish before exit.
// The handle goes before `Drop` stops waiting, unless dropping it takes longer than
// `STOP_WAIT`: on X11 the last one alive hands what the app copied to the clipboard
// manager, which must finish before exit.
drop(clipboard);
drop(tx);
})
.ok()?;
Some(Self { wants: Some(wants), wanted: false, verdicts, last: false })
Some(Self { wants: Some(wants), wanted: false, verdicts, last: false, stop: Box::new(wait_for_worker) })
}
/// Paste can take from the system clipboard: `wanted` (nothing copied in the app, a document
@@ -96,7 +97,17 @@ impl Drop for Probe {
/// never answers) until it has let go of its clipboard handle.
fn drop(&mut self) {
self.wants = None;
let end = Instant::now() + STOP_WAIT;
while self.verdicts.recv_timeout(end.saturating_duration_since(Instant::now())).is_ok() {}
let quit = Instant::now();
(self.stop)(&self.verdicts, quit, stop_by(quit));
}
}
/// When dropping the probe at `quit` stops waiting for its worker.
pub(crate) fn stop_by(quit: Instant) -> Instant {
quit + STOP_WAIT
}
/// Waits until the worker has dropped its sender (it has let go of its clipboard handle) or `end`.
fn wait_for_worker(verdicts: &Receiver<bool>, _quit: Instant, end: Instant) {
while verdicts.recv_timeout(end.saturating_duration_since(Instant::now())).is_ok() {}
}
+2 -2
View File
@@ -251,14 +251,14 @@ fn long_page_notes_are_translated() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 56_692.91, "height": 2_834.65})).unwrap();
let mut notes: Vec<String> = vec![];
for p in [json!({"compatibility": "1.5"}), json!({"preset": "PDF/X-4:2010"})] {
for p in [json!({"compatibility": "1.5", "longPagesInPoints": false}), json!({"preset": "PDF/X-4:2010"})] {
let r = s.execute("document.exportPdf", &p).unwrap();
let warnings = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str());
notes.extend(warnings.filter(|w| w.contains("14,400 pt")).map(str::to_string));
}
notes.push(s.execute("document.exportPdf", &json!({"preset": "PDF/X-1a:2001"})).unwrap_err().to_string());
s.execute("file.new", &json!({"width": 85_040, "height": 17})).unwrap();
let r = s.execute("document.exportPdf", &json!({})).unwrap();
let r = s.execute("document.exportPdf", &json!({"longPagesInPoints": false})).unwrap();
let warnings = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str());
notes.extend(warnings.filter(|w| w.contains("too long and narrow")).map(str::to_string));
assert_eq!(notes.len(), 5, "{notes:?}");
+12 -2
View File
@@ -205,7 +205,8 @@ fn svg_continues_in_svg_options() {
/// Without Use Artboards, a PDF continues in Save PDF too, without its artboard choice, and the
/// file is one page of the art's bounds. Its options apply: a drawing 10 m long is written at
/// full size in points with "Write pages longer than 200 in at full size in points".
/// full size in points with "Write pages longer than 200 in at full size in points" (on by
/// default), and with a `UserUnit` without it.
#[test]
fn pdf_art_continues_in_the_save_pdf_dialog() {
let (mut app, written) = app(2);
@@ -223,13 +224,22 @@ fn pdf_art_continues_in_the_save_pdf_dialog() {
app.run("shape.rectangle", json!({"x": 0, "y": 100, "width": 28_346.46, "height": 50})).unwrap();
app.run("file.exportAs", json!({"format": "pdf"})).unwrap();
confirm(&mut app).unwrap();
set(&mut app, "longPagesInPoints", json!(true));
frame(&mut app);
confirm(&mut app).unwrap();
let bytes = written.borrow()[1].1.clone();
assert!(!String::from_utf8_lossy(&bytes).contains("/UserUnit"));
let width = vectorcraft_pdf::import(&bytes).unwrap().artboards[0].rect.width();
assert!((28_346.0..28_350.0).contains(&width), "{width}");
app.run("file.exportAs", json!({"format": "pdf"})).unwrap();
confirm(&mut app).unwrap();
set(&mut app, "longPagesInPoints", json!(false));
frame(&mut app);
confirm(&mut app).unwrap();
let bytes = written.borrow()[2].1.clone();
assert!(String::from_utf8_lossy(&bytes).contains("/UserUnit"));
let width = vectorcraft_pdf::import(&bytes).unwrap().artboards[0].rect.width();
assert!((28_346.0..28_350.0).contains(&width), "{width}");
}
#[test]
@@ -1,13 +1,13 @@
//! The 3D and Materials panel's Materials tab: the document's Graphics (its symbols) as thumbnails,
//! Add as Single Graphic, and the graphics mapped onto the selected 3D object's planar faces with
//! their face, position, size and turn. Picking a thumbnail maps that graphic onto the selected
//! objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic
//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, or
//! Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic
//! onto the selected objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic
//! (`threeD.addGraphic`). Editing a mapped graphic changes the effect's `graphics` parameter, which
//! the panel sends as it sends every other setting.
use egui::{Sense, Stroke, StrokeKind, vec2};
use serde_json::{Value, json};
use vectorcraft_effects::{GRAPHICS, MappedGraphic, PlanarFace, ROTATE};
use vectorcraft_effects::{GRAPHICS, MappedGraphic, PlanarFace, REVOLVE, ROTATE};
use super::revolve::{heading, label, number};
use crate::VectorcraftApp;
@@ -96,7 +96,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
}
ui.add_space(10.0);
if !takes {
dim_label(ui, tl!("Graphics map onto planar faces: pick the Plane or Extrude object type."));
dim_label(ui, tl!("Graphics map onto the Plane, Extrude and Revolve object types."));
return;
}
let raw = d.fields.get(GRAPHICS).cloned().unwrap_or(Value::Null);
@@ -121,7 +121,8 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
ui.add_space(6.0);
let Some(g) = list.get(index).cloned() else { return };
let mut edited = g.clone();
if effect != ROTATE {
// A plane has one face, and Revolve's graphics go on its side.
if effect != ROTATE && effect != REVOLVE {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0;
label(ui, tl!("Face"));
+3
View File
@@ -1537,6 +1537,8 @@ font-technology Variable Променливи
Objects on Path Tool Инструмент „Обекти по пътя“
Attach Objects on Path Прикрепяне на обекти към пътя
Expand Objects on Path Разширяване на обекти по пътя
Detach Откачване
Detach Object from Path Откачване на обект от пътя
Release Live Paint Освобождаване на динамично оцветяване
Release Repeat Освобождаване на повторение
Release Slice Освобождаване на отрязък
@@ -4514,6 +4516,7 @@ axis Both И двете
@msg paths contain invalid coordinates пътищата съдържат невалидни координати
@msg paths: give at least one file пътища: посочете поне един файл
@msg replace: the object to replace was changed or deleted замяна: обектът за замяна е променен или изтрит
@msg the document it was prepared for is no longer active документът, за който е подготвено, вече не е активен
@msg pattern missing липсва мостра
@msg patterns nested too deeply are filled with mid-grey мострите, вложени прекалено дълбоко, се запълват със средно сиво
@msg percent must be above 0 and at most 6400, not {p} percent трябва да е над 0 и най-много 6400, а не {p}
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -1813,6 +1813,8 @@ digits Malayalam Malajalam
Objects on Path Tool Alat objekti na putanji
Attach Objects on Path Priloži objekte na putanju
Expand Objects on Path Proširi objekte na putanji
Detach Odvoji
Detach Object from Path Odvoji objekat s putanje
Release Live Paint Oslobodi živo bojenje
Release Repeat Oslobodi ponavljanje
Release Slice Oslobodi isječak
@@ -4909,6 +4911,7 @@ imageTrace Outline Obris
@msg paths contain invalid coordinates putanje sadrže nevažeće koordinate
@msg paths: give at least one file paths: navedite barem jednu datoteku
@msg replace: the object to replace was changed or deleted replace: objekat za zamjenu je promijenjen ili izbrisan
@msg the document it was prepared for is no longer active dokument za koji je pripremljeno više nije aktivan
@msg pattern missing uzorak nedostaje
@msg patterns nested too deeply are filled with mid-grey previše duboko ugniježđeni uzorci ispunjavaju se srednje sivom
@msg percent must be above 0 and at most 6400, not {p} percent mora biti iznad 0 i najviše 6400, a ne {p}
@@ -4944,6 +4947,7 @@ imageTrace Outline Obris
@msg select a repeat odaberite ponavljanje
@msg select an Intertwine group odaberite Intertwine grupu
@msg select an Objects on Path group odaberite grupu objekata na putanji
@msg choose the object to detach with its Select/Move widget odaberite objekat koji želite odvojiti njegovom ručicom Odaberi/Pomjeri
@msg a path inside a compound path, blend, envelope, repeat or Intertwine group can't take objects putanja unutar složene putanje, stapanja, omotnice, ponavljanja ili Intertwine grupe ne može primiti objekte
@msg a clipping path can't take objects putanja isijecanja ne može primiti objekte
@msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path objekti unutar stapanja, omotnice, ponavljanja ili Intertwine grupe ne mogu se priložiti putanji
Can't render this file because it contains an unexpected character in line 2 and column 73.
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more